.NET tutorials for beginners
What Is .NET ?
.NET is a major technology change for Microsoft and the software world. Just like the computer world moved from DOS to Windows, now they are moving to .NET. But don't be surprised if you find anyone saying that "I do not like .NET and I would stick with the good old COM and C++". There are still lot of people who like to use the bullock-cart instead of the latest Honda car.
What is Visual Studio.NET ?
Many people always get confused with Visual Studio .NET (VS.NET) and
.NET technology. VS.NET is just an editor, provided by Microsoft to help
developers write .NET programs easily . VS.NET editor
automatically generates lot of code, allows developers to drag and drop
controls to a form, provide short cuts to compile and build the
application etc.Understand Visual Studio .NET
VisualStudio
is a very user friendly tool. But there are enough stuff to confuse any
one new to Visual Studio family. The purpose of this chapter is to make
you familiar with different options in Visual Studio.NET (VS.NET) We
will not cover the entire visual studio guide. We are just explaining
the most commonly used features of VS.NET.
When you work on any project,
VS.NET has several child windows to assist you in the application
development. These windows are attached on the left, bottom and right
sides of the main window. You can click on these small windows to expand
it and see the content of them. Some of the most commonly used child
windows are explained below. Most of these windows will be enabled only
when you have created a project and working on a WebForm/WinForm.
| Toolbox Toolbox provides all the drag and drop controls for your application. Depending on the kind of application you are working on, the toolbox will show appropriate controls and you can drag and drop them to your form. If you are developing a web application, toolbox will show ASP.NET controls and if you are developing a Windows application, it will show Windows controls (like Radio button, text box, buttons etc). You can simply drag and drop any controls from the toolbox to your form. After you drag and drop any control, double click on the control to go the default event associated with the control. The Toolbox will be enabled only when you have a WebForm or WinForm opened in Design mode and is usually located on TOP LEFT corner of the VS.NET. By default, all windows including Toolbox will be displayed as Minimized (Marked as A in picture). You will see only the small icon and the text 'Toolbox' written vertically on the left bar of VS.NET. You can click on this minimized window to expand it (Expanded window is marked as C.). When you move the mouse away from the window, it will again automatically minimize. You can keep the toolbox always expanded by pressing the pushpin (Marked with B.) The above behaviour is common for all the windows explained below. They will be minimized by default and you can point the mouse over it to expand it. Use the pushbutton to keep it expanded. |
| Design mode & HTML mode If you are developing a web application, you can switch between design mode and HTML mode for any web form. When you are in HTML mode, it will show you the HTML tags and ASP.NET code and you can manually edit it. YOu can switch to the Design mode by clicking the Design button on BOTTOM LEFT corner of VS.NET. In design mode, you can see how your ASP.NET page is going to look like when some one view your web page. Also, you can drag and drop controls from the toolbox, which will automatically generate the HTML for it. Typically, developers switch between these two modes very frequently. You can go to design mode to drag/drop controls, right click on the controls to set correct properties etc. Then, click on the HTML mode to view the generated HTML. You can manually cmake changes to the automatically generated HTML. If you change any properties in HTML mode, the changes will be reflected when you switch to Design Mode |
| Solution Explorer Solution Explorer, located on TOP RIGHT corner of VS.NET, displays your solution, all projects included in each solution and the list of files in each project. They are listed in the form of a tree control. Typically, for a single application, you will have 1 solution and one or more projects. When you create a new application, you are have to create single Visual Studio project. In more complex applications, there may be more than one projects. All these projects are grouped into a single solution. Even if you do not create a solution separately, a solution will be automatically created for you. To add a new file to your project, you can right click on the project name (JustTestis the project name in the picture) and choose the menu option Add. It will give you the option to choose a file type. You can choose an appropriate type. For WinForms and WebForms, you can see the file in design mode and the code associated with it. Double click on any form and it will be opened in design mode. Right click on any form and select the menu option 'View Code' to view the code associate with the form. |
| Output Output window, located on BOTTOM LEFT corner of VS.NET, displays the result of your project compilation. When you compile your project, all errors, warnings and compilation results will be displayed in this window. In addition to the Output window, they are few other windows located in the BOTTOM LEFT corner of VS.NET. Task List - shows individual tasks. Typically, when you compile your project, all errors and warnings will be added to your task list. You can double click on any item in the task list to go directly to the code associated with the task .Command Window - you can execute code statements here. When you are debugging, you can evaluate the value of any variables by typing ? followed by the variable name. Find Results - when you search for any text in file(s) using VS.NET, the results will be displayed in this window. |
VS.NET allows you to create several types of projects. Most of the time you will be using one of two categories:
Building a project To try this, create a new Windows Project as explained above. It will create a sample form. Go to the main menu and select the menu item Build > Build Solution. This process will compile all the files included in your project and show you the result in the Output window. If the result shows '0 failed', your build is success and your application is ready to deliver!! To Run the application you just Built, go to the main menu and select Debug > Start Without Debugging. This will launch the application you just developed. You can drag and drop several controls to the form and try running it. When you compile (build) the code, if there is any errors or warnings, the details will be shown in the 'Task List' window. You can click on the specific item in this window to go directly to the line of code associated with the error. |
What is XML?
First what you are thinking is it a programming language like our c,c++ or it’s presentation language like HTML .YES it’s a presentation language not a programming language . Before going into deep about XML we should remember one think ie it’s a case sensitive language where as HTML is not a case sensitive .As i said before that it’s mainly used for structured documents.You don'y have any pre defined tags here .
Download VS.NET
Unfortunately, VS.NET is not a free download !
If you want to
have Visual Studio 2002 or Visual Studio 2003, you need to purchase it.
It is going to cost you around US$ 750 or more...
However, here
is a good news. You can download trial versions of Visual Studio 2005
from Microsoft. Note that, this free download is a limited version. You
have to download separate versiosn of C#, VB.NET etc.
"Hello World" Application
Here we will guide you through step by step process to create your first
sample .NET application. All our sample code will be using C# syntax.
Readers are suggested to stick to this new elegant language, than going
back to your favorite VB style.
Hello World Application using C#
Let
us get started the traditional way, with a 'Hello World' application.
We hope you all have Visual Studio.NET installed on your computer. If
you have VS.NET, goto the menu option File > New > Project. Select
'Visual C# projects' and choose the project template 'Console
Application'. This will create a default
A simple C# program would look like the following.
using System; public class Hello { public static void Main (string[] args) { Console.WriteLine("Hello C# World"); } }
When you create a new Console Application, it will create a default class and you can just insert one line of code into it:
Console.WriteLine("Hello C# World");
Now compile and run your first program by pressing Ctrl + F5. You will see the following result :
> Hello C# World
You are done! You got your first C# program successfully running.
If you do not have VS.NET, you may use any editor (including notepad) to create your first C# program. Create a new file with the name sample.cs and type the C# code shown. Now go to the command prompt and navigate to the folder where you have the .NET framework installed. Compile your csharp file by using the command 'csc': csc c:\samples\sample.cs csc is the C# compiler. The above command will produce the output file sample.exe. You can run the sample.exe and you will see the output from the program. |
Analyzing your first program
See the first line of code :
using System;
"System" is a namespace and the "using" directive says that all classes in the "System" namespace can beused in this class without using the fully qualified name. In our class, "Console" is a class in the namespace "System". To use this class you have to actually write :System.Console.WriteLine ("...");
But the using System; directive on top of the classallows us to use the class without including the namespace. So, you can now simply write :
Console.WriteLine("...");
If you are familiar with Object Oriented Programming, you might not need more explanation for the next line - declaring a class.
public static void Main (string[] args) - is the Main method, which is thestarting point of the application.
string[] args is the list of arguments that are passed to this application. (In our case, we are not passing any command line parameters).
Console.WriteLine("...") is another line of important code. Console is a class, part of .NET class library included in System namespace. WriteLine is a method part if this class and used to printoutput to the default Console.
C# Language Syntax
Declaring Variables
The following sample shows different ways you can declare a variable: int a;
int salary, incomeTax, sum;
int count = 10;
string name;
string fullName= "Little John";
Loop Statements
while
int i = 0;
while ( i < 5 )
{
Console.WriteLine ( i );
++i;
}
The above loop repeates 5 times and prints the value of i.
The output of above code would be like this :
0
1
2
3
4
for
for ( int i = 0; i < 5; i++ )
{
Console.WriteLine ( i );
}
The above loop repeates 5 times just like the while loop and prints the value of i.
The output of above code would be like this :
0
1
2
3
4
do ... while
int i = 0;
do
{
Console.WriteLine ( i );
i++;
}
while ( i < 5 );
The above loop is pretty much same as the while loop. The only difference is, the condition is checked only after executing the code inside the loop.
foreach
string [] names = new string[]{ "Little John", "Pete", "Jim", "Bill" };
foreach ( string name in names )
{
Console.WriteLine ( name );
}
foreach loop can be used to iterate through a collection like array, ArrayList etc.
The above code displays the following output:
Little john
Pete
Jim
Bill
Conditional Operators
if ... else
This is the conditional operator, used to selectively execute portions of code, based on some conditions.
string name = "Little John";
if ( name == "Jim" )
{
Console.WriteLine( "you are in 'if' block" );
}
else
{
Console.WriteLine( "you are in 'else' block" );
}
in the above case, it prints :
you are in 'else' block
Flow Control Statements
break
'break' statement is used to break out of loops ('while', 'for', switch' etc).
string [] names = new string[] { "Little John", "Pete", "Jim", "Bill" };
foreach ( string name in names )
{
Console.WriteLine ( name );
if ( name == "Pete" )
break;
}
In
the above sample, it iterates through the array of 4 items, but when it
encounters the name "Pete", it exits the loop and will not continue in
the loop anymore.
The output of above sample would be :
Little John
Pete
continue
'continue'
statement is also used to in the loops ('while', 'for' etc). When
executed, 'continue' statement will move the exection to the next
iteration in the loop, without continuing the lines of code after the
'continue' inside the loop.
string [] names = new string[]{ "Little John", "Pete", "Jim", "Bill" };
foreach ( string name in names )
{
if ( name == "Pete" )
continue;
Console.WriteLine ( name );
}
In
the above sample, when the value of name is "Pete", it executes the
'continue' which will change the execution to the next iteration,
without executing the lines below it. So, it will not print the name, if
the name is "Pete".
The output of above sample would be :
Little John
Jim
Bill
switch
if
you have to writeseveral if...else conditions in your code, switch
statement is a better way of doing it. The following sample is self
explanatory:
int i = 3;
switch ( i )
{
case 5:
Console.WriteLine( "Value of i is : " + 5 );
break;
case 6:
Console.WriteLine( "Value of i is : " + 6 );
break;
case 3:
Console.WriteLine( "Value of i is : " + 3 );
break;
case 4:
Console.WriteLine( "Value of i is : " + 4 );
break;
default:
Console.WriteLine( "Value of i is : " + i );
break;
}
In the above sample, depending on the value of the conditional item, it executes appripriate case. In our code, since the value of i is 3, it executes the third case. The output will be as shown below:
Value of i is : 3
DataTypes in C#
DataTypes are the basic building block of any
language. Microsoft has tried to standardise the datatypes in .NET
framework by introducing a limited, fixed set of types that can be used
to represent almost anything in programming world.
C++ was very
rich in datatypes, but that leads to confusion too. Especially, when you
write components that may be consumed by applications written in other
platforms, you have to make sure the types used are compatible with
other platforms too!
.NET types start from a clean slate. All
.NET languages share the same types. So, they are all compatible and no
worries.This means, you can call C# code from VB.NET and vice versa,
without worrying about type conversions.
.NET data types are either structures or classes, part of the System namespace. For example, the following data types are implemented as struct in .NET:
Int16
Int32
Double
(String is implemented as a class in .NET, for various reasons.)
If you are not very familiar with struct and class, don't worry about it. You can just use them as if they are simple data types.
Here is how you can declare variables of type Int, Double and String:
Int16 age, employeeNumber;
Double salary;
String name, address;
You
can use any of the .NET data types directly in any .NET language - in
C#, VB.NET or xyz.NET.But in addition to the .NET types, each language
provides a set of primitive types, which map to the corresponding types
in .NET class library. This is why you may see some people use string and some others use String. There is no big difference. string is a primitive data type in C# and String is the corresponding class in .NET class library. The string in C# is mapped to the class in .NET class library. So, whether you use string or String,there is no real difference.
DataTypes in C# and the corresponding class/struct in .NET class library
The following list shows the list of data types available in C# and their corresponding class/struct in .NET class library.
C# Data type Mapped to .NET class/struct
sbyte System.SByte
byte System.Byte
char System.Char
float System.Single
decimal System.Decimal
double System.Double
ushort System.UInt16
short System.Int16
uint System.UInt32
int System.Int32
ulong System.UInt64
long System.Int64
bool System.Boolean
string System.String
object System.Object
Value Types & Reference Types
In C# data types are classified into two :
value types
reference types
The following tables shows some of the differences between values types and reference types.
value types reference types
allocated on stack allocated on heap
a value type variable contains the data itself reference type variable contains the address of memory location where data is actually stored.
when
you copy a value type variable to another one, the actual data is
copied and each variable can be independently manipulated. when
copying a reference type variable to another variable, only the memory
address is copied. Both variables will still point to thesame memory
location, which means, if you change one variable, the value will be
changed for the other variable too.
integer, float, boolean, double etc are value types. string and object are reference types.
struct is value type. classes and interfaces are reference types.
(String is implemented as a class in .NET, for various reasons.)
If you are not very familiar with struct and class, don't worry about it. You can just use them as if they are simple data types.
Here is how you can declare variables of type Int, Double and String:
You can use any of the .NET data types directly in any .NET language - in C#, VB.NET or xyz.NET.But in addition to the .NET types, each language provides a set of primitive types, which map to the corresponding types in .NET class library. This is why you may see some people use string and some others use String. There is no big difference. string is a primitive data type in C# and String is the corresponding class in .NET class library. The string in C# is mapped to the class in .NET class library. So, whether you use string or String,there is no real difference.
DataTypes in C# and the corresponding class/struct in .NET class library
The following list shows the list of data types available in C# and their corresponding class/struct in .NET class library.
| C# Data type | Mapped to .NET class/struct |
| sbyte | System.SByte |
| byte | System.Byte |
| char | System.Char |
| float | System.Single |
| decimal | System.Decimal |
| double | System.Double |
| ushort | System.UInt16 |
| short | System.Int16 |
| uint | System.UInt32 |
| int | System.Int32 |
| ulong | System.UInt64 |
| long | System.Int64 |
| bool | System.Boolean |
| string | System.String |
| object | System.Object |
Value Types & Reference Types
In C# data types are classified into two :
The following tables shows some of the differences between values types and reference types.
| value types | reference types |
| allocated on stack | allocated on heap |
| a value type variable contains the data itself | reference type variable contains the address of memory location where data is actually stored. |
| when you copy a value type variable to another one, the actual data is copied and each variable can be independently manipulated. | when copying a reference type variable to another variable, only the memory address is copied. Both variables will still point to thesame memory location, which means, if you change one variable, the value will be changed for the other variable too. |
| integer, float, boolean, double etc are value types. | string and object are reference types. |
| struct is value type. | classes and interfaces are reference types. |
Classes and Object model in .NET
What is a 'class' ?
In
modern object oriented programming, large computer programs are divided
into several 'classes'. Typically, a large project will have several
hundred classes. A class represents an entity in a program. For example,
if you are doing a small program called calculator, you will typically
have a single (or more) class called 'Calculator' (you can give any name
for your class). The class will have several 'methods', that will do
the functionality of the class.
So, your calculator may have methods like the following:
Add()
Subtract()
Multiply()
Divide()
Here is a sample calculator class, written in C# :
using System;
public class Calculator
{
public int Add(int value1, int value2)
{
return value1 + value2;
}
public int Subtract(int value1, int value2)
{
return value1 - value2;
}
public int Multiply(int value1, int value2)
{
return value1 * value2;
}
public int Divide(int value1, int value2)
{
return value1 / value2;
}
}
Property in C# class
How do you access member variables of any class
from outside the class ? In most of the languages including C++ , you
will make the member variables public so that you can create an instance of the class and directly access the public fields, as shown below:
public class Car
{
// private fields.
public string color;
// constructor
public Car()
{
}
}
The above class has one public field : color. You may access this field from outside the class as shown below:
Car car = new Car();
car.color = "red";
string color = car.color;
But
this is the old way ! This would still work with C#, but the suggested
approach is to use "Property" instead of directly accessing member
variables.
The following code snippet shows how to create "Property" in a class.
public class Car
{
// private fields.
private string color;
// constructor
public Car()
{
}
public string Color
{
get
{
return color; // return the value from privte field.
}
set
{
color = value; // save value into private field.
}
}
}
The
above class has one private field - color. Then we have one "Property"
called 'Color', which is used to represent the private field. Note that
the field is private and the Property is public. (We have used the same
name with upper/lower case to represent the 'Property' and 'field', but
you may give any name you want.)
Each property has two parts :
get
set
The get part is executed when you access the value of the Property as shown below:
Car car = new Car();
string color = car.Color;
When executed, the above get accessor will return the value stored in the field 'color'.
The set part is executed when you assign a value to the Property as shown below:
Car car = new Car();
car.Color = "RED";
When executed, the above set accessor will assign the value "RED" to the private field 'color'. (Note that'value' is a keyword, which will have the value assigned to it.)
So, what is the difference ?
On
the first look, there is no difference! You can achieve the same
behaviour by writing 2 different methods ( like SetColor(...),
GetColor() ).
First advantage of using property is, code looks
cleaner than having 2 separate methods. You can simply call a property
as if it was a field in the class Well, then you may ask why make it 2
methods, we can make it a public field, so that we can access it by
creating an instance of the class.
The main advantage over using a
Property instead of a public field is, with the property, you will get a
chance to write few lines of code (if you want) in the get and set
accessors. So, you can perform some validation or any other logic before
returning any values or assigning to the private field.
See the modifed class below:
public class Car
{
// private fields.
private string color;
// constructor
public Car()
{
}
public string Color
{
get
{
if ( color == "" )
return "GREEN";
else
return color;
}
set
{
if ( value == "" )
thrown new Exception ("Wrong value.");
else
color = value;
}
}
}
Let us analyze the get
part first. Here we are checking whether there is a valid value in the
field 'color' before we return the value. If it is empty, we are getting
a chance to return a default value 'Green'. This way, we can make sure
that whoever calls the property 'Color' will always get a valid color,
never an empty string.
In the set part, we are doing a
validation to make sure we always assign a a valid value to our field.
If someone assign an empty string to the 'Color' property, he will get
an exception (error).
Car car = new Car();
car.Color = "";
The above code will throw an error because we are trying to assign an empty string and the set accessor will throw an error if it an empty string. This way, we can make sure that we allow only valid values to be assigned.
So,
i guess now you would appreciate the purpose of "Property". So, no more
public fields! Always have private fields and write public properties
as wrapper for them if required to expose them to outside the class.
Namespaces
A Namespace is a group of related classes. It is a good practice to group related classes into a namespace when you create a class library.
The
main advantage of using namespaces is, to avoid conflicts when you have
multiple classes with the same name. For example, .NET comes with a
class called 'Form'. Suppose you also write another class called 'Form'
in your application and if you refer to the class 'Form', how does the
compiler know which Form you are refering to ?
Here is the
importance of 'namespace'. You can refer to the .NET Form using the
fully qualified name, including the namespace like this :
System.Windows.Forms.Form
And you can refer to your own Form like this :
MyApplication.Form, where MyApplication is your namespace.
So, namespaces allow you to avoid name conflicts!
All
classes in .NET class library are grouped into namespaces. You can use
all the classes using the fully qualified name, including the namespace
also along with the class name.
System.Windows.Forms.Form
System.String
System.Double
If you want to declare a Button object, you must do the following :
System.Windows.Forms.Button myButton;
It is not mandatory to use the namespace also along with the name. You may use the using directive on top of the class and safely avoid the need to write the fully qualified name everytime when you refer to a class.
using System.Windows.Forms.Button;
If you have the above line of code on top of the class file, you don't need to type the namespace name System.Windows.Forms with all the classes in this namespace. You can simply use class name directly as shown below:
Button myButton;
.NET Namespaces
Here is a list of some of the namespaces in .NET class library.
System
System.Xml
System.Data
System.Data.OleDb
If you want to declare a Button object, you must do the following :
System.Windows.Forms.Button myButton;
It is not mandatory to use the namespace also along with the name. You may use the using directive on top of the class and safely avoid the need to write the fully qualified name everytime when you refer to a class.
using System.Windows.Forms.Button;
If you have the above line of code on top of the class file, you don't need to type the namespace name System.Windows.Forms with all the classes in this namespace. You can simply use class name directly as shown below:
Button myButton;
.NET Namespaces
Here is a list of some of the namespaces in .NET class library.
|
|
WinForms
WinForms is the most commonly used feature of .NET.
'Windows'
based applications in .NET is called 'WinForms'. The .NET framework
comes with a good number of classes to support 'Form' based application
development.
A WinForm application will have atleast one 'Form'
(window), which would be used for the interaction between the
application and user. A Form can contain other controls like TextBox,
Label, Button etc. Large WinForms applications will have several
'Forms', some of them used to capture data from user and some of them
used to display data to user. By performing certain actions in each
form, user can navigate to other 'Forms' in the application.
Event driven programming
Event
Driven programming model is the most commonly used feature in modern
programming. In this model, you will write appropriate code for each
event. Examples for events are
Button Click
Mouse Move
Mouse Click
Key Press
In Winforms application, users interact with the application using various actionsin
the window (like clicking a button, moving mouse, pressing keys in
keyboard etc). These actions will generate various events. When an event
is generated, the code written for that event will be executed.
For
example, in a user registration screen, you may have several controls
like text boxes where user can enter their name, address, age etc. Once
user enter all the information, he may press the 'Submit' button. As a
developer, you would have written code in the button click event, to
save this user entered data into a database. This is how typically a
WinForms based application works in an event driven programming model.
To create WinForms applications:
Open Visual Studio .NET
Select the menu : File > New > Project
Choose from the project types : Visual C# Projects
From the Templates, choose the application type 'Windows Application'
Enter the project name in the space for 'Name'.
Make
sure the 'Location' is pointing to your folder. You may press the
Browse button to select your personal folder, so that all your projects
will be saved in your folder.
In Winforms application, users interact with the application using various actionsin the window (like clicking a button, moving mouse, pressing keys in keyboard etc). These actions will generate various events. When an event is generated, the code written for that event will be executed.
For example, in a user registration screen, you may have several controls like text boxes where user can enter their name, address, age etc. Once user enter all the information, he may press the 'Submit' button. As a developer, you would have written code in the button click event, to save this user entered data into a database. This is how typically a WinForms based application works in an event driven programming model.
To create WinForms applications:
|
|
Displaying Simple MessageBox
Reading the text value from a textbox
Displaying a message box
About the sample application
This application has 1 textbox and a button. If you type anything in
the textbox and press the button, it will display the same text you
typed in a MessageBox.
Download and unzip the sample application
from this page. After you unzip, you will get several files. Some of the
important files are :
1. Chapter1.csproj - This is the C# project file. Double click this file to
open the project.
2. Form1.cs - This is the file for the Form1 in teh sample application.
After
you open the project, see the 'Solution Explorer' bar on the right side
of the Visual Studio. You can click on that to expand it, which will
display the list of all files in the project. (Or, you can go to the
menu 'View > Solution Explorer' to open the solution explorer.
Click
on 'Form1.cs' in the solution explorer to open the Form. Now you can
see the Form in 'design mode'. Right click on the 'Form1.cs' in the
solution explorer and choose 'View Code' to see the source code behind
this Form (Or, press F7 from the Form to see the code).
Let us analyze the code:
The
code has lot of Visual Studio generated code. For timebeing ignore all
those code and scroll down to the event handler code in the bottom of
the file.
System.Windows.Forms.MessageBox.Show( "You typed : " + txtMessage.Text );
DialogResult result = MessageBox.Show( "Did you like this application ?",
"Caption", MessageBoxButtons.YesNo, MessageBoxIcon.Question );
if ( result == DialogResult.Yes )
MessageBox.Show("You selected YES");
else
MessageBox.Show("You selected NO");
The first line will simply display a messagebox and show the text typed by the user. 'MessageBox' is a class inside the namespace
'System.Windows.Forms'. We have a statement 'using
System.Windows.Forms' on top of the source code. This is like a source
code. This will help us avoid typing 'System.Windows.Forms.' everytime
when we want to use a class inside this namespace.
The next few lines of code do a bit more. Here we are displaying a message box, with some additional attributes.
The second optional parameter of the 'Show' method is the 'caption' for the messagebox.
The
third parameter tells that the messagebox will have two buttons - YES
and NO. You have several other options like MessageBoxButtons.OK,
MessageBoxButtons.OKCancel etc.
And, the last parameter says 'display a question Icon in the messagebox'. There are many other types of icons you can display.
And
another important part is, the MessageBox returns a value when the user
press a button to close the messagebox. Our MessageBox asks a question
'Did you like this application ?" and gives two options to the user -
YES or NO.
The return value is of type 'DialogResult' and is
assigned to the variable 'result'. We are checking the value of the
result and depending on whether user pressed the YES button or NO
button, appropriate message will be displayed.
About the sample application This application has 1 textbox and a button. If you type anything in the textbox and press the button, it will display the same text you typed in a MessageBox.
Download and unzip the sample application from this page. After you unzip, you will get several files. Some of the important files are :
1. Chapter1.csproj - This is the C# project file. Double click this file to
open the project.
2. Form1.cs - This is the file for the Form1 in teh sample application.
After you open the project, see the 'Solution Explorer' bar on the right side of the Visual Studio. You can click on that to expand it, which will display the list of all files in the project. (Or, you can go to the menu 'View > Solution Explorer' to open the solution explorer.
Click on 'Form1.cs' in the solution explorer to open the Form. Now you can see the Form in 'design mode'. Right click on the 'Form1.cs' in the solution explorer and choose 'View Code' to see the source code behind this Form (Or, press F7 from the Form to see the code).
Let us analyze the code:
The code has lot of Visual Studio generated code. For timebeing ignore all those code and scroll down to the event handler code in the bottom of the file.
System.Windows.Forms.MessageBox.Show( "You typed : " + txtMessage.Text );
DialogResult result = MessageBox.Show( "Did you like this application ?",
"Caption", MessageBoxButtons.YesNo, MessageBoxIcon.Question );
if ( result == DialogResult.Yes )
MessageBox.Show("You selected YES");
else
MessageBox.Show("You selected NO");
The first line will simply display a messagebox and show the text typed by the user. 'MessageBox' is a class inside the namespace 'System.Windows.Forms'. We have a statement 'using System.Windows.Forms' on top of the source code. This is like a source code. This will help us avoid typing 'System.Windows.Forms.' everytime when we want to use a class inside this namespace.
The next few lines of code do a bit more. Here we are displaying a message box, with some additional attributes.
The second optional parameter of the 'Show' method is the 'caption' for the messagebox.
The third parameter tells that the messagebox will have two buttons - YES and NO. You have several other options like MessageBoxButtons.OK, MessageBoxButtons.OKCancel etc.
And, the last parameter says 'display a question Icon in the messagebox'. There are many other types of icons you can display.
And another important part is, the MessageBox returns a value when the user press a button to close the messagebox. Our MessageBox asks a question 'Did you like this application ?" and gives two options to the user - YES or NO.
The return value is of type 'DialogResult' and is assigned to the variable 'result'. We are checking the value of the result and depending on whether user pressed the YES button or NO button, appropriate message will be displayed.
C# sample for basic file operations
In the attached sample application, you can type some
text and save into a text file. Also, you can select a text file and
display the content in a textbox.
In addition to the basic file
operations, you can learn some good programming practices and error
handling/validation techniques.
This chapter and the attached sample application demonstrates the usage of following .NET classes and methods:
System.IO.Path.GetExtension() - Method to check the extension of a file.
System.IO.File.Exists() - Check if a file alread exists.
System.Windows.Forms.OpenFileDialog - "File Open Dialog" to choose a file from the disk.
DialogResult.OK - Result from a File Open Dialog.
MessageBox.Show() - Displaying a message to the user.
string.Trim() - Remove white space characters from beginning and end of string.
throw new Exception() - Create and throw a new exception.
System.IO.StreamWriter - Stream writer to write into files.
System.IO.StreamReader - Read from file.
Application.Exit() - Closing an application.
C# sample for retrieving html content from any websites
This chapter will teach you how to retrieve content of any website using .NET classes.
This chapter and the attached sample application demonstrates the usage of following .NET classes and methods:
System.Net.WebRequest() - Class to perform the web related operations.
System.Net.WebRequest.Create(url) - Create a web request.
System.Net.WebRequest.GetResponse() - Get the html content of the URL.
System.IO.StreamReader - Read from file.
Application Configuration Files
.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\data\spider.mdb" />
<add key="SupportEmail" value="webmaster-6@dotnetspider.com" />
</appSettings>
</configuration>
And to read from this config file, just use the following code in your application:
string dbPath = System.Configuration.ConfigurationSettings.AppSettings["DatabasePath"];
string email = System.Configuration.ConfigurationSettings.AppSettings["SupportEmail"];
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"]; string email = ConfigurationSettings.AppSettings["SupportEmail"];
Note:
When you compile your application, VS.NET will automatically create a file called <your application name>.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 <your application name>.exe.config and NOT the app.config. Users can modify the data in <your application name>.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.
|
Debugging in VS.NET
Debugging in VS.NET
|
|
|
If you make a syntax error, then the compiler will tell you and you can easily solve the issue. But what if there is a logical error? You may never know what went wrong, just by looking into the code. During runtime, the application may give wrong results, which may not be noticed immediately by anyone. When someone report that your "calculator program" gives the result 10 when adding 5 and 4, what will you do? A logical error in a small calculator program may be an easy to fix issue, but what if it is a very complex accounting software?
The Debugger becomes a very handy tool in such situations. A Debugger is a software process that help you monitor the execution of your code. Microsoft gives us a very powerful debugger, integrated with the VS.NET. When you execute your code in debug mode, you can watch how it executes each line of code. You can run (debug) the application step by step, line by line and see the value of each variable at any point of time. You can visually count how many times a whileloop executes and see whether it executes the ifblock or else block.
So, in short, debugger help you watch how your code is executed. You can see how your calculator program calculates 5 + 4 = 10 and easily figure out the logical error.
Debugging your project
Running your project in Debug mode doesn't need lot of work. Just choose the menu : Debug > Start or press F5. Now your application will run in debug mode. To run your application in non-debug mode, choose the menu : Debug > Start without Debugging or press Ctrl F5.
You may not feel any difference whether you run in debug mode or non-debug mode. In both the cases, your application runs as usual! To find the difference, you can use breakpoints
.BreakPoints
BreakPoints are used to stop the execution at certain lines of code in the application and monitor the values of various variables etc at that point of time. To put breakpoints, click on any line of code and press F9or click on the leftbar of any line of code. When a breakpoint is enabled, the line will be highlighted with BROWN color and a BROWN circle will appear on the left bar (See image below). To remove a breakpoint, press F9 again.
Open your project and mark breakpoints in different lines of code. Now start the debugger by pressing F5. Note that every time the execution passes through the lines marked as 'breakpoint', execution stops there. You can press F5 to continue the execution again. Or, press F10 to continue the execution line by line! When the execution stops on a breakpoint, or when you continue execution line by line by pressing F10, you can point your mouse over any variable and it will show you the value of that variable at that point of time. You can see how the values are changed at each line of code and this helps you easily figure out the logical errors. This process is called 'Debugging'. Next time, when you hear someone complaining about his 'debugging nightmares', you know what it is!
Change path of execution
When the execution reaches a breakpoint, you can see a little YELLOW Arrow on the leftbar of the current line of code and the line will be highlighted with YELLOW color (See image below). When you press the F10, the execution will proceed to the next line of code.
You can change this execution path by clicking on the yellow arrow on the leftbar and dragging it into any other line of code. For example, if you are currently inside an if block, you can drag the execution to the else block (or, to some other line of code), thus changing the application behaviour the way you want! Don't you agree that the Debugger is a very powerful tool?
Quick Watch
While debugging, you can view the value of any variable instantly by pointing the mouse over the variable (See image below. You can see a very small light yellow window showing name = "Little John". This is displayed when the mouse is pointed over the variable name). But this will work only for simple types like int, string etc. In case of types like DataTable, DataSet, ArrayList etc, you can right click on the object name and choose Quick Watch. A small window will open and will show you the complete object. You can expand the properties of the object and view the values of each proeprty. In case of a DataSet, you can Quick Watch the dataset and expand each table inside the dataset, each row in each table, each column in each row etc. Thus the Quick Watch will help you view the values of the 'complete object'.
Watch Window
When you debug the application and step through each line, it is not really necessary to point the mouse on each variable to view the value. Just add the variable to the 'Watch Window' and the values are always visible in the little 'Watch Window' in the bottom of your VS.NET (see image below. The variable nameis added to the watch window). To add any variable to Watch Window, righ click on the variable and choose 'Add Watch'. You can choose the same option from the 'Quick Watch' window also.
The 'Watch Window' may be minimized by default. You can point your mouse on the 'Watch' icon in the bottom of the VS.NET to expand this window. Use the 'push button' in the watch window to keep it always expanded.If 'Watch Window' is not visible in the bottom, select the menu option from VS.NET main menu : Debug > Windows > Watch > Watch 1
System.Diagnostics.Debug.WriteLine
You may use System.Diagnostics.Debug.WriteLineto print any values into the output window while debugging.Ex:
System.Diagnostics.Debug.WriteLine( "*** My name is : " + name );System.Diagnostics.Debug.WriteLine( "+++ See the Output window now." );System.Diagnostics.Debug.WriteLine( "=== End." );
See the image below to see how it appears in the output window.
Advanced features
The debugger comes with several other advanced features like conditional breakpoints, CallStack etc. You may find more information from MSDN or other web sites. To keep it simple and helpful for beginners, we have mentioned only the commonly used features of VS.NET debugger.
Accessing Database
Database Concepts
Database is the media to store data. If you have an application that has to store and retrieve data, your application must be using a database.
A File is the simplest form of saving the data in the disk, but is not the most efficient way of managing application data. A database is basically a collection of one or more files, but in a custom format, and data is organized in a specific format such a way that it can be retrieved and stored very efficiently.
Some examples for databases are :
|
MS Access is a very light weight database provided by Microsoft for applications with less number of users and relatively small quantity of data. MS Access saves data into database files with the extension .mdb. Usually, MS Access comes along with MS Office package. If you already have the .mdb database file, you can freely use it with your application and you do not need MS Access software. The MS Access software is required only if you want to directly open the database and manipulate the data or change the database schema. SQL Server (Microsoft product) and Oracle (Oracle Corp.) are more complex, advanced, relational databases and they are much more expensive. It can support large number of users and very high quantity of data. If you are developing a software, which might be accessed simulatenously by 100s of users or if you expect your data may grow 100s of MBs, you might consider one of these. (We are learning Microsoft .NET.. so you might want to consider the SQL Server than Oracle, for which Microsoft provides special data access components!!) In this tutorial, we will be using only MS Access for simplicity. Most of the samples provided in this site uses MS Access database for simplicity and easy download. ADO.NETADO.NET is the data access model that comes with the .NET Framework. ADO.NET provides the classes required to communicate with any database source (including Oracle, Sybase, Microsoft Access, Xml, and even text files). DataAccess Providers in .NETADO.NET comes with few providers, including: There are other providers available, but we are not including them here as this tutorial is meant for beginners! When you want them, search for ADO.NET providers in Google or MSDN Microsoft made the SQL Server. So they gave a separate provider, specifically made for SQL Server. We can use the OleDb provider for all other database sources including MS Access, Oracle, Sybase etc. There is a separate provider available for Oracle. A DATA PROVIDER is a set of classes that can be used to access, retrieve and manipulate data from the databases. Both OleDb and SqlClient has its own set of classes, but they have the same concepts. We would like to classify the classes into two broad categories (this is not a microsoft classification, anyway!) The job of first category of classes is to communicate with database and send or retrieve data from the database. The second category of the classes will be used as a carrier of data. Classes for communicating with databaseThe Connection, Command, DataReader, and DataAdapter objects are the core elements of the ADO.NET provider model.
Each provider may have classes equivalent to above objects. The name of the classes vary slightly to represent the provider type appropriately. Depending on the type of database you work on, you will have to choose either OleDb or SqlClient (or, some other provider) objects. Since all our samples use MS Access database, we will be using OleDb objects in all the samples. If you like to use SqlServer, you just need to replace the OleDb objects with the equivalent SqlClient objects. Classes for holding dataThe following are the main classes used to hold data in Ado.NET: We can use the DataAdapter or DataReader to populate data in DataSet. Once we populate data from database, we can loop through all Tables in the DataSet and through each record in each Table. |
Create, Read, Update, Delete - ADO.NET sample
Here is some sample code to execute a simple query.
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Samples\\Employee.mdb";
OleDbConnection myConnection = new OleDbConnection( connectionString );
myConnection.Open();
string query = "insert into EMPLOYEE_TABLE (EmployeeID, Name, Address) VALUES (101, 'John', '3960 CliffValley Way')";
OleDbCommand myCommand = new OleDbCommand();
myCommand.CommandText = query;
myCommand.Connection = myConnection;
myCommand.ExecuteNonQuery();
myConnection.Close();
Let
us analyze the code. First we have declared a connection string. The
connection string points to an MS Access database. Before you execute
this code, make sure you have the database in the path specified. Or,
change the path accordingly.
In the next step, we are creating a OleDbConnectionobject
and passing the connection string to this object. The line
'myConnection.Open();' will open a connection to the MS Access database
specified in the connection string. If the database doesn't exists or if
it is not able to open a connection for some other reason, the '.Open'
call will fail.
Next step is, creating a OleDbCommand object. This command object is used to execute sql statements and uses the connection opened by the OleDbConnection object.
Note that before executing a command, we have to establish a valid connection to the database.
And finally, after we have executed with the command, we will close the connection.
The
above sample code executes a sql statement and returns no data from
database. We are calling the method 'ExecuteNonQuery()' on the command
object. If we have a 'select ...' statement which returns data from
database, we cannot use the 'ExecuteNonQuery()' method.
The following sample demonstrates using OleDbDataAdapterObject and DataSet to retrieve data from databbase.
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Samples\\Employee.mdb";
OleDbConnection myConnection = new OleDbConnection( connectionString );
string query = "select * from EMPLOYEE_TABLE";
OleDbDataAdapter myAdapter = new OleDbDataAdapter( query, myConnection );
DataSet employeeData = new DataSet();
myAdapter.Fill ( employeeData );
Here we are creating a OleDbConnection object and we are just passing the object to the OleDbDataAdapterobject. Also, we pass the 'select ...' query to the OleDbDataAdapter. Next, we call the '.Fill()' method of the OleDbDataAdapter.
This step will populate the dataset ( called 'employeeData' ) with the
data retrieved for the sql statement 'select * from EMPLOYEE'.
As
you already know, a DataSet can contain a collection of tables. But in
our case, our sql statement will retrieve data from only one table. So,
our DataSet will have only one table.
We can iterate through the table in the dataset and retrieve all the records. See the following code demonstrating this:
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Samples\\Employee.mdb";
OleDbConnection myConnection = new OleDbConnection( connectionString );
string query = "select * from EMPLOYEE_TABLE";
OleDbDataAdapter myAdapter = new OleDbDataAdapter( query, myConnection );
DataSet employeeData = new DataSet();
myAdapter.Fill( employeeData );
// Repeat for each table in the DataSet collection.
foreach ( DataTable table in employeeData.Tables )
{
// Repeat for each row in the table.
foreach ( DataRow row in table.Rows )
{
MessageBox.Show( "Employee Number : " + row["EmployeeNumber"].ToString() );
MessageBox.Show( "Name : " + row["Name"].ToString() );
MessageBox.Show( "Address : " + row["Address"].ToString() );
}
}
DataSet, DataTable, DataRow
DataSet and DataTable are the key components in
ADO.NET programming. In simple words, DataSet represents an in memory
representation of the database. We can load an entire database into a
DataSet and manipulate the data in memory. If you aremore familiar with
DataSet, you can Add, Edit and Update data in the dataset and then just
call a single method 'AcceptChanges()' whichwill save all the changes
back to the database.
A DataSet contains one or more DataTables
A DataTable contains DataRows.
What is DataSet ?
A DataSet is an in memory representation of data loaded from any data source. Even though the most common data sourceis database,
we can use DataSet to load data from other data sources including XML
files etc. In this article, we will talk about the role of DataSet in
manipulating data from database.
In .NET, a DataSet is a class
provided by the .NET Framework. The DataSet class exposes several
proeprties and methods that can be used to retrieve, manipulate and save
data from various data sources.
Just like any other classes in
object oriented programming, we have to create an instance of DataSet
class to work with data. Typically, we may create a new instance of a
DataSet and use other classes provided by .NET Framework to populate the
DataSet. See the following example:
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Samples\\Employee.mdb";
OleDbConnection myConnection = new OleDbConnection( connectionString );
string query = "select * from EMPLOYEE_TABLE";
OleDbDataAdapter myAdapter = new OleDbDataAdapter( query, myConnection );
DataSet employeeData = new DataSet();
myAdapter.Fill ( employeeData );
Here we are creating a OleDbConnection object and we are just passing the object to the OleDbDataAdapterobject. Also, we pass the 'select ...' query to the OleDbDataAdapter. Next, we call the '.Fill()' method of the OleDbDataAdapter.
This step will populate the dataset ( called 'employeeData' ) with the
data retrieved for the sql statement 'select * from EMPLOYEE'.
As
you already know, a DataSet can contain a collection of tables. But in
the above case, our sql statement will retrieve data from only one
table. So, our DataSet will have only one table.
Commonly used properties and methods of DataSet
Property : Tables
The Tables propertly allows us to retrieve the tables contained in the DataSet. This property returns a DataTableCollection
object. The following sample code demonstrates iterating through the
collection of tables in a data set and print the name of all the tables.
DataSet employeeData = new DataSet();
myAdapter.Fill( employeeData );
// Repeat for each table in the DataSet collection.
foreach ( DataTable table in employeeData.Tables )
{
MessageBox.Show ( table.TableName );
}
Or, you can use the indexer to access any specific table in the collection.
DataSet employeeData = new DataSet();
myAdapter.Fill( employeeData );
// Repeat for each table in the DataSet collection.
for ( int i = 0; i < employeeData.Tables.Count; i++ )
{
DataTable table = employeeData.Tables[i];
MessageBox.Show ( table.TableName );
}
Method : GetXml()
The GetXml() method returns the XML representation of the data from the DataSet.
DataSet employeeData = new DataSet();
myAdapter.Fill( employeeData );
string xmlData = employeeData.GetXml();
Method : WriteXml(...)
The
WriteXml() method allows to save XML representation of the data from
the DataSet to an XML file. There are many overloaded method available,
which takes various parameters. The example shown below takes a file
name as parameter and saves the data in DataSet into xml format to the
file name specified as parameter. We can optionally save only the data
or both data and schema.
DataSet employeeData = new DataSet();
myAdapter.Fill( employeeData );
employeeData.WriteXml( "c:\\MyData.xml" );
Method : ReadXml(...)
The
ReadXml() method allows to load the DataSet from an XML representation
of the data. There are many overloaded method available, which takes
various parameters. The example shown below takes a file name as
parameter and loads the data from XML file into the DataSet. This method
can be used to load either the data only or both data and schema from
the XML.
DataSet employeeData = new DataSet();
employeeData.ReadXml( "c:\\MyData.xml" );
There is another method called 'ReadXmlSchema()', which can be used to load only the schema from a file.
The
methods WriteXml() and ReadXml() are useful to save the data from a
database into some temporary files, transport to other places or keep it
as a local file and load later. Many applications, including the SpiderAlerts tool
available for download from this site, uses DataSet to manipulate data
and saves/retrieves them from local disk using the WriteXml() and
ReadXml() methods.
The SpiderAlerts
tool communicates with webservices in our site and retrieves the alerts
in the form of a DataSet. Once the Alerts are retrieved, it is saved
into local computer using the WriteXml method. (This implementation may
be changed soon in the future versions of this tool. We are considering
saving(serializing) the DataSet into Isolated Storage (IsolatedStorage
is a new feature part of the .NET Framework - it is a kind of hidden
file system).
What is DataSet ?
A DataSet is an in memory representation of data loaded from any data source. Even though the most common data sourceis database, we can use DataSet to load data from other data sources including XML files etc. In this article, we will talk about the role of DataSet in manipulating data from database.
In .NET, a DataSet is a class provided by the .NET Framework. The DataSet class exposes several proeprties and methods that can be used to retrieve, manipulate and save data from various data sources.
Just like any other classes in object oriented programming, we have to create an instance of DataSet class to work with data. Typically, we may create a new instance of a DataSet and use other classes provided by .NET Framework to populate the DataSet. See the following example:
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Samples\\Employee.mdb"; OleDbConnection myConnection = new OleDbConnection( connectionString ); string query = "select * from EMPLOYEE_TABLE"; OleDbDataAdapter myAdapter = new OleDbDataAdapter( query, myConnection ); DataSet employeeData = new DataSet(); myAdapter.Fill ( employeeData );
Here we are creating a OleDbConnection object and we are just passing the object to the OleDbDataAdapterobject. Also, we pass the 'select ...' query to the OleDbDataAdapter. Next, we call the '.Fill()' method of the OleDbDataAdapter. This step will populate the dataset ( called 'employeeData' ) with the data retrieved for the sql statement 'select * from EMPLOYEE'.
As you already know, a DataSet can contain a collection of tables. But in the above case, our sql statement will retrieve data from only one table. So, our DataSet will have only one table.
Commonly used properties and methods of DataSet
Property : Tables
The Tables propertly allows us to retrieve the tables contained in the DataSet. This property returns a DataTableCollection object. The following sample code demonstrates iterating through the collection of tables in a data set and print the name of all the tables.
DataSet employeeData = new DataSet();
myAdapter.Fill( employeeData );
// Repeat for each table in the DataSet collection.
foreach ( DataTable table in employeeData.Tables )
{
MessageBox.Show ( table.TableName );
}
Or, you can use the indexer to access any specific table in the collection.
DataSet employeeData = new DataSet();
myAdapter.Fill( employeeData );
// Repeat for each table in the DataSet collection.
for ( int i = 0; i < employeeData.Tables.Count; i++ )
{
DataTable table = employeeData.Tables[i];
MessageBox.Show ( table.TableName );
}
Method : GetXml()
The GetXml() method returns the XML representation of the data from the DataSet.
DataSet employeeData = new DataSet(); myAdapter.Fill( employeeData ); string xmlData = employeeData.GetXml();
Method : WriteXml(...)
The WriteXml() method allows to save XML representation of the data from the DataSet to an XML file. There are many overloaded method available, which takes various parameters. The example shown below takes a file name as parameter and saves the data in DataSet into xml format to the file name specified as parameter. We can optionally save only the data or both data and schema.
DataSet employeeData = new DataSet(); myAdapter.Fill( employeeData ); employeeData.WriteXml( "c:\\MyData.xml" );
Method : ReadXml(...)
The ReadXml() method allows to load the DataSet from an XML representation of the data. There are many overloaded method available, which takes various parameters. The example shown below takes a file name as parameter and loads the data from XML file into the DataSet. This method can be used to load either the data only or both data and schema from the XML.
DataSet employeeData = new DataSet(); employeeData.ReadXml( "c:\\MyData.xml" );
There is another method called 'ReadXmlSchema()', which can be used to load only the schema from a file.
The methods WriteXml() and ReadXml() are useful to save the data from a database into some temporary files, transport to other places or keep it as a local file and load later. Many applications, including the SpiderAlerts tool available for download from this site, uses DataSet to manipulate data and saves/retrieves them from local disk using the WriteXml() and ReadXml() methods.
The SpiderAlerts tool communicates with webservices in our site and retrieves the alerts in the form of a DataSet. Once the Alerts are retrieved, it is saved into local computer using the WriteXml method. (This implementation may be changed soon in the future versions of this tool. We are considering saving(serializing) the DataSet into Isolated Storage (IsolatedStorage is a new feature part of the .NET Framework - it is a kind of hidden file system).
More about DataTable and DataRow
A DataTable is a class in .NET Framework and in simple words a DataTable object represents a table from a database.
DataSet
and DataTable are the key components in ADO.NET programming. While
DataSet can be used to represent a database as a whole, a DataTable
object can be used to represent a table in the Database/DataSet. A
DataSet can contain several DataTables.
In typical database
oriented applications, DataSet and DataTable are used a lot to
manipulate data. DataAdapter or other classes can be used to populate a
DataSet. Once a DataSet is populated, we can access the DataTables
contained within the DataSet.
Just like any database table
contains multiple rows (records), a DataTable can contain multiple
DataRows. Each row contains multiple fields representing each column in
the table.
The typical process to retrieve records from a database in ADO.NET includes the following steps:
Open a connection to database
Use a data adapter to fill a DataSet.
Access the DataTable contained in the DataSet
|
The following sample code explains these steps. This sample code retrieves data from an MS Access database.
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Samples\\Employee.mdb";
OleDbConnection myConnection = new OleDbConnection( connectionString );
string query = "select * from EMPLOYEE_TABLE";
OleDbDataAdapter myAdapter = new OleDbDataAdapter( query, myConnection );
DataSet employeeData = new DataSet();
myAdapter.Fill( employeeData );
// Repeat for each table in the DataSet collection.
foreach ( DataTable table in employeeData.Tables )
{
// Repeat for each row in the table.
foreach ( DataRow row in table.Rows )
{
MessageBox.Show( "Employee Number : " + row["EmployeeNumber"].ToString() );
MessageBox.Show( "Name : " + row["Name"].ToString() );
MessageBox.Show( "Address : " + row["Address"].ToString() );
}
}
How to create a DataTable In most of the cases, we just access the DataTable in a DataSet. We do not need to create a new instance of the DataTable. When a DataSet is populated from database, the DataTable is created with proper schema and data. If we explicitely create DataTable, we have to create the proper schema. It is bit confusing if you are not very familiar with the database structure and schema. |
Exception Handling in .NET
If you write a program, it is for sure that it will have errors and
issues. You cannot avoid them. But what you can do is write the code
such a way that it is easy to find the errors and issues so that you can
solve them easily. You need the real skill to write 'maintainable
code'.
What is maintainable code ?
If
an existing application is given to a new employee in the company and
ask him to fix a problem in that,most probably he will come back with
the answer : "oh, it is stupid code.. I can't figure out what they have
written. Instead of trouble shooting the issues in this code, I can re
write the entire application with less time."
This is a common
scenario in the programming world. The above answer shows the code is
not a maintainable code. Over a period of time, there will be lot of
changes required in existing applications to adapt to the new
requirements. Only if you write 'maintainable code', you can enhance
your application when new requirements come up and solve issues.
There
is no specific set of rules to make an application 'maintainable'.
There are lot of factors involved in it including following coding
standards, writing lot of comments within code, writing self explanatory
code, separating application into multiple well defined layers, having
good exception handling etc.
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 behaviour.
What is the difference between 'Exception' and 'Error' ?
Error
is an expected situation in an application. For example, you want to
create a file in the folder "C:\Projects\Test\". If you attempt to
create a file when this folder doesn't exists, it will make the
operating system throw an exception. But you should not leave it to the
operating system to throw the exception. This has to be handled through
code. You must first check for the existence of the folder before you
attempt to write the file. If the folder doesn't exists, you must first
create the folder. This is how a stable application should be written.
Exception
is a runtime error that the program may encounter during the execution
of the program. For example, hard disk may be full when you attempt to
write into a file, network connection may be lost while your application
is communicating with another computer etc. There is no clear
definition, but typically, Exceptions are unpredictable errors during
runtime.
What is 'Exception Handling'?
When
you ride a bike, you may wear a helmet. When you go for boating, you
might use a life jacket. A car driver might use seat belts while driving
at high speed in a high way. What is the purpose ? To handle exceptions
(accidents), right ? We do not know when it might happen, so we are
prepared to 'handle' such situations any time.
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 an exception.
}
catch(Exception ex)
{
// Code to handle exception
}
Just
like a bike rider wrap his head in a helmet to protect from accident,
the above syntax will protect the code within the try block from
accidents (exceptions).
If any statement within the try block
raises an exception, the control of execution will be transfered to the
first line within the catch block. You can write the error handling code
in the catch block, like recording the error message into a log file,
sending an email to the administrator about the problem occurred,
showing an appropriate error message to the user etc.
See the following code :
try
{
Statement 1
Statement 2
Statement 3
}
catch(Exception ex)
{
Statement 4
Statement 5
}
Statement 6
In
normal flow of program, the statements 1, 2, 3, 6 will be executed.
Statements 4 and 5 will be executed only if an exception occurs.
Assume
there is an exception at statement 2. In this scenario, statements 1,
2, 4, 5 and 6 will be executed. Statement 3 will not be executed at all,
because an exception occurred at statement 2 and program flow was
transferred to the catch block.
'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.
Sample Code :
try
{
Statement 1
Statement 2
Statement 3
}
catch(Exception ex)
{
Statement 4
Statement 5
}
finally
{
Statement 6
Statement 7
}
Statement 8
In
normal flow of program, the statements 1, 2, 3, 6, 7 and 8 will be
executed. Statements 4 and 5 will be executed only if an exception
occurs.
Assume there is an exception at statement 2. In this scenario, statements 1, 2, 4, 5, 6, 7 and 8 will be executed.
Note
that the statements 6 and 7 are executed in both the cases. The bottom
line is, the code within the 'finally' block is executed whether there
is an exception or not.
You can use the finally block to do any code cleanup. For example, you are doing some database operations inside a try block.
try
{
Statement 1 - Open database
Statement 2 - Execute Query
Statement 3 - Close Database
}
catch(Exception ex)
{
Statement 4 - Show messagebox to user
}
In
the above code sample, what will happen if an exception occurs when the
statement 2 is executed ? The catch block will be executed and a
message box will be shown to the user. But the Statement 3 is never
executed in that case, which means the database will not be closed.
Here is where the finally block will be helpful.
try
{
Statement 1 - Open database
Statement 2 - Execute Query
}
catch(Exception ex)
{
Statement 3 - Show messagebox to user
}
finally
{
Statement 4 - Close Database
}
See
the improved code. We have moved the code to close the database to the
'finally' block. The statement to close the database will be executed
whether there is an exception or not.
Why should we catch exceptions ?
Why
should you use a helmet when you ride a bike ? To protect your head
from crashing when there is an accident, right ? Just like that,
exception handling will protect your application from crashing when
there is an 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.
Exception classes in .NET
.NET Framework provides several classes to work with exceptions. When
there is an exception, the .NET framework creates an object of type
'Exception' and 'throws' it. This Exception object contains all
information about the 'error'.
If you enclose your code within
the try-catch block, you will receive the exception object in the
'catch' block when the exception occurs. You can use this object to
retrieve the information regarding the error and take appropriate
action.
try
{
// Code which can cause an exception.
}
catch(Exception ex)
{
// Code to handle exception
MessageBox.Show ( ex.Message );
}
Within
the catch block, you can use the Exception object to get more
information about the error. The exception object exposes a property
called 'Message', which gives a description about the error. This may
not be a very friendly message for the end user. But you can use it to
log the error and show another friendly message to the user.
The System.Exception class
In
.NET, all exceptions are derived from the Exception class. The
Exception class is defined inside the System namespace.Other derived
exception classes are spread across many other namespaces.
Since
all other exceptions are derived from the System.Exception class, if you
catch System.Exception, that would cover all exceptions derived from
System.Exception also. So, the statement catch (Exception) would
catch all exceptions of type System.Exception and all derived
exceptions. In .NET, all exceptions are derived from System.Exception.
So,catch (Exception) will catch all posibble exceptions in your .NET application.
Specify what exception type you want to catch
See the catch block in the above sample code. catch ( Exception ex ) - specifies that we want to catch all exceptions of Type Exception. So, if there is an exception of Type Exception, it will be caught by the catch block.
If
you specify an exception Type in the catch statement, it will catch all
exceptions of the specified type and all types derived from it.
See the following sample :
try
{
// Code which can cause an exception.
}
catch(System.Web.HttpException ex)
{
// Code to handle exception
MessageBox.Show ( ex.Message );
}
The above example will only catch the exception of type System.Web.HttpException and any other exception derived from it. So, if there is any exception of type System.ArithmeticException, it will not be handled and it may lead to program termination.
Handling specific Exception types
In
my previous article, I mentioned few examples from real life - "When
you ride a bike, you may wear a helmet. When you go for boating, you
might use a life jacket. A car driver might use seat belts while driving
at high speed in a high way. What is the purpose ? To handle exceptions
(accidents), right ? We do not know when it might happen, so we are
prepared to 'handle' such situations any time. "
Yes, a helmet
helps a bike rider when he meet with an accident. A life jacket may be
helpful in water and a seat belt would help a car driver. But what if
some one ride a bike with a helpmet, life jacket and a seat belt ? That
may not look good, right ?
Similarly, in Exception handling, you
do not need to catch all exceptions. You need to catch only the
'expected' exceptions. Which means,if you are doing an arithmetic
calculation, you must handle ArithmeticException and DivideByZeroException. When you are accessing the web from your code, you must handle HttpException.
The
bottom line is, depending on the nature of the code, you must handle
the appropriate, specific exceptions, instead of catching the father of
all exceptions (System.Exception).
Multiple catch blocks
You
can have any number of catch blocks for each try block. For example, if
you are doing some operation which involve web access and also some
arithmetic operations, you can handle both System.Web.HttpException and System.ArithmeticException. See the sample below:
try
{
// Code which can cause a web exception or arithmetic exception.
}
catch(System.Web.HttpException ex)
{
MessageBox.Show ( "A web exception occurred." );
}
catch(System.ArithmeticException ex)
{
MessageBox.Show ( "An arithmetic exception occurred." );
}
Program Flow
When
an exception occurs within a try block, the program control will jump
to the first catch block and compare if the exception type is same the
as the type specified in the catch block. If the type matches, it will
execute the catch block. If the types do not match, it will jump to the
next catch block and compare. Like this, it will compare against all
catch blocks until a match is found. If there is no catch block found
which matches the exception type, it will become an unhandled exception
and will lead to program termination
Catch derived exceptions first and base exception last
A
base exception type will match the derived exceptions also. If there is
a catch block with the type 'Exception', it will catch all types of
exceptions. So, you have multiple catch blocks, you must specify the
derived exception types first and the base types last. See the following
code:
try
{
// Code which can cause a web exception or arithmetic exception.
}
catch (System.Exception ex)
{
MessageBox.Show ( "An exception occurred." );
}
catch (System.Web.HttpException ex)
{
MessageBox.Show ( "A web exception occurred." );
}
In
the above code, assume there is a web exception occurred. The exception
type will be compared against the first catch block. Since the
WebException is derived from System.Exception or oneof it's derived
classes, the types will match and the first catch block will be
executed. So, you might be expecting that the catch (System.Web.HttpException) block will be executed, but it would never get called because of the catch(System.Exception ex) before that.
You must change the above code as shown below :
try
{
// Code which can cause a web exception or arithmetic exception.
}
catch (System.Web.HttpException ex)
{
MessageBox.Show ( "A web exception occurred." );
}
catch(System.Exception ex)
{
MessageBox.Show ( "An exception occurred." );
}
Now, if there is a web exception, it will go to the catch (System.Web.HttpException ex) block. All other exceptions will go to catch (System.Exception ex).
Some commonly used .NET Exception classes
System.ArithmeticException
- This is the base class for exceptions that occur during arithmetic
operations, such as System.DivideByZeroException and
System.OverflowException.
System.ArrayTypeMismatchException -
ArrayTypeMismatchException is thrown when a an incompatible object is
attpemted to store into an Array.
System.DivideByZeroException - This exception is thrown when an attempt to divide a number by zero.
System.IndexOutOfRangeException
- IndexOutOfRangeException is thrown when attempted to access an array
using an index that is less than zero or outside the bounds of the
array.
System.InvalidCastException - Thrown when an explicit
type conversion from a base type or interface to a derived type fails at
run time.
System.NullReferenceException - This exception is thrown when an object is accessed but it is null.
System.OutOfMemoryException
- OutOfMemoryException is thrown if the 'new' operation (creating new
object) fails due to in sufficient memory.
System.OverflowException - OverflowException is thrown when an arithmetic operation overflows.
System.StackOverflowException
- StackOverflowException is thrown when the execution stack is
exhausted by having too many pending method calls, most probably due to
infinite loop.
ArgumentException - The exception that is thrown when one of the arguments provided to a method is not valid.
Custom Exceptions
The Microsoft .NET team has done a good job by providing us a rich set
of Exception classes. Most of the time, these exception classes are
sufficient enough to handle any common error situation. However, it may
be required that our application would need some additional exception
classes, that are not available in .NET Framework.
The .NET
Framework exception handling mechanism allows us to create our own
custom exception classes and use it in our applications.
Custom Exceptions
All exceptions in .NET are derived from the root exception class - System.Exception. There are two other
exception classes immediately derived from the System.Exception :
|
All exceptions thrown by the .NET Framework is derived from the SystemException class. If we raise any exception from our application, it should be derived from the System.ApplicationException. This will differentiate our exceptions from the system generated exceptions. It is easy to create a custom exception class. Just create a new class and mark it as derived from System.ApplicationException
public class UserNotExistsException : System.ApplicationException
{
}
Now we have derived a custom exception class and we can use it in ourr application. See the sample code, showing how we can throw ourr custom exception.
public void UpdateUser( User userObj )
{
if ( some error condition )
{
throw new UserNotExistsException();
}
}
The 'throw' statement allows us to raise an exception programmatically. Here we are creating a new object of type 'UserNotExistsException' and throwing it. Another class or method which calls our method should handle this exception.
try
{
UpdateUser( userObj );
}
catch ( UserNotExistsException ex )
{
MessageBox.Show ( ex.Message );
}
In this sample, we are calling the method UpdateUser(...), which might throw an exception of type UserNotExistsException. If this exception is raised, it will go to our catch block and we are showing a message to the user. Enhancing our custom exception In the custom exception we defined above, we haven't specified any constructor. But since we derive it from the ApplicationException, it will use the public constructors available in AppicationException. It is a good idea to provide at least one constructor, which takes an error message as a parameter.
public class UserNotExistsException : System.ApplicationException
{
public UserNotExistsException ( string message ) : base ( message )
{
}
}
Now, when we throw this exception, we have to pass an error message to the constructor. The error handlers will be able to retrieve this message from the Exception object and show a better message to the user.
public void UpdateUser( User userObj )
{
if ( some error condition )
{
throw new UserNotExistsException( "The user you are trying to update does not exists." );
}
}
See the exception handler code :
try
{
UpdateUser( userObj );
}
catch ( UserNotExistsException ex )
{
MessageBox.Show ( ex.Message );
}
Now the user will see the more friendly error message which we passed as part of the exception, while throwing it. You can customize the custom exception classes such a way that it passes any information you want including the date and time the exception occurred, the method name in which the exception was first raised, user name of the current user etc. You may also provide a Save() method for your custom exception class so that when a caller catch our custom exception, he can call the Save() method, which will record the error information to the disk. |
Introduction to XML
XML stands for eXtended Markup Language. XML has some similarities to HTML, which is also another Markup Language (HyperText Markup Language).
An
important difference between XML and HTML is, XML is used to define
data, while HTML is basically used to display/format text. Main use of
HTML is to make web pages. But XML is used in a wide variety of
applications now and is becoming a standard for data exchange between
different paltforms.
Unlike HTML, XML has no pre-defined set of tags.
You can define your own tags to structure and organize your data. Let
us see some sample XML :
<Company>
<Employees>
<Employee Id="101" Name="John" ></Employee>
<Employee Id="102" Name="Lisa" ></Employee>
<Employee Id="103" Name="Bill" ></Employee>
</Employees>
<Departments>
<Department Name="Sales"></Department>
<Department Name="Software"></Department>
<Department Name="HR"></Department>
</Departments>
</Company>
The
above piece of XML is quite self explanatory. It is used to represent
the data related to a company. One thing to note here is, the tags like
<Company>, <Employees> etc are not predefined. Any XML
document can have it's own set of tags. Only thing is, a valid XML
document should follow some rules (like each tag should have a matching
closing tag. There more such rules...)
Need for XML
XML
is a platform neutral standard. Since it is represented in plain text,
any platform can understand it. You can use XML to exchange data between
Unix and Windows, Mainframes and windows applications and virtually any
other platforms. It is a simple, easy to use *language* to
exchange/store data.
In real world, if you have to store data,
you have several choices. One of the most common mechanism is databases.
Databases are the best choice if you have lot of data to be
stored/manipulated. But if you have to send data to another application
or platform, databases will not be much helpful. Suppose you have your
data stored in an SQL Server database. What if your manager ask you to
give the list of Employees in the Sales department ? How will you give
the data to him? You cannot give your SQL Server database to him. He may
not have a SQL Server software or he may not have the technical
expertise to view data from SQL Server. XML is very helpful in such
scenarios. You just need to generate an XML from the SQL Server database
with the required records and hand over the XML as a print out or
email. XML is so simple so that any one can simply read it using any
text editor.
There are several XML viewers
and editors available, which will help you read XML in the form of a
tree view. Internet Explorer is a good XML viewer. Simply copy the above
XML and save into a file called 'sample.xml'. Then open the xml file in
internet explorer and see how it works!
You can define
your own XML tags based on your needs. You can have nested tags too,
which help you organize the data any way you want it. See a slightly
different version of the above XML:
<Company>
<Employees>
<Employee Id="101" Name="John" ></Employee>
<Employee Id="102" Name="Lisa" ></Employee>
<Employee Id="103" Name="Bill" ></Employee>
</Employees>
<Departments>
<Department Name="Sales">
<Manager>
<Name>Fred</Name>
<Address>3000 Briarcliif Way</Address>
<Email>Fred@spiderkerala.com</Email>
<Phone>
<ResidencePhone>616 304 1093</ResidencePhone>
<OfficePhone>616 304 1093</OfficePhone>
</Phone>
</Manager>
</Department>
<Department Name="Software">
<Manager>
<Name>Joe</Name>
<Address>3960 Whispering Way</Address>
<Email>Joe@spiderkerala.com</Email>
<Phone>
<ResidencePhone>616 304 1093</ResidencePhone>
<OfficePhone>616 304 1093</OfficePhone>
</Phone>
</Manager>
</Department>
</Departments>
</Company>
The XML data altogether is called an 'XML Document'. .NET gives several classes to read and manipulate XML Documents. We will explore some of them in upcoming chapters.
You might have seen our Tutorial Index,
which lists all chapters. You can click on any chapter title and
navigate to the corresponding page. This index is populated from an XML
file.
Click here to view the XML file, from which we load our tutorial chapters.
The
reason we load it from an XML file is, our chapters are continuously
changing and we add new chapters frequently. All our chapters have a
link to Next Chapter. If we hard-code these links in all
chapters, we have to make changes in several places when we change the
order of some chapters or when we add new chapters. There is all
possibility that we might make some mistakes and some of the chapters
may lead to 'wrong next chapter'. In our current implementation, we
programmatically read the XML file and display the Tutorial Index. Also, each page has a piece of code which read the current page URL and find the Next Page Url
from the XML file based on the current page URL. This mechanism helps
us add new chapters without making any changes to existing pages. All we
have to do is, just insert one line of entry in the XML file and the
changes will be automatically reflected in all other relevant pages.
Even if we want to re-order some of the chapters, we just need to
re-arrange the entries in the XML file.
We use the following code to load our Chapter Index from the XML file:
public string GetChapters( string filePath )
{
// Create an xml document.
XmlDocument doc = new XmlDocument();
// Load the XML from the file.
doc.Load(filePath);
// Retrieve all categories from the xml.
XmlNodeList categories = doc.SelectNodes("DotNetSpider/tutorials/Category");
string chapterString = "";
int chapter = 0;
// Iterate through all the categories
foreach ( XmlNode categoryNode in categories )
{
// Add category name to the string.
chapterString += "<BR><BR><font size=4>" + categoryNode.Attributes["Name"].Value + "</font><BR>";
// Get all chapters in the current category.
XmlNodeList chapters = categoryNode.SelectNodes("Chapter");
// Loop through all chapters in the current category and add to the string.
foreach ( XmlNode chapterNode in chapters )
{
++chapter;
chapterString += " <LI>Chapter " + chapter +
" : <a href='" + chapterNode.Attributes["Url"].Value + "'>" +
chapterNode.Attributes["Name"].Value + "</a>";
}
}
// Return the string, which contains the list of chapters.
return chapterString;
}
We
explored some areas where XML can be used. But XML can be used in a
very wide range of ways. We will explore more advanced uses of XML in
another chapter.
XML Specification
We
gave a very brief introduction to XML in this chapter. This chapter is
meant to give a very brief introduction and we haven't covered many
important aspects of XML here. We will explain most of them in some
other chapters.
Introduction to HTML
What is HTML
HTML(Hypertext Markup Language) - is the language used for creating hypertext documents (web pages) and controlling how Web pages appear.
Even
though it is a language, it is different from other programming
languages like C++ or Java. In languages like C++ and Java, you can
write complex applications and the language has its own syntax and
rules. But you can use HTML to develop only web pages.
Some facts about HTML
HTML is plain text, composed of tags.
HTML tags are always enclosed in angle-brackets ( < >)
HTML is not case sensitive, that means, it doesn't matter whether you type them in lower case or upper case.
Tags typically are used in begin-end pairs. Most of the HTML tags have an open tag and a close tag: Eg:
<B>...</B>
<I>...</I>
<FONT>...</FONT>
<BODY>...</BODY>
Some
tags like <HTML>, <HEAD> etc are mandatory in any html
file. A basic HTML file will have the following structure:
<html>
<head>
<title>your title</title>
</head>
<body>
your page content
</body>
</html>
All
the HTML tags in the above code is mandatory for an HTML page. You may
copy and paste the above code into a file in notepad and name it
test.html. Open the file in internet explorer to see how it works.
<B>...</B> <I>...</I> <FONT>...</FONT> <BODY>...</BODY>
Some tags like <HTML>, <HEAD> etc are mandatory in any html file. A basic HTML file will have the following structure:
<html> <head> <title>your title</title> </head> <body> your page content </body> </html>
All the HTML tags in the above code is mandatory for an HTML page. You may copy and paste the above code into a file in notepad and name it test.html. Open the file in internet explorer to see how it works.
Web Services
Webservices are services exposed over the internet.
Typically, webservice is just like any other class library, written in
any language. What make it a 'web service' is, it can be accessed across internet.
Eventhough
webservice is a new technology with a wide range of usage, it is a
pretty simple concept. It doesn't require much additional knowledge to
create web services if you are already familiar with C# or VB.NET. (Web
services are not specific to .NET. Even Java has web service
applications, but here we are discussing only the .NET web services.)
As
we mentioned, web services are exposed over internet. To make this
happen, it has to be hosted with a web site. Othen than hosted as part
of a web site to make this visible across internet, web services have no
web pages or UI. It is just a set of classes with public/private
methods and properties.
Web services are a group of [web]
methods. Consumer applications can treat this as just another class
library. Regular class libraries are located along with the same
application and we can call any methods in the class libraries
(assemblies). But in case of web services, the assembly is located in
the internet server. The consumer application will not have direct
access to the assembly. Consumer applications have to add a reference to
the webservice URL and then call methods in it. The method call goes
across the internet using SOAP protocal and
results are returned across internet in the form of XML. The
communication across internet happens transparently and the application
need not know anything about this communication.
Creating a simple web service
If
you are using VS.NET, it won't take more than 2-3 minutes to create
your first webservice. Follow the steps below to create a web service:
Choose New Projectfrom VS.NET and create a C# project of type 'ASP.NET Web Service' and give the name 'MyWebService'
The
new project will have a default page 'Service1.asmx'. This is your
first web service page. Web service pages have the extension .asmx (like ASP.NET pages have the extension .aspx)
The
code behind file 'Service1.asmx.cs' have a class 'Service1'. This is
like other regular classes with the only difference that it inherits the
system class System.Web.Services.WebService. This is required for web service classes.
VS.NET creates a sample method for you. All you have to do is, uncomment the following method in Service1.asmx.cs
//[WebMethod]
//public string HelloWorld()
//{
//return "Hello World";
//}
Note that this method is pretty much same as any other regular method.
The only difference is, it has an attribute [WebMethod]. This attribute make
the method visible across internet. If you remove this attribute, your
application will still compile, but the consumer applications cannot call this
method across internet.
Ok,
thats all you have to do to create a simple webservice. Build your
solution and your web service is ready to be called by other
applications.
Create a consumer application
A
wide range of applications can consume the web services, including web
page, other web services, windows applications etc. let us create a
sample windows application and call our web service.
Create a new C# Windows Application.
Right click on the 'References' in the Solution Explorer, under your project name. Choose 'Web References'.
Another window will open and will allow you to specify the URL of the web service to be referenced.
Type
the URL of your web service in the space provided for 'URL'. If you
have created the web service in the local machine's default web site,
the URL might be like this :
http://localhost/MyWebService/Service1.asmx
If
you have given a different name fro the project or if you have changed
the default service name, then your URL may differ. Type the URL and
press enter. It will attempt to connect with the web service and if
succeeded it will retrieve the public web methods and display. Once you
get this success screen, press the 'Add Reference' button on the screen
to add the web reference to your application. There is a space to
specify the 'web reference name', which will have the default value
'localhost'. Leave it as it is.
Now you are ready to make calls to the webservice. Just use the following code in your application:
localhost.Service1 service = new localhost.Service1();
string result = service.HelloWorld();
MessageBox.Show( result );
Let
us analyze our code. The first line creates an instance of the Service1
class, just like any regular class. Only thing is it uses the namespace
'localhost'. This is same as the 'web reference name' we specified
while adding the web reference. We can use any web reference name when
we add the reference and have to use the same name as namespace while
making calls to the web service class.
In the second line, we are
actually calling the web method 'HelloWorld()' and it returns the
result as a string. Note this is just like any other method call. So,
your application makes the call to web service as if it is calling any
local class library calls!! The communication with web service, wrapping
your calls in SOAP/XML, retrieve results from web service, unwrap the
SOAP/XML to get the actual result etc are done behind the scene by the
framework and you need not do any additional work to make all this work.
Now
you can go back to your web service, add more methods with different
parameters and play around with that. You will be able to call methods
in the web service just like you use any local class. Note that when you
make any changes to the method name or parameters, or if you add new
methods, you will need to refresh your web reference to get access to
the updated web service methods. To do this, go to the Server Explorer,
right click on the web reference name 'localhost' under the 'Web
References'. Then choose 'Refresh'. This will communicate with the web
service again and retrieve the latest web service data.
How does all this work?
To
make calls to any classes, your application need to know the details of
the class. To successfully compile your code, it has to have
information about the class, what are the public methods and properties
etc. But in your sample code which calls the web service, the actual Service1class resides in the web (in your case, in your local web server). So how does the application compile without having the 'Service1' class in your application?
This is where the framework help you. When you add a 'web reference' to the web service URL, VS.NET actually creates local proxy
in your application. A local proxy is a minimal version of the actual
class. The proxy has just the sufficient information about the 'real
class', which is required for your application to successfully compile.
The proxy class has the list of all public web methods in the real web
service class and it knows the parameters and their data types of each
method.
The most important thing is, your application is actually using this proxy class and not the real web service class.
localhost.Service1 service = new localhost.Service1();
string result = service.HelloWorld();
MessageBox.Show( result );
In the above code, localhost.Service1is
actually the proxy class (a representative of a real class), which is
created automatically by VS.NET when you added the web reference. You
are creating an instance of the proxy class and calling the 'HelloWorld()'
method of this proxy. Since the proxy class knows that it is 'only a
proxy of the real class', it redirects all calls to the 'real web
service class'. The method 'HelloWorld()'
in the proxy class takes care of converting the call to a web request
using SOAP/XML. After retrieving the result of the web request to the
real web service class, this proxy class takes the responsibility of
parsing the SOAP/XML response and returning only the result string to
the calling applicationn. So the proxy class does all the dirty job for
you.
The proxy class has no implementation of the functionality.
It just redirects the call to the web service. So, if you make any
changes to the implementation in the web service, still you will get the
'updated result' when you make calls to web service. But, if you change
the method name, or change the parameter types in the web service and
do not 'refresh the web reference', then your application will compile
with the old proxy. But when the proxy redirect the call to the web
service, it will find that the parameters or method names do not match
and it will fail. So, if there is any change in the method names or
parameters, you must refresh your web reference.
//[WebMethod]
//public string HelloWorld()
//{
//return "Hello World";
//}
Note that this method is pretty much same as any other regular method. The only difference is, it has an attribute [WebMethod]. This attribute make
the method visible across internet. If you remove this attribute, your
application will still compile, but the consumer applications cannot call this
method across internet.
Ok, thats all you have to do to create a simple webservice. Build your solution and your web service is ready to be called by other applications.
Create a consumer application
A wide range of applications can consume the web services, including web page, other web services, windows applications etc. let us create a sample windows application and call our web service.
Type the URL of your web service in the space provided for 'URL'. If you have created the web service in the local machine's default web site, the URL might be like this :
http://localhost/MyWebService/Service1.asmxIf you have given a different name fro the project or if you have changed the default service name, then your URL may differ. Type the URL and press enter. It will attempt to connect with the web service and if succeeded it will retrieve the public web methods and display. Once you get this success screen, press the 'Add Reference' button on the screen to add the web reference to your application. There is a space to specify the 'web reference name', which will have the default value 'localhost'. Leave it as it is.
Now you are ready to make calls to the webservice. Just use the following code in your application:
localhost.Service1 service = new localhost.Service1(); string result = service.HelloWorld(); MessageBox.Show( result );Let us analyze our code. The first line creates an instance of the Service1 class, just like any regular class. Only thing is it uses the namespace 'localhost'. This is same as the 'web reference name' we specified while adding the web reference. We can use any web reference name when we add the reference and have to use the same name as namespace while making calls to the web service class.
In the second line, we are actually calling the web method 'HelloWorld()' and it returns the result as a string. Note this is just like any other method call. So, your application makes the call to web service as if it is calling any local class library calls!! The communication with web service, wrapping your calls in SOAP/XML, retrieve results from web service, unwrap the SOAP/XML to get the actual result etc are done behind the scene by the framework and you need not do any additional work to make all this work.
Now you can go back to your web service, add more methods with different parameters and play around with that. You will be able to call methods in the web service just like you use any local class. Note that when you make any changes to the method name or parameters, or if you add new methods, you will need to refresh your web reference to get access to the updated web service methods. To do this, go to the Server Explorer, right click on the web reference name 'localhost' under the 'Web References'. Then choose 'Refresh'. This will communicate with the web service again and retrieve the latest web service data.
How does all this work?
To make calls to any classes, your application need to know the details of the class. To successfully compile your code, it has to have information about the class, what are the public methods and properties etc. But in your sample code which calls the web service, the actual Service1class resides in the web (in your case, in your local web server). So how does the application compile without having the 'Service1' class in your application?
This is where the framework help you. When you add a 'web reference' to the web service URL, VS.NET actually creates local proxy in your application. A local proxy is a minimal version of the actual class. The proxy has just the sufficient information about the 'real class', which is required for your application to successfully compile. The proxy class has the list of all public web methods in the real web service class and it knows the parameters and their data types of each method.
The most important thing is, your application is actually using this proxy class and not the real web service class.
localhost.Service1 service = new localhost.Service1(); string result = service.HelloWorld(); MessageBox.Show( result );In the above code, localhost.Service1is actually the proxy class (a representative of a real class), which is created automatically by VS.NET when you added the web reference. You are creating an instance of the proxy class and calling the 'HelloWorld()' method of this proxy. Since the proxy class knows that it is 'only a proxy of the real class', it redirects all calls to the 'real web service class'. The method 'HelloWorld()' in the proxy class takes care of converting the call to a web request using SOAP/XML. After retrieving the result of the web request to the real web service class, this proxy class takes the responsibility of parsing the SOAP/XML response and returning only the result string to the calling applicationn. So the proxy class does all the dirty job for you.
The proxy class has no implementation of the functionality. It just redirects the call to the web service. So, if you make any changes to the implementation in the web service, still you will get the 'updated result' when you make calls to web service. But, if you change the method name, or change the parameter types in the web service and do not 'refresh the web reference', then your application will compile with the old proxy. But when the proxy redirect the call to the web service, it will find that the parameters or method names do not match and it will fail. So, if there is any change in the method names or parameters, you must refresh your web reference.
No comments:
Post a Comment