Dot NET Concepts Prakash
Dot NET Concepts Prakash
Dot NET Concepts Prakash
NET GENERAL
With dot NET, Microsoft introduces a completely new architecture for Windows
applications (WinForm), Data Access (ADO.NET), Web Applications (ASP.NET),
Windows components (Assemblies), Distributed Applications (.NET remoting), and
above all the XML based Web Services. The famous figure for the representation
of dot net is presented below:0
What is the .NET framework?
The .NET framework is a collection of all the tools and utilities required to execute
the .NET managed applications on a particular platform. The MS.NET framework
includes the standard compilers (C#, VB.NET, J#, C++.NET, Jscript.NET), various
utilities like (caspol, ngen, installutil, tlbimp, sn, asmreg, ildasm, etc), runtime
environment (CLR), garbage collector, security manager, thread manager,
assembly loader, just in time compilers, and the standard framework or base
class libraries. It is important to realize that while the implementation of .Net
applications is platform independent; the implementation of .NET framework is
platform specific. In fact, it is this particular specific implementation of the .NET
framework that makes the managed .NET applications platform independent.
The general conception is that most of the VB6 developers will upgrade to VB.NET
while developers coming from Java or C++ to .NET are likely to go for C#. Since
web developers for Windows using ASP are familiar with VB and VB Scripts,
therefore, most of the web development with ASP.NET at the start is likely to be
dominated by VB.NET; but after sometime C# will be able to attract at least half
of these developers. Keeping technical side away, C++ and thus C# developers
are generally paid more than those of VB developers. So, this might also be the
factor for making C# the language of choice on .NET framework.
Web applications are programs that used to run inside some web server (e.g.,
IIS) to fulfill the user requests over the http. A typical example of web application
is Hotmail and Google.
Web services are web applications that provide services to other applications over
the internet. Google search engine’s web service, e.g., allows other applications
to delegate the task of searching over the internet to Google web service and use
the result produced by it in their own applications.
An assembly can be a single file or it may consist of the multiple files. In case of
multi-file, there is one master module containing the manifest while other
assemblies exist as non-manifest modules. A module in .NET is a sub part of a
multi-file .NET assembly. Assembly is one of the most interesting and extremely
useful areas of .NET architecture along with reflections and attributes, but
unfortunately very few people take interest in learning such theoretical looking
topics.
COM (Component Object Model) is the component model based on the object
oriented design, which means that the components represented by the COM
component exists in the form of classes and objects implementing a standard
specification defined by COM. COM components can be used by any program
running on Windows Operating System; be it is written with VB, C++, Java or
even some .NET compliant language like C# and VB.NET.
Dot NET assembly is the component standard specified by the .NET. Hence, dot
net assemblies are understandable to only Microsoft.NET and can be used only in
.NET managed applications.
The most popular implementation, after MS.NET, is the open source ‘Mono’
Project on Linux (See www.go-mono.com)
Microsoft has released almost all the source code of their .NET framework for
FreeBSD and Mac OS under the title of Shared Source Common Language
Infrastructure (SSCLI). Check out the SSCLI 1.0 release - which already builds on
WindowsXP, FreeBSD, and Mac OS X 10.2, released under Microsoft's Shared
Source Initiative. http://msdn.microsoft.com/net/sscli/
http://www.microsoft.com/resources/sharedsource/default.mspx
However, there are few contrasts in the architecture and design of the two virtual
machines. Microsoft .NET framework’s architecture is more coupled to the
Microsoft Windows Operating System which makes it difficult to implement it on
various operating systems and physical machines. Java, on the other hand, is
available on almost all major platforms. At the darker side, J2EE architecture and
JVM is more coupled to the Java programming language while Microsoft.NET has
been designed from the scratch to support language independence and language
integration. Microsoft.NET covers the component development and integration in
much more detail than Java. The versioning policy of .NET is simply the best
implemented versioning solution in the software development history. Java has
got the support of industry giants like Sun, IBM, Apache and Oracle while the
Microsoft.NET is supported by giants like Microsoft, Intel, and HP.
To use a COM component in your Visual Studio.NET project, you need to add a
reference of the COM component in the Reference node of the project node of the
solution inside the solution explorer window. The great thing about Visual
Studio.Net is that it allows you to add a reference to the COM component in
exactly the similar way as you add the reference to the .NET assembly. The Visual
Studio.NET automatically creates the runtime callable wrapper assembly for the
referenced COM component.
To add a reference to a COM component, right click the ‘Reference’ node under
the project node inside the solution explorer and select the ‘Add Reference…’
option. It will show you a user interface screen where you browse for the target
COM component. When you have selected the component, press the ‘Select’
button and then press OK. This will add a new reference node in the Reference
sub tree of the project. By selecting the added reference node, you can edit its
properties from the properties window.
Note: The process of importing a COM component into .NET is called ‘COM
interoperability with .NET’
The .NET Framework has two main components: the Common Language Runtime
(CLR) and the .NET Framework class library.
The Runtime can be considered an agent that manages code at execution time.
Thus providing core services such as memory management, thread management,
and remoting. Also incorporating strict type safety, security and robustness.
The class library is a comprehensive collection of reusable types that you can use
to develop traditional command-line, WinForm (graphical user interface)
applications, Web Forms and XML Web services.
The .NET Framework provides a Runtime environment called the Common
Language Runtime or (CLR) that handles the execution of the code and provides
useful services for the implementation of the application. CLR takes care of code
management upon program execution and provides various services such as
memory management, thread management, security management and other
system services. The managed code targets CLR benefits by using useful features
such as cross-language integration, cross-language exception handling,
versioning, enhanced security, deployment support, and debugging.
Common Type System (CTS) describes how types are declared, used and
managed. CTS facilitates cross-language integration, type safety, and high
performance code execution. The CLS is a specification that defines the rules to
support language integration. This is done in such a way, that programs written in
any language (.NET compliant) can interoperate with one another. This also can
take full advantage of inheritance, polymorphism, exceptions, and other features.
The CAS security policy revolves around two key concepts - code groups and
permissions. Each .NET assembly is a member of a particular code group and
each code group is granted the permissions specified in a named permission set.
An example: Using the default security policy, a control downloaded from a web
site belongs to the 'Zone - Internet' code group which complies to the
permissions defined by the 'Internet' named permission set.
Microsoft defines some default policies but you can modify these and even create
your own. To view the code groups defined on your system; Run 'caspol' from the
command-line and checkout the different options on display.
What is serialization in .NET and what are the ways
to control serialization?
Serialization is the process of converting an object into a stream of bytes. On the
other hand Deserialization is the process of creating an object from a stream of
bytes. Serialization/Deserialization is used to transport or to persist objects.
Serialization can be defined as the process of storing the state of an object to a
storage medium. During this process, the public and private fields of the object
and the name of the class, including the assembly are converted to a stream of
bytes. Which is then written to a data stream. Upon the object's subsequent
deserialized, an exact clone of the original object is created.
Binary serialization preserves Type fidelity, which is useful for preserving the state
of an object between different invocations of an application. For example: An
object can be shared between different applications by serializing it to the
clipboard.
You can serialize an object to a stream, disk, memory, over a network, and so
forth. Remoting uses serialization to pass objects "By Value" from one computer
or application domain to another. XML serialization serializes only public
properties and fields and does not preserve Type fidelity. This is useful when you
want to provide or consume data without restricting the application that uses the
data.
As XML is an open standard, it is an attractive choice for sharing data across the
Web. SOAP is also an open standard, which makes it an attractive choice too.
There are two separate mechanisms provided by the .NET class library -
XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses
XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter
for remoting. Both are available for use in your own code.
Visual Studio .NET and the .NET Framework make it easy to add ADSI
functionality with the DirectoryEntry and DirectorySearcher components.
Using ADSI you can create applications that perform common administrative
tasks, such as backing up databases, accessing printers and managing user
accounts. ADSI allows:
4) Access and use a single or hierarchical tree structure for administering and
maintaining a diverse and complicated network.
System.DirectoryServices
using System;
using System.Runtime.InteropServices;
class MainApp
{
[DllImport("user32.dll", EntryPoint="MessageBox")]
public static extern int MessageBox(int hWnd, String
".NET", 0 );
mm.Attachments.Add(ma);
SmtpMail.SmtpServer="mail.programmersheaven.com";
SmtpMail.Send(mm);
C# .NET
What is C#?
C# (pronounced C-Sharp) is a new programming language introduced with the
Microsoft .NET framework and is no doubt the language of choice in .NET
environment. It was first created in the late 1990's as part of Microsoft’s whole
.NET strategy. It is a whole new language free of backward compatibility curse
and a whole bunch of new, exciting and promising features. It is an Object
Oriented Programming language, which at its core, has similarities with Java,
C++ and VB.
In fact, C# combines the power & efficiency of C++, simple & clean OO design of
Java, and code simplification of Visual Basic. Like Java, C# also does not allow
multiple inheritance and use of pointers (in safe and managed code) while it does
provide garbage memory collection at runtime, type and memory access
checking. But, contrary to java, C# keeps the different useful concepts of C++
like operator overloading, enumerations, pre-processor directives, pointers (in
unmanaged and un-safe code), function pointers (in the form of delegates), also
promises to have template support (with the name of generics) in next versions.
Like VB it also supports the concepts of properties (context sensitive accessor to
fields).
Sample C# Application
Using System
Class Sample
{
public static void main()
{
Console.WriteLine (“Hello World”)
}
}
Example: A Jagged Array can be used is to create a table in which the lengths of
the rows are not same. This Array is declared using square brackets ( [ ] ) to
indicate each dimension.
Class Jagged
{
public static void Main()
{
int [][] jagged=new int [3][];
jagged[0]=mew int[4]
jagged[1]=mew int[3]
jagged[2]=mew int[5]
int I;
‘Storing values in first array
for (I=0;I<4;I++)
jagged[0][I]=I;
‘Storing values in second array
for( I=0;I<3;I++)
jagged[1][I]=I;
for(I=0;I<5;I++)
jagged[2][I]=I;
for (I=0;I<4;I++)
Console.WriteLine(jagged[0][I])
for (I=0;I<3;I++)
Console.WriteLine(jagged[1][I])
for(I=0;I<5;I++)
Console.WriteLine(jagged[2][I])
}
What is the difference between "Value Types" and
"Reference Types"?
Many programming languages provide built-in data types such as integers and
floating-point numbers. These are copied when they are passed in to arguments
i.e. they are passed "By Value". In .NET terms, these are called Value Types".
The .NET Framework defines built-in value types such as System.Int32 and
System.Boolean which correspond and are identical to primitive data types used
in programming languages.
The language you are using will provide functionality to define your own Value
Types. These user defined Types derive from System.ValueType. If you want to
define a Type representing a value that is a complex number (two floating-point
numbers), you might choose to define it as a value type. Why? Because you can
pass the Value Type efficiently "By Value". If the Type you are defining could be
more efficiently passed "By Reference", you should define it as a class instead.
Variables of Reference Types are referred to as objects. These store references to
the actual data.
• class
• interface
• delegate
• object
• string
ADO .NET
What is ADO.Net?
Most of the today’s applications need to interact with database systems to persist,
edit or view data. In .Net data access service is provided through ADO.Net
(ActiveX Data Object in Dot Net) components. ADO.Net is an object oriented
framework that allows you to interact with database systems. We usually interact
with database systems through SQL queries or stored procedures. ADO.Net
encapsulates our queries and commands to provide a uniform access to various
database management systems.
ADO.Net is a successor of ADO (ActiveX Data Object). The prime features of
ADO.Net are its disconnected data access architecture and XML integration.
The data reader, on the other hand, is directly connected to the database
management system. It passes all the queries to the database management
system, which executes them and returns the result back to the application.
However, since the dataset stores the records in the local buffer in the
hierarchical form, it does take up more resources and may affect the overall
performance of the application.
How to select dataset or data reader?
The data reader is more useful when you need to work with large number of
tables, database in non-uniform pattern and you need not execute the large no.
of queries on few particular table.
When you need to work on fewer no. of tables and most of the time you need to
execute queries on these fewer tables, you should go for the dataset.
It also depends on the nature of application. If multiple users are using the
database and the database needs to be updated every time, you must not use
the dataset. For this, .Net provides the connection oriented architecture. But in
the scenarios where instant update of database is not required, dataset provides
optimal performance by making the changes locally and connecting to database
later to update a whole batch of data. This also reduces the network bandwidth if
the database is accessed through network.
Disconnected data access is suited most to read only services. On the down side,
disconnected data access architecture is not designed to be used in the
networked environment where multiple users are updating data simultaneously
and each of them needs to be aware of current state of database at any time
(e.g., Airline Reservation System).
Class Description
The DataSet is a local buffer of tables or a collection of disconnected
DataSet
record sets
DataTable is used to contain the data in tabular form using rows and
DataTable
columns. DataRow Represents a single record or row in DataTable
DataRow Represents a single record or row in DataTable
DataColumn Represents a column or field of DataTable
DataRelation Represents the relationship between different tables in a data set.
Represents the constraints or limitations that apply to a particular field or
Constraint
column.
ADO.Net also contains some database specific classes. This means that different
database system providers may provide classes (or drivers) optimized for their
particular database system. The provider for such classes are called the Dot Net
Framework Data Providers. Microsoft itself has provided the specialized and
optimized classes for their SQL server database system. The name of these
classes start with ‘Sql’ and these are contained in System.Data.SqlClient
namespace. Similarly, Oracle has also provided its classes (driver) optimized for
Oracle DB System. Microsoft has also provided the general classes which can
connect your application to any OLE supported database server. The name of
these classes start with ‘OleDb’ and these are contained in System.Data.OleDb
namespace. In fact, you can use OleDb classes to connect to SQL server or Oracle
database but using the database specific classes generally provides optimized
performance.
Class Description
Connection Represents a connection to the database system
Represents SQL query or command to be executed at the database
Command
management system
A class that connects to the database system, fetch the record and fill the
DataAdapter dataset. It contains four different commands to perform database
operations; Select, Update, Insert, Delete.
DataReader A stream that reads data from the database in connected design
Parameter Represents a parameter to a stored procedure
What is a dataset?
A dataset is the local repository of the data used to store the tables and
disconnected record set. When using disconnected architecture, all the updates
are made locally to dataset and then the updates are performed to the database
as a batch.
This query is used to select certain columns of certain records from a database
table.
selects all the fields of all the records from the table name ‘emp’
selects the fields empno and ename of all records from the table name ‘emp’
SELECT * from emp where empno < 100
selects all those records from the table name ‘emp’ that have the value of the
field empno less than 100
selects all those records from the table name ‘article’ and ‘author’ that have same
value of the field authorId
inserts a record to emp table and set its empno field to 101 and its ename field to
‘John Guttag’
updates the record whose empno field is 101 by setting its ename field to ‘Eric
Gamma’
This query is used to delete the existing record(s) from the database table
deletes the record whose empno field is 101 from the emp table
Class Description
Connection Represents a connection to the database system
Represents SQL query or command to be executed at the database
Command
management system
A class that connects to the database system, fetch the record and fill the
DataAdapter dataset. It contains four different commands to perform database
operations; Select, Update, Insert, Delete.
DataReader A stream that reads data from the database in connected design
Parameter Represents a parameter to a stored procedure
• Dot Net Framework data provider for Microsoft SQL Server DBMS
• Dot Net Framework data provider for Oracle DBMS (available only in
Framework 1.1)
• Dot Net Framework data provider for OLEDB supporting DBMS
• Dot Net Framework data provider for ODBC supporting data sources
(available only in Framework 1.1)
C# Version
// for Sql Server
string connectionString = "server=P-III; database=programmersheaven;" +_
"uid=sa; pwd=;";
VB.Net Version
' for Sql Server
Dim connectionString As String = "server=P-III; database=programmersheaven;"
+ _ "uid=sa; pwd=;"
First of all we have defined the instance name of the server, which is P-III on my
system. Next we defined the name of the database, user id (uid) and password
(pwd). Since my SQL server doesn't have a password for the System
Administrator (sa) user, I have left it blank in the connection string. (Yes I know
this is very dangerous and is really a bad practice - never, ever use a blank
password on a system that is accessible over a network)
For Oracle Database Server, used with the Oracle data provider, we can write the
connection string like:
C# Version
string connectionString = "Data Source=Oracle8i;User Id=username;" +
"Password=pwd; Integrated Security=no;";
VB.Net Version
Dim connectionString As String = "Data Source=Oracle8i;User Id=username;" +
_
"Password=pwd; Integrated Security=no;"
For MS Access Database, used with the OLE DB data provider, we can write the
connection string like:
C# Version
// for MS Access
string connectionString = "provider=Microsoft.Jet.OLEDB.4.0;" +
"data source = c:\\programmersheaven.mdb";
VB.Net Version
' for MS Access
Dim connectionString As String = "provider=Microsoft.Jet.OLEDB.4.0;" + _
"data source =
c:\programmersheaven.mdb"
First we have defined the provider of the access database. Then we have defined
the data source which is the address of the target database.
For MS SQL Server, used with the ODBC data provider, we can write the
connection string like:
C# Version
string connectionString = "Driver={SQL
Server};Server=FARAZ;Database=pubs;Uid=sa;Pwd=;";
VB.Net Version
Dim connectionString As String = "Driver={SQL
Server};Server=FARAZ;Database=pubs;Uid=sa;Pwd=;"
C# Version
SqlConnection conn = new SqlConnection(connectionString);
VB.Net Version
Dim conn As New SqlConnection(connectionString)
For Oracle Database Server used with Oracle data provider, the connection is
created like this:
C# Version
OracleConnection conn = new OracleConnection(connectionString);
VB.Net Version
Dim conn As New OracleConnection(connectionString)
C# Version
OleDbConnection conn = new OleDbConnection(connectionString);
VB.Net Version
Dim conn As New OleDbConnection(connectionString)
C# Version
OdbcConnection conn = new OdbcConnection(connectionString);
VB.Net Version
Dim conn As New OdbcConnection(connectionString)
Here we have passed the connection string to the constructor of the connection
object.
C# Version
OdbcCommand cmd = conn.CreateCommand();
cmd.CommandText = "select * from authors";
VB.Net Version
Dim cmd As OdbcCommand
cmd = conn.CreateCommand()
cmd.CommandText = "select * from authors"
C# Version
// for Sql Server
SqlDataAdapter dataAdapter = new SqlDataAdapter(commandString, conn);
VB.Net Version
Dim da As New SqlDataAdapter(commandString, conn)
Here we have created a new instance of data adapter and supplied it command
string and connection object in the constructor call.
For Access, the data adapter is created like
C# Version
// for MS Access
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(commandString,
connectionString);
VB.Net Version
Dim da As New OleDbDataAdapter(commandString, connectionString)
Here we have created a new instance of data adapter and supplied it command
string and connection string in the constructor call.
C# Version
DataSet ds = new DataSet();
VB.Net Version
Dim ds As New DataSet()
Now we need to fill the DataSet with the result of the query. We will use the
dataAdapter object for this purpose and call its Fill() method. This is the step
where data adapter connects to the physical database and fetch the result of the
query.
C# Version
dataAdapter.Fill(ds, "prog");
VB.Net Version
da.Fill(ds, "prog")
Here we have called the Fill() method of dataAdapter object. We have supplied it
the dataset to fill and the name of the table (DataTable) in which the result of
query is filled.
This is all we needed to connect and fetch the data from the database. Now the
result of query is stored in the dataset object in the prog table which is an
instance of DataTable. We can get a reference to this table by using the indexer
property of dataset object’s Tables collection
C# Version
DataTable dataTable = ds.Tables["prog"];
VB.Net Version
Dim dataTable As DataTable
dt = ds.Tables("prog")
The indexer we have used takes the name of the table in dataset and returns the
corresponding DataTable object. Now we can use the tables Rows and Columns
collection to access the data in the table.
C# Version
DataTable dt = ds.Tables["student"];
string stId = dt.Rows[0]["StudentID"].ToString();
string stName = dt.Rows[0]["StudentName"].ToString();
string stDateOfBirth = dt.Rows[0][2].ToString();
VB.Net Version
Dim dt As DataTable
dt = ds.Tables("student")
stId = dt.Rows(0)("StudentID").ToString()
stName = dt.Rows(0)("StudentName").ToString()
stDateOfBirth = dt.Rows(0)(2).ToString()
Here we have retrieved various fields of the first record of the student table read
in the dataset. As you can see, we can either specify the column name in string
format or we can specify the column number in integer format. Also note that the
field value is returned in the form of Object, so we need to convert it to the string
before using it. Similarly, you need to cast variables of other data types before
using them.
C# Version
int stAge = int.Parse(dt.Rows(0)("Age").ToString());
VB.Net Version
Dim stage As Integer
stAge = Integer.Parse(dt.Rows(0)("Age").ToString())
C# Version
dataAdapter.Update(ds, "student");
ds.AcceptChanges();
VB.Net Version
da.Update(ds, "student")
ds.AcceptChanges()
Here ‘da’ is the reference to the data adapter object, ‘ds’ is the reference to the
dataset, and ‘student’ is the name of table we want to update.
Note: For the next four FAQs, we will demonstrate sample applications. For these
applications to work, you need following database and tables created in your
database server. A database named ‘ProgrammersHeaven’ is created. It has a
table named ‘Article’. The fields of the table ‘Article’ are
The ‘ProgrammersHeaven’ database also contains a table named ‘Author’ with the
following fields
The dataTable object will be used to reference the table returned as a result of
the query. The currRec and totalRec integer variables are used to keep track of
the current record and total records in the table.
Loading table
/*string connectionString =
"provider=Microsoft.Jet.OLEDB.4.0;" +
"data source =
c:\\programmersheaven.mdb";*/
// for MS Access
"article.authorId as
authorId, " +
"name, lines,
dateOfPublishing " +
"FROM " +
"WHERE " +
"author.authorId =
article.authorId";
// for MS Access
dataTable = ds.Tables["prog"];
currRec = 0;
totalRec = dataTable.Rows.Count;
FillControls();
btnNext.Enabled = true;
btnPrevious.Enabled = true;
In the start, we have created the connection, data adapter and filled the dataset
object which we have discussed earlier. It should be noted that we have
commented the code for OleDb provider (MS-Access) and are using the SQL
Server specific code. If you like to use Access database, you can simply comment
the SQL server code and de-comment the Access code.
Next we assigned the data table resulted from query to the dataTable object
which we declared at class level, assigned zero to currRec variable and assigned
the number of rows in the dataTable to totalRec variable
dataTable = ds.Tables["prog"];
currRec = 0;
totalRec = dataTable.Rows.Count;
Then we called the FillControls() method which fills the controls (text boxes) on
the form with the current record of table “prog”. Finally we have enabled the Next
and Previous Button
The FillControls() method in our program fills the controls on the form with the
current record of the data table. The method is defined as
which is equivalent to
txtArticleId.Text = dataTable.Rows[currRec]["artId"].ToString();
Hence when you start the application and press the LoadTable button, you will see
the following output
Here we decrement the currRec variable and check if has crossed the first record
and if it has then we move it to the last record. Once again, we call the
FillControls() method to display the current record. Now you can navigate through
the records using the Next and Previous buttons.
• The Data Adapter class (SqlDataAdapter) has properties for each of the
insert, update and delete commands. First of all we need to prepare the
command (SqlCommand) and add it to the data adapter object. The
commands are simple SQL commands with parameters. You may use the
Visual Studio .Net designer to easily create these commands.
• Secondly we need to add parameters to these commands. The parameters
are simply the names of the data table fields involved in the particular
command. Visual Studio .Net also build it for you in its Data Adapter
configuration wizard.
• The two steps described above are done only once in the application. For
each insert, update and delete; we insert, update and delete the
corresponding data row (DataRow) of the data table (DataTable) object.
• After any update we call the Update() method of the data adapter class by
supplying to it, the dataset and table name as parameters. This updates
our local dataset.
• Finally we call the AcceptChanges() method of the dataset object to store
the changes in the dataset to the physical database.
C# Version
SqlConnection conn = new SqlConnection("server=FARAZ;
database=programmersheaven; uid=sa; pwd=;");
string cmdStr = "select * from article";
SqlDataAdapter da = new SqlDataAdapter(cmdStr, conn);
VB.Net Version
Dim conn As New SqlConnection("server=FARAZ; database=programmersheaven;
uid=sa; pwd=;")
da.InsertCommand = cmdBuilder.GetInsertCommand()
da.UpdateCommand = cmdBuilder.GetUpdateCommand()
da.DeleteCommand = cmdBuilder.GetDeleteCommand()
C# Version
DataTable dt = ds.Tables["Article"];
dt.Rows[2]["lines"] = 600;
da.Update(ds, "Article");
VB.Net Version
Dim dt = ds.Tables("Article")
dt.Rows(2)("lines") = 700
da.Update(ds, "Article")
Here ‘da’ and ‘ds’ are the references of the DataAdapter and DataSet objects
respectively.
How do I update the physical database with the
changes in the dataset?
You can update the physical database by calling the AcceptChanges() method of
the data set.
C# Version
DataTable dt = ds.Tables["Article"];
dt.Rows[2]["lines"] = 600;
da.Update(ds, "Article");
ds.AcceptChanges();
VB.Net Version
Dim dt = ds.Tables("Article")
dt.Rows(2)("lines") = 700
da.Update(ds, "Article")
ds.AcceptChanges()
Here ‘da’ and ‘ds’ are the references of the DataAdapter and DataSet objects
respectively.
C# Version
DataTable dt = ds.Tables["Article"];
dt.Rows[2]["lines"] = 600;
da.Update(ds, "Article");
ds.AcceptChanges();
VB.Net Version
Dim dt = ds.Tables("Article")
dt.Rows(2)("lines") = 700
da.Update(ds, "Article")
ds.AcceptChanges()
C# Version
DataTable dt = ds.Tables["Article"];
// Insert
DataRow dr = dt.NewRow();
dr[0] = 4;
dr[1] = "MFC Programming";
dr[2] = "VC++ MFC Library";
dr[3] = 3;
dr[4] = 3000;
dr[5] = DateTime.Parse("8/14/1999");
dt.Rows.Add(dr);
da.Update(ds, "Article");
ds.AcceptChanges();
VB.Net Version
Dim dt As DataTable
dt = ds.Tables("Article")
' Insert
Dim dr As DataRow
dr = dt.NewRow()
dr(0) = 4
dr(3) = 3
dr(4) = 3000
dr(5) = DateTime.Parse("8/14/1999")
dt.Rows.Add(dr)
da.Update(ds, "Article")
ds.AcceptChanges()
C# Version
DataTable dt = ds.Tables["Article"];
// Delete
DataRow dr = dt.Rows[3];
dr.Delete();
da.Update(ds, "Article");
ds.AcceptChanges();
VB.Net Version
Dim dt As DataTable
dt = ds.Tables("Article")
' Delete
Dim dr As DataRow
dr = dt.Rows(3)
dr.Delete()
da.Update(ds, "Article")
ds.AcceptChanges()
C# Version
string connString = "server=FARAZ; database=programmersheaven;" +
"uid=sa; pwd=";
SqlConnection conn = new SqlConnection(connString);
conn.Open();
VB.Net Version
Dim connString As String = "server=siraj;
database=programmersheaven;" + _
"uid=sa; pwd="
Dim conn As New SqlConnection(connString)
conn.Open()
Then you create a command using this connection and the command text.
C# Version
string cmdString = "select * from author";
SqlCommand cmd = new SqlCommand(cmdString, conn);
VB.Net Version
Dim cmdString As String = "select * from author"
Dim cmd As New SqlCommand(cmdString, conn)
Then you execute the command with the command object’s ExecuteReader()
method. The ExecuteReader method returns the object of type IDataReader
C# Version
SqlDataReader reader = cmd.ExecuteReader();
VB.Net Version
Dim reader As SqlDataReader = cmd.ExecuteReader()
Now you read the individual records using this data reader. To advance to the
next record, you call its Read() method which returns Boolean to indicate if there
exists a next row. If the DataReader’s Read() method returns true then the
DataReader acts as a database row (record). Now you can access the fields of this
particular row specifying the column names (or integral indexes) in its indexers.
C# Version
while(reader.Read())
{
txtData.Text += reader["authorId"].ToString();
txtData.Text += ", ";
txtData.Text += reader["name"].ToString();
txtData.Text += "\r\n";
}
VB.Net Version
While reader.Read()
txtData.Text += reader("authorId").ToString()
txtData.Text += ", "
txtData.Text += reader("name").ToString()
txtData.Text += vbCrLf
End While
Finally, you need to close the database connection opened before performing the
database operation (SELECT, in our case)
C# Version
conn.Close();
VB.Net Version
conn.Close()
C# Version
string connString = "server=siraj; database=programmersheaven;" +
"uid=sa; pwd=";
SqlConnection conn = new SqlConnection(connString);
string cmdString = "select * from author";
SqlCommand cmd = new SqlCommand(cmdString, conn);
conn.Open();
while(reader.Read())
{
txtData.Text += reader["authorId"].ToString();
txtData.Text += reader["name"].ToString();
txtData.Text += "\r\n";
conn.Close();
VB.Net Version
Dim connString As String = "server=siraj;
database=programmersheaven;" + _
"uid=sa; pwd="
Dim conn As New SqlConnection(connString)
Dim cmdString As String = "select * from author"
Dim cmd As New SqlCommand(cmdString, conn)
conn.Open()
While reader.Read()
txtData.Text += reader("authorId").ToString()
txtData.Text += reader("name").ToString()
txtData.Text += vbCrLf
End While
conn.Close()
C# Version
string connString = "server=FARAZ; database=programmersheaven;" +
"uid=sa; pwd=";
SqlConnection conn = new SqlConnection(connString);
// INSERT Query
string cmdString ="INSERT INTO Author " +
"(authorId, name) " +
"VALUES(3, 'Anders Hejlsberg')";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
VB.Net Version
Dim connString As String = "server=FARAZ;
database=programmersheaven;" + _
"uid=sa; pwd="
Dim conn As New SqlConnection(connString)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
C# Version
string connString = "server=FARAZ; database=programmersheaven;" +
"uid=sa; pwd=";
SqlConnection conn = new SqlConnection(connString);
// UPDATE Query
string cmdString = "UPDATE Author " +
"SET name = 'Grady Booch' " +
"WHERE authorId = 3";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
VB.Net Version
Dim connString As String = "server=FARAZ;
database=programmersheaven;" + _
"uid=sa; pwd="
Dim conn As New SqlConnection(connString)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
C# Version
string connString = "server=FARAZ; database=programmersheaven;" +
"uid=sa; pwd=";
SqlConnection conn = new SqlConnection(connString);
// DELETE Query
string cmdString = "DELETE FROM Author " +
"WHERE authorId = 3";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
VB.Net Version
Dim connString As String = "server=FARAZ;
database=programmersheaven;" + _
"uid=sa; pwd="
Dim conn As New SqlConnection(connString)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
We strongly recommend the readers to use the references of these interface type
to perform the database operations wherever possible. Using these, you can write
a code that is data provider independent. Consider a data access module which is
supplied the database connection and which performs the database operations
using this connection. This module does not know which data provider the
connection belongs and uses the interface approach. Following code demonstrate
this data access module
C# Version
internal class DataAccessModule
{
private IDbConnection conn;
private IDbCommand cmd;
this.conn = conn;
cmd = conn.CreateCommand();
conn.Open();
return reader["value"].ToString();
else
return null;
// more functions...
VB.Net Version
Friend Class DataAccessModule
Me.conn = conn
cmd = conn.CreateCommand()
conn.Open()
End Sub
Return reader("value").ToString()
Else
Return Nothing
End If
End Function
End Class
The name of stored procedure is UpdateProc and it has the input parameters for
each of the fields of our Article table. The query to be executed when the stored
procedure is run updates the record with the supplied primary key (@artId) using
the supplied parameters. It is very similar to the code we have written to initialize
command in the previous example and we hope you don’t have any problem in
understanding this even you are not familiar with stored procedure.
The stored procedure above is named InsertProc and is very similar to the
UpdateProc except that here we are using the INSERT SQL statement instead of
the UPDATE command.
That’s it! The sample code to use with data adapter is:
C# Version
// Preparing Insert SQL Command
SqlCommand insertCommand = new SqlCommand("InsertProc", conn);
insertCommand.CommandType = CommandType.StoredProcedure;
dataAdapter.InsertCommand = insertCommand;
insertCommand.UpdatedRowSource = UpdateRowSource.None;
...
VB.Net Version
' Preparing Insert SQL Command
Dim insertCommand = New SqlCommand("InsertProc", conn)
insertCommand.CommandType = CommandType.StoredProcedure
dataAdapter.InsertCommand = insertCommand
insertCommand.UpdatedRowSource = UpdateRowSource.None
VB.Net Version
Dim conn As IDbConnection
conn = New SqlConnection();
...
Dim cmd As IDbCommand
cmd = new OracleCommand();
• Do not write the connection string in your code as it may change. Either
write it in a text file or an xml file and read it on the application startup.
For security purposes, you may also write the encrypted connection string
in the text/xml file
• Try to use the stored procedures wherever possible especially when you
are to write a series of queries whose individual results are not required to
be used in the code in between this series of queries.
• Do not use the complex queries in the source code. If the query is getting
complex, try to make the views inside the database server and use the
views instead.
• Practice using the transactions when it makes sense, especially with error
handling codes
• Put special consideration in the error handling code. The database
operation may fail due to various reasons such as invalid connection
string, invalid table/field name in the query, database server failure,
connection failure, too many connections on the server or the server busy,
invalid query, etc You need to consider all these while writing the code for
error handling.
• Using Visual Studio.Net’s debugger is a very good and useful practice to
find the possible errors. Remember, Ado.Net exception messages are not
much useful (or quite vague) in general for debugging; hence the use of
watch and quick watch debugger windows is extremely useful and helpful
in when debugging the code.
• When using dataset and disconnected architecture, we don’t update the
data source (by calling DataAdapter’s Update() method and DataSet’s
AcceptChanges() method) for each update. Instead we make the changes
local and update all these changes later as a batch. This provides
optimized use of network bandwidth. BUT, this off course is not a better
option when multiple users are updating the same database. When
changes are not to be done locally and need to be reflected at database
server at the same time, it is preferred to use the connected oriented
environment for all the changes (UPDATE, INSERT and DELETE) by calling
the ExecuteNonQuery() method of your command (SqlCommand or
OleDbCommand) object.
• Disconnected data access is suited most to read only services. In common
practice clients are often interested in reading and displaying data. In this
type of situation, the disconnected data access excels as it fetches the
whole data in a single go and store it in the local buffer (dataset). This
local storage of data eliminates the need of staying connecting to the
database and fetching single record at a time. On the down side,
disconnected data access architecture is not designed to be used in the
networked environment where multiple users are updating data
simultaneously and each of them needs to be aware of current state of
database at any time (e.g., Airline Reservation System).
What is data grid and what is the use of it?
Data Grid is the standard control for viewing data in .Net environment. A data
grid control is represented in .Net by System.Windows.Forms.DataGrid class. The
data grid control can display the data from a number of data sources e.g. data
table, dataset, data view and array.
C# Version
private void btnLoadData_Click(object sender, System.EventArgs e)
{
string connectionString = "server=FARAZ;
database=programmersheaven;" +
"uid=sa; pwd=;";
SqlConnection conn = new SqlConnection(connectionString);
string cmdString = "SELECT * FROM article";
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmdString, conn);
DataSet ds = new DataSet();
dataAdapter.Fill(ds, "article");
dgDetails.SetDataBinding(ds, "article");
VB.Net Version
Private Sub btnLoadData_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnLoadData.Click
"uid=sa; pwd=;"
dataAdapter.Fill(ds, "article")
dgDetails.SetDataBinding(ds, "article")
End Sub
Here we first created data adapter and filled the data set using it as we used to
do in other applications. The only new thing is the binding of “article” table to the
data grid control which is done by calling the SetDataBinding() method of the
DataGrid class. The first parameter of this method is the dataset while the second
parameter is the name of table in the dataset.
C# Version
dgDetails.SetDataBinding(ds, "article");
VB.Net Version
dgDetails.SetDataBinding(ds, "article")
When you execute this program and select the Load button you will see the
output presented in the previous figure.
In this example, we will use data grid to show the related records from article and
author table. In order to specify the relationship between the two tables we need
to use the DataRelation class as:
C# Version
dgDetails.SetDataBinding(ds, "article")
DataRelation relation = new DataRelation("ArtAuth",
ds.Tables["author"].Columns["authorId"],
ds.Tables["article"].Columns["authorId"]
);
VB.Net Version
Dim relation As New DataRelation("ArtAuth", _
ds.Tables("author").Columns("authorId"), _
ds.Tables("article").Columns("authorId") _
)
Here the first argument of DataRelation constructor is the name for the new
relation while second and third arguments are the columns of the tables which
will be used to relate the two tables. After creating this relationship we need to
add it to the Relations collection of the dataset.
C# Version
ds.Relations.Add(relation);
VB.Net Version
ds.Relations.Add(relation)
Hence the modified code for the Load Data button is:
C# Version
private void btnLoadData_Click(object sender, System.EventArgs e)
{
string connectionString = "server=P-III;
database=programmersheaven;" +
"uid=sa; pwd=;";
SqlConnection conn = new SqlConnection(connectionString);
dataAdapter.Fill(ds, "article");
dataAdapter.Fill(ds, "author");
ds.Tables["author"].Columns["authorId"],
ds.Tables["article"].Columns["authorId"]
);
ds.Relations.Add(relation);
dgDetails.DataSource = dv;
VB.Net Version
Private Sub btnLoadData_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnLoadData.Click
Dim connectionString As String = "server=P-III;
database=programmersheaven;" + _
"uid=sa; pwd=;"
dataAdapter.Fill(ds, "article")
dataAdapter.Fill(ds, "author")
ds.Tables("author").Columns("authorId"), _
ds.Tables("article").Columns("authorId") _
ds.Relations.Add(relation)
dgDetails.DataSource = dv
End Sub
In the above code we first filled the dataset with the two tables, defined the
relationship between them and then added it to the dataset. In the last two lines,
we created an instance of DataView class by supplying the parent table in its
constructor call and then set the DataSource property of data grid to this data
view.
When we compile and execute this application, the data grid will show the records
of parent table with ‘+’ button on the left of each record
When you press the ‘+’ button on the left of the record, it will expand to show the
name of relationship as a link
Now when you click the relation name, the data grid will show all the related
records in the child table
Still you can see the parent record at the top of all the rows of the child table. You
can go back to the parent table using the back arrow button (ç) at the title bar of
the data grid.
You can see from the above points that the basic issue is the identification of the
address (or connection string) of the database server. The most important point
to remember here is that the application must perform in any condition and must
not be crashed because of any condition and most of the problems (if not all)
should be handled without any change in the code or any update patch
installation
• The easiest and very sound solution is to provide the database script to
create necessary database and tables along with the installation and ask
your user to run the script on the target database server to create the
required database. Then ask the user to supply the connection string at
the installation setup time.
• You can create the database with the installation by executing the
database creation script with the installation. But before this, you have to
ask the user the location (the computer on the network) where the
database server exists, and the user name, password to login to the
database.
• The connection string should be stored in a text or binary or xml file. You
can also encrypt the connection string before writing it to the file. The
application, thus, is required to decrypt and load the connection string in
the memory at each startup.
• The application should load the connection string at each startup and
attempt to connect to the database. If the connection attempt fails then it
should inform the user that the database is not available and ask the user
to setup the database and try again. The application should also allow the
user to change the database connection string any time and, it the
application logic permits, let the user specify to work without database. If
the user specifies a new connection string during the application startup or
regular execution, the application should save it for later use.
• One solution to the schema changed problem is to use views and stored
procedure wherever possible. But if this is not done or the change is too
big to be catered by the views and/or stored procedure then you can
supply a new data access module update (a new DLL may be). For this
reason, it is advised to separate the data access code in a separate
physical and logical module (or assembly in .Net language) so you can
change it without affecting the overall application. But when using this, the
interface (the method signatures) should be made that abstract that they
does not exactly map to the physical database schema but to the logical
schema. Finally, if the database schema change is major (which is not a
very good sign for the application overall design) then there is no solution
but to change the code and ship the installation again!!!
If you are using the database specific provider classes (like those from
System.Data.SqlClient or System.Data.OracleClient) then you can generate the
connection string easily by taking the specific inputs from the user. For example,
if you are using SQL Server and the classes from the System.Data.SqlClient
namespace then we can ask user the SQL Server instance name, the user name,
password of if he/she is using the Windows Authentication to log in and the
database name.
So how you can use this dialog in your program? For this you need add a
reference to COM component ‘Microsoft OLE DB Service Component 1.0 Type
Library’ which should be available if you have installed Microsoft ActiveX Data
Components. Once you have added the component, you can show the Data Link
Properties dialog box by making an object of type MSDASC.DataLink class and
calling its PromptNew() method.
C# Version
MSDASC.DataLinks udl = new MSDASC.DataLinksClass();
udl.PromptNew();
VB.Net Version
Dim udl As MSDASC.DataLinks
udl = New MSDASC.DataLinksClass
udl.PromptNew()
The above code will show the Data Link Properties dialog box. But how can we get
the connection string generated by the dialog box? The PromptNew() method
returns a connection type object which can be captured in an object of type
ADODB.Connection. Hence for this, add a reference to ‘adodb’ .Net assembly in
your project, and get the connection string using the ConnectionString property
of this object. The following code snippets demonstrate this:
C# Version
string connStr = "";
if(conn != null)
connStr = conn.ConnectionString;
VB.Net Version
Dim connStr As String
connStr = conn.ConnectionString
End If
You can use this code in the overrided Install() method of your project’s installer
class (the class derived from System.Configuration.Install.Installer class), and
add the project output in the ‘Custom Actions’ of the setup project.
C# Version
string connStr = "";
sw.WriteLine(connStr);
// ...
connStr = sr.ReadLine();
VB.Net Version
Dim connStr As String = ""
sw.WriteLine(connStr)
' ...
connStr = sr.ReadLine()
C# Version
string connStr = "";
XmlNode xn = xmlDoc.CreateNode(XmlNodeType.Element,
"ConnectionString", "");
xn.InnerText = connStr;
xmlDoc.AppendChild(xn);
xmlDoc.Save(@"C:\ConnectionString.xml");
// ...
xmlDoc.Load(@"C:\ConnectionString.xml");
XmlNode xn = xmlDoc.SelectSingleNode("ConnectionString");
connStr = xn.InnerText;
VB.Net Version
Dim connStr As String = ""
Dim xn As XmlNode
xn.InnerText = connStr
xmlDoc.AppendChild(xn)
xmlDoc.Save("C:\ConnectionString.xml")
' ...
xmlDoc.Load("C:\ConnectionString.xml")
Dim xn As XmlNode
xn = xmlDoc.SelectSingleNode("ConnectionString")
connStr = xn.InnerText
The first step, then, is to add an installer class. The easiest way to do is to right
click the project icon in the solution explorer and select ‘Add New Item…’ and in
the pop-up window, select Installer class, name it appropriately and select ‘Open’
button to add it. Now right click the newly added installer class and select view
code. You will notice that this new class is automatically inherited from the
System.Configuration.Install.Installer class
The only thing you need to do now in this class is to override the Install() method
of the base class, write the code you want to execute when the installation setup
is executed. We have written the code to display the Data Link Properties dialog
box and save the resulted connection string into an xml file, so later the
application can use it.
if(conn != null)
connStr = conn.ConnectionString;
XmlNode xn = xmlDoc.CreateNode(XmlNodeType.Element,
"ConnectionString", "");
xn.InnerText = connStr;
xmlDoc.AppendChild(xn);
xmlDoc.Save(@"C:\ConnectionString.xml");
This is all for the setup, we have added a button to our database deployment
application form which displays the connection string in a message box. It
retrieves the connection string from the xml file generated by the installation
setup program.
xmlDoc.Load(@"C:\ConnectionString.xml");
XmlNode xn = xmlDoc.SelectSingleNode("ConnectionString");
connStr = xn.InnerText;
Now the application is ready. We will start building our setup project. For this, add
a new ‘Setup and Deployment’ project to the solution by right clicking the solution
and selecting ‘Add New Project…’ in the pop-up window, selecting the ‘Setup
Project’ from the ‘Setup and Deployment Projects’ section. Once the setup project
is added to the solution, right click it in the solution explorer and select View--
>File System. Here right click the application folder icon and select Project Output
--> Primary Out put of your data access project. This will automatically add the
project dependencies. Now right click the ‘Primary Output of your project’ and
create its short cut. Copy this shortcut to the Desktop folder and the User
Program Menu and rename shortcut appropriately.
Now to ask the setup project run our custom installation code (we have written in
the Installer class in the data access application), we need to add the primary
output of our project to the custom actions of the setup project. To do this, right
click the setup project in the solution explorer, and select View --> Custom
Actions. Here right click ‘Install’ and select ‘Add Custom Action’. In the popup
window, select the primary output of the database access application from the
application folder and click OK.
This is all we need to do! Rebuild the solution and remove any minor bugs (if they
do popup). When your setup project will be built, it will generate a Setup.exe file
in its debug (or release folder depending on the project configuration). Run this
setup.exe to install this application. The setup will ask you the connection string
and save it in the xml file.
After installation is complete, run the application using its desktop icon. When you
will click the button on the form, it will read the connection string from the xml
file and display it in the message box.
How to use relation objects in a dataset?
DataSet's that contain multiple DataTable objects can use DataRelation
objects to relate one table to another. Adding a DataRelation to a DataSet adds
by default a UniqueConstraint to the parent table and a ForeignKeyConstraint to
the child table.
The code sample below creates a DataRelation using two DataTable objects in
a DataSet. Each DataTable contains a column named CustID which serves as a
"relation" between two the DataTable objects. The example adds a single
DataRelation to the Relations collection of the DataSet. The first argument in the
sample specifies the name of the DataRelation being created. The second
argument sets the parent DataColumn and the third argument sets the child
DataColumn.
custDS.Relations.Add("CustOrders",
custDS.Tables["Customers"].Columns["CustID"],
custDS.Tables["Orders"].Columns["CustID"]);
OR
parentCol = DataSet1.Tables["Customers"].Columns["CustID"];
childCol = DataSet1.Tables["Orders"].Columns["CustID"];
DataRelation relCustOrder;
parentCol, childCol);
DataSet1.Relations.Add(relCustOrder);
DataReader Vs DataSet?
The ADO.NET DataReader is used to retrieve "read-only" / "forward-only" data
from a database. Using the DataReader increases application performance and
reduces system overheads. This is due to one row at a time is stored in memory.
You create a DataReader by calling Command.ExecuteReader after creating
an instance of the Command object.
The following line of code is used to retrieve rows from a data source.
The Read method of the DataReader object is used to obtain a row from the
results of the query, like so.
(myReader.Read()) Console.WriteLine("\t{0}\t{1}",
myReader.GetInt32(0), myReader.GetString(1));
myReader.Close();
The DataAdapter acts as a bridge between a DataSet and a data source for
retrieving and saving data. The DataAdapter provides this bridge by "mapping
Fill". Which changes the data in the DataSet to match the data in the data
source. Upon this an Update occurs, which changes the data in the data source
to match the data in the DataSet.
Set the query string as the name of the stored procedure and then set the
CommandType to be CommandType.StoredProcedure. Below is an example
of one input and one output parameter.
if(myConn.State == ConnectionState.Closed)myConn.Open();
SqlCommand myCmd = new
SqlCommand("sp_my_stored_procedure",myConn);
myCmd.CommandType = CommandType.StoredProcedure;
SqlParameter parm;
parm.Direction = ParameterDirection.Input;
myCmd.Parameters["@custid"].Value = OrderID;
SqlDbType.VarChar,50));
parm.Direction = ParameterDirection.Output;
da.SelectCommand = myCmd;
da.Fill(ds);
Conn.Open()
dapt.Fill(dst, "Table1")
DataGrid1.SetDataBinding(dst, "Table1")
Conn.Close()
Upon running the above code, Table1 from the a "Test" database will be displayed
in a DataGrid.
The working senario is a database called "Emp" with a table named "Table1" with
three columns. Also a Form with three TextBoxes and one Command Button.
Imports System.Data.OleDb
Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Dim icount As Integer
Dim str As String
Try
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\emp.mdb;Persist Security_ Info=False")
cn.Open()
str = "insert into table1 values(" & CInt(TextBox1.Text) & ",'" &
TextBox2.Text & "','" & TextBox3.Text & "')" 'string stores the command
'and CInt is used to convert number, to string
End Try
End Sub
The following code demonstrates how to connect to a ?SQL Server and display
data from the "Discounts" table in the sample database "PUBS".
Imports System.Data.SqlClient
myConnection = New
SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
'establishing connection
Try
myConnection.Open()
'opening the connection
myCommand = New SqlCommand("Select * from discounts", myConnection)
While dr.Read()
'reading from the datareader
MessageBox.Show("discounttype" & dr(0).ToString())
MessageBox.Show("stor_id" & dr(1).ToString())
MessageBox.Show("lowqty" & dr(2).ToString())
MessageBox.Show("highqty" & dr(3).ToString())
MessageBox.Show("discount" & dr(4).ToString())
'displaying the data from the table
End While
dr.Close()
myConnection.Close()
Catch e As Exception
End Try
End Sub
End Class
How to insert an image in Access Database?
The following code asks for a path of a Gif image. Then inserts the Gif image to
an Access database.
Imports System
Imports System.IO
Imports System.Data
Dim o As System.IO.FileStream
Dim r As StreamReader
Dim gifFile As String
Try
Source=Test.mdb")
Con.Open()
Cmd.ExecuteNonQuery()
Con.Close()
Catch ex As Exception
Console.Write(ex.ToString)
End Try
End Sub
End Class
A file will be inserted in the Database each time the code is executed.
ASP.NET
The script (ASP.NET scripts), logic (code behind) and presentation (view) are
separated from each other so they may evolve independently. There are much
more server controls now available in .Net including the standard calendar and
amazingly useful data grid controls. The ASP.Net web applications can now use
.NET assemblies and COM components to serve the client requests. ASP.NET
pages are now compiled contrary to the ASP pages which are interpreted by the
ISA server. Truly speaking, there is no comparison between ASP and ASP.NET...
ASP.NET simply rules!
What is ASP.NET?
ASP.NET is a powerful programming platform for developing web-based
applications and services. It comes with rich set of web controls to create
dynamic, fast and interactive web pages. Web pages built using ASP.NET are
called ASP.NET web pages or web forms. ASP.NET simplifies web development by
using WYSIWYG (what you see is what you get) editors. ASP.NET helps to build
complex web applications with the use of drag and drop control support. Visual
Studion.NET helps us to build web applications (ASP.NET) using either the C# or
VB programming language. The following features are making developers choose
ASP.NET over other technologies:
ASP.NET configures IIS to prevent direct browser access to "web.config" files. This
ensures that their values cannot become public (Attempts to access them will
cause ASP.NET to return 403: Access Forbidden). At run time, ASP.NET uses these
"web.config" configuration files to hierarchically compute a unique collection of
settings for each incoming URL target request. These settings are calculated only
once and then cached across subsequent requests. ASP.NET automatically
watches for file changes and will invalidate the cache if any of the configuration
files change.
Web services are designed for use by other programs or applications rather than
directly by end user. Programs invoking a Web service are called clients. SOAP
over HTTP is the most commonly used protocol for invoking Web services.
There are three main uses of Web services. Application integration Web services
within an intranet are commonly used to integrate business applications running
on different platforms. For example, a .NET client running on Windows 2000 can
easily invoke a Java Web service running on a mainframe or Unix machine to
retrieve data from a legacy application.
Commercial Web services focus on selling content and business services to clients
over the Internet similar to familiar Web pages. Unlike Web pages, commercial
Web services target applications as their direct users.
Example, Continental Airlines exposes flight schedules and status Web services
for travel Web sites and agencies to use in their applications. Like Web pages,
commercial Web services are valuable only if they offer services that are needed.
It makes sense to sell real-time weather information or stock quotes as a Web
service. Technology can help you add value to your services and explore new
markets. However ultimately customers pay for contents and/or business
services, not for technology.
Microsoft, IBM and Ariba also are hosting the initial deployment of the UDDI
service. This is conceptually patterned after DNS (the Internet service that
translates URLs into TCP addresses).
UDDI uses a private agreement profile of SOAP (UDDI doesn't use the SOAP
serialization format because it's not well suited to passing complete XML
documents (it's aimed at RPC style interactions). The main idea is that businesses
use SOAP APIs to register themselves with UDDI. Other businesses search the
UDDI when they want to discover a trading partner.
The Microsoft Simple Object Access Protocol (SOAP) Toolkit 2.0 includes a TCP/IP
trace utility, MSSOAPT.EXE. You use this trace utility to view the SOAP messages
sent by HTTP between a SOAP client and a service on a server. In order to use the
Trace Utility, perform the following steps on the server. Open the Web Services
Description Language (WSDL) file.
1) In the WSDL file, locate the <soap:address> element that corresponds to the
service and change the location attribute for this element to port 8080.
<http://MyServer/VDir/Service.wsdl>
to
<http://MyServer:8080/VDir/Service.wsdl>
.
2) Run MSSOAPT.exe.
3) File menu, New, Click "Formatted Trace" (if you don't want to see HTTP
headers) or click Unformatted Trace (if you want to see HTTP headers). 4) In the
Trace Setup dialog box, click OK to accept the default values.
To see all send/receive messages from a service, do the following steps on the
client.
localhost:8080
Make a note of the current host and port.
<http://MyServer/VDir/Service.wsdl>
to
<http://localhost:8080/VDir/Service.wsdl>
and make note of "MyServer". 3) On the client, run MSSOPT.exe.
4) File menu, New, and either click Formatted Trace (if you don't want to see
HTTP headers) or click Unformatted Trace (if you do want to see HTTP headers).
7) Click OK.
The HtmlInputFile class represents an HTML input control that the user will use
on the client to select a file to upload.
The HttpPostedFile class represents the uploaded file. This is obtained from the
.PostedFile property of the HtmlInputFile control.
In order to use the HtmlInputFile control, you need to add the enctype attribute
to your form tag as follows:
Tip
The /data directory is the only directory with write permissions enabled for an
anonymous user. Therefore, you will need to make sure that your code uploads
the file to the /data directory or one of its subdirectories.
How do I send an email from my ASP.NET page?
Include the System.Web.Mail.MailMessage and the System.Web.Mail.SmtpMail
classes to send email from ASPX pages.
Tip
In order to send email through your mail server, you should set the static
SmtpServer property of the SmtpMail class to mail-fwd.
However, you will probably also have application-specific values that you want to
preserve. This can be done using state management options.
• HTML Server Controls: These controls refer to the HTML elements that
can be used in server code. The HTML elements can be converted into
HTML server controls.
• ASP.NET Server controls: ASP.NET server controls are the general
controls like textbox, buttons, tables etc.
• Validation Controls: these controls are used to validate user input.
Normally these controls are attached with textboxes, checkboxes and radio
buttons to check the values entered or selected.
• USER Controls: These controls are those controls that are created by the
user and are used just like all other controls.
To use the control, drag it from the toolbox. In the properties window you will
there are three key properties:
The advertisement file is an XML file which contains information about the image
to be displayed and the page to which the user should be redirected on click.
The following example assumes there are two images named one.gif and two.gif.
Below is the XML to correspond with our
example:
<Advertisement>
<Ad>
<ImageUrl>
one.gif
</ImageUrl>
<NavigateUrl>
http://www.codepedia.com
</NavigateUrl>
<AlternateText>
The Web's fastest growing technical encyclopdia
</AlternateText>
<Impressions>
1
</Impressions>
<Keyword>
Visual Basic
</Keyword>
</Ad>
<Ad>
<ImageUrl>
two.gif
</ImageUrl>
<NavigateUrl>
http://www.programmersheaven.com
</NavigateUrl>
<AlternateText>
Where the pro's are
</AlternateText>
<Impressions>
1
</Impressions>
<Keyword>
Programming
</Keyword>
</Ad>
</Advertisements>
Drag a calendar control and a textbox from the toolbox. We will display the date
selected from the calendar control in the textbox.
End Sub
In Runtime Mode - Select a date from the calendar control. That date will now be
the .Text Value of the textbox.
All you have to make the RequiredFieldValidator work is to open the properties of
the control. Looking at two properties; ErrorMessage and ControltoValidate
specifically. The ErrorMessage property should be completed with a warning that
the field needs to be completed. Secondly, the ControltoValidate property is used
to tag which control is to be validated.
End Sub
What is a CompareValidatorControl?
CompareValidator is used to make sure that a value matches a specified value.
This control is often used when validating passwords. Important properties of this
control are .ControlToValidate and .ControlToCompare.
Run the code and enter some text in both the textboxes and click the button. If
both the TextBox values are the same then no error message will arise else an
error.
Run the code and try entering some values in the TextBox. If the value entered is
within the specified range ( 8 High, 3 Low ) then nothing happens else an error
message is displayed.
What is a RegularExpressionValidator?
RegularExpressionValidator control is used to check a value against a regular
expression. It checks whether the value of the associated input control matches
the pattern of the regular expression. This Control generally used to check
whether the entered phone number or email address matches a set format. A
notable property of this control is the ValidationExpression property, which is used
to set the validation criteria and which comes with some predefined formats.
If an existing server control almost meets your requirements but lacks some
required features, you can customize the control by deriving from it and
overriding its properties, methods, and events. If none of the existing Web server
controls (or their combinations) meet your requirements, you can create a
custom control by deriving from one of the base control classes. These classes
provide all the functionality like other Web server controls. You only need to write
the logic for the programming features you require.
If none of the existing ASP.NET server controls meet the specific requirements of
your applications, you can create either a Web user control or a Web custom
control that encapsulates the functionality you need.
The main difference between the two controls lies in ease of creation vs. ease of
use at design time. Web user controls are easy to make, but they can be less
convenient to use in advanced scenarios. Web user controls can be developed
almost exactly the same way that you develop Web Form pages.
Like Web Forms, user controls can be created in the visual designer or they can
be written with code separate from the HTML. They can also support execution
events. However, since Web user controls are compiled dynamically at run time
they cannot be added to the Toolbox and they are represented by a simple
placeholder when added to a page.
This makes Web user controls harder to use if you are accustomed to full Visual
Studio .NET design-time support, including the Properties window and Design
view previews. Also the only way to share the user control between applications is
to put a separate copy in each application, which takes more maintenance if you
make changes to the control.
Web custom controls are compiled code, which makes them easier to use but
more difficult to create. Web custom controls must be authored in code. Once you
have created the control you can add it to the Toolbox and display it in a visual
designer with full Properties window support and all the other design-time
features of ASP.NET server controls. In addition you can install a single copy of
the Web custom control in the global assembly cache and share it between
applications, which make maintenance easier.
Windows Forms
• The form designer allows you to design the User Interface (UI) of the
applications by simple drag and drop of the controls.
• The Properties window allows you to set different properties for form and a
number of windows controls
• The Intellisense (help completing the syntax as you place dot (.) with
objects, enumeration and namespace and when you create new objects)
• Project and solution management with solution explorer that helps
manage applications consisting of multiple files, which is what usually
happens
• Standard debugger that allows you to debug your program by putting
break points for observing run-time behavior of the variables and objects
in the program
• Hot compiler that checks the syntax of your code as you type it and report
any errors present
• Dynamic Help on number of topics using Microsoft Development Network
(MSDN) Library
• Compilation and building applications
• Execution of your application with/without debugger
• Deploying your .NET application over the Internet or on CDs
C# Version
WinForm Architecture As stated earlier, .NET provides WinForm and other controls
through base classes in the System.Windows.Forms namespace. The class
System.Windows.Forms.Form is the base class of all WinForms in .NET. In order
to design a windows application, we need: 1. Create a Windows Application
project in Visual Studio.NET or add references to System.Windows.Forms and
System.Drawing to your current project. If you are not using Visual Studio at all,
use /reference option of the command line compiler to add these assemblies. 2.
Write a new class to represent the WinForm and derive it from
System.Windows.Forms.Form class as
class MyForm : System.Windows.Form
{
...
}
3. Instantiate various controls, set their appropriate properties and add these to
MyForm’s Controls collection. 4. Write another class containing the Main()
method. In the Main() method, call the System.Application.Run() method by
supplying it an instance of MyForm.
class Test
{
static void Main()
{
Application.Run(new MyForm());
}
}
The Application.Run() method registers your form as a windows application in the
operating system so that it may receive event messages from the Windows
Operating System.
VB.NET Version
WinForm Architecture As stated earlier, .NET provides the WinForm and other
controls through base classes in the System.Windows.Forms namespace. The
class System.Windows.Forms.Form is the base class of all WinForms in .NET. In
order to design a windows application, we need to: 1.Create a Windows
Application project in Visual Studio.NET, or add references to
System.Windows.Forms and System.Drawing to your current project. If you are
not using Visual Studio at all, use the /reference option of the command line
compiler to add these assemblies. 2. Write a new class to represent the WinForm
and derive it from the
System.Windows.Forms.Form class:
Public Class MyForm
Inherits System.Windows.Forms.Form
…
End Class
3. Instantiate various controls, set their appropriate properties and add these to
MyForm's Controls collection. 4. Write another class containing the Main()
method. In the Main() method, call the System.Application.Run() method,
supplying it with an instance of
MyForm.
Class Test
Public Sub Main()
Application.Run(New MyForm())
End Sub
End Class
C# Version
Building the “Hello WinForm” Application Let’s now build our first windows
application called “Hello WinForm”. The application will present a simple window
with “Hello WinForm” greeting at the center. The source code of the program is:
using System;
using System.Windows.Forms;
using System.Drawing;
namespace CSharpSchool
class Test
Application.Run(new MyWindow());
using System;
using System.Windows.Forms;
using System.Drawing;
Later, we derived a new class ‘MyWindow’ from the Form class defined in
System.Windows.Forms
class MyWindow : Form
{
...
}
In the constructor of MyWindow, we specified the size and title of the form. The
size is defined using the System.Drawing namespace’s Size class. We passed two
integers to the constructor of Size to specify the width and the height of the form.
Next in the constructor, we created a text label and added it to the Controls
collection of the Form. A text label is used to write some text on the form. The
System.Windows.Forms.Label class is used to create a text label in windows
applications. We set the text of the Label using its Text property which is of string
type. All the controls contained by a form must be added to its Controls
collection; hence we have also added our label to this collection.
this.Controls.Add(lblGreeting);
Finally, we have created a Test class containing the Main() method. In the Main()
method, we have instantiated the MyWindow class and passed its reference to the
Application.Run() method so it may receive messages from the Windows
Operating System.
When we execute the above code, the following screen is presented as output
To close the application, press the close button on the title bar.
Adding Event Handling Let’s now add a button labeled ‘Exit’ to the form. The ‘Exit’
button will close the application when it is clicked. In .NET, Push Buttons are
instances of the System.Windows.Forms.Button class. To associate some action
with the button click, we need to create an event handler and register (or add) it
to the Button’s Click event. Following is the code for this modified application
using System;
using System.Windows.Forms;
using System.Drawing;
namespace CSharpSchool
class Test
Application.Run(new MyWindow());
}
class MyWindow : Form
// Form
this.StartPosition =
FormStartPosition.CenterScreen;
// Label
// Button
btnExit.Text = "Exit";
Application.Exit();
}
In the constructor of MyWindow, first we have set certain properties of the Form.
In this code, we have also used the StartPosition property of the Form, which sets
the start up position of the form on the screen. The type of this property is an
enumeration called ‘FormStartPosition’. We have set the start position of the form
to the center of the screen.
The new inclusion in the code is the Exit button called ‘btnExit’. We have created
the button using the base class System.Windows.Forms.Button. Later, we set
various properties of the button like its text label (Text), its Location and its Size.
Finally, we have created an event handler method for this button called
BtnExitOnClick(). In the BtnExitOnClick() method, we have written the code to
exit the application. We have also registered this event handler to the btnExit’s
Click event (To understand the event handling in C#, see lesson 10 of the C#
school). In the end, we have added a label and button to the form’s Controls
collection. Note that this time we have used AddRange() method of form class to
add an array of controls to the Controls collection of form. This method takes an
array of type Control as its parameter.
Now you can press either the Exit Button or the close button at title bar to exit
the application.
VB.NET Version
Building the "Hello WinForm" Application Let's build our first windows
application, which we will call "Hello WinForm". The application will present a
simple window with a "Hello WinForm" greeting at the center. The source code of
the program is:
Imports System
Imports System.Windows.Forms
Imports System.Drawing
Class Test
Application.Run(New MyForm())
End Sub
End Class
Class MyForm
Inherits Form
MyBase.new()
Me.Controls.Add(lblGreeting)
End Sub
End Class
Imports System
Imports System.Windows.Forms
Imports System.Drawing
From the '.NET' tab of the Add Reference Dialog box, select the
System.Windows.Forms.dll and System.Drawing.dll and select OK. This completes
the process of adding references to assemblies in your project. Lets go back to
our sample application. Later, we derived a new class, 'MyForm', from the Form
class defined in
System.Windows.Forms.
Class MyForm
Inherits Form
...
End Sub
End Class
In the constructor of MyForm, we specified the size and title of the form (by
setting the size and text properties). The size is defined using the
System.Drawing namespace's Size class. We passed two integers to the
constructor of Size to specify the width and the height of the form.
Next in the constructor, we created a text label and added it to the Controls
collection of the Form. A text label is used to write some text on the form. The
System.Windows.Forms.Label class defines a text label in a Windows application.
We set the text of the Label using its Text property, which is of the string type. All
the controls contained by a form must be added to its Controls collection; hence
we have also added our label to this collection.
Me.Controls.Add(lblGreeting)
End Sub
Finally, we have created a Test class containing the Main() method. In the Main()
method, we have instantiated the MyForm class and passed its reference to the
Application.Run() method so it may receive messages from the Windows
Operating System. When we execute the above code, the following screen is
displayed: To close the application, press the close button on the title bar.
Adding Event Handling Let's now add a button labeled 'Exit' to the form. The 'Exit'
button will close the application when it is clicked. In .NET, Push Buttons are
instances of the System.Windows.Forms.Button class. To associate some action
with the button click, we need to create an event handler and register (or add) it
to the Button's Click event. Below is the code for this application.
Imports System
Imports System.Windows.Forms
Imports System.Drawing
Class Test
Application.Run(New MyForm())
End Sub
End Class
Class MyForm
Inherits Form
MyBase.new()
' Form
' Label
btnExit.Text = "Exit"
End Sub
Application.Exit()
End Sub
End Class
In the constructor of MyForm, first we have set certain properties of the Form. In
this code, we have also used the StartPosition property of the Form, which sets
the position of the form on the screen when the application starts. The type of
this property is an enumeration called 'FormStartPosition'. We have set the start
position of the form to the center of the screen. The new inclusion in the code is
the Exit button called 'btnExit'. We have created the button using the base class
System.Windows.Forms.Button. Later, we have set various properties of the
button, specifically its text label (Text), its Location and its Size. Finally, we have
created an event handler method for this button called BtnExitOnClick(). In the
BtnExitOnClick() method, we have written the code to exit the application. We
have also subscribed this event handler to the btnExit's Click event (To
understand the event handling in VB.Net, see lesson 10 of the VB.Net school). In
the end, we have added both the label and the button to the form's Controls
collection. Note that this time we have used the AddRange() method of form class
to add an array of controls to the Controls collection of form. This method takes
an array of type Control as its parameter. When the code is run, the following
window will be displayed: Now you can press either the Exit Button or the close
button at title bar to exit the application.
Alternate procedure for Event Handling – Using the ‘Handles’ Keyword Note that
in the previous code, we subscribed Exit buttons event handler using the
‘AddHandler’ keyword. We can also do this using the ‘Handles’ keyword with the
Event Handler method. But to use the ‘Handles’ keyword, the Exit button needs to
be instance variable of the form class defined with the ‘WithEvents’ keyword. The
complete source code of the MyForm class is
Class MyForm
Inherits Form
MyBase.new()
' Form
' Label
' Button
btnExit.Text = "Exit"
End Sub
Public Sub BtnExitOnClick(ByVal sender As Object, ByVal e As EventArgs)
Handles btnExit.Click
Application.Exit()
End Sub
End Class
This procedure of event handling (using the ‘Handles’ keyword) is usually followed
by Visual Studio.NET standard code for Form based applications (Windows and
Web Applications)
For example, to add the event handling code for the Exit button in the Hello
WinForm application (demonstrated in FAQ 5), simply double click the Exit button
in the designer. It will create a new event handler for the Exit button’s Click event
and take you to the source code as shown in the following figure
C# Version
Write the code to close the application (Application.Exit()) in the event handler.
The IDE in fact has not only created the event handler but also has registered it
with the Exit button’s Click event.
C# Version
Adding Event Handling A control exposes an event by defining its delegate. We
can add our own event handler for the event by writing an event handler method
and adding it to the event’s delegate.
For example, add a button labeled ‘Exit’ to the form of FAQ 8. The ‘Exit’ button
will close the application when it is clicked. In .Net, Push Buttons are instances of
the System.Windows.Forms.Button class. To associate some action with the
button click, we need to create an event handler and register (or add) it to the
Button’s Click event. Following is the code for this modified application
using System;
using System.Windows.Forms;
using System.Drawing;
namespace CSharpSchool
class Test
Application.Run(new MyWindow());
// Form
this.StartPosition =
FormStartPosition.CenterScreen;
// Label
// Button
Application.Exit();
We have highlighted the interested parts in the above code by bold formatting.
We have created the Exit button called ‘btnExit’ using the class
System.Windows.Forms.Button. Later, we set various properties of the button like
its text label (Text), its Location and its Size. Finally, we have created an event
handler method for this button called BtnExitOnClick(). In the BtnExitOnClick()
method, we have written the code to exit the application. We have also registered
this event handler to the btnExit’s Click event (To understand the event handling
in C#, see lesson 10 of the C# school). In the end, we have added a label and
button to the form’s Controls collection.
Now you can press either the Exit Button or the close button at title bar to exit
the application.
VB.NET Version
Adding Event Handling A control exposes an event by defining its ‘delegate’.
We can add our own event handler for the event by writing an event handler
method and adding it to the event's delegate. Let's add a button labeled 'Exit' to
the form. The 'Exit' button will close the application when it is clicked. In .Net,
Push Buttons are instances of the System.Windows.Forms.Button class. To
associate some action with the button click, we need to create an event handler
and register (or add) it to the Button's Click event. Below is the code for this
application.
Imports System
Imports System.Windows.Forms
Imports System.Drawing
Class Test
Application.Run(New MyForm())
End Sub
End Class
Class MyForm
Inherits Form
MyBase.new()
' Form
' Label
' Button
End Sub
Application.Exit()
End Sub
End Class
The interesting lines defining the event handler for the button is highlighted with
bold formatting. We have created an event handler method for this button called
BtnExitOnClick(). In the BtnExitOnClick() method, we have written the code to
exit the application. We have also subscribed this event handler to the btnExit's
Click event (To understand the event handling in VB.NET, see lesson 10 of the
VB.NET school). Now you can press either the Exit Button or the close button at
title bar to exit the application. Alternate procedure for Event Handling – Using
the ‘Handles’ Keyword Note that in the previous code, we subscribed Exit buttons
event handler using the ‘AddHandler’ keyword. We can also do this using the
‘Handles’ keyword with the Event Handler method. But to use the ‘Handles’
keyword, the Exit button needs to be instance variable of the form class defined
with the ‘WithEvents’ keyword. The complete source code of the MyForm class is
Class MyForm
Inherits Form
' Form
' Label
' Button
btnExit.Text = "Exit"
End Sub
Application.Exit()
End Sub
End Class
Note that the button is now instantiated with the ‘WithEvents’ keyword and the
event handler is specifically marked with the ‘Handles’ keyword to qualify it as an
event handler method. This procedure of implementing event handling (using the
‘Handles’ keyword) is usually followed by Visual Studio.NET standard code for
Form based applications (Windows and Web Applications)
What are the lifetime events of a form?
Some important lifetime events of a form include:
Load: This event is fired when the form is first loaded in the program. It is called
when the Form.Show() or Form.ShowDialog() method is called for the first time.
Activated: This event is triggered whenever the form gets the application focus.
It is fired when the form is first loaded (along with Load event), when the form is
brought in front, or when the form is restored from the minimized state.
Deactivated: This event is triggered whenever the form loses the application
focus. It is fired when the form is closed, when the form is brought into
background, or when the form is minimized.
VB.NET Version
myForm.Size = New System.Drawing.Size(400, 300)
C# Version
myForm.WindowState = FormWindowState.Maximized;
VB.NET Version
myForm.WindowState = FormWindowState.Maximized
C# Version
myForm.Visible = False;
VB.NET Version
myForm.Visible = False
C# Version
myForm.Visible = True;
VB.NET Version
myForm.Visible = True
You can also display your form for the first time using the Show() or the
ShowDialog() methods of the form class. The Show() method displays the form in
Non-Modal fashion, while the ShowDialog() method displays the form in Modal
mode. See the following FAQs for the description of Modal and Non-Modal forms
The Non modal form, on the other hand, does not prevent you from accessing
other form windows of the application, when they are present on the screen using
the Show() method of the form.
C# Version
myForm.Show();
VB.NET Version
myForm.Show()
C# Version
myForm.ShowDialog();
VB.NET Version
myForm.ShowDialog()
It will display the form as a Modal dialog and would not allow the user to access
any other form of the application when it is present on the screen.
this.WindowState = FormWindowState.Normal;
this.WindowState = FormWindowState.Maximized;
VB.NET Version
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
Me.WindowState = FormWindowState.Minimized
Me.WindowState = FormWindowState.Normal
Me.WindowState = FormWindowState.Maximized
End Sub
Note that the above code snippet is using the System.Threading.Thread class’
Sleep method to suspend the form for 2 seconds. Hence, you would be required
to include the System.Threading namespace to your form class source code.
C# Version
Using System.Threading;
VB.NET Version
Imports System.Threading
To disable the minimize box at the form title bar, set the Minimize property of the
form to false.
You can not hide only the close box from the form title bar using the form’s
property.
Similarly, you can not only hide maximize or minimize boxes from the title
window.
You can hide maximize and minimize boxes from the title bar by setting the
FormBorderStyle property of the form to the FixedToolWindow or the
SizableToolWindow. But remember that with FormBorderStyle set to the
FixedToolWindow or SizableToolWindow, the form will not be displayed in the
Windows task bar or in the window that appears when the user presses ALT+TAB.
You can hide the Control box from the title bar of the form by setting the
ControlBox property of the form to false. This will hide the control box and system
menu from the form window.
C# Version
myForm.Close();
VB.NET Version
myForm.Close()
Remember that this will only close the form and not the application. To close or
exit the application, call the Application.Exit() method.
C# Version
Application.Exit();
VB.NET Version
Application.Exit()
C# Version
MessageBox.Show("Welcome to Win Form");
VB.NET Version
MessageBox.Show("Welcome to Win Form")
To add the title to the message box, call the MessageBox.Show() like:
C# Version
MessageBox.Show("Welcome to Win Form", "Greeting");
VB.NET Version
MessageBox.Show("Welcome to Win Form", "Greeting")
The following example code shows the message box with Yes, No, Cancel button
to confirm application close and closes the application if the user selects the Yes
button
C# Version
DialogResult dlgRes = null
dlgRes = MessageBox.Show(
"Are you sure you want to close without saving the document",
"Confirm Document Close",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Question);
if(dlgRes == DialogResult.Yes)
Application.Exit();
VB.NET Version
Dim dlgRes As DialogResult
dlgRes = MessageBox.Show( _
"Are you sure you want to close without saving the document", _
"Confirm Document Close", _
MessageBoxButtons.YesNoCancel, _
MessageBoxIcon.Question)
Application.Exit()
End If
How do I add another form into my win form
application?
To add and design a new form at design time, right click the target project node
in the Solution Explorer and select AddàAdd Windows Form… This will add a new
form; design it by placing controls and setting necessary properties.
To show the new form at run time, instantiate the new form and call its Show() or
ShowDialog() method.
Let we name the new form as ‘MySecondForm’, then on the click event of the
button of our first (startup) form, we can write the following code:
C# Version
MySecondForm frm2 = new MySecondForm();
frm2.Show(); // will present the non-modal form
VB.NET Version
Dim frm2 As New MySecondForm()
frm2.Show() ' will present the non-modal form
C# Note
Remember that only those forms that have a valid Main() method can be selected
as the startup object.
You can make a form scrollable by setting its AutScroll property to true
You can now show this splash form when the main application is loading.
C# Version
private void Form1_Load(object sender, System.EventArgs e)
{
this.Hide();
Form2 frmSplash = new Form2();
frmSplash.Show();
frmSplash.Update();
Thread.Sleep(5000);
frmSplash.Close();
this.Visible = true;
}
VB.NET Version
Private Sub Form1_Load(ByVal sender As System.Object, _
yVal e As System.EventArgs) Handles MyBase.Load
Me.Hide()
frmSplash.Show()
frmSplash.Update()
Thread.Sleep(5000)
frmSplash.Close()
Me.Visible = True
End Sub
What basics should be remembered while developing
win form apps?
Some Important Points for designing Windows Applications
• Make your form layout simple and easy to understand. It is important that
the user of your application finds it familiar. The behavior should be
expected and should not surprise the user.
• The Format menu of the Visual Studio.NET IDE is very useful when
designing the form layout. It provides a number of useful options for
alignment and size of the controls.
• Almost all the controls have some similar properties like Location, Size,
Enabled, Visible, TabIndex, etc. The TabIndex property is very important.
It describes the sequence followed by the windows focus when the user
presses the Tab button of keyboard.
• Usually we don't change the Name property of labels as we don’t need to
use the label variable in our code most of the time.
• The controls should be named so that their purpose can be recognized,
e.g., you may name the ‘Purchase’ button as btnPurchase, text box for
entering email may be txtEmail and so on.
• Although now it is not a standard convention, but it is useful to add a
three letter prefix to the name of your controls so that they are
recognizable with their name. Most of the developers used to follow the
convention like prefixing Label with lbl (lblGreeting), TextBox with txt
(txtComments), Button with btn (btnPurchase), CheckBox with cbx
(cbxProgCS), RadioButton with rbn (rbnFullPayment) and GroupBox with
gbx (gbxPaymentMode).
Me.MaximizeBox = False
End Sub
End Class
Controls
Each control, and thus form, exposes a number of events that can be triggered
on certain user action or application behavior. For example, a button raises Click
event whenever it is clicked and the text box raises the TextChanged event
whenever its text is changed. The application developer can write even handler to
catch these events and perform corresponding action. Beside these, a form also
has certain set of events called the form life cycle events. These events are
triggered during the life cycle of form to indicate the current state of the form.
If we have defined the top and bottom anchoring and the form is resized, the
control will resize itself to have the same distance from top and bottom. Consider
the figure below; here the button is anchored top and bottom
When the form is resized, the button resizes itself to keep the same distance from
top and bottom
In the figure below, we have docked the button to the top of the window
When the control is resized, the control remains stuck to the top of the window
You can define a control to have a fill dock property so that it may fill all the
available space in the parent window or parent control. In the figure below, we
have docked the tree view control at left and the list view control with fill docking
property
When the form is resized, the tree view will remain at left (changing only its
height and not width) while the list view will expand itself to the rest of the
available space on the form
System.Drawing.Graphics g = comboBox1.CreateGraphics();
foreach(object o in comboBox1.Items)
Note. If no text is selected then any all new text will be blue-italic-verdana within
the RichEditBox.
RichTextBox1.Focus();
RichTextBox1.SelectionColor = Color.Blue;
using System.Text;
using System.IO;
private void button1_Click(object sender, System.EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open the text file you wish" ;
ofd.InitialDirectory = "c:\" ;
ofd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
if(ofd.ShowDialog() == DialogResult.OK)
{
StreamReader sr = File.OpenText(ofd.FileName);
string s = sr.ReadLine();
StringBuilder sb = new StringBuilder();
while (s != null)
{
sb.Append(s);
s = sr.ReadLine();
}
sr.Close();
textBox1.Text = sb.ToString();
}
}
This control can be very useful when you are working with controls both at design
time and run time (which are not visible at design time).
characters. E.g. Only a single digit number or a double digit number and so on. To
control the input, use the KeyPress event like below:
TextBox1.KeyPress
End If
End Sub
Open two forms (form1 and form2), add a Command Button and a Textbox to
Form1 and a Textbox to Form2.
NewWindow.Show()
End Sub
TextBox1.Text = NewWindow.TextBox1.Text
End Sub
End Class
System.Windows.Forms.LinkLabelLinkClickedEventArgs)Handles_
LinkLabel1.LinkClicked
System.Diagnostics.Process.Start("www.yahoo.com")
End Sub
Upon running the application,click on the Text on the LinkLabel. The website,
Yahoo.com will open in a new browser.
ComboBox1.Items.Add(“India”)
ComboBox1.Items.Add(“Australia”)
ComboBox1.Items.Add(“Sweden”)
ComboBox1.Items.Add(“Spain”)
ComboBox1.Items.Add(“England”)
ComboBox1.Items.Add(“United States”)
ComboBox1.Items.Add(“Russia”)
ComboBox1.Items.Add(“China”)
ComboBox1.Items.Add(“Japan”)
ComboBox1.Items.Add(“New Zeland”)
End Sub
To sort the items alpahbetically, select the .Sorted property and set it to True.
Open a new project Add a Command Button to the Form. Place the following code
in the click event of the command button.
Below is an example:
XML
How
String Value="";
if (Node.Attributes["Attribute1"] == null)
// doesn't exist
Value="";
}
else
// exists
Value=Node.Attributes["Attribute1"].Value.ToString();
An IDE helps manage the application by assisting you to break your application
into projects, separate files and grouping the files into folders. For example if you
are developing an accounts management system, you may break it into three
projects;
Then, you may further divide the user interface project to three folders;
Apart from this, an IDE also provide its support from the start of development to
the creation of final installation. It provides an intelligent text editor that
recognizes various parts of your code and also highlights the possible errors as
you type it. It helps you in compiling and testing individual projects and also the
complete application. It provides an integrated debugger to identify the bugs in
your program and the possible cause of them. One of the most appealing features
of an IDE like Visual Studio.Net is that it provides designers for various tasks like
Windows Application User Interface designing, Web form designing and the
database connection with simple drag and drop and setting a few properties.
Once you have completed the application development and tested it through
debugger, the IDE also helps you in building its installation program so that the
application can be shipped to the client. Hence, an IDE supports developers
throughout the life cycle of the application.
Solution Explorer
The solution explorer presents the hierarchical view of the projects included in the
current solution. It presents the detailed view of the individual projects with the
contained source code files (which may be grouped into some folders), the
references to the assemblies (projects or library code) used by the project and
any other resource files like icons, pictures, sounds, animation, etc.
The solution explorer does not only present the view of the solution hierarchy but
also allows you to customize the solution or projects settings. It allows you to add
and remove existing and new projects to the solutions, add and remove the
references and resource files. It also allows you to change the name of the
solution, projects, folders and files, their build options, output file names and
things like that.
Now there is a single toolbox for all the Visual Studio.NET’s languages and tools.
The toolbox (usually present on the left hand side) contains a number of common
controls for windows, web and data applications like text box, check box, tree
view, list box, menus, file open dialog, etc.
Properties Tab (usually present on the right hand side in IDE) allows you to set
the properties on different controls and form without getting into code
Class View Tab shows all the classes that your project contains along with the
methods and fields in tree hierarchy. This is similar to VC++ 6’s class view.
• File Menu: Used to create, open, save and close the project, solution or
individual source files.
• Edit Menu: Used for text editing and searching in the Visual Studio source
code editor.
• View Menu: Provides options for setting the visibility of different Visual
Studio windows and to switch between code and designer views.
• Project Menu: Used for setting different properties of the Visual Studio
Project. A Visual Studio project is a collection of files that make up a single
assembly or a single object file (we will explore the concept of assemblies
in coming lessons).
• Build Menu: This menu is used to compile and build the source file, project
or solution. The result of a build is an executable file or a code library.
• Debug Menu: This menu provides various options related to the Visual
Studio.Net Debugger. Debugging is the process of finding logical errors in
the program, and a debugger helps make this proccess easier.
• Data Menu: Provides various options for Data Access in .Net
• Format Menu: Provides access to a set of useful operations for formatting
the controls and their layout in the Form Designer view.
• Tools Menu: Provides the access to various useful Visual Studio.NET tools.
Form Designer The Visual Studio.NET form designer allows you to design the
windows and web forms for your application’s user interface. It simplifies the task
by allowing you to just drag and drop the required controls from the toolbox to
the designer’s emulated form. It even sets the default properties for your
controls. You can then change the properties of the form and control through the
Properties Tab of the Visual Studio.NET IDE. The form designer also allows you to
attach the even handlers with the controls.
Code Editor
The Visual Studio.NET Code Editor supports you in writing the code for your
application. The code editor is tightly integrated with the designers. As you
change the properties and add controls, the designer puts the required code in
you application source code files which can be viewed using the code editor. The
code editor is quite smart; it highlights the various categories of the code like
keyword, constant and even the syntax and semantic errors. It provides the code
completion through its intellisense; when you place dot (in C# and VB.NET) with
your object references and namespaces it automatically shows the list of all
available options to select from. Finally, the code editor is also used to debug the
application using the integrated debugger.
A great thing about the Visual Studio.NET solutions is that it may contain projects
built with any of the VS.NET compliant language. Hence, now your solution may
consists of a database handling project in Visual C#, the GUI Application project
in VB.NET and the protocol implementation project in VC++.NET!
• Console applications are light weight programs run inside the command
prompt (DOS) window. They are commonly used for test applications.
• Windows Applications are form based standard Windows desktop
applications for common day to day tasks. Microsoft word is an example of
a Windows application.
• Web applications are programs that used to run inside some web server
(e.g., IIS) to fulfill the user requests over the http. A typical example of
web application is Hotmail and Google.
• Web services are web applications that provide services to other
applications over the internet. Google search engine’s web service, e.g.,
allows other applications to delegate the task of searching over the
internet to Google web service and use the result produced by it in their
own applications.
• Class library contains components and libraries to be used inside other
applications. A Class library can not be executed and thus it does not have
any entry point.
• Windows Control Library contains user defined windows controls to be
used by Windows applications
• Web Control Library contains user defined web controls to be used by
web applications
To compile all the source files of all the projects contained in a solution and build
the resulting assemblies or the complete application, right click the solution node
in the solution explorer and select Rebuild solution.
Then pressing F11, will take us to the body of the GetInteger() method and the
execution control will pause at its first line.
The Step Over option (accessible through DebugàStep Over or key F10) executes
the code in the line at which the debugger is paused and takes the execution
control to the next line. For example, if the execution is paused at a line marked
line 1 in the code below:
Then pressing F10, will execute the code at ‘line 1’ and will take the execution
control to the line marked ‘line 2’ in the above code and the execution control will
pause at the line // 2.
A solution is a logical binding for the projects and it does not have any
representation in the build files.
You may specify the build type of an assembly (project) by right clicking its
project and selecting properties from the pop up menu. It will show the property
pages for the project. You can select the build type by selecting Configuration
Properties and then selecting the build type from the combo box at top labeled
Configuration
Index
• Visual Studio .NET IDE provides a single environment for developing all
types of .NET applications. Application’s range from single form
applications to complex n-tier applications and also Rich Web Applications.
• You can customize the IDE based on your preferences. By use of "My
Profile settings". With these settings you can set the IDE screen the way
you want, the way the keyboard behaves and you can also filter the help
files based on the language of your choice.
• The IDE comes with a built-in browser that helps you navigate the Internet
without launching another browser app.
The following are the different options available in VS.NET and what they are
used for.
• Windows Control Library: This allows the creation of your own windows
controls. These can also be added to the tool box to make it easier if you
wish to use these resources in other projects.
• Web Control Library: Allows you to create User-defined controls for the
Web. Similar to user defined windows controls but these are specifically for
Web usage.
What is C#?
C# (pronounced C-Sharp) is a new programming language introduced with the
Microsoft .NET framework and is no doubt the language of choice in .NET
environment. It was first created in the late 1990's as part of Microsoft’s whole
.NET strategy. It is a whole new language free of backward compatibility curse
and a whole bunch of new, exciting and promising features. It is an Object
Oriented Programming language, which at its core, has similarities with Java,
C++ and VB.
In fact, C# combines the power & efficiency of C++, simple & clean OO design of
Java, and code simplification of Visual Basic. Like Java, C# also does not allow
multiple inheritance and use of pointers (in safe and managed code) while it does
provide garbage memory collection at runtime, type and memory access
checking. But, contrary to java, C# keeps the different useful concepts of C++
like operator overloading, enumerations, pre-processor directives, pointers (in
unmanaged and un-safe code), function pointers (in the form of delegates), also
promises to have template support (with the name of generics) in next versions.
Like VB it also supports the concepts of properties (context sensitive accessor to
fields).
Sample C# Application
Using System
Class Sample
{
public static void main()
{
Console.WriteLine (“Hello World”)
}
}
Class Jagged
{
public static void Main()
{
int [][] jagged=new int [3][];
jagged[0]=mew int[4]
jagged[1]=mew int[3]
jagged[2]=mew int[5]
int I;
‘Storing values in first array
for (I=0;I<4;I++)
jagged[0][I]=I;
‘Storing values in second array
for( I=0;I<3;I++)
jagged[1][I]=I;
for(I=0;I<5;I++)
jagged[2][I]=I;
for (I=0;I<4;I++)
Console.WriteLine(jagged[0][I])
for (I=0;I<3;I++)
Console.WriteLine(jagged[1][I])
for(I=0;I<5;I++)
Console.WriteLine(jagged[2][I])
}
The .NET Framework defines built-in value types such as System.Int32 and
System.Boolean which correspond and are identical to primitive data types used
in programming languages.
The language you are using will provide functionality to define your own Value
Types. These user defined Types derive from System.ValueType. If you want to
define a Type representing a value that is a complex number (two floating-point
numbers), you might choose to define it as a value type. Why? Because you can
pass the Value Type efficiently "By Value". If the Type you are defining could be
more efficiently passed "By Reference", you should define it as a class instead.
Variables of Reference Types are referred to as objects. These store references to
the actual data.
• class
• interface
• delegate
• object
• string
VB.NET Frequenly Asked Questions
• VB6 was not a type-safe language while VB.NET is a type safe language.
There is no variant type in VB.NET and no magical type conversions
happen in VB.NET
• VB6 used ‘On Error Goto’ syntax to handle exceptions at runtime. VB.NET
uses the Try…Catch…Finally syntax to handle exceptions at runtime.
• A lot of code (like user interface code) in VB6 was hidden from developer.
In VB.NET no code is hidden from developer and you can access and
control each part of your application
• VB6 was only considered good for desktop windows application. In VB.NET
you can also develop web applications, distributed applications, create
.NET windows and web controls and components, write windows and web
services.
• In VB.NET, you can also use reflections to read the meta-data of types and
using reflection emit you can also generate code to define and invoke
types at runtime.
• VB.NET uses .NET framework class library along with specialized VB library
(System.VisualBasic) as a standard library. As a result, the standard
library for VB.NET is much enhanced and useful compared to VB6 standard
library
• VB6 used ASP to build web applications. VB.NET uses ASP.NET to build
web applications.
Module Module 1
Sub Main ()
System.Console.WriteLine ("Hello World”)
End Sub
End Module
Compilation of the program using the Visual Studio .NET Command Prompt is also
possible. To compile the program using that type "vbc sample.vb" at the
command prompt.
What are namespaces and what is the importance
of them?
A namespace is a collection of different classes which are built into .NET. This
very much like packages in Java. You need to import these namespaces to work
with any .NET language. All the functionality of .NET is within these
namespaces. The main namespace is the System namespace and all other
namespaces are built into this System namespace.
Some of these namespaces and what they are used for are summarized below.
• System: Includes essential classes and base classes that define commonly
used Data Types, events, interfaces, attributes etc.
• System.Data: Includes classes that make up ADO.NET and allows to build
data-handling components.
• System.Drawing: Provides access to graphics that gives access to
drawing methods.
• System.IO: Provides access to writing data streams and Files.
• System.Net: Provides interface to many protocols used on the Internet.
• System.Security: Includes classes to support the security system.
• System.Threading: Includes classes that support threading.
• System.Web.Services: Includes classes for creating and using Web
Services.
• System.Windows.Forms.: Includes classes for creating windows based
applications.
The following code does not perform any special function but will show where to
place an Option statement.
Example: To call a Windows API functions you have to include a dynamic link
library (DLL) reference that the function you are calling resides in. This is done
using the DLLImport attribute as follows:
You can also use an attribute like <Attribute> or pass it's value to a parameter as
you can do with procedures like <Attribute("hello")>.
Module Module 1
Enum Months
January=1
Feburary=2
March=3
April=4
May=5
June=6
July=7
August=8
September=9
October=10
November=11
December=12
End Enum
Sub Main()
End Sub
End Module
Months.December.
The output of the above code displays December is the 12th Month.
How do I convert text from lower case to upper
case in VB.NET?
The following code shows how text can be converted from lower case to upper.
Module Module1
Sub Main ()
Dim str1 as String=”Welcome to String”
Dim str2 as String
Str2=UCase(str1)
Or
Str2=Str1.ToUpper
System.Console.WriteLine(str2)
End Sub
Imports System.Math
Module Module1
Sub Main()
System.Console.WiteLine(“Pi = “ & 4 * Atan())
End Sub
End Module
Example
Imports System.Math
Module Module1
Sub Main ()
Dim Dts as Date
Dts = # 10/15/2001
System.Console.WriteLine(“New Date: & DateAdd(DateInterval.Month, 22, Dts))
End Sub
End Module
The above code adds 22 months to the date we declared in the Program.
Module Module1
Delegate Sub SubDelegate1(ByVal str as String)
Sub Main()
Dim Mess as SubDelegate1
Mess-AddressOf Display
Mess.Invoke(“Hello from Delegates”)
End Sub
System.Console.WriteLine(StrText)
End Sub
End Module
The above code displays “Hello from Delegates” just like a normal program but it
uses Delegates to do it.
Imports System.IO
Public Class Form1 Inherits System.Windows.Forms.Form
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles MyBase.Load
Dim fs as New FileStream("exp.txt",FileMode.Create,FileAccess.Write)
Dim s as new StreamWriter(fs)
s.BaseStream.Seek(0,SeekOrigin.End)
s.WriteLine("ProgrammersHeaven has lot of programming goodies")
s.WriteLine(" good resource for most popular programming languages")
s.Close()
End Sub
End Class
What is Anchoring and Docking?
The VB terms Docking and Anchoring are used to make sure that a control
covers the whole client area of a form.
Upon "docking" a window, it adheres to the edges of it's container (the Form). To
"dock" a particular control, select the Dock property of the control from the
properties window.
Selecting the Dock property opens up a small window like structure where you
can select towards which side on the Form should the control be docked.
You can use Anchoring to "anchor" a control to the edges of it’s container (the
Form). Selecting this property in the properties window opens up a small window
from where you can select what edge to "anchor" the control to.
With system.Net.DNS.GetHostByName(system.Net.DNS.GetHostName())
sam1 = sam.ToString
End With
GetIPAddress = sam1
End Function
shostname = system.Net.DNS.GetHostName
End Sub
End Class
Execute the "getip.exe". The computer's name and IP address will be displayed in
the Console.
Imports System
Class SystemInfo
Console.WriteLine("")
Console.WriteLine("Current User")
Console.WriteLine(Environment.UserName)
Console.WriteLine("")
Console.WriteLine(Environment.MachineName)
Console.WriteLine("")
Console.WriteLine("OS version")
Console.WriteLine(Environment.OSVersion)
Console.WriteLine("")
Console.WriteLine("System Directory")
Console.WriteLine(Environment.SystemDirectory)
Console.WriteLine("")
Console.WriteLine("TMP Folder")
Console.WriteLine(Environment.GetEnvironmentVariable("TMP"))
Console.WriteLine("")
Console.WriteLine("Class Path")
Console.WriteLine(Environment.GetEnvironmentVariable("ClassPath"
))
Console.WriteLine("")
Console.readLine()
End Sub
End Class
<Document>
<Customer>
<Name>Sandeep</Name>
<Age>23</Age>
<Occupation>Developer</Occupation>
</Customer>
</Document>
Imports System
Class WriteToXML
dset.ReadXml("Test.xml")
Console.Write(dset.GetXml)
'Getting data from the user to be saved into the XML file
name = Console.ReadLine
age = Console.ReadLine
occupation = Console.ReadLine
v(0) = fname
v(1) = age
v(2)=occupation
dset.Tables(0).Rows.Add(v)
dset.WriteXml("Test.xml")
Console.Write(dset.GetXml)
End
When you run this code, the data from the XML file will be displayed. Also the
data you enter will be updated into the XML file.
Imports System
Imports Microsoft.VisualBasic
Sub Mysub()
End Interface
' Implementing the above defined interface, need to use the keyword
implements to use the interface
mc.Mysub()
End Sub
End Sub
str="hello matey"
return (str)
End Function
End Class
The following example converts a user prompted Bitmap image file into .Gif
format.
File ImageConverter.vb
Imports System
Imports System.Drawing
Class ConvertImages
str = Console.ReadLine()
End Sub
End Class
End Class
End Sub
End Class
System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly
.GetExecutingAssembly.Location)
Return .FileMajorPart & "." & .FileMinorPart & "." & .FileBuildPart & "." &
.FilePrivatePart
End With
End Function
With
System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly
.GetExecutingAssembly.Location)
Return .Comments
End With
End Function
Upon running the version information of the Assembly file is displayed.
Closely related to managed code is managed data. This is the data that is
allocated and de-allocated by the Common Language Runtime's garbage
collector. As said earlier C#, Visual Basic, and J#.NET data is managed by
default. C++ data can, however, be marked as unmanaged through the use of
special keywords. Visual Studio .NET C++ data is unmanaged by default (even
when using the /CLR switch), but when using Managed Extensions for C++, a
class can be marked as managed by using the __gc keyword.
As the name suggests this means that the memory used for instances of the class
is managed by the garbage collector. In addition the class becomes a full
participating member of the .NET Framework with the benefits and restrictions
that it brings. An example of a benefit is proper interoperability with classes
written in other languages (for example, a managed C++ class can inherit from a
Visual Basic class).
An example of a restriction is that a managed class can only inherit from one
base class.
What is an Assembly?
An Assembly is the building block of a VB.NET application. An Assembly is a
complied and versioned collection of code and metadata. Once complete forms an
"atomic" functional unit.
Assemblies come in the form of a Dynamic Link Library (DLL) file or Executable
an program file(EXE). They differ as they contain information found in a type
libraries. All the .NET programs are constructed from these Assemblies.
Assemblies are made of two parts. Firstly, the manifest which is similar to a
Table Of Contents(TOC). This holds the name and version of the assembly.
Secondly, the modules which are internal files of Intermediate Language (IL)
code which are ready to run.
When programming, developers don't directly deal with assemblies as the CLR
and the .NET framework takes care of that behind the scenes.
An assembly includes:
#End Region
ByVal e As System.EventArgs)
Handles Button1.Click
TextBox1.Text = Application.ExecutablePath
End Sub
End Class
Imports System
Imports System.Diagnostics
program.Start()
Module Module1
Sub Main()
Dim a=0, b=1, c As Integer
Try
c=b / a
'the above line throws an exception
System.Console.WriteLine("C is " & c)
Catch e As Exception
System.Console.WriteLine(e)
'catching the exception
End Try
System.Console.Read()
End Sub
End Module
The output of the above code displays a message stating the exception. The
reason for the exception is because any number divided by zero is infinity.
Module Module1
Sub Main()
Dim d As Double
d = 132.31223
Dim i As Integer
i = CType(d, i)
'two arguments, type we are converting from, to type desired
System.Console.Write("Integer value is" & i)
End Sub
End Module