Tuesday, August 25, 2009

What is the difference between int.parse() and convert.int32()

If we want to convert a string value (Lets say we have a string “23”) to integer we have 2 options. One is to use the Int.Parse method and other is to use the Convert.ToInt32.

The real query with every one was what is the difference between the two. The answer is null handling. The difference between the 2 is the manner in which null is handled. If you pass a null value to convert.ToInt32 method it will return back 0. But the same is not true with Int.Parse. If we pass null to Int.Parse method it will throw an ArgumentNullException exception.

Although Convert.ToInt32 method does not throw an exception but it can have a big drawbacks. If you use it on a query string value(where u are also expecting the value 0) then the Convert.ToInt32 might cause programmatic error.

######################################################################################


The difference lies in the way both handles NULL value.

When encountered a NULL Value, Convert.ToInt32 returns a value 0. On other hand,Parse is more sensitive and expects a valid value. So it would throw an exception when you pass in a NULL.

string stringInt = "01234";

int iParse = int.Parse(stringInt);

int iConvert = Convert.ToInt32(stringInt);


##################################################################################3

string MyString = "12345";
int MyInt = int.Parse(MyString);
MyInt++;
Console.WriteLine(MyInt);
// The result is "12346".

#################################################################################
int.Parse for Integer Conversion in C#
--------------------------------------

1. Using int.Parse

First, here we see the int.Parse method. int.Parse is the simplest method, and is also the author's favorite for many situations. It throws exceptions on invalid input, which can be slow if they are common. It is does not contain any internal null checks.

=== Example program that uses int.Parse (C#) ===

using System;

class Program
{
static void Main()
{
// Convert string to number.
string text = "500";
int num = int.Parse(text);
Console.WriteLine(num);
}
}

=== Output of the program ===

500


2. Using Convert.ToInt32

Third, we look at the Convert.ToInt32 method. Convert.ToInt32, along with its siblings Convert.ToInt16 and Convert.ToInt64, is actually a static wrapper method for the int.Parse method. It can be slower than int.Parse if the surrounding code is equivalent.

=== Example program that uses Convert.ToInt32 (C#) ===

using System;

class Program
{
static void Main()
{
// Convert 'text' string to an integer with Convert.ToInt32.
string text = "500";
int num = Convert.ToInt32(text);
Console.WriteLine(num);
}
}

=== Output of the program ===

500


3. Which method should I use?

The it's recommendation is to use int.Parse when your input will be valid, as it makes for simpler calling code. It isn't always perfect, but it is a winner. On the other hand, use int.TryParse when you will be dealing with corrupt data.


Good Website : http://dotnetperls.com/datetime-1

Friday, August 14, 2009

What is ItemCommand ?

Dev Palmistry

DataGrid.ItemCommand Event


System.Web.UI.WebControls Namespace DataGrid Class

Occurs when a button within a DataGrid control is clicked.

[ VB ]
Public Event ItemCommand As DataGridCommandEventHandler

[ C# ]
public event DataGridCommandEventHandler ItemCommand;

[ C++ ]
public: __event DataGridCommandEventHandler* ItemCommand;

In [ JScript ], you can handle the events defined by a class, but you cannot define your own.
Remarks

The ItemCommand event is raised whenever any button associated with an item in the DataGrid is clicked. This provides for programmatically determining which specific command button is clicked and take appropriate action. This event is commonly used to handle button controls with a given CommandName value in the DataGrid control.
Event Data

Information related to the ItemCommand event is passed via a DataGridCommandEventArgs object to the method assigned to handle the event. The following DataGridCommandEventArgs properties provide information specific to this event.
Property Description
CommandSource Gets the source of the command.
Item Gets the DataGridItem associated with the event.

What is the namespace of StringBuilder ?

The System.Text is the namespace are used in StringBuilder

The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

You can create a new instance of the StringBuilder object by initializing your variable with one of the overloaded constructor methods, as illustrated in the following code example.


[ C# ]
StringBuilder myStringBuilder = new StringBuilder ( "Hello World!" );

Setting and Retrieving the Connection String Using Web.Cofig !!

In Connecting to a Database, we have shown the essential steps to establish and open a connection to a data source from within a Web Forms page. In this application, we use a slightly different approach of storing the connection string in the application configuration file ( web.config ), thereby making the connection string globally available to any page in the application. This technique is basically implemented as follows.

In the web.config file for the application, include the following:

configuration>
appsettings>
add key="myDbConn" value="server=servername; uid=userid; pwd=password; database=dbname">
/add>
/appsettings>

changing the values ( shown in italics ) to correspond to your settings.

Then on each page that you need to initialize a connection, use:

SqlConnection myConn = new SqlConnection
( ConfigurationSettings.AppSettings [ "myDbConn" ] );

Monday, August 3, 2009

N-Tier Architecture !!

Dev Palmistry

3-Tier Architecture in ASP.NET with C#

3-Tier architecture is a very well know buzz word in the world of software development whether it web based or desktop based. In this article I am going to show how to design a web application based on 3-tier architecture.

Introduction

3-Tier architecture generally contains UI or Presentation Layer, Business Access Layer (BAL) or Business Logic Layer and Data Access Layer (DAL).

Presentation Layer (UI)
Presentation layer cotains pages like .aspx or windows form where data is presented to the user or input is taken from the user.

Business Access Layer (BAL) or Business Logic Layer
BAL contains business logic, validations or calculations related with the data, if needed. I will call it Business Access Layer in my demo.

Data Access Layer (DAL)

DAL contains methods that helps business layer to connect the data and perform required action, might be returning data or manipulating data (insert, update, delete etc). For this demo application, I have taken a very simple example. I am assuming that I have to play with record of persons (FirstName, LastName, Age) and I will refer only these data through out this article.


Designing 3-Tier Architecture

For the ease of understanding, I have created BAL, DAL into the App_Code folder. In real scenario, you should create separate projects for BAL, DAL (as Class Library) and UI (as Web project) and reference your BAL into UI.



Data Access Layer
Lets proceed with desiging 3-Tier architecture. To do that lets proceed with DAL, BAL and then UI. Add a class named by right clicking App_Code folder. (In my case I have a 3-Tier folder inside App_Code folder, you can directly add inside App_Code or you can create a separate project for DAL and add reference of this project into your BAL.) and copy-paste folowing code (Your can overwrite your default written code for the class file by pasting this code). Here, I have assumed that you will create the respective stored procedure yourself into the database or you may download attachment from http://www.dotnetfunda.com/articles/article18.aspx article and look for App_Data folder for complete database structure and stored procedure for this article.

Data Access Layer (DAL)


Code for Data Access Layer



In the above code, I have a member variable called connStr that is getting database connection string from my web.config file that is being used through out the class. I have separate method for inserting, deleting, updating records into database and loading records from database. I am not goint into details of how I am connecting database and manipulating the data just to make this tutorials short.


Business Access Layer (BAL)

Now, create a class named PersonBAL3 into App_Code folder by right clicking it and write respective methods for calling Insert, Delete, Update and Load methods of Data Access Layer class file (PersonDAL3) (In my case I have a 3-Tier folder inside App_Code folder, you can directly add inside App_Code or you can create a separate project for BAL and add reference of this project into your Presentation Layer). As we don't have any business logic here so simply instantiate the PersonDAL3 class of DAL and call methods. Below is the code for BAL (Your can overwrite your default written code for the class file by pasting this code).




Till now we haev our Business Access Layer and Database Access Layer ready. Now we have to write our Presentation Layer that will use our Business Access Layer methods. Lets create a form that will have three textboxes for FirstName, LastName and Age.


Presentation Layer




Create an Insert.aspx page (make is as Startup page) and copy paste following code to bring the insert form something like displaying in the picture.
Code for Insert Record form


















































Add Records


First Name:








Display="dynamic">




Last Name:








Display="dynamic">




Age:








Display="dynamic">



Operator="DataTypeCheck" Type="Integer">


 







Now, lets write method that will fire when Submit button will be clicked on the from.
Code for AddRecords method


protected void AddRecords(object sender, EventArgs e)

{

//Lets validate the page first

if (!Page.IsValid)

return;



int intResult = 0;

// Page is valid, lets go ahead and insert records

// Instantiate BAL object

PersonBAL3 pBAL = new PersonBAL3();

// Instantiate the object we have to deal with

string firstName = txtFirstName.Text;

string lastName = txtLastName.Text;

int age = Int32.Parse(txtAge.Text);



try

{

intResult = pBAL.Insert(firstName, lastName, age);

if (intResult > 0)

lblMessage.Text = "New record inserted successfully.";

else

lblMessage.Text = "FirstName ["+ txtFirstName.Text +"] alredy exists, try another name";



}

catch (Exception ee)

{

lblMessage.Text = ee.Message.ToString();

}

finally

{

pBAL = null;

}

}


In the above code, first I am validating the page by using Page.IsValid method just to check if correct data has been entered. Then I have instantiated PersonBAL3 and calling Insert method of it (pBAL.Insert) by passing firstName, lastName, age as parameter.

Dispalying Records into GridView




Create a .aspx file called List.aspx and create a GridView something like displayed into the picture. To list the record into GridView that will also enable us to Edit, Delete record, copy paste following code.

Code for GridView



DataKeyNames="PersonID" AutoGenerateEditButton="True" AutoGenerateColumns="False"

OnRowEditing="EditRecord" OnRowUpdating="UpdateRecord" OnRowCancelingEdit="CancelRecord"

OnRowDeleting="DeleteRecord" PageSize="5" >























<%# Eval("FirstName") %>





asp:TextBox ID="txtFName" runat="Server" Text='<%# Eval("FirstName") %>'>









<%# Eval("LastName") %>





asp:TextBox ID="txtLName" runat="Server" Text='<%# Eval("LastName") %>'>









<%# Eval("Age") %>





asp:TextBox ID="txtAge" runat="Server" Text='<%# Eval("Age") %>'>

























Code to Load records and Displaying Records into GridView


private DataTable BindGrid()

{

PersonBAL3 p = new PersonBAL3();



try

{

DataTable dTable = p.Load();

GridView1.DataSource = dTable;

GridView1.DataBind();

}

catch (Exception ee)

{

lblMessage.Text = ee.Message.ToString();

}

finally

{

p = null;

}



return dTable;

}


In the above method I am instantiating PersonBAL3 class and calling Load method to get the record into DataTable and binding it into GridView.

Code to Delete Records


protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)

{

int personID = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());





// instantiate BAL

PersonBAL3 pBAL = new PersonBAL3();

try

{

pBAL.Delete(personID);



lblMessage.Text = "Record Deleted Successfully.";

}

catch (Exception ee)

{

lblMessage.Text = ee.Message.ToString();

}

finally

{

pBAL = null;

}



GridView1.EditIndex = -1;

// Refresh the list

BindGrid();

}


Above method will fire when Delete link will be clicked on the GridView. In the above code, I am instantiating PersonBAL3 and calling Delete method by passing personID as parameter so that select reocrds will be deleted from datbase.




Above method will fire when Update link will be clicked for a particular row of the GridView in edit mode. In the above method, I am instantiating PersonBAL3 and calling the Update method by p[assing required parameters.

Now we have all set to go, now just run your project and try inserting records. You can also navigate to another page your created (list.aspx) and try updating, deleting records.

Conclusion

By using 3-Tier architecture in your project you can achive

1. Seperation - the functionality is seperated from the data access and presentation so that it is more maintainable
2. Independence - layers are established so that if one is modified (to some extent) it will not affect other layers.
3. Reusability - As the layers are seperated, it can exist as a module that can be reused by other application by referencing it.

Hope this article helped you understanding 3-Tier architecture and desiging it.

Thanks and Happy Coding !!!

N-Tier Architecture !!

Dev Palmistry

What is n-Tier Architecture?

This is a very important topic to consider when developing an application. Many elements need to be considered when deciding on the architecture of the application, such as performance, scalability and future development issues. When you are deciding on which architecture to use, first decide on which of the three aforementioned elements you think is most valuable -- as some choices you make will impact on others. For example, some choices that boost performance will impact on the scalability or future development of your design, etc.

Here we will talk generally about what n-Tier architecture is, and then we will have a look at different n-Tier architectures you can use to develop ASP.NET applications and issues that arise relating to performance, scalability and future development issues for each one.

Firstly, what is n-Tier architecture? N-Tier architecture refers to the architecture of an application that has at least 3 "logical" layers -- or parts -- that are separate. Each layer interacts with only the layer directly below, and has specific function that it is responsible for.

Why use n-Tier architecture? Because each layer can be located on physically different servers with only minor code changes, hence they scale out and handle more server load. Also, what each layer does internally is completely hidden to other layers and this makes it possible to change or update one layer without recompiling or modifying other layers.

This is a very powerful feature of n-Tier architecture, as additional features or change to a layer can be done without redeploying the whole application. For example, by separating data access code from the business logic code, when the database servers change you only needs to change the data access code. Because business logic code stays the same, the business logic code does not need to be modified or recompiled.

[Note] tier and layer mean the same thing [End Note]

An n-Tier application usually has three tiers, and they are called the presentation tier, the business tier and the data tier. Let's have a look at what each tier is responsible for.

Presentation Layer
Presentation Layer is the layer responsible for displaying user interface and "driving" that interface using business tier classes and objects. In ASP.NET it includes ASPX pages, user controls, server controls and sometimes security related classes and objects.

Business Tier
Business Tier is the layer responsible for accessing the data tier to retrieve, modify and delete data to and from the data tier and send the results to the presentation tier. This layer is also responsible for processing the data retrieved and sent to the presentation layer.

In ASP.NET it includes using SqlClient or OleDb objects to retrieve, update and delete data from SQL Server or Access databases, and also passing the data retrieved to the presentation layer in a DataReader or DataSet object, or a custom collection object. It might also include the sending of just an integer, but the integer would have been calculated using the data in the data tier such as the number of records a table has.

BLL and DAL
Often this layer is divided into two sub layers: the Business Logic Layer (BLL), and the Data Access Layers (DAL). Business Logic Layers are above Data Access Layers, meaning BLL uses DAL classes and objects. DAL is responsible for accessing data and forwarding it to BLL.

In ASP.NET it might be using SqlClient or OleDb to retrieve the data and sending it to BLL in the form of a DataSet or DataReader. BLL is responsible for preparing or processing the data retrieved and sends it to the presentation layer. In ASP.NET it might be using the DataSet and DataReader objects to fill up a custom collection or process it to come up with a value, and then sending it to Presentation Layer. BLL sometimes works as just transparent layer. For example, if you want to pass a DataSet or DataReader object directly to the presentation layer.

Data Tier
Data tier is the database or the source of the data itself. Often in .NET it's an SQL Server or Access database, however it's not limited to just those. It could also be Oracle, mySQL or even XML. In this article we will focus on SQL Server, as it has been proven to be the fastest database within a .NET Application.

Logical Layers vs. Physical Layers (Distributed)
Logical Layers and Physical Layers are the ones that confuse people. Firstly, a logical layer means that layers are separate in terms of assembly or sets of classes, but are still hosted on the same server. Physical layer means that those assemblies or sets of classes are hosted on different servers with some additional code to handle the communication between the layers. E.g. remoting and web services.

Deciding to separate the layers physically or not is very important. It really depends on the load your application expects to get. I think it's worth mentioning some of the facts that might affect your decision.

Please DO note that separating the layers physically WILL slow your application down due to the delay in communicating between the servers throughout the network, so if you are using the physical layer approach, make sure the performance gain is worth the performance loss from this.

Hopefully you would have designed your application using the n-Tier approach. If this is the case, then note that you can separate the layers in the future.

Cost for deploying and maintaining physically separated applications is much greater. First of all, you will need more servers. You also need network hardware connecting them. At this point, deploying the application becomes more complex too! So decide if these things will be worth it or not.

Another fact that might affect your decision is how each of the tiers in the application are going to be used. You will probably want to host a tier on a separate server if more than 1 service is dependent on it, e.g. You might want to host business logic somewhere else if you have multiple presentation layers for different clients. You might also want a separate SQL server if you have other applications using the same data.


#####################################################################################


3-Tier Architecture

As the 3-Tier Architecture is the most commonly used architecture in the world, I will start my blogging on this topic.

I have noticed in the past 6 years of writing software that many developers ignore this software engineering paradigm for many reasons. Some include ...

*
Return on Investment
*
Software Lifecycle Turnaround time
*
Knowledgeable Resources
*
and the list goes on

I will discuss in more details of these reasons in another blog entry so back to the topic of 3-Tier architecture.

A 3-Tier architecture uses the Divide and Conquer strategy and is broken down into 3 logical layers.

*
Presentation Layer (PL)
*
Business Logic Layer (BLL)
*
Data Access Layer (DAL)

Ideally, each layer specializes in one or a handful of functionalities that service the upper layer. Each of the three layers should be designed so that the layer above it does not need to understand nor know the implementation details of any of the layers below it. This is accomplished by providing well defined interfaces that the above layers use. The advantage of "Programming to the Interface" is that, you can change the implementation details and still have the application work as defined. One caveat is that, if the interfaces change, then it will take more effort and time to update the layer above it. Therefore, when designing an application, its important to define the interfaces properly.

Here is an example:

public interface IDatasource
{
Customer GetCustomer(int id)
}

public TextDataSource : IDataSource
{
public Customer GetCustomer(int id)
{
// reads data from a text file
}
}

public SQLDataSource : IDataSource
{
public Customer GetCustomer(int id)
{
// uses ADO.NET to read data from a SQL Server database
}
}

public class MyProgram
{
public static void Main(string[] args)
{
// the DataSourceFactory will create a data source depending on some settings
// and return the appropriate implementation of the data source
IDataSource ds = DataSourceFactory.GetInstance().GetDataSource();
Console.WriteLine(ds.GetCustomer(15).FirstName)
}
}

As you can see from the example, MyProgram does not need to know which datasource it is querying. All it needs to know is the interface it must use to retrieve a customer record. If we have numerous implementations then by changing only the configurations which are declarative and available outside of the compiled code, we can change the datasource the application should use to retrieve data without changing the application logic itself.

Now lets see how we can use the "Programming to the Interface" paradigm to create a 3-Tier architecture.

The Presentation Layer is responsible for rendering the data retrieved by the BLL (with the help of the DAL). The only logic that is necessary in this layer is how to manipulate the data and display it to the user in an easy to consume manner. Along with rendering the content, it should be responsible for rudimentary data validation such as missing fields, regular expression matching for emails and other content, numeric validation, range validations, etc.

In .NET, there are a slew of UI specific controls that one may use to render the data. Some controls include the DataList, DataGrid, Label, TextBox and of course custom controls for the advanced developers. There are also pre-built validation controls that are bundled with the .NET framework. I'll post some links later with examples of how to use these controls soon.

Depending on the application you are building, the presentation layer may be one or more of the following types of applications: web, windows, windows service, smart client or console. By properly defining the responsibilities of each layer, the only logic that is necessary for developers to write is the presentation layer. Since retrieving a customer record is the same throughout the application (through the BLL) you can abstract out all the details hence simplifying your software.

On the same note, your application may also expose Web services and Remoting services so it is essential to centralize the code. Otherwise the logic for retrieving a customer (which may include security authorization and authentication, data validation, pre-processing and post-processing) will need to be duplicated in many places. Code duplication may seem like a viable solution at the early stages of the software lifecycle, but it is extremely hard to maintain such pieces of software.

The Business Logic Layer is like your kernel for your application. It should be the component that performs all the business logic for your application. This ranges from validations, running business logic, running application processes such as sending emails and retrieving and persisting data using the Data Access Layer.

Although, validations were performed on the presentation layer, it is imperative that you revalidate the data because browsers could have been spoofed or older browsers might have completely ignored some of the validations or the developers working on the presentation layer did not validate the data properly.

Depending on the complexity of your application, businesses logic code may not reside on the same server or in a centralized location so there are advanced means of executing such logic remotely. With .NET this process has been extremely simplified and available to you within a few clicks of your mouse. One of which is .NET Remoting which is an advanced topic that I'll opt out for now. And the other is the buzz word that many have heard; Web Services.

Both writing and using a Web Service is once again simplified by Microsoft. Visual Studio 2003 and 2005 will be able to download the WSDL and generate the proxies for you so you can invoke the functions as you may within business object in your application. If you don't have Visual Studio, then you may use the "wsdl.exe" utility that is bundled with .NET Framework on the command prompt.

If you have business logic on legacy systems that were built with Microsoft Technologies such as COM+ that can not be rewritten for what ever reason, not to worry. You can use COM+ wrappers provided by the .NET Framework to communicate with the legacy systems.

The Data Access Layer is responsible for accessing and manipulating data from data sources such as SQL Server, Microsoft Access, Oracle, MySQL, etc. Many applications on the Internet today rely heavily on data found in many databases and it is important to centralize the access to this data. Some reasons are ...

*
Security
*
Code Maintenance and Resue
*
Scalability

Databases contain confidential information about people and it is not necessary for everyone in your organizational hierarchy to have access to such data. For example, credit card information stored on Amazon.com shouldn't be available for an entry level employee working in a warehouse. By centralizing the access the database, we are able to authenticate and authorize the users requesting data and manipulating the data.

Since our economy is constantly in a flux, it is never safe to assume that once you have created your data model, it will not change for a decade. In fact, that data model may change tomorrow, a week from now or in an year, but it will change and as software architects, it is our responsibility to foresee such events and design systems that will be able to change with time. If the code isn't centralized, a database change as simple as adding a new column may result in days of changes to many systems, regression testing and deployment of many applications. Is this really necessary?

By creating simple reusable components, developers are able to abstract out all of the details of creating connections, handling errors, invoking appropriate stored procedures or executing Transact-SQL or SQL/PL code, retrieving the data, closing the connection away from the Business Logic Layer.

Typical code (using ADO.NET) to retrieve a customer record may look as the following:

SqlConnection connection = null;

try
{
connection = new SqlConnection(mySqlConnection);
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM Customers WHERE CustomerID = " + cid
return CustomerFactory.GetInstance().GetCustomer(cmd.ExecuteReader());
}
catch (Exception e)
{
Console.WriteLine("Exception :: " + e.Message);
}
finally
{
if (connection != null && connection.State != ConnectionState.Closed)
connection.Close();
}

So what's the big deal about writing a few lines of code? Well, imagine repeating these lines in 5 different places and 2 weeks later, making a change and remembering all the pieces of code to change. Compared to this solution, I suggest the following:

Customer customer = CustomerDAO.GetInstance().GetCustomer(customerID);

Where the ADO.NET code is abstracted away by the GetCustomer(int) function and now making a change to the function will take minutes and the change will affect all pieces of code that depends on retrieving customer records. The above examples use Design Patterns, more specifically the Factory Pattern and the Singleton Pattern and you may further read about them at your leisure.

Scalability is huge to enterprise level applications that require time crucial data. It’s beyond the scope of this article so I will leave it out for the time being.


##################################################################################