Professional Documents
Culture Documents
Microsoft .NET is a software development platform based on virtual machine based architecture. Dot net is designed from the scratch to support programming language independent application development. The entire .NET programs are independent of any particular operating system and physical hardware machine. They can run on any physical machine, running any operating system that contains the implementation of .NET Framework. The core component of the .NET framework is its Common Language Runtime (CLR), which provides the abstraction of execution environment (Physical machine and Operating System) and manages the overall execution of any of the .NET based program.
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:
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.
What is the difference between Console, Windows, Web applications and Web services?
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 engines 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.
There are two kind of assemblies in .NET; private and shared. Private assemblies are simple and copied with each calling assemblies in the calling assemblies folder. Shared assemblies (also called strong named assemblies) are copied to a single location (usually the Global assembly cache). For all calling assemblies within the same application, the same copy of the shared assembly is used from its original location. Hence, shared assemblies are not copied in the private folders of each calling assembly. Each shared assembly has a four part name including its face name, version, public key token and culture information. The public key token and version information makes it almost impossible for two different assemblies with the same name or for two similar assemblies with different version to mix with each other. 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.
What are the differences between a .NET Assembly, a Windows DLL and a COM Component?
A Windows DLL contains library code to be used by any program running on Windows. A DLL may contain either structured or object oriented libraries. 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.
What are the differences between a .NET Assembly, a Windows DLL and a COM Component?
A Windows DLL contains library code to be used by any program running on Windows. A DLL may contain either structured or object oriented libraries. 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.
an
executable
An executable assembly exists as the .exe file while a class library exists as the .dll file. Executable assembly represent executable applications having some entry (e.g., Main() method in C#). A class library, on the other hand, contains components and libraries to be used inside various applications. A Class library can not be executed and thus it does not have any entry point.
need
to
build
or
execute
.NET
To execute a standalone .NET application (Windows or Console application), one needs to first compile all its constituent assemblies and modules including the executable assembly. Once, the constituent assemblies are compiled, one needs to make sure that the target system contains the .NET framework. The application can now be executed by running its executable assembly (the .exe file). The executable assembly (.exe) is a Win32 executable that hosts the .Net CLR (Common Language Runtime), which exists as a COM component, in its process space and initializes it. Once the CLR is hosted and initialized, the starting point of the .NET executable assembly is passed to the hosted CLR which starts the execution of the program by translating and executing the parts of the program code.
Microsoft has secured certification for both C# and CLI from ECMA and ISO/IEC as Industry standards. This is a very important step for Microsoft and .Net platform because this enhances the credibility of the newer .Net platform and allures a larger portion of technology industry into adopting .Net as their development platform. Several companies and government organizations only utilize ISO certified technologies; for example, in Australia anything ISO certified is also considered Australian standard according to the rules of the Australian government. Several academic institutions will now be interested in teaching standard C#. Another major outcome of having an open industry standard specification is .Net platform could be getting ported to other platforms like Linux and UNIX; best example is the Mono Project by Ximian- it is an open source implementation of .Net platform for UNIX and Linux based on ECMA approved Public Domain Specification of C# and CLI. Microsoft submitted the specifications to ECMA, which in turn fast-tracked them through ISO. In doing so, Microsoft released all intellectual property in the core C#/CLI platform to the public domain. No one needs a license to implement C#/CLI. This will also help everybody in better understanding the implementations of C# and CLI which are at the core of .Net platform. However, the whole of .Net platform is not a Public domain standard- Microsoft still owns complete Intellectual property rights to several class libraries and API within the .Net platform.
What about the implementation of .NET other than Microsoft.Net on Windows Operating System?
Microsoft has implemented .NET framework for all of its operating system suits (excluding MS Windows 95 and earlier) on all supported hardware platforms. For handheld and small devices, Microsoft has released a compact framework of .NET (http://msdn.microsoft.com/vstudio/device/compact.aspx ). But, there are various other implementations being developed on platforms other than Microsoft Windows. You can read the discussion on the portability of .NET at (See http://zdnet.com.com/2100-1107-960049.html) 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
traditional
In traditional programming languages, the source code of a program is compiled to a specific platforms assembly language and then machine language code. Later the library code required by the program is linked to it. Finally the operating system executes the program when desired by the user. The complete process is depicted in the following figure:
In the presence of dot net framework, a program is not compiled to the native machine executable code; rather it gets compiled to an intermediate language code called Microsoft Intermediate Language (MSIL) or Common Intermediate Language (CIL). The Dot Net Common Language Runtime (CLR) then converts this intermediate code at runtime to the machine executable code. The optimization is carried out at runtime. A program also does not call the operating system APIs directly; rather it delegates this task to the CLR which performs the desired operations on behalf of the program and returns the results of the operations back to the program. The CLR also performs the memory management, garbage collection, security and thread management on behalf of the program. Dot NET framework is shipped with the supporting object oriented framework of common code libraries, called the .NET Framework Class Library (FCL), to facilitate the common operations. Hence the .Net manages the overall execution of an application. This is the reason why the code running on .Net framework is sometimes called the managed code. The complete process is depicted in the following Figure. Note that only the CLR (and thus the .Net framework and not the user application) is interacting and coupled with the platform and operating system.
they can optimize the code extremely efficiently resulting in very robust applications. Also, since JITer knows the exact current state of executable code, they can also optimize the code by in-lining small function calls (like replacing body of small function when its called in a loop, saving the function call time). Although, Microsoft stated that C# and .Net are not competing with languages like C++ in efficiency, speed of execution, JITers can make your code even faster than C++ code in some cases when program is run over extended period of time (like web-servers).
used by other programs as necessary. The presence of standard Garbage Collector frees the programmer from keeping track of dangling data.
At runtime, the .NET assembly (compiled IL code) is translated to native machine code and executed by the CLR.
managed access to memory and no direct access to memory is allowed to their managed applications. However, there are few contrasts in the architecture and design of the two virtual machines. Microsoft .NET frameworks 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.
one
use
MS.NET
for
software
Well, most of the software development all over the world is done on and for Microsoft Windows Operating System. Dot Net is now the standard software development environment for the Microsoft Windows operating system. It dramatically simplifies the development of windows, web based, data access applications, components, controls and web services. Dot net comes with amazing features like XML configuration, reflection, and attributes to ease the overall software development life cycle. Finally, the dot net is supported by the Microsoft Visual Studio Integrated Development Environment; the best IDE available for any software development environment. Visual Studio .NET (VS.NET) supports all the areas of software development from project creation to debugging and installation.
How true it is that .NET and Java programs are quite in-efficient when compared to C++?
The startup of managed .NET and Java programs is definitely slower than the traditional C++ programs as it involves the hosting of CLR into managed application process in .NET and starting the JVM in a new process in case of Java. The execution also is a bit slower during the initial period of program execution as the intermediate code is translated to the machine code on the fly at runtime. But
as the program runs various parts repeatedly, the execution gets pace too. Since, the CLR and JVM optimizes the code more efficiently than the static C++ compilers, the execution speed of the program may actually be faster after sometime of the program startup when most of the code is translated. Hence, in the longer run, the .Net and Java based programs should not be in-efficient when compared to C++. We used should here as the actual performance depends on the particular implementation and implementation strategy.
What are XML Doc comments (comments start with three slashes ///)?
The XML Doc comments are special kind of comments that can be recognized by Document utility to automatically generate the documentation of your methods, types and regions.
Using COM components in .NET and How to add a reference to a COM component?
The .NET does not encourage the use of COM component directly inside the managed application! Although, the .NET framework contains utilities that enable COM components to be used inside the .Net applications seamlessly. How it is done? The .NET utilities like TlbImp generates the wrapper .NET assembly for the COM component which provides the same calling interface to the client as exposed by the COM component. Inside the wrapper methods, it calls the actual methods of the COM component and returns the result back to the caller. The generated wrapper .NET assembly is called the Runtime Callable Wrapper or RCW. 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
What is .NET Framework and what are CLR, CTS and CLS?
. NET is a software platform. It's a language-neutral environment for developing .NET applications that can easily and securely operate within it.
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.
What is Code Access Security (CAS)? How does CAS work? Who defines the CAS code groups?
Code Access Security (CAS) is part of the .NET security model. CAS determines whether or not a piece of code is allowed to run and also what resources to use. For example, CAS will prevent malicious code from entering your system and causing havoc. 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.
What is Active Directory? What namespace should I use to use Active Directories?
Active Directory Service Interfaces (ADSI) is a programmatic interface for the Microsoft Windows Active Directory. It enables your applications to interact with different directories on a network using a single interface. 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:
1) Log on once to work with diverse directories. The DirectoryEntry component class provides username and password properties that can be entered at Runtime and are passed to the Active Directory object you are bound to. 2) Use of an Application-Programming Interface (API) to perform tasks on multiple directory systems. This includes multi protocol support. The DirectoryServices namespace provides the classes to perform most administrative functions such as creating users. 3) Perform "Rich Querying" on directory systems. ADSI technology supports searching for objects with two query dialects: SQL and LDAP. 4) Access and use a single or hierarchical tree structure for administering and maintaining a diverse and complicated network. 5) Integrate directory information with databases such as ?SQL Server. The DirectoryEntry path may be used as an ADO.NET connection string. Name space to be imported when working with Active Directories:
System.DirectoryServices
".NET", 0 );
} }
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
} }
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.
Another important aspect of the disconnected architecture is that it maintains the local repository of data in the dataset object. The dataset object stores the tables,
their relationship and different constraints. The user performs operations like update, insert, delete to this dataset locally and finally the changed dataset is stored in actual database as a batch when needed. This greatly reduces the network traffic and results in the better performance.
connected
data
access
In the connected environment, it is your responsibility to open and close the database connection. You first establish the database connection, perform the interested operations to the database and when you are done, close the database connection. All the changes are done directly to the database and no local (memory) buffer is maintained.
What's the difference between accessing data with dataset or data reader?
The dataset is generally used when you like to employ the disconnected architecture of the ADO.Net. It reads the data into the local memory buffer and perform the data operations (update, insert, delete) locally to this buffer. 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. Since no memory buffer is maintained by the data reader, it takes up fewer resources and performs more efficiently with small number of data operations. The dataset, on the other hand is more efficient when large number of updates are to be made to the database. All the updates are done in the local memory and are updated to the database in a batch. Since database connection remains open for the short time, the database management system does not get flooded with the incoming requests.
All generic classes for data access are contained in the System.Data namespace. A short description of the core classes of ADO.Net is presented below:
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. The core objects that make up a data provider are:
Represents SQL query or command to be executed at the database 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 Command
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.
selects all the fields of all the records from the table name emp
SELECT empno, ename from emp
selects the fields empno and ename of all records from the table name emp
selects all those records from the table name emp that have the value of the field empno less than 100
SELECT * from article, author where article.authorId = author.authorId
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
deletes the record whose empno field is 101 from the emp table
How do different components of ADO.Net interact with each other in disconnected architecture?
The Data Adapter contains in it the Command and Connection object. It uses the connection object to connect to the database, execute the containing command, fetch the result and update the DataSet.
How do different components of ADO.Net interact with each other in connected architecture?
Here, the Command object contains the Connection object. The Command object uses the containing connection (that must be opened) to execute the SQL query and if the SQL statement is SELECT, returns the DataReader object. The data reader object is the stream to the database which reads the resulting records from the DB and passes them to the application
What are the core objects that make up a dot net framework data provider?
The core objects that make up a data provider are:
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 are the standard dot net framework data providers that are shipped with the Dot Net Framework 1.1?
The Dot Net Framework 1.1 is shipped with four different data providers: Dot Net Framework data provider for Dot Net Framework data provider Framework 1.1) Dot Net Framework data provider for Dot Net Framework data provider (available only in Framework 1.1) Microsoft SQL Server DBMS for Oracle DBMS (available only in OLEDB supporting DBMS for ODBC supporting data sources
Why should one use a specialized data provider when the data can be accessed with general data providers?
The specialized data providers (e.g., SQL Server and Oracle) are built specially for a particular kind of DBMS and works much more efficiently than the general data providers (e.g., OLEDB and ODBC). In practice, the specialized data providers are many times efficient than the general data providers.
What is the Dot Net Framework data provider for SQL Server?
The dot net framework data provider for SQL Server is the optimized data provider for Microsoft SQL Server 7 or later. It is recommended to use SQL Server data provider to access the SQL Server DB than general provider like OLEDB. The classes for this provider are present in the System.Data.SqlClient namespace.
The dot net framework data provider for OLEDB provides connectivity with the OLEDB supported database management systems. It is the recommended middle tier for the SQL Server 6.5 or earlier and Microsoft Access Database. It is a general data provider. You can also use it to connect with the SQL Server or Oracle Database Management Systems. The classes for this provider are present in the System.Data.OleDBClient namespace.
What are the basic steps involved in data access with ADO.Net in disconnected environment?
Data access using ADO.Net involves the following steps: Defining the connection string for the database server Defining the connection (SqlConnection, OleDbConnection, etc) to the database using the connection string Defining the command (SqlCommand, OleDbCommand, etc) or command string that contains the query Defining the data adapter (SqlDataAdapter, OleDbDataAdapter, etc) using the command string and the connection object Creating a new DataSet object If the command is SELECT, filling the dataset object with the result of the query through the data adapter Reading the records from the DataTables in the datasets using the DataRow and DataColumn objects If the command is UPDATE, INSERT or DELETE, then updating the dataset through the data adapter Accepting to save the changes in the dataset to the database
Which namespaces I need to add to my project for each of the standard data provider?
You need to add following namespaces for the specified data providers:
Data Provider Namespace MS SQL Server System.Data.SqlClient Oracle Database System.Data.OracleClient OLE DB Databases System.Data.OleDBClient ODBC Data Sources System.Data.ODBCClient
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 = Server};Server=FARAZ;Database=pubs;Uid=sa;Pwd=;"; "Driver={SQL
VB.Net Version
Dim connectionString As String Server};Server=FARAZ;Database=pubs;Uid=sa;Pwd=;" = "Driver={SQL
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.
How do I create a command and supply the SQL query to ADO.Net? (Command object and command string)
First of all, you create a command object (SqlCommand, OracleCommand, OleDbCommand, OdbcCommand) using the connection object (SqlConnection, OracleConnection, OleDbConnection, OdbcConnection) and set its CommandText property to the SQL query to execute.
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.
C# Version
// for MS Access OleDbDataAdapter connectionString); dataAdapter = new OleDbDataAdapter(commandString,
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 objects 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")
Dim stId As String stId = dt.Rows(0)("StudentID").ToString() Dim stName As String stName = dt.Rows(0)("StudentName").ToString() Dim stDateOfBirth As String 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())
We update the dataset and table by calling the Update method of the data adapter. This saves the changes in the local repository of data: dataset. To save the changed rows and tables to the physical database, we call the AcceptChanges() method of the DataSet class.
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
Field Name Type Description artId (Primary Key) Integer The unique identity of article Title String The title of the article Topic or Series name of the article like Multithreading in Topic String Java or C# School authorId (Foreign Integer Unique identity of author Key) Lines Integer No. of lines in the article dateOfPublishing Date Date of publishing of the article
The ProgrammersHeaven database also contains a table named Author with the following fields
Field Name Type Description authorId (Primary Key) Integer The unique identity of author name String Name of author
We have set the Name property of the text boxes (from top to bottom) as txtArticleID, txtArticleTitle, txtArticleTopic, txtAuthorId, txtAuthorName, txtNumOfLines and txtDateOfPublishing. Also we have set the ReadOnly property of all the text boxes to true as dont want the user of application to change the text. The names of buttons (from top to bottom) are btnLoadTable, btnNext and btnPrevious. Initially we have disabled the Next and Previous buttons (by setting their Enabled property to false). We have also defined three variables in the Form class as
public class ADOForm : System.Windows.Forms.Form { DataTable dataTable; int currRec=0; int totalRec=0;
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
For LoadTable button, we have written the following event handler
private void btnLoadTable_Click(object sender, System.EventArgs e) { // for Sql Server string connectionString = "server=P-III; database=programmersheaven;" + "uid=sa; pwd=;";
string commandString = "SELECT " + "artId, title, topic, " + "article.authorId authorId, " + "name, dateOfPublishing " + "FROM " + "article, author " + "WHERE " + "author.authorId article.authorId"; = lines, as
dataAdapter.Fill(ds, "prog");
FillControls();
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
Here we have set the Text property of the text boxes to the string values of the corresponding fields of current record. We have used the Rows collection of the dataTable and using its indexer we have got the DataRow representing the current record. We then accessed the indexer property of this DataRow using the column name to get the data in the respective field. If this explanation looks weird to you, you can simplify the above statements as
DataRow row = dataTable.Rows[currRec]; // getting current row object data = row["artId"]; // getting data in the artId field string strData = data.ToString(); // converting to string txtArticleId.Text = strData; // display in the text box
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
We have set the Name property of the text boxes (from top to bottom) as txtArticleID, txtArticleTitle, txtArticleTopic, txtAuthorId, txtAuthorName, txtNumOfLines and txtDateOfPublishing. Also we have set the ReadOnly property of all the text boxes to true as don't want the user to change the text. The names of the buttons (from top to bottom) are btnLoadTable, btnNext and btnPrevious. Initially we have disabled the Next and Previous buttons (by setting their Enabled property to false). We have also defined three variables in the Form class:
Public Class ADOForm Inherits System.Windows.Forms.Form various methods Private dataTable As dataTable Private currRec As Integer = 0 Private totalRec As Integer = 0 ' Private global members to be used in
...
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 number of records in the table. Loading table For the LoadTable button, we have written the following event handler
Private Sub btnLoadTable_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoadTable.Click ' for Sql Server Dim connectionString As String = "server=P-III; database=programmersheaven;" + _ "uid=sa; pwd=;"
connectionString
As
String
"data
source
Dim commandString As String = "SELECT " + _ "artId, title, topic, " + _ "article.authorId as authorId, " + _ "name, lines, dateOfPublishing " + _ "FROM " + _ "article, author " + _ "WHERE " + _ "author.authorId = article.authorId"
dataTable = ds.Tables("prog")
FillControls()
End Sub
First we created the connection, data adapter and filled the dataset object, all of which we have discussed earlier. It should be noted that we have commented out the code for the OleDb provider (MS-Access) and are using SQL Server specific code. If you would like to use an Access databases, you can simply comment the SQL server code out and de-comment the Access code. Next, we have assigned the data table resulting from the query to the dataTable object which we declared at the class level, assigned zero to currRec variable and assigned the number of rows in the dataTable to the totalRec variable:
dataTable=ds.Tables("prog")currRec=0totalRec=dataTable.Rows.Count
Then we called the FillControls() method, which fills the controls (text boxes) on the form with the current record of the table "prog". Finally we enabled the Next and Previous Buttons.
Here we have set the Text property of the text boxes to the string values of the corresponding fields of the current record. We have used the Rows collection of the dataTable and using its indexer we have got the DataRow representing the current record. We have then accessed the indexer property of this DataRow
using the column name to get the data in the respective field. If this explanation looks weird to you, you can simplify the above statements to:Dim row As DataRow = dataTable.Rows(currRec) ' getting current row Dim data As Object = row("artId") ' getting data in the artId field Dim strData As String = data.ToString() ' converting to string txtArticleId.Text = strData ' display in the text box
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 first increment the integer variable currRec and check if it has crossed the last record (using the totalRec variable) in the table. If it has, then we move the current record to the first record. We then call the FillControls() method to display the current record on the form. Similarly the event handler for the Previous button looks like this:
Private Sub btnPrevious_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnPrevious.Click currRec -= 1 If currRec < totalRec Then currRec = totalRec - 1 End If FillControls() End Sub
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); DataSet ds = new DataSet(); da.Fill(ds, "Article"); SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da); da.InsertCommand = cmdBuilder.GetInsertCommand(); da.UpdateCommand = cmdBuilder.GetUpdateCommand(); da.DeleteCommand = cmdBuilder.GetDeleteCommand();
VB.Net Version
Dim conn As New uid=sa; pwd=;") SqlConnection("server=FARAZ; database=programmersheaven;
Dim cmdStr As String cmdStr = "select * from article" Dim da As New SqlDataAdapter(cmdStr, conn)
Dim cmdBuilder As New SqlCommandBuilder(da) da.InsertCommand = cmdBuilder.GetInsertCommand() da.UpdateCommand = cmdBuilder.GetUpdateCommand() da.DeleteCommand = cmdBuilder.GetDeleteCommand()
What are the general steps for updating the records in dataset?
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. Secondly we need to add parameters to these commands. 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
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;
VB.Net Version
Dim dt = ds.Tables("Article") dt.Rows(2)("lines") = 700
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;
VB.Net Version
Dim dt = ds.Tables("Article")
dt.Rows(2)("lines") = 700
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);
VB.Net Version
Dim dt As DataTable dt = ds.Tables("Article")
' Insert Dim dr As 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)
C# Version
DataTable dt = ds.Tables["Article"]; // Delete DataRow dr = dt.Rows[3]; dr.Delete();
VB.Net Version
Dim dt As DataTable dt = ds.Tables("Article")
The connected environment of data access is the traditional procedure for accessing data programmatically. The differentiating property of the connected data access environment is that here you (the programmer) is required to manage the connection with the database. You can only perform database operations when, there exists an open connection to the database. Hence, before performing any database operation (select, update, insert, delete), the programmer opens a database connection and close the database connection after performing the database operations. The important objects for working in the connected environment are: Connection (SqlConnection, OleDbConnection, etc): It represents a connection to the database. All the connection objects in the ADO.Net implement the System.Data.IDbConnection interface. Command (SqlCommand, OleDbCommand, etc): It represents the SQL command sent to the database, e.g., SELECT, UPDATE, INSERT, DELETE. All commands in ADO.Net implements IDbCommand interface DataReader (SqlDataReader, OleDbDataReader, etc): It represents a data stream that can be used to read the result of your query returned by the database server. Using this object, you read the individual records and their fields returned as a result of your query to the database server. All the data readers in ADO.Net implement the System.Data.IDataReader interface.
How do I read data (or records) from database using data reader?
To read data from the database, (SqlConnection, etc) and open it. you first make a connection object
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 database=programmersheaven;" + _ "uid=sa; pwd=" Dim conn As New SqlConnection(connString) conn.Open() = "server=siraj;
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 objects 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 DataReaders 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 txtData.Text txtData.Text txtData.Text } += += += += reader["authorId"].ToString(); ", "; reader["name"].ToString(); "\r\n";
VB.Net Version
While reader.Read() txtData.Text += txtData.Text += txtData.Text += txtData.Text += End While reader("authorId").ToString() ", " reader("name").ToString() vbCrLf
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);
while(reader.Read()) { txtData.Text += reader["authorId"].ToString(); txtData.Text += ", "; txtData.Text += reader["name"].ToString(); txtData.Text += "\r\n"; } conn.Close();
VB.Net Version
Dim connString As String 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) = "server=siraj;
While reader.Read() txtData.Text += reader("authorId").ToString() txtData.Text += ", " 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')"; SqlCommand cmd = new SqlCommand(cmdString, conn);
VB.Net Version
Dim connString As String database=programmersheaven;" + _ "uid=sa; pwd=" Dim conn As New SqlConnection(connString) = "server=FARAZ;
' INSERT Query Dim cmdString As String = "INSERT INTO Author " + _ "(authorId, name) " + _ "VALUES(3, 'Anders Hejlsberg')"
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";
VB.Net Version
Dim connString As String database=programmersheaven;" + _ "uid=sa; pwd=" Dim conn As New SqlConnection(connString) = "server=FARAZ;
' UPDATE Query Dim cmdString As String = "UPDATE Author " + _ "SET name = 'Grady Booch' " + _ "WHERE authorId = 3"
command does not return anything and thus the method to call on the SqlCommand object is called ExecuteNonQuery().
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";
VB.Net Version
Dim connString As String database=programmersheaven;" + _ "uid=sa; pwd=" Dim conn As New SqlConnection(connString) = "server=FARAZ;
' DELETE Query Dim cmdString As String = "DELETE FROM Author " + "WHERE authorId = 3"
How do I write common code for different dot net framework data providers?
The System.Data namespace contains the interfaces implemented by different dot net framework data providers, such as: IDbConnection implemented by SqlConnection, OracleConnection, OleDbConnection, OdbcConnection classes represents a connection with the database server IDbCommand implemented by SqlCommand, OracleCommand, OleDbCommand, OdbcCommand classes represents an SQL command passed to the database server IDbDataAdapter implemented by SqlDataAdapter, OracleDataAdapter, OleDbDataAdapter, OdbcDataAdapter classes represents a data adapter used to fill the data set in the disconnected environment of the ADO.Net IDataReader implemented by SqlDataReader, OracleDataReader, OleDbDataReader, OdbcDataReader classes represents a data reader used to read records from the database server, analogous to read only, forward only cursor IDbTransaction implemented by SqlTransaction, OracleTransaction, OleDbTransaction, OdbcTransaction classes represents a transaction established with the database server
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;
private const string GetValueCmdText ="SELECT value FROM MyTable WHERE name = '";
{ cmd.CommandText = GetValueCmdText + name + "'"; IDataReader reader = cmd.ExecuteReader(); if(reader.Read()) { return reader["value"].ToString(); } else { return null; } }
// more functions... }
VB.Net Version
Friend Class DataAccessModule
Private Const GetValueCmdText As String ="SELECT value FROM MyTable WHERE name = '"
Public Sub New(ByVal conn As IDbConnection) Me.conn = conn cmd = conn.CreateCommand() conn.Open() End Sub
Public Function GetValue(ByVal name As String) As String cmd.CommandText = GetValueCmdText + name + "'" Dim reader As IDataReader = cmd.ExecuteReader() If (reader.Read()) Then Return reader("value").ToString() Else Return Nothing End If End Function
End Class
What is the advantage of using stored procedure over the SQL queries?
Writing the SQL statements inside our code is usually not a good idea. In this way you expose your database schema (design) in the code which may be changed. Hence most of the time programmers use stored procedures instead of plain SQL statements. A stored procedure is a precompiled executable object that contains one or more SQL statements. Hence you can replace your complex SQL statements with a single stored procedure. Since, stored procedures are precompiled objects they execute faster at the database server. Most of the time, stored procedures contain more than one command; in this case, the time to pass the individual commands to the database server from the program is saved. The database is issued just one command (to execute the stored procedure) and the DB server executes all the commands and returns the result in the end. Hence, the overall interaction time with the DB server reduces in a great deal. This can result in a huge optimization in case where the DB server is accessed via a slow network.
How do stored procedure look like, can you provide some sample stored procedures?
Here we are presenting a brief review of four basic type of stored procedure for SELECT, INSERT, UPDATE and DELETE operations. In SQL Server, you can create and add stored procedures to your database using the SQL Server Enterprise Manager.
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 dont 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.
Here we have used only one parameter as to delete a record you only need its primary key value.
This probably is the simplest of all. It does not take any parameter and only selects all the records from the Article table. All the four stored procedures presented above are kept extremely simple so that the reader does not find any difficulty in understanding the use of stored procedure in his C#/VB.Net code. The real world stored procedures are much more complex and off course useful than these!
Thats 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
What are the important points when developing a data access app with ADO.Net?
Always try to use the base interfaces for connection, command, data reader and other objects. Always try to use the SqlClient, SqlServerCe and OracleClient to connect with the Sql Server, Sql Server CE and Oracle Database servers as they are specialized and optimized for the specific database servers. Still remember to reference the data provider specific objects (SqlConnection, OracleCommand) to reference with the base interface (IDbConnection, IDbCommand)
C# Version
IDbConnection conn = new SqlConnection(); ... IDbCommand cmd = new OracleCommand();
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.Nets 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 dont update the data source (by calling DataAdapters Update() method and DataSets 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).
How can I make my first application with DataGrid using the data from ADO.Net?
Lets create a simple application first that loads a table data from database server to the data grid control. First of all, add a data grid control and a button to your form from Visual Studio toolbox. We have set the Name property of data grid to dgDetails and its CaptionText property to ProgrammersHeaven Database. The name of button is btnLoadData. The event handler for button is:
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
As
String
"server=P-III;
"uid=sa; pwd=;"
Dim conn As New SqlConnection(connectionString) Dim cmdString As String = "SELECT * FROM article" Dim dataAdapter As New SqlDataAdapter(cmdString, conn) Dim ds As New DataSet() 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.
How can I make my data grid to view data from multiple related tables?
Lets see how we can use Data Grid control to show multiple related tables. When two tables are related, one is called the parent table while the other is called the child table. The child table contains the primary key of parent table as a foreign key. For example in our ProgrammersHeaven database, table Author is the parent table of the Article table as the Article table contains AuthorId as foreign key which is a primary key in the Author table. 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
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);
string cmdString = "SELECT * FROM article"; SqlDataAdapter dataAdapter = new SqlDataAdapter(cmdString, conn); DataSet ds = new DataSet(); dataAdapter.Fill(ds, "article");
cmdString = "SELECT * FROM author"; dataAdapter = new SqlDataAdapter(cmdString, conn); dataAdapter.Fill(ds, "author");
VB.Net Version
Private Sub btnLoadData_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnLoadData.Click
As
String
"server=P-III;
"uid=sa; pwd=;" Dim conn As New SqlConnection(connectionString) Dim cmdString As String = "SELECT * FROM article" Dim dataAdapter As New SqlDataAdapter(cmdString, conn) Dim ds As New DataSet() dataAdapter.Fill(ds, "article")
cmdString = "SELECT * FROM author" dataAdapter = New SqlDataAdapter(cmdString, conn) dataAdapter.Fill(ds, "author")
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.
What are the issues related to the deployment of data access application?
Some of the basic issues related to the deployment of the data access applications are: Can we suppose the required database exists at the target location? If the database does exist then how can we get the connection string of it? Should we get it at the installation time? Or at the first run? If the database does not exist then how it can be created? Is it the responsibility of human installing our application? Or the application should create it at the time of installation? If the database is to be created by the application installation, then how does the installation setup know where (on which machine) to create the database? And what user name and password the setup should use to create the database? Once, the database is created or its connection string is found at the setup time, then how to store the connection string for later use (regular execution)? What if the database address (connection string) is changed during the application life cycle then what should be the application behavior? How can the application be aware of the new connection string? If the database schema is hard-coded in the code (like table and field names) and the DB schema is changed (table/field name or data type is changed or new field/table added or some fields/tables deleted) because of any reason, then how to fix this problem?
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
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
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 = "";
VB.Net Version
Dim connStr As String
Dim udl As MSDASC.DataLinks udl = New MSDASC.DataLinksClass Dim conn As ADODB.Connection = udl.PromptNew()
You can use this code in the overrided Install() method of your projects installer class (the class derived from System.Configuration.Install.Installer class), and add the project output in the Custom Actions of the setup project.
How do I supply the connection string during first run or during the regular execution?
Well that should be very simple Just add the Data Link Properties dialog box at the start of the application or during the regular execution of the application whenever you need it. Alternatively, you can also provide your own designed user interface for connection string related properties, if your application supports specific .Net data providers (like System.Data.SqlClient or System.Data.OracleClient)
C# Version
string connStr = "";
// ...
// Read connection string from the text file StreamReader sr = new StreamReader(@"C:\ConnectionString.txt"); connStr = sr.ReadLine();
VB.Net Version
Dim connStr As String = ""
' Write connection string to text file Dim sw As New StreamWriter("C:\ConnectionString.txt") sw.WriteLine(connStr)
' ...
' Read connection string from the text file Dim sr As New StreamReader("C:\ConnectionString.txt") connStr = sr.ReadLine()
C# Version
string connStr = "";
// Write connection string to xml file XmlDocument xmlDoc = new XmlDocument(); XmlNode xn "ConnectionString", ""); = xmlDoc.CreateNode(XmlNodeType.Element,
// ...
// Read connection string from the text file XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(@"C:\ConnectionString.xml"); XmlNode xn = xmlDoc.SelectSingleNode("ConnectionString"); connStr = xn.InnerText;
VB.Net Version
Dim connStr As String = ""
' Write connection string to xml file Dim xmlDoc As New XmlDocument Dim xn As XmlNode xn = xmlDoc.CreateNode(XmlNodeType.Element, "ConnectionString", "") xn.InnerText = connStr xmlDoc.AppendChild(xn) xmlDoc.Save("C:\ConnectionString.xml")
' ...
' Read connection string from the xml file Dim xmlDoc As New XmlDocument xmlDoc.Load("C:\ConnectionString.xml") Dim xn As XmlNode xn = xmlDoc.SelectSingleNode("ConnectionString") connStr = xn.InnerText
Access
We will start with the assumption that you have a data access application. Note that we are only providing here the C# example. The VB.Net example is exactly similar. Why we didnt include the VB.Net example? Because, the intent here is not to explain the code but the procedure of how to create the data accessing applications deployment project which is independent of the language being used. All the code we will present here has already been presented in the previous FAQs and explained in much detail. 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
public class Installer1 : System.Configuration.Install.Installer
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.
public override void Install(IDictionary stateSaver) { base.Install (stateSaver); string connStr = "";
// Write connection string to xml file XmlDocument xmlDoc = new XmlDocument(); XmlNode "ConnectionString", ""); xn = xmlDoc.CreateNode(XmlNodeType.Element,
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.
private void btnShowConnStr_Click(object sender, System.EventArgs e) { string connStr = "";
// Read connection string from the xml file XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(@"C:\ConnectionString.xml"); XmlNode xn = xmlDoc.SelectSingleNode("ConnectionString"); connStr = xn.InnerText; MessageBox.Show(connStr, file"); "Connection String from XML
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.
OR
private void CreateRelation() { DataColumn parentCol; DataColumn childCol;
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.
SqlDataReader myReader = myCommand.ExecuteReader();
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 DataSet is a in-memory representation of data that provides a consistent relational programming model regardless of the data source. It can be used with multiple data sources. The DataSet represents a complete set of data including related tables, constraints, and relationships among the tables. The methods and objects in a DataSet are consistent with those in the relational database model. The DataSet can also persist and reload its contents as XML and its schema as XML Schema definition language (XSD) schema. 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. On connecting to a Microsoft ?SQL Server database, an increase in overall performance can be obtained by using the SqlDataAdapter along with its associated SqlCommand and SqlConnection. For other OLE DB-supported databases, use the DataAdapter with its associated OleDbCommand and OleDbConnection.
SqlDataAdapter da = new SqlDataAdapter(); da.TableMappings.Add("your mapping","your mapping"); da.SelectCommand = myCmd; DataSet ds = new DataSet(); da.Fill(ds); DataTable resultTable = ds.Tables[0];
ConnString = Source=C:\Test.mdb"
"Provider=Microsoft.Jet.OLEDB.4.0;"
&
"Data
Dim Conn As New System.Data.OleDb.OleDbConnection(ConnString) Conn.Open() Dim dapt As New System.Data.OleDb.OleDbDataAdapter("Table1", Conn)
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.
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 cmd = New OleDbCommand(str, cn) icount = cmd.ExecuteNonQuery &
MessageBox.Show(icount) 'displays number of records inserted Catch End Try End Sub
A file will be inserted in the Database each time the code is executed.
ASP.NET
What is the difference between ASP and ASP.NET?
Web application development in .NET with ASP.NET has evolved a great deal. The overall architecture of web applications in .Net is much more improved and robust. The enhanced features in ASP.NET make it the best available technology for web application development. The code behind the ASP.Net scripts can be in written in any .Net compliant programming language. 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 applications can be designed and developed using RAD (Rapid Application Development) tools. ASP.NET web forms support a variety of controls and also support user created and third party controls. Any .NET FrameWork language can be used to develop ASP.NET applications. ASP.NET uses the Common Language Runtime (CLR) resource and benefits from it's features.
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.
What are Web Services and the underlying protocol used with it?
Web Services are applications that provide services on the internet. Web services allow for programmatic access of business logic over the Web. Web services typically rely on XML-based protocols, messages, and interface descriptions for communication and access. 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. Business integration Web services allow trading partners to engage in e-business allowing them to leverage the existing Internet infrastructure. Organizations can send electronic purchase orders to suppliers and receive electronic invoices. Doing e-business with Web services means a low barrier to entry because Web services can be added to existing applications running on any platform without changing legacy code. 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.
How to generate a WebService proxy? What are SOAP, WSDL, and UDDI?
SOAP is an XML-based messaging protocol designed for exchanging formatted data (messages) over the Internet. Using SOAP you can send request and reply messages. SOAP is simple, easy to use, light weight and completely neutral with respect to operating systems, programming languages, and distributed computing platforms. After SOAP came into existence as a mechanism for exchanging XML messages among enterprises, a function was needed to describe the messages and how they are exchanged.
The Web Services Description Language (WSDL) is a particular form of an XML Schema. Developed by Microsoft and IBM for the purpose of defining the XML message, operation, and protocol mapping of a web service accessed using SOAP or other XML protocol. WSDL defines web services in terms of "endpoints" that operate on XML messages. The WSDL syntax allows both the messages and the operations on the messages to be defined abstractly, so they can be mapped to multiple physical implementations. The current WSDL specification describes how to map messages and operations to SOAP 1.1, HTTP GET/POST and MIME. WSDL creates web service definitions by mapping a group of endpoints into a logical sequence of operations on XML messages. The same XML message can be mapped to multiple operations (or services) and bound to one or more communications protocols using "ports". The "Universal Description, Discovery, and Integration" (UDDI) defines a data model (in XML). Also SOAP API's for registration and searching business information, web services that a business exposes to the Internet are also covered. UDDI is an independent consortium of vendors founded by Microsoft, IBM and Ariba. This project purpose of developing an Internet standard for web service description registration and discovery. 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 information in UDDI is categorized according to industry type and geographical location, allowing UDDI subscribers to search through lists of potentially matching businesses. Once a specific business is chosen, another call to UDDI is made to obtain the specific contact information for that business. The contact information includes a pointer to the target business's WSDL or other XML schema file describing the web service that the target business publishes.
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. Using the Trace Utility on Client To see all send/receive messages from a service, do the following steps on the client. 1) Copy the WSDL file from the server to the client. 2) Modify location attribute of the <soap:address> element in the local copy of the WSDL document to direct the client to
localhost:8080
Make a note of the current host and port. For example, Change
<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). 5) In the Destination host box, enter the host specified in Step 2. 6) In the Destination port box, enter the port specified in Step 2. 7) Click OK.
Below is a simple example of how to upload a file via an ASP.NET page using C#.
<%@ Import Namespace="System" %> <%@ Import Namespace="System.Web" %> <%@ Import Namespace="System.Web.UI.HtmlControls" %> <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Drawing" %> <html> <head> <title>upload_cs</title> </head> <script language="C#" runat="server"> public void UploadFile(object sender, EventArgs e) { if (loFile.PostedFile != null) { try { String strFileName, strFileNamePath, strFileFolder; strFileFolder = Context.Server.MapPath(@"data\"); strFileName = loFile.PostedFile.FileName; strFileName = Path.GetFileName(strFileName); strFileNamePath = strFileFolder + strFileName; loFile.PostedFile.SaveAs(strFileNamePath); lblFileName.Text = strFileName; lblFileLength.Text = loFile.PostedFile.ContentLength.ToString(); lblFileType.Text = loFile.PostedFile.ContentType; pnStatus.Visible = true; } catch (Exception x) { Label lblError = new Label(); lblError.ForeColor = Color.Red; lblError.Text = "Exception occurred: " + x.Message; lblError.Visible = true; this.Controls.Add(lblError); } } } </script> <body> <form id="upload_cs" method="post" runat="server" enctype="multipart/formdata"> <P> <INPUT type="file" id="loFile" runat="server"> </P> <P> <asp:Button id="btnUpload" runat="server" Text=" Upload " OnClick="UploadFile"></asp:Button></P> <P> <asp:Panel id="pnStatus" runat="server" Visible="False"> <asp:Label id="lblFileName" Font-Bold="True" Runat="server"></asp:Label> uploaded<BR> <asp:Label id="lblFileLength" Runat="server"></asp:Label> bytes<BR> <asp:Label id="lblFileType" Runat="server"></asp:Label> </asp:Panel></P> </form> </body> </html
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.
Tip In order to send email through your mail server, you should set the static SmtpServer property of the SmtpMail class to mail-fwd.
3. Reduces total response time per page request. Using HTTP compression helps end users experience a 50% reduction in download time. 4. HTTP compression reduces the size of files sent from your Web server to the Web browser by an average of 30 to 50 percent which is a dramatic decrease in bandwidth. 5. Using IIS 6.0 compression feature you can have savings in monthly bandwidth charges. 6. You can reduce bandwidth by enabling compression, and serve more users with the same hardware. 7. You can delay or eliminate the need to add more Web servers by enabling IIS 6.0 compression, even when your site gets more traffic. 8. Management code for compression is now part of core IIS 6.0 Web server for speed and stability. 9. Server-side compatibility issues are resolved. 10. Granular compression allows turning compression on/off at the global, site, folder, and file levels.
What is State Management and what are the different ways to maintain a state in .Net?
Web pages are recreated each time a page is posted to a server. In traditional Web programming, this would ordinarily mean that all information associated with the page and the controls within the page would be lost with each round trip. To overcome this inherent limitation of traditional Web programming, the ASP.NET page framework includes various options to help you preserve changes when Managing the State. The page framework includes a facility called view state that automatically preserves property values of the page and all controls on it between round trips. However, you will probably also have application-specific values that you want to preserve. This can be done using state management options. Client-Based State Management Options: View State Hidden Form Fields Cookies Query Strings Server-Based State Management Options: Application State Session State Database Support
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.
The above tags are explained below: <ImageUrl>: The image URL that presents the advertisement image. <NavigateUrl>: The on click redirect URL. <AlternateText>: Image description/name thats show when the mouse is over the image ( Optional use ). <Keyword>: Optional parameter that specifies the keyword (category) like books, programming etc. <Impressions>: A number input that indicates the weight of the advertisment. This can be use to control the order of rotation with respect to other advertisments in the file. Again, this is optional.
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. The sample code for that is:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal_ e As System.EventArgs) Handles Button1.Click TextBox2.Text = TextBox1.Text
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. .ControlTovalidate property is used to set the control to be validated and the .ControlToCompare property is used to identify the control to be compared. To work with this control drag a CompareValidatorControl, a Command Button and two TextBoxes from the ToolBox. The intention is to enter two values the textboxes. If the two values do not match, an error is generated denoting that the values are not alike. Set the following control properties in CompareValidatorControl; .ControlToCompare property as TextBox1 and .ControltoValidate property as TextBox2. 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.
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. To work with a RegularExpressionValidator control; Drag a TextBox and a Command Button from the ToolBox. Our intention is to check for the format of an email address and display an error message if the input format is not correct. An example of a correctly formated inpput would be "xyz@programmersheaven.com". To implement format definition. In the properties window of the Regularexpression click on the ellipse button for ValidationExpression and select Internet E-mail Address from the pop-up window. When you run the program and enter a value not in the format of abc@xyz.com the error message is displayed.
What is the difference between a Web User Control and a Web Custom Control?
Web custom controls are compiled components that run on the server and encapsulate the user-interface and other related functionality into reusable packages. They can include all the design-time features of standard ASP.NET server controls, including full support for Visual Studio design features such as the Properties window, the visual designer, and the Toolbox. There are several ways to create Web custom controls: You can compile a control that combines the functionality of two or more existing controls. For example, if you need a control that encapsulates a button and a text box. You can create it by compiling the existing controls together. 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.
How are the Windows form applications different from the Console Applications?
Windows applications are facilitated with the Windows standard user interface controls (like button, text box, list box, picture box and etc) and the standard events of Windows operating system. On the other hand, the Console Application can only take user input and output from/to the Console, command or a shell window. Windows form applications are more responsive and may use a lot of features like shortcut and icons. On the other hand, console applications are light weight and are used for testing and background service type applications. Several Java based web servers are implemented on Windows using Console application.
How are the Windows form applications different from the Console Applications?
Windows applications are facilitated with the Windows standard user interface controls (like button, text box, list box, picture box and etc) and the standard events of Windows operating system. On the other hand, the Console Application can only take user input and output from/to the Console, command or a shell window. Windows form applications are more responsive and may use a lot of features like shortcut and icons. On the other hand, console applications are light
weight and are used for testing and background service type applications. Several Java based web servers are implemented on Windows using Console application.
What support does the Visual Studio.NET provide for the development of .NET win form applications?
Visual Studio.NET provides an enormous support for the development of Win Form applications. The key features of Visual Studio.NET IDE include: 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
How do I make my first Hello, WinForm .NET form application using VS.NET and Visual C#?
C# Version Using Visual Studio.NET to build the Hello WinForm Application So we have had a lot of Visual Studio.NET introduction. Now, lets use Visual Studio.NET IDE to build the Hello WinForm application which we created earlier in the lesson. Creating a new Project First of all, we need to create a new C# Windows Application Project. For this, start Visual Studio.NET and click File -> New -> Project. It will show the following screen [IMAGE1] From the above screen, select Visual C# Projects in Project types and Windows Application in Templates. Write the name of the new project (LearningWinForm in the above figure) in the text box labeled Name. Select the disk path where you wish to store the project using Browse Button and click OK. It will show you an empty form in the designer view similar to the figure below [IMAGE2] The layout of the form designer screen may be somewhat different from the one shown above. Your toolbox and properties window may be visible and some other
windows may not be visible. You can change these settings using View menu as described earlier in the lesson. Setting various properties of the form You can change the default properties of the form using the Properties window. For this, select (click) the form and select the properties window (If the properties window is not visible in the right hand pan, select View -> Properties Window). Now change the title of the form and the name of the forms class in the code using Text and Forms Name property respectively as shown in the following figure. IMAGE3] Adding Controls to the Form Now select the Label control from toolbox and place it on the form and resize it as appropriate. Select (click) the label on the form and from the properties window, set its Text property to Hello WinForm and the Name property to lblGreeting. The name of a control is the name of its corresponding instance in the source code. Now select the Button control from toolbox and place it on the form and resize it appropriately. Select (click) the button and set its Name property as btnExit and Text property as Exit from the properties window. The form should now look like [IMAGE4] Adding Event Handling Now, we need to add the event handling code for the Exit button. For this, simply double click the Exit button in the designer. It will create a new event handler for the Exit buttons Click event and take you to the source code as shown in the following figure [IMAGE5] 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 buttons Click event. Executing the application That is it! The Hello WinForm application is complete. To compile and execute the application, select Build -> Build Solution (or press Ctrl+Shift+B) and then select Debug -> Start Without Debugging (or press Ctrl+F5). Authors Note: Unfortunately, my copy of Visual Studio.NET 2001 does not change the name of form (from Form1 to MyForm in our case) in the call to Application.Run() method in the Main() method. I have to explicitly change the Main() method like this
static void Main() { Application.Run(new MyForm()); }
If you are also experiencing the same problem with your copy of Visual Studio.NET, make sure to change the name of the form in Main() method also whenever you change its name in the Properties Window in order to avoid the compilation error This will compile and start the Hello WinForm application in a new window as shown below
[IMAGE6] To close the application, click the Exit button or the close button at the title bar of the window. The code generated by the Form Designer You can toggle between Form Designer and Code using View -> Designer and View -> Code. After switching to the code, you will find the code generated by the form designer to be very similar to that we have written earlier in the lesson. To understand the code better, we recommend removing all the comments and region boundaries.
How do I make my first Hello, WinForm .NET form application using VS.NET and Visual Basic.NET?
VB.NET Version Using Visual Studio.NET to build the "Hello WinForm" Application Let's use the Visual Studio.NET IDE to build the "Hello WinForm" application. Creating a new Project First of all, we need to create a new VB.NET Windows Application Project. For this, start Visual Studio.NET and click File -> New -> Project. It will show the following screen: [IMAGE7] From the above screen, select 'Visual Basic Projects' in Project types and 'Windows Application' in Templates. Write the name of the new project ('LearningWinForm' in the above figure) in the text box labeled Name. Select the location where you wish to store the project using the Browse... Button and click OK. It will show you an empty form in the designer view similar to the figure below: [IMAGE8] The layout of the form designer screen may be somewhat different from the one shown above. Your toolbox and properties window may be visible and some other windows may not be visible. You can change these settings using the View menu as described earlier in the lesson. Setting various properties of the form You can change the default properties of the form using the Properties window. For this, select (click) the form and select the properties window (If the properties window is not visible in the right hand pane, select View -> 'Properties Window). Now change the title of the form and the name of the form's class in the code by changing the Text and Name properties, as shown in the following figure. [IMAGE9] Adding Controls to the Form Now select the Label control from the toolbox, place it on the form and resize it as appropriate. Select (click) the label on the form and from the properties window, set its Text property to "Hello WinForm" and the Name property to 'lblGreeting'. The name of a control is the name of its corresponding instance in the source code. Now select the Button control from the toolbox, place it on the form and resize it appropriately. Select (click) the button and set its Name property to 'btnExit' and its Text property to 'Exit' using the properties window. The form should now look like this: [IMAGE10] Adding Event Handling Now we need to add the event handling code for the Exit button. For this, simply double click the Exit button in the designer.
This 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: [IMAGE11] 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. Executing the application That is it! The 'Hello WinForm' application is complete. To compile and execute the application, select Build ->Build Solution (or press Ctrl+Shift+B) and then select Debug -> Start Without Debugging (or press Ctrl+F5). This will compile and start the 'Hello WinForm' application in a new window as shown below: [IMAGE12] To close the application, click the Exit button or the close button on the title bar of the window. The code generated by the Form Designer You can toggle between the Form Designer and Code using View -> Designer and View -> Code. After switching to the code, you will find the code generated by the form designer to be very similar to that we have written earlier in the lesson. To understand the code better, we recommend removing all the comments and region boundaries.
architecture
of
.NET
win
form
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 MyForms 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
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. Index
How do I make my first Hello, WinForm .NET form application without VS.NET in Visual C#? C# Version
Building the Hello WinForm Application Lets 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 MyWindow : Form { public MyWindow() : base() { this.Text = "My First Windows Application"; this.Size = new Size(300, 300);
Label lblGreeting = new Label(); lblGreeting.Text = "Hello WinForm"; lblGreeting.Location = new Point(100, 100);
this.Controls.Add(lblGreeting); } } }
Understanding the Code In the start, we included three namespaces to our application using System; using System.Windows.Forms;
using System.Drawing;
The System namespace, as we stated in the first lesson, is the necessary ingredient of all C# applications. In fact, the Application class that we used later in the Main() method is defined in this namespace. The System.Windows.Forms namespaces contains the base classes for windows controls like Form, Label and Button. Finally, including the System.Drawing namespace is necessary as it contains the useful classes related to the drawing of controls. The Size and Point classes used later in the program are actually defined in System.Drawing namespace. 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 namespaces Size class. We passed two integers to the constructor of Size to specify the width and the height of the form.
public MyWindow() : base() { this.Text = "My First Windows Application"; this.Size = new Size(300, 300);
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.
public MyWindow() : base() { this.Text = "My First Windows Application"; this.Size = new Size(300, 300);
Label lblGreeting = new Label(); lblGreeting.Text = "Hello WinForm"; lblGreeting.Location = new Point(100, 100);
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 Lets 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 Buttons Click event. Following is the code for this modified application
using System; using System.Windows.Forms; using System.Drawing;
class MyWindow : Form { public MyWindow() : base() { // Form this.Text = "My First Windows Application"; this.Size = new Size(300, 300); this.StartPosition FormStartPosition.CenterScreen; =
// Label
Label lblGreeting = new Label(); lblGreeting.Text = "Hello WinForm"; lblGreeting.Location = new Point(100, 100);
// Button Button btnExit = new Button(); btnExit.Text = "Exit"; btnExit.Location = new Point(180, 180); btnExit.Size = new Size(80, 30); btnExit.Click += new EventHandler(BtnExitOnClick);
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 btnExits 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 forms 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. The output of the code will be Now you can press either the Exit Button or the close button at title bar to exit the application.
How do I make my first Hello, WinForm .NET form application without VS.NET in Visual Basic.NET? 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
End Class
Public Sub New() MyBase.new() Me.Text = "My First Windows Application" Me.Size = New Size(300, 300)
Dim lblGreeting As New Label() lblGreeting.Text = "Hello WinForm" lblGreeting.Location = New Point(100, 100)
Understanding the Code At the start, we included three namespaces in our application:
Imports System Imports System.Windows.Forms Imports System.Drawing
The System namespace, as we stated in the first lesson, is the necessary ingredient of all VB.NET applications. In fact, the Application class that we used later in the Main() method is defined in this namespace. The System.Windows.Forms namespaces contains the base classes for windows controls, e.g. Form, Label and Button. Finally, including the System.Drawing namespace is necessary as it contains the classes related to the drawing of controls. The Size and Point classes used later in the program are actually defined in the System.Drawing namespace. The System.Windows.Forms and System.Drawing namespaces can not be added to a project just by writing Imports statement for them. We also need to add references to the assemblies (for now take assemblies as Windows DLLs or library files for .NET) that contain the code of types these namespaces. For this we need to add reference to System.Windows.Forms.dll and System.Drawing.dll. To add a reference write click the Reference folder under the current project in the solution explorer and select Add Reference It will show the following window 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 ...
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.
Public Sub New() MyBase.new() Me.Text = "My First Windows Application" Me.Size = New Size(300, 300)
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.
Public Sub New() MyBase.new() Me.Text = "My First Windows Application" Me.Size = New Size(300, 300)
Dim lblGreeting As New Label() lblGreeting.Text = "Hello WinForm" lblGreeting.Location = New Point(100, 100)
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
End Sub
End Class
Public Sub New() MyBase.new() ' Form Me.Text = "My First Windows Application" Me.Size = New Size(300, 300)
' Label Dim lblGreeting As New Label() lblGreeting.Text = "Hello WinForm" lblGreeting.Location = New Point(100, 100)
' Button Dim btnExit As New Button() btnExit.Text = "Exit" btnExit.Location = New Point(180, 180) btnExit.Size = New Size(80, 30) AddHandler btnExit.Click, AddressOf BtnExitOnClick
Public Sub BtnExitOnClick(ByVal sender As Object, ByVal e As EventArgs) 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
' Form controls are usually private ' instance members of the form class Private WithEvents btnExit As New Button() Private lblGreeting As New Label()
' Form Me.Text = "My First Windows Application" Me.Size = New Size(300, 300)
' Label
' Button btnExit.Text = "Exit" btnExit.Location = New Point(180, 180) btnExit.Size = New Size(80, 30) 'AddHandler btnExit.Click, AddressOf BtnExitOnClick
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)
How do I provide the event handling for my form and controls using VS.NET?
Adding Event Handling You can provide event handling for forms and controls by implementing their respective event handlers. To implement an event handler for a form or control, go to Events tab of the properties window, and double click the desired event handler name. The form designer will add the event handler for the selected event in the source code of the application and take you there. If you want to implement a default event handler of the form or control, simply double click it. 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 buttons 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 buttons Click event.
How event handling is implemented in win form and .NET form controls with C#? 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 events 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 Buttons Click event. Following is the code for this modified application
using System; using System.Windows.Forms; using System.Drawing;
class MyWindow : Form { public MyWindow() : base() { // Form this.Text = "My First Windows Application"; this.Size = new Size(300, 300); this.StartPosition FormStartPosition.CenterScreen; =
// Label Label lblGreeting = new Label(); lblGreeting.Text = "Hello WinForm"; lblGreeting.Location = new Point(100, 100);
// Button Button btnExit = new Button(); btnExit.Text = "Exit"; btnExit.Location = new Point(180, 180); btnExit.Size = new Size(80, 30); btnExit.Click += new EventHandler(BtnExitOnClick);
{ 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 btnExits 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 forms Controls collection. The output of the code will be Now you can press either the Exit Button or the close button at title bar to exit the application.
How event handling is implemented in win form and .NET form controls with VB.NET? 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
End Class
Public Sub New() MyBase.new() ' Form Me.Text = "My First Windows Application" Me.Size = New Size(300, 300)
' Label Dim lblGreeting As New Label() lblGreeting.Text = "Hello WinForm" lblGreeting.Location = New Point(100, 100)
' Button Dim btnExit As New Button() btnExit.Text = "Exit" btnExit.Location = New Point(180, 180) btnExit.Size = New Size(80, 30) AddHandler btnExit.Click, AddressOf BtnExitOnClick
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 controls are usually private ' instance members of the form class Private WithEvents btnExit As New Button() Private lblGreeting As New Label()
Public Sub New() MyBase.new() ' Form Me.Text = "My First Windows Application" Me.Size = New Size(300, 300)
' Label
' Button
btnExit.Text = "Exit" btnExit.Location = New Point(180, 180) btnExit.Size = New Size(80, 30) 'AddHandler btnExit.Click, AddressOf BtnExitOnClick
Public Sub BtnExitOnClick(ByVal sender As Object, ByVal e As EventArgs) Handles btnExit.Click 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)
C# Version
myForm.Size = new System.Drawing.Size(400, 300);
VB.NET Version
myForm.Size = New System.Drawing.Size(400, 300)
What does it mean by Startup Window State of the form? How do I set the startup window state of the form?
The startup window state specifies whether the form should be displayed in normal, maximized or minimized state. It can be set using the WindowState property of the form. The data type of this property is System.Windows.Forms.FormWindowState enumeration, which has three members; Maximized, Minimized and Normal.
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
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.
C# Version
private void button1_Click(object sender, System.EventArgs e) { // Minimize the form window this.WindowState = FormWindowState.Minimized;
Thread.Sleep(2000);
Thread.Sleep(2000);
VB.NET Version
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Button1.Click
Thread.Sleep(2000)
Thread.Sleep(2000)
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
How do I hide maximize, minimize and close box at the form title bar?
To disable the maximize box at the form title bar, set the Maximize property of the form to false.
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 forms 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.
my
win
form
application
To exit the win form application programmatically, call the Application.Exit() method.
C# Version
Application.Exit();
VB.NET Version
Application.Exit()
message
box
in
my
form
To show the message box, call the MessageBox class Show() method. The message box is the modal form that notifies the user about certain event in the application and optionally takes the user feedback. The Show() is an static (C#) / Shared (VB.NET) method of the System.Windows.Forms.MessageBox class. It has a number of overloaded versions. The simplest one take the message text and display it in the message box.
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);
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)
C# Version
MySecondForm frm2 = new MySecondForm();
frm2.Show();
// frm2.ShowDialog();
VB.NET Version
Dim frm2 As New MySecondForm() frm2.Show() ' will present the non-modal form
' frm2.ShowDialog()
C# Note
Remember that only those forms that have a valid Main() method can be selected as the startup object.
What does it mean by scrollable forms in .NET? How can make my own form scrollable?
.NET introduces with it a concept of scrollable forms. A scrollable form is just like an html page that can be scrolled. You can access its controls by scrolling it down or right; if the contents (controls) dont fit in the form display area. You can make a form scrollable by setting its AutScroll property to true
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() Dim frmSplash As New Form2 frmSplash.Show() frmSplash.Update() Thread.Sleep(5000) frmSplash.Close() Me.Visible = True End Sub
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).
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Me.MaximizeBox = False End Sub End Class
Controls
What are win form controls? How they represented in .NET framework class library? are
A form may contain various user interface (UI) controls. The controls represent the visual components that allow user to interact with the application and perform the desired task. All the controls, in .Net, are represented by subclasses of System.Windows.Forms.Control class. Each form has a collection (named Controls) to store the constituent controls of the form. In fact, a form itself is a special type of control called Container Control, i.e., the Form class itself is derived from the ContainerControl class which is a subclass of the Control class. A container control, as the name suggests, may contain other controls. Other examples of the Container control include Panel and Tab Control.
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.
TextBox1.KeyPress If(e.KeyChar < "10" Or e.KeyChar > "100") Then MessageBox.Show("Enter Double Digits") End If End Sub
Private Sub Form1_Load(ByVal sender System.EventArgs) Handles MyBase.Load NewWindow.Show() End Sub
As
System.Object,
ByVal
As
Private Sub Button1_Click(ByVal sender System.EventArgs) Handles Button1.Click TextBox1.Text = NewWindow.TextBox1.Text End Sub
As
System.Object,
ByVal
As
End Class
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.
Assume that there is a TextBox on a Form and we want to display a description when the mouse is over the TextBox. Below is an example:
Private Sub Form5_Load(ByVal sender As System.Object, ByVal e _ As System.EventArgs) Handles MyBase.Load ToolTip1.SetToolTip(TextBox1, "Enter Some text") 'using the SetToolTip method to set the tip for the TextBox and the text that should appear End Sub
explorer, class view, properties tab, tool box, standard menu and toolbars. The key features of Visual Studio.NET IDE include: Keywords and syntax highlighting 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 help manage applications consisting of multiple files, which is what usually happens Help building user interface with simple drag and drop over the form window Properties tab that allows you to set different properties on a number of windows and web controls 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 Developer Network (MSDN) Library Compilation and building applications Execution of your application with/without debugger Deploying your .Net application over the Internet or on CDs
Why use the IDE when we can develop a .NET application for free?
The basic purpose of using the Visual Studio.NET or any IDE is to manage the application code. As the requirements and thus application evolves, the size of code increases. It is important to manage this code well, so the later modification and debugging can be carried out smoothly. This code management also makes it possible to use the library code developed previously and to develop the application in such a way so that various parts of it can be reused in future applications. The application is divided into several modules that are linked to work together to perform the required functionality. This is where the Integrated Development Environment (IDE) comes! 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; one for user interface application, other for accounts implementation, and the last one for information storage (into database or file system).
Then, you may further divide the user interface project to three folders; first (Forms) containing user interface forms second (AccountsAccessor) containing classes to interact with the accounts implementation project third (StorageAccessor) containing classes to interact with the information storage project
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.
Is there any other IDE available for the development of .NET programs?
Fortunately, there are a number of IDEs and source code editors available for the development of .Net programs. Some of these are introduced below: Borland C#Builder for the Microsoft? .NET Framework http://www.borland.com/csharpbuilder/ Borland C# Builder is perhaps the second most popular IDE for development with C# programming language after Visual Studio.Net. According to Borland, It is an integral component of the Borland solution for application lifecycle management, C#Builder accelerates the delivery of .NET Framework solutions with a design-driven approach to development that increases team productivity. C#Builder provides support for direct interoperability between the .NET Framework, the J2EE? platform, and CORBA? infrastructure, helping to simplify and reduce the cost of integrating .NET solutions with your existing software systems. And for faster, easier, and more flexible database development, C#Builder delivers high-performance native support for major enterprise-class databases. #develop (read as Sharp-Develop) http://www.icsharpcode.net/OpenSource/SD/ It is a free IDE for C# and VB.NET projects on Microsoft's .NET platform. It is open-source (GPL), and you can download both source code and executables from there site. In addition, you can find the latest information and changes on #develop, as well as get in touch with the team in the forum.
PrimalCode http://www.sapien.com/primalcode.htm PrimalCode is an innovative .NET development environment incorporating complete capability in a compact size that works with your existing hardware. Ideal for professional coders, PrimalCode streamlines every .NET project phase, from start-up to deployment. You can work faster, free from hours of repetitive and routine tasks. Best of all, PrimalCode needs only minimal drive space, so it runs full speed on your existing desktops or laptops.
What are the different parts and areas of Visual Studio.NET IDE's called?
The figure below highlights various parts of the Visual Studio.NET IDE.
You can see the toolbox window at the left hand side (#1) and the properties window at the right hand side (#2) of the above snapshot. The toolbox allows you to add different controls to your form. Once the control is placed on the form, you can change its various properties from the Properties window. You can also change the location and size of the controls using the mouse. Event properties can be changed by switching to the Event Properties panel (#3) in the Properties Window. The Toolbox, Properties Window, Help Window, Solution Explorer Window, Class View Window, Output Window and other helping windows in Visual Studio IDE can be set for Docking and Auto hiding. Windows that are set for auto hide appears only when they get focus (e.g. they have mouse pointer over them or receive a mouse click), and hide when they lose focus. A window can be set for auto hide by the button marked #4 in the above figure. The hidden windows are always accessible through the left and right hand panes of the form designer window. The right hand pane is marked with #5 in the above figure and has got the class view, help and solution explorer windows in the hidden state. If some of these windows are not visible in your visual studio IDE, you can make them visible from the View menu on the standard menu bar. 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.
Toolbox, Properties and Class View Tabs Now there is a single toolbox for all the Visual Studio.NETs 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++ 6s class view. Menus in the Visual Studio .NET IDE 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 applications user interface. It simplifies the task by allowing you to just drag and drop the required controls from the toolbox to the designers 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.
What are the different types of projects that can be created with Visual Studio.NET?
Visual Studio.NET allows you to create projects of these types: 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 engines 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
it
mean
by
code
folding
in
Visual
The Visual Studio.NET automatically groups the code at various boundaries (method, property, class, structure, interface, and namespace bodies). It then allows you to expand/collapse the regions of these code body groups using the familiar plus/minus sign used in the tree-view control (e.g., in Windows Explorer) which allows you to fold (collapse)/unfold (expand) the code regions
You can also define your own regions using the #region#end region block with your code.
The hot compiler highlights the syntax errors in your program as you type the code. The following figure shows an illustration of hot compiler in Visual Studio.NET
What is the difference between the Design View and the Code View of the Visual Studio.NET?
The design view opens the VS.NET form designer that allows you to place user interface controls on the form by simple drag and drop, resize them and set various properties in the convenient way. The designer automatically generates the required code for the program. The code view opens the source code editor that allows you to see the actual code of the program and perform any desired edition.
How can I compile and build a particular project and the whole solution?
To compile all the source files of the project and build the resulting assembly, right click the target project node in the solution explorer and select Rebuild project. 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.
What features does the Visual Studio.NET debugger provide to the developers?
Visual Studio.NET provides an integrated debugger. The debugger allows you to debug your application from within the Visual Studio.NET IDE and code editor. You can use the code editor to specify the break points and see the runtime values of the variables of a program. You can control the execution of your program step by step; e.g. you can pause the execution of the program after each line, you can jump the control of execution to the next method in the execution sequence. You can even change the runtime values of the variables at runtime and re-execute it! Its simply an amazing tool!
What is the difference between running an application with and without debugger?
When an application is run with debugger, the debugger will provide its services during the execution. This may slow down the execution of the program and is useful when the program is in the development and testing phase. When program is run without debugger, it is executed in the similar way as it will be executed at the client (user of the application) machine. The execution of the program without debugging is useful when application is about to be deployed or in the testing phase, when we are interested in measuring the efficiency and the throughput of the application.
How can I add a break point in my code? How can I remove a breakpoint?
To add a break point for some line, click at its left panel. You can also do this by right clicking the target line and selecting the 'Insert breakpoint'. To remove a break point from some line, click on its left pan. You can also do the same by right clicking on a target line and select 'Remove breakpoint'.
How can I see the runtime values of different variables of my code using debugger?
You can see the runtime value of a particular variable by just pointing a mouse over it when the program is running in debugger mode and is paused at some breakpoint. It will only show the value of any live variable. To see the runtime values of all the local variables of a method, see the 'Locals' debug window. This window is also accessible from Debug > Windows > Locals
Index
How can I see the runtime values of the content of a class or structure?
A class or a structure is represented in Locals and other debug windows with expandable tree. You can see its members by expanding its object node
When the execution of a program is paused at a breakpoint, how can I resume the execution?
You can resume the execution, either by selecting Debug > Continue (press F5) or using the various Step options like Step Into (F11) or Step Over (F10).
How do I step into and step over the code with debugger? What do stepping intoand stepping over actually mean?
The Step Into option (accessible through Debug -> Step Into or key F11) takes the execution control inside the calling method. For example, if the execution is paused at a line having code
int p = obj.GetInteger();
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 DebugStep 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:
int p = obj.GetInteger(); // line 1 Console.WriteLine(p); // line 2
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.
How do I change the name of the resulting assembly files (.exe and .dll)?
Right click the project and select properties. It will show the property pages for the project. You can change the resulting assembly name from Common Properties> General > Assembly Name.
references
in
context
of
the
VS.NET
A reference is the name and address of the .NET assembly or a COM component used inside some source files of the project. The Visual Studio.NET uses these added references when compiling your project assembly. A reference enables the language compiler to locate the referenced assemblies and COM component.
To add a reference to a .NET assembly, right click the Reference option under the project inside the solution explorer and select the Add Reference option. It will show you a user interface screen where you browse for the target assembly. When you have selected the assembly, 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. Index
What are the developing options in VS.NET? And what project templates are there?
Upon starting developing applications with Visual Studio .NET, Its possible to develop applications based on your choice. Here is a rundown of the different types of applications that can be developed using a vanilla install of VS.NET. Opening a new project: The following are the different options available in VS.NET and what they are used for. Windows Applications: This template allows you to create standard windows based applications.
Class Library: Class libraries are those that provide functionality similar to Active X and DLL's by creating classes that that can be used from other applications. 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. ASP.NET Web Applications: Create web-based application using IIS. You can develop Web pages, Rich Web Applications and Web Services. ASP.NET Web Service: For developing XML Web Services. 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. Console Application: Development of command line based applications. No GUI needed Windows Service: Windows Services are background programs that run without promp. An example would eb an SMTP server. Other: This template is to develop other kinds of applications such as enterprise applications, database applications etc.
will show you a user interface screen that allows you to add various kinds of items like report, icon, class file, windows form, etc. Select the appropriate item from here.
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 Microsofts 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). In addition to this, C# comes up with some new/exciting features like reflections, attributes, marshalling, remoting, threads, streams, data access with ADO.NET, etc. C# programming language is designed from the scratch keeping in mind the Microsoft.Net environment. MS.Net (and thus C#) programs runs on top of the Common Language Runtime (CLR), which provides the runtime support to them. 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. The following code demonstrates the creation of a two-dimensional jagged array.
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
} }
VB.NET also supports language interoperability with various .NET compliant languages. This means that you can use and enhance the code written in other .NET compliant languages. Similarly the code written in VB.NET can also be used and enhanced by other .NET compliant languages. Although VB6 also provided this functionality through COM but it was limited and difficult to use and manage. VB.Net makes it easier because of the presence of Intermediate Language (IL) and Common Language Specification (CLS) of the .NET architecture. VB6 uses COM (Component Object Model) as component architecture. VB.NET uses assemblies as its component architecture. The Assemblies architecture has removed a lot of problems with COM including DLL-Hell and versioning problem. Components created in VB6 (COM) need to make and update registry entries. VB.NET does not require any registry entry making the deployment easier VB6 used ASP to build web applications. VB.NET uses ASP.NET to build web applications. VB6 used ADODB and record-sets to implement data access applications. VB.NET uses ADO.NET and datasets to build data access applications. The ADO.NET also supports the disconnected data access.
Run the program by pressing "F5" on the keyboard or by selecting Debug->Start. The output of the program is Hello World. 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.
Example using the Option Statement. The following code does not perform any special function but will show where to place an Option statement.
Option Strict Off Imports System Module Module 1 Sub Main () Console.WriteLine (Using Option) End Sub End Module
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")>.
Sub Main() System.Console.WriteLine(December is & Months.December & th Month) End Sub End Module
When using constant's declared in an Enumeration, you need to refer to it like so:
Months.December.
The output of the above code displays December is the 12th Month.
The above code adds 22 months to the date we declared in the Program.
The above code displays Hello from Delegates just like a normal program but it uses Delegates to do it.
Shared Function GetIPAddress() As String Dim sam As System.Net.IPAddress Dim sam1 As String
GetIPAddress = sam1
End Function
Dim shostname As String shostname = system.Net.DNS.GetHostName console.writeline("Name of the System is = " & shostname) console.writeline("Your IP address is= " & GetIPAddress) End Sub
End Class
Compile the file as "vbc getip.vb /r:system.net.dll" Execute the "getip.exe". The computer's name and IP address will be displayed in the Console.
Imports System
Class SystemInfo
</Customer> </Document>
Shared Sub main() Dim dset As New System.Data.DataSet() Dim str As String = "Test.xml" 'Load the XML file in the data set dset.ReadXml("Test.xml") 'Read the XML content on the console Console.Write(dset.GetXml) 'Getting data from the user to be saved into the XML file Console.Write("Enter Name : ") Dim name, age, occupation As String name = Console.ReadLine Console.Write("Enter Age : ") age = Console.ReadLine Console.Write("Enter Occupation : ") occupation = Console.ReadLine Console.Write(name & age & occupation) Dim v(1) As String 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.
Class myclass Implements MyInt ' Implementing the above defined implements to use the interface interface, need to use the keyword
Function MyFun() As String Implements NewInt.MyFun dim str as string str="hello matey"
Class ConvertImages Shared Sub main() Dim str As String Console.Write("Path of the Image File to Convert :") str = Console.ReadLine() 'Initialize the bitmap object by supplying the image file path Dim bmp As New Bitmap(str) bmp.Save(str + ".gif", System.Drawing.Imaging.ImageFormat.Gif)
Console.Write("Image Sucessfully Converted to " & str & ".gif") End Sub End Class
End Class
Public Class Dest Protected overrides Sub Finalize() calling the Finalize method End Sub
End Class
Information
From
The
System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly .GetExecutingAssembly.Location) Return .FileMajorPart & "." & .FileMinorPart & "." & .FileBuildPart & "." & .FilePrivatePart End With End Function
Function Display() As String With System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly .GetExecutingAssembly.Location) Return .Comments End With End Function
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: Information for each public class or type used in the assembly Information on all public methods in each class. For instance, the method name and return values (if any) Information on every public parameter for each method, such as the parameter's name and type Information on public enumerations including names and values Information on the assembly version (each assembly has a specific version number)
Intermediate Language code to execute Required resources such as pictures, assembly metadata
#End Region
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click TextBox1.Text = Application.ExecutablePath End Sub End Class
sample demonstrates
how
to use
Try-Catch-Finally
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.
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