Visual Studio Net
 

What is Visual Studio.NET?

Microsoft Visual Studio.NET is an integrated development environment which is the successor of Microsoft Visual Studio 6. It eases the development process of .NET Application to great deal for Visual C#.NET, Visual Basic.NET, Visual C++.NET, Visual JScript.NET, Visual J#.NET, ASP.NET, etc The revolutionary approach in this new Visual Studio.NET is that for all the Visual Studio.NET Compliant Languages there is a single IDE, debugger, project and solution 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 IDE’s and source code editors available for the development of .Net programs. Some of these are introduced below:

Borland C#Builder for the Microsoft? .NET Frameworkhttp://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.

PrimalCodehttp://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.NET’s languages and tools. The toolbox (usually present on the left hand side) contains a number of common controls for windows, web and data applications like text box, check box, tree view, list box, menus, file open dialog, etc.

Properties Tab (usually present on the right hand side in IDE) allows you to set the properties on different controls and form without getting into code

Class View Tab shows all the classes that your project contains along with the methods and fields in tree hierarchy. This is similar to VC++ 6’s class view.

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 application’s user interface. It simplifies the task by allowing you to just drag and drop the required controls from the toolbox to the designer’s emulated form. It even sets the default properties for your controls. You can then change the properties of the form and control through the Properties Tab of the Visual Studio.NET IDE. The form designer also allows you to attach the even handlers with the controls.

Code Editor

The Visual Studio.NET Code Editor supports you in writing the code for your application. The code editor is tightly integrated with the designers. As you change the properties and add controls, the designer puts the required code in you application source code files which can be viewed using the code editor. The code editor is quite smart; it highlights the various categories of the code like keyword, constant and even the syntax and semantic errors. It provides the code completion through its intellisense; when you place dot (in C# and VB.NET) with your object references and namespaces it automatically shows the list of all available options to select from. Finally, the code editor is also used to debug the application using the integrated debugger.

What are VS.NET solutions and projects?

A Project is a combination of executable and library files that make an application or one of its modules (not a .NET assembly or VB.NET module; simply a separate part of the overall application). A project’s information is usually placed in a file with extension like ‘.vbproj’ where ‘vb’ represents Visual Basic (source programming language) and ‘proj’ stands for Project. Similarly C# projects are stored as ‘.csproj’ file where ‘cs’ stands for C Sharp. There are different kind of projects like Console Application, Windows application, ASP.Net Web Application, Class Library, Windows Control Library, Web Services and others.

A solution on the other hand is a placeholder for different logically related projects that make up an application. For example, a solution may consist of ASP.NET Web Application project and Windows Form project. The information for solution is stored in ‘.sln’ files while they can be managed using Visual Studio.NET’s Solution Explorer. Solutions are similar to VB 6’s Project Group and VC++ 6’s workspace.

A great thing about the Visual Studio.NET solutions is that it may contain projects built with any of the VS.NET compliant language. Hence, now your solution may consists of a database handling project in Visual C#, the GUI Application project in VB.NET and the protocol implementation project in VC++.NET!

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 engine’s web service, e.g., allows other applications to delegate the task of searching over the internet to Google web service and use the result produced by it in their own applications.
  • Class library contains components and libraries to be used inside other applications. A Class library can not be executed and thus it does not have any entry point.
  • Windows Control Library contains user defined windows controls to be used by Windows applications
  • Web Control Library contains user defined web controls to be used by web applications

How are projects different from the namespaces?

A Project is a physical grouping of the source code and resource files that make up an assembly and stored into some file. A namespace, on the other hand, is a logical grouping of related types which not necessarily reside into same assembly. A namespace may contain sub or child namespaces while there is not concept of child or sub projects. Finally, project is a Visual Studio.NET standard, while namespace is a .NET standard.

How are namespaces different from assemblies?

An assembly is a physical grouping of the source code and resource files that is stored into some file(s). A namespace, on the other hand, is a logical grouping of related types which not necessarily reside into same assembly. A namespace may contain sub or child namespaces while there is not concept of child or sub assemblies (module is something different from child namespace, as modules are integral and necessary parts of an assembly). An assembly not only contains the source code, it also contains manifest, version information (optional public key token) and culture information. A program may reference two or more assemblies with the same name (but with different versions) but a program can not contain two namespaces with the same name.

What does it mean by code folding in Visual Studio.NET?

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.

What does it mean by syntax highlighting?

Visual Studio.NET Code Editor highlights the keywords and syntax errors in your code as you type it with different colors and waves. This is called the syntax highlighting.

What does it mean by VS.NET hot compilation?

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 are regions in Visual Studio.NET IDE’s code view?

A region is a part of the code that can be folded/un-folded in the Visual Studio.NET code editor. You can also define your own regions using the #region…#end region block with your code.

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! It’s 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 run an application with and without debugger?

To run the application with debugger, select Debug > Run or press F5. To run the application without debugger, select Debug > Run without debugger or press Ctrl+F5

What are break points in context with the debugger?

A break point is the line of code at which you want your program to be paused (when running in debugger mode) and see the runtime values of different variables in the program. If the program control ever reaches this line during the execution of the program, it pause the execution and allows you to see and edit the values of the variables of your program.

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

What does it mean by 'watch' in context of the debugger?

Instead of pointing mouse pointer over a variable to show its value or using the Locals to view the values of all the local variables, you can also add only interested variables in the Debugger’s Watch Window (accessible through Debug -> Windows -> Watches -> Watch 1). The values in Watch window are always visible in the bottom of your VS.Net. To add any variable to Watch Window, right click on the variable and choose 'Add Watch' or drag it to the watch window.

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 into’and 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 DebugàStep Over or key F10) executes the code in the line at which the debugger is paused and takes the execution control to the next line. For example, if the execution is paused at a line marked line 1 in the code below:

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 are projects and solutions mapped to .NET assemblies?

In Visual Studio.NET, each project is compiled to a single assembly with references to the referenced assemblies and other code libraries. It is important to remember that up-till now Visual Studio.NET (2003) only supports single file assembly and not a multi-file assembly. It means that all the source code of a project is built to a single file representing the project’s assembly. Hence, if a solution contains five projects then when it (the solution) is built, it will emit five different assemblies each containing a single .dll or .exe file depending on the type of project selected.

A solution is a logical binding for the projects and it does not have any representation in the build files.

How much projects a solution may have?

There is no such limit; a solution may contain any number of projects. The projects can be coded in any VS.NET compliant programming language. A solution, basically, representation the raw application and it should contain only those projects which are the part of the application.

How to set the start application of a multi project solution?

You can specify the startup project of the application by selecting it from the startup project property of the solution which can be accessed by right clicking the solution and selecting the properties option from the pop up menu. It will show the property pages for the solution. You can change the startup project from Common Properties -> Startup project -> Single Startup project. Note that the startup project must represent an executable assembly (Console application, windows application or a web application) and not a library project.

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.

What is the difference between a debug and a release build?

The debug build is created with some embedded information which allows the debugger to debug the application and exposes the runtime behavior of the application. On the down side, the debug build is a bit slower and inefficient in execution and larger in size.

You may specify the build type of an assembly (project) by right clicking its project and selecting properties from the pop up menu. It will show the property pages for the project. You can select the build type by selecting Configuration Properties and then selecting the build type from the combo box at top labeled Configuration

What are references in context of the VS.NET projects?

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.

How many types of reference are there in the Visual Studio.NET?

There are basically three types of references that can be added to a project:

  • Reference to the .NET assembly (including components, library and controls)
  • Web reference to web services (see the succeeding question for details)
  • Reference to COM component (see the succeeding question for details)

What are web references in context of the VS.NET projects?

A web reference represents a reference to the web service, at its simplest. Getting inside, a web reference is a reference to the proxy classes to call the web service. These proxy classes are implemented for you by the VS.NET IDE for you through the Web Service Description Language (wsdl) file downloaded from the web service URL. These proxy classes provide the same calling interface to the clients of web service. When you call methods on a proxy class, it in turn calls the methods of the web service over the internet through SOAP (Simple Object Access Protocol) and returns the result back to your program.

How do I add a reference to a .NET assembly in my project?

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 is Visual Studio.NET IDE and what is the importance of it?

The Visual Studio .NET IDE is the default Development Environment for all Microsoft .NET based applications. Its got a full set set of usefull features. The VS.NET IDE provides many options for developers and is packed with much funtionality that simplifies application development.

Important Features of Visual Studio .NET IDE.

  • One IDE for all .NET based Projects
  • Visual Studio .NET IDE provides a single environment for developing all types of .NET applications. Application’s range from single form applications to complex n-tier applications and also Rich Web Applications.
  • The option to choose from Multiple Programming Languages
  • You can customize the IDE based on your preferences. By use of "My Profile settings". With these settings you can set the IDE screen the way you want, the way the keyboard behaves and you can also filter the help files based on the language of your choice.
  • The IDE comes with a built-in browser that helps you navigate the Internet without launching another browser app.

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.

How do I change the icon of my application?

Right click the startup project node in the solution explorer window and select the properties option. It will show the property pages for the project. You can change the application icon from Common Properties -> General -> Application Icon. Note that this is the icon for the application that will be attached with its executable file and shortcuts to it. To change the icon of the individual forms of your application, select the icon by editing the icon property of your form.

How do I make folders in the project?

To create a folder into a project, right click the target project node in the solution explorer and select ‘Add Folder…’ option. This will add a new folder to the project, specify the name of the folder and press Enter. The folders inside a project help you manage and separate source files for different purpose in the same project. For example, you may divide the windows form project to three folders;

  • first (Forms) containing user interface forms
  • second (Constants) containing constant values (enumerations and error codes) to be used in the project
  • third (StorageAccessor) containing classes for the database handling.

How do I add a new or existing file to a project or to a project folder?

To add a file to a project or to a project folder, right click its node in the solution explorer and select either ‘Add New Item…’ or ‘Add Existing Item…’ option. This 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.

How do I add a new or existing project to a solution?

To add a project to a solution, right click the solution node inside the solution explorer and select the ‘Add Project…’ or ‘Add existing project’ option. It will show you a user interface screen where you can browse for the target project. This will add a new project node in the solution tree.

What is C#?

C# (pronounced C-Sharp) is a new programming language introduced with the Microsoft .NET framework and is no doubt the language of choice in .NET environment. It was first created in the late 1990's as part of Microsoft’s whole .NET strategy. It is a whole new language free of backward compatibility curse and a whole bunch of new, exciting and promising features. It is an Object Oriented Programming language, which at its core, has similarities with Java, C++ and VB.

In fact, C# combines the power & efficiency of C++, simple & clean OO design of Java, and code simplification of Visual Basic. Like Java, C# also does not allow multiple inheritance and use of pointers (in safe and managed code) while it does provide garbage memory collection at runtime, type and memory access checking. But, contrary to java, C# keeps the different useful concepts of C++ like operator overloading, enumerations, pre-processor directives, pointers (in unmanaged and un-safe code), function pointers (in the form of delegates), also promises to have template support (with the name of generics) in next versions. Like VB it also supports the concepts of properties (context sensitive accessor to fields).

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”)
}
}

What are Jagged Arrays in C#?

A special type of array is introduced in C#. A Jagged Array is an array of an array in which the length of each array index can differ.

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

for( I=0;I<3;I++)

jagged[1][I]=I;

‘Storing values in third array

for(I=0;I<5;I++)

jagged[2][I]=I;

‘Displaying values from first array

for (I=0;I<4;I++)

Console.WriteLine(jagged[0][I])

‘Displaying values from second array

for (I=0;I<3;I++)

Console.WriteLine(jagged[1][I])

‘Displaying values from third array

for(I=0;I<5;I++)

Console.WriteLine(jagged[2][I])

}

}

Run the code to see the output.

What is the difference between "Value Types" and "Reference Types"?

Many programming languages provide built-in data types such as integers and floating-point numbers. These are copied when they are passed in to arguments i.e. they are passed "By Value". In .NET terms, these are called Value Types".

The RunTime supports two kinds of Value Types:

1 Built-in value types

The .NET Framework defines built-in value types such as System.Int32 and System.Boolean which correspond and are identical to primitive data types used in programming languages.

2 User-defined value types

The language you are using will provide functionality to define your own Value Types. These user defined Types derive from System.ValueType. If you want to define a Type representing a value that is a complex number (two floating-point numbers), you might choose to define it as a value type. Why? Because you can pass the Value Type efficiently "By Value". If the Type you are defining could be more efficiently passed "By Reference", you should define it as a class instead. Variables of Reference Types are referred to as objects. These store references to the actual data.

The following are the Reference Types:

  • class
  • interface
  • delegate

This following are the "built-in" Reference Types:

  • object
  • string

VB.NET Frequenly Asked Questions

What is the difference between VB6 and VB.NET

There are quite a few differences in VB6 and VB.NET. We will highlight some of these here in points:

  • The greatest change in VB6 and VB.NET is of runtime environment. VB6 used the VB-Runtime while VB.NET uses the .Net Common Language Runtime (.Net CLR). The CLR is much better designed and implemented than VB-Runtime. The CLR uses better code translation through Just in Time compiler while VB-Runtime interprets the code. The CLR Garbage Collector is also more efficient than VB6 one as it may detect cyclic references too.
  • VB6 was interpreter based language while VB.NET is a compiled language
  • VB6 was not a type-safe language while VB.NET is a type safe language. There is no variant type in VB.NET and no magical type conversions happen in VB.NET
  • VB6 used ‘On Error Goto’ syntax to handle exceptions at runtime. VB.NET uses the Try…Catch…Finally syntax to handle exceptions at runtime.
  • A lot of code (like user interface code) in VB6 was hidden from developer. In VB.NET no code is hidden from developer and you can access and control each part of your application
  • VB.NET has much enhanced object oriented support than VB6
  • VB6 does not allow developing the multithreaded applications. In VB.NET you can create multithreaded applications.
  • VB6 was only considered good for desktop windows application. In VB.NET you can also develop web applications, distributed applications, create .NET windows and web controls and components, write windows and web services.
  • In VB.NET, you can also use reflections to read the meta-data of types and using reflection emit you can also generate code to define and invoke types at runtime.
  • VB.NET uses .NET framework class library along with specialized VB library (System.VisualBasic) as a standard library. As a result, the standard library for VB.NET is much enhanced and useful compared to VB6 standard library
  • VB.NET is platform independent because of .Net framework. Programs written in VB.NET can run on any platform where .Net framework is present. The platform include both hardware and software (operating system) platforms.
  • 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.

What are Console Applications in VB.NET?

Console Applications have only recently been introduced in VB (Excluding VB for DOS). They are command line based and run in within a DOS Shell (DOS Window). Unlike Windows Applications, Console Applications do not support Windows GUI's. Which means that you can't work with controls from the toolbox.

To work with Console Applications select File->New->Project and in selected "Console Application" from the template under Visual Basic or Visual C#.

Example (Sample.vb) of a Console Application.

Module Module 1
Sub Main ()
System.Console.WriteLine ("Hello World”)
End Sub
End Module

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.

What are namespaces and what is the importance of them?

A namespace is a collection of different classes which are built into .NET. This very much like packages in Java. You need to import these namespaces to work with any .NET language. All the functionality of .NET is within these namespaces. The main namespace is the System namespace and all other namespaces are built into this System namespace.

Some of these namespaces and what they are used for are summarized below.

  • System: Includes essential classes and base classes that define commonly used Data Types, events, interfaces, attributes etc.
  • System.Data: Includes classes that make up ADO.NET and allows to build data-handling components.
  • System.Drawing: Provides access to graphics that gives access to drawing methods.
  • System.IO: Provides access to writing data streams and Files.
  • System.Net: Provides interface to many protocols used on the Internet.
  • System.Security: Includes classes to support the security system.
  • System.Threading: Includes classes that support threading.
  • System.Web.Services: Includes classes for creating and using Web Services.
  • System.Windows.Forms.: Includes classes for creating windows based applications.

What is the importance of the Option statement?

The Option statement is used to prevent syntax and logical errors in code. The possible suffixes of this statement are:

  • Option Explicit: Is the default abd is On. Option Explicit requires declaration of all variables before they are used.
  • Option Compare: This can be set to Binary or Text and it specifies if stringsp are to be compared using binary or text comparison operations.
  • Option Strict: The default is Off. An example: If value of one data type is assigned to another then Visual Basic will consider that as an error. If you want to assign a value of one Type to another then you should set it to On and use the conversion functions.

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

What are attributes in Visual Basic .NET?

Attributes are items that hold information about items we are using in VB.NET. They are used when VB.NET needs to know more than what standard syntax can specified. Attributes are enclosed in angle brackets<>.

Example: To call a Windows API functions you have to include a dynamic link library (DLL) reference that the function you are calling resides in. This is done using the DLLImport attribute as follows:

Public Shared Function<DllImport""user32.dll")>MessageBox(Byval..)

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")>.

What are Enumerations in VB.NET and how are they used?

Enumerations are new in VB.Net (As apposed to VB(i)) and they are used to group related sets of constants. To create a Enumeration you use the Enum statement. Example using a Enumeration

Module Module 1
Enum Months
January=1
Feburary=2
March=3
April=4
May=5
June=6
July=7
August=8
September=9
October=10
November=11
December=12
End Enum

Sub Main()

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.

How do I convert text from lower case to upper case in VB.NET?

The following code shows how text can be converted from lower case to upper.

Module Module1
Sub Main ()
Dim str1 as String=”Welcome to String”
Dim str2 as String
Str2=UCase(str1) 
Or
Str2=Str1.ToUpper
System.Console.WriteLine(str2)
End Sub

How do I handle Math functions in VB.NET?

Higher Mathematical functions in VB.NET are in the methods of the System.Math namespace. Calculation of a hyperbolic cosecant value and so on is possible by using the methods in this namespace.

Example using a Math Function

Imports System.Math
Module Module1
Sub Main()
System.Console.WiteLine(“Pi = “ & 4 * Atan())
End Sub
End Module

How do I handle Date and Time in VB.NET?

Working with Dates is one to think about. Especially if your data needs to be spread accross timezones Also there are different date formats to take in to consideration. VB.NET Has some good Date() Functions, one of which is demonstrated below:

Example

Imports System.Math
Module Module1
Sub Main ()
Dim Dts as Date
Dts =# 10/15/2001
System.Console.WriteLine(“New Date: & DateAdd(DateInterval.Month, 22, Dts))
End Sub
End Module

The above code adds 22 months to the date we declared in the Program.

How do I create Procedure Delegates?

Delegates are used to work with the address of procedures. This is much like pointers in C and C++. Sometimes it's useful to pass the location of a procedure to other procedures.

Example working with Delegates:

Module Module1
Delegate Sub SubDelegate1(ByVal str as String)
Sub Main()
Dim Mess as SubDelegate1
Mess-AddressOf Display
Mess.Invoke(“Hello from Delegates”)
End Sub

Sub Display(ByVal str as String)

System.Console.WriteLine(StrText)

End Sub

End Module

The above code displays “Hello from Delegates” just like a normal program but it uses Delegates to do it.

How do I use the InputBox Function?

An InputBox function is much like a  ?JavaScript prompt window which allows the input of text. To work with the InputBox, drag a Command Button and a TextBox from the Toolbar. Opon clicking the Command Button the InputBox prompts asks for a name. Once entered, press OK. That text will now be displayed in the Textbox.

The sample code for the click event

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles Button1.Click
Dim Show As String
Show = InputBox("Enter your name")
TextBox1.Text = Show
End Sub

How do I write data to a text file in VB.NET?

The following code creates a text file and inserts some text.

Imports System.IO
Public Class Form1 Inherits System.Windows.Forms.Form
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles MyBase.Load
Dim fs as New FileStream("exp.txt",FileMode.Create,FileAccess.Write)
Dim s as new StreamWriter(fs)
s.BaseStream.Seek(0,SeekOrigin.End)
s.WriteLine("ProgrammersHeaven has lot of programming goodies")
s.WriteLine(" good resource for most popular programming languages")
s.Close()
End Sub
End Class

What is Anchoring and Docking?

The VB terms Docking and Anchoring are used to make sure that a control covers the whole client area of a form.

Upon "docking" a window, it adheres to the edges of it's container (the Form). To "dock" a particular control, select the Dock property of the control from the properties window.

Selecting the Dock property opens up a small window like structure where you can select towards which side on the Form should the control be docked.

You can use Anchoring to "anchor" a control to the edges of it’s container (the Form). Selecting this property in the properties window opens up a small window from where you can select what edge to "anchor" the control to.

How to get computer name and IP address?

The following code uses the System.NET.DNS namespace to access the "computer name" and it's IP address.

Option Strict Off
Imports system
Imports System.Net.DNS
Public Class GetIP

Shared Function GetIPAddress() As String

Dim sam As System.Net.IPAddress

Dim sam1 As String

With system.Net.DNS.GetHostByName(system.Net.DNS.GetHostName())

sam = New System.Net.IPAddress(.AddressList(0).Address)

sam1 = sam.ToString

End With

GetIPAddress = sam1

End Function

Shared Sub main()

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.

How to get the environment information in VB.NET?

The System.Environment namespace includes the functionality to get the environment information such as the UserName and OS Version.

File name is SystemInfo.vb 

Imports System

Class SystemInfo

Shared Sub main()

Console.WriteLine("")

Console.WriteLine("Current User")

Console.WriteLine(Environment.UserName)

Console.WriteLine("")

Console.WriteLine("Name of the Machine")

Console.WriteLine(Environment.MachineName)

Console.WriteLine("")

Console.WriteLine("OS version")

Console.WriteLine(Environment.OSVersion)

Console.WriteLine("")

Console.WriteLine("System Directory")

Console.WriteLine(Environment.SystemDirectory)

Console.WriteLine("")

Console.WriteLine("TMP Folder")

Console.WriteLine(Environment.GetEnvironmentVariable("TMP"))

Console.WriteLine("")

Console.WriteLine("Class Path")

Console.WriteLine(Environment.GetEnvironmentVariable("ClassPath"))

Console.WriteLine("")

Console.readLine()

End Sub

End Class

How do I read and write data to an XML file?

The following code demonstrates how to read and write to an XML file.

<?xml version="1.0" standalone="yes"?> 

<Document>

<Customer>

<Name>Sandeep</Name>

<Age>23</Age>

<Occupation>Developer</Occupation>

</Customer>

</Document>

Imports System

Class WriteToXML

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.

How to work with an interface in VB.NET?

The following code demonstrates the ability to work with an interface. An interface defines a method's name and not it's contents.

Imports System
Imports Microsoft.VisualBasic

Public Interface NewInt

Sub Mysub()

Function MyFun() As String

End Interface

Class myclass Implements MyInt

' Implementing the above defined interface, need to use the keyword implements to use the interface

Shared Sub Main()

Dim mc As New myclass()

mc.Mysub()

End Sub

Sub Mysub() Implements NewInt.Mysub

MsgBox("Hello from INterfaces")

End Sub

Function MyFun() As String Implements NewInt.MyFun

dim str as string

str="hello matey"

return (str)

End Function

End Class

How to convert the format of images in VB.NET?

To convert the format of an image you need to use the System.Drawing namespace. Using this code you can convert to a variety of graphic file formats, such as GIF or JPG.

The following example converts a user prompted Bitmap image file into .Gif format.

File ImageConverter.vb

Imports System

Imports System.Drawing

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

What is the concept of destructors in VB.NET?

Destructors are used to de-allocate resources i.e. to clean up after an object is no longer available.

Finalize is the destructor which is normally used. Finalize is called automatically when the .NET runtime determines that the object is no longer being used. Using the Finalize method in code looks like this:

Public Class Form1 Inherits System.Windows.Forms.Form

Dim obj1 as new Class1 ()

End Class

Public Class Dest

Protected overrides Sub Finalize()

‘ calling the Finalize method

End Sub

End Class

How do I get Version Information From The AssemblyInfo File?

To get version information at Runtime in VB .NET, use the following code:

Function Version() As String With _ 

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

Upon running the version information of the Assembly file is displayed.

What is managed code and managed data?

Managed code is the code that is written to target the services of the Common Language Runtime (CLR). In order to target these services, the code must provide a minimum level of information to the runtime. All of the C#, Visual Basic .NET and J# .NET code is managed by default.

Closely related to managed code is managed data. This is the data that is allocated and de-allocated by the Common Language Runtime's garbage collector. As said earlier C#, Visual Basic, and J#.NET data is managed by default. C++ data can, however, be marked as unmanaged through the use of special keywords. Visual Studio .NET C++ data is unmanaged by default (even when using the /CLR switch), but when using Managed Extensions for C++, a class can be marked as managed by using the __gc keyword.

As the name suggests this means that the memory used for instances of the class is managed by the garbage collector. In addition the class becomes a full participating member of the .NET Framework with the benefits and restrictions that it brings. An example of a benefit is proper interoperability with classes written in other languages (for example, a managed C++ class can inherit from a Visual Basic class).

An example of a restriction is that a managed class can only inherit from one base class.

What is an Assembly?

An Assembly is the building block of a VB.NET application. An Assembly is a complied and versioned collection of code and metadata. Once complete forms an "atomic" functional unit.

Assemblies come in the form of a Dynamic Link Library (DLL) file or Executable an program file(EXE). They differ as they contain information found in a type libraries. All the .NET programs are constructed from these Assemblies. Assemblies are made of two parts. Firstly, the manifest which is similar to a Table Of Contents(TOC). This holds the name and version of the assembly. Secondly, the modules which are internal files of Intermediate Language (IL) code which are ready to run.

When programming, developers don't directly deal with assemblies as the CLR and the .NET framework takes care of that behind the scenes.

An assembly includes:

  • 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

How do I find the path from where the application is running?

To learn the path of your running application, do the following. Drag a Textbox and a Command Vbutton from the ToolBar and use the following code.

Public Class Form1 Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

#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

How do I get the screen resolution of my working area?

To get the screen resolution of your current working area use the System.Windows.Forms.Screen.PrimaryScreen.Bounds property

How can I run a .EXE from a VB.NET application?

To run a .EXE file from a VB.NET application you need to import the System.Diagnostics namespace. The following sample shows how to run Notepad from a VB.NET application.

Imports System
Imports System.Diagnostics

Dim program As New Process()

program.StartInfo.FileName = "Notepad.exe"

program.StartInfo.Arguments = " "

program.Start()

What is Try- Catch –Finally Exception Handling?

Exceptions are Runtime errors that occur when an unexpected process causes the program to abort. Such kind of situations can be kept at bay using Exception Handling. By looking for potential problems in the code / entity life cycle, we can handle most of the errors that may encountered. As a result the application to continue to run without being dogged by errors. VB.NET supports Structured exception handling by using Try...Catch...Finally

The following code sample demonstrates how to use Try-Catch-Finally exception handling.

Module Module1
Sub Main()
Dim a=0, b=1, c As Integer
Try
c=b / a
'the above line throws an exception
System.Console.WriteLine("C is " & c)
Catch e As Exception
System.Console.WriteLine(e)
'catching the exception
End Try
System.Console.Read()
End Sub
End Module

The output of the above code displays a message stating the exception. The reason for the exception is because any number divided by zero is infinity.

How do I convert one DataType to other using the CType Function?

The CType is pretty generic conversion Function.

The example below demonstrates using a CType Function to convert a Double value to an Integer value.

Module Module1
Sub Main()
Dim d As Double
d = 132.31223
Dim i As Integer
i = CType(d, i)
'two arguments, type we are converting from, to type desired
System.Console.Write("Integer value is" & i)
End Sub
End Module