Tuesday, May 19, 2009

Basic .Net Framework Questions

What is .NET?

.Net is software development platform to build, test, run and host software applications.
It is based on Virtual machine Architecture.
In which High level languages like C# Vb.net Codes get compiled into CIL code that are OS, hardware independent and this Platform independent codes are converted into native or executable code through JIT compiler.


If we see this world with perspective of OOPs, Every thing in this world is treated as object. With OOPs we get power to create Objects of our own and use them according to the need.


A Class is abstract model which defines a new abstract data type in a programming language, so that we can re-use abstract data type with the help of objects that are instance of class.


It is a mechanism that binds together data and code and makes it safe from outside interference and misuse. Data is enclosed in water-tight compartment known as object, instance of class.

Encapsulation provides the boundary between a class's external interface—that is, the public members visible to the class's users—and its internal implementation details. The advantage of encapsulation for the class developer is that he can expose the members of a class that will remain static, or unchanged, while hiding the more dynamic and volatile class internals. As you saw earlier in this chapter, encapsulation is achieved in C# by virtue of assigning an access modifier—public, private, or protected—to each class member.

Encapsulation is the ability to hide the internal workings of an object's behavior and its data. For instance, let's say you have a object named Bike and this object has a method named start(). When you create an instance of a Bike object and call its start() method you are not worried about what happens to accomplish this, you just want to make sure the state of the bike is changed to 'running' afterwards. This kind of behavior hiding is encapsulation and it makes programming much easier.


Polymorphism is a feature of OOPS that enables one entity to be used as generic for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as "one interface, multiple methods"

Method Overloading is example of compile time polymorphism
Method Overriding is example of Run-time polymorphism

Inheritance is the process by which derived class can acquire the features of base class.

Constants are used to provide readability and act as a single point of change for known values. Constants are shared members by default and are used whenever values are guaranteed not to change.

Fields are variables used to hold state in a class or struct. To provide data encapsulation, fields are commonly created with the private access modifier. Public fields lock the class interface and data together, making it difficult to change the code without breaking compatibility.

Properties represent a piece of data exposed by the class. Properties extend the concept of a field by adding a layer of abstraction between a class's internal and external representation. Properties give the designer the ability to change how state is managed within the class while not affecting how state is managed outside the class. Properties can be designated as read-only or write-only, simply by excluding the getter or setter, to prevent unwanted usage of the property.

Methods perform the functionality of the class. Multiple methods can have the same name with different signatures to provide multiple implementations. Such a practice is called method overloading.
Fields, properties, and methods can all be declared as static. Static type members are accessible without an object reference and normally address things that you would associate with the class's general concept not a specific instance.

Events provide a way for classes to notify listeners when certain actions have occurred. Since events are not required to be handled, they should typically be used to send information not critical to the central operation of the class.

Constructors allow you to customize the object creation process. If no constructor is specified the C# compiler will inject a default constructor into the class's MSIL.


This is the simplest relationship between objects. Example every customer has sales. So Customer object and sales object have an association relation between them.


This is also called as composition model. Example in order to make a “Accounts” class it has use other objects example “Voucher”, “Journal” and “Cash” objects. Therefore, accounts class is aggregation of these three objects.

What is .Net Framework

The Microsoft .Net Framework is a platform that provides tools and technologies you need to build Networked Applications as well as Distributed Web Services and Web Applications. The .Net Framework provides the necessary compile time and run-time foundation to build and run any language that conforms to the Common Language Specification (CLS).The main two components of .Net Framework are Common Language Runtime (CLR) and .Net Framework Class Library (FCL).

The Common Language Runtime (CLR) is the runtime environment of the .Net Framework , that executes and manages all running code like a Virtual Machine. The .Net Framework Class Library (FCL) is a huge collection of language-independent and type-safe reusable classes. The .Net Framework Class Libraries (FCL) are arranged into a logical grouping according to their functionality and usability is called Namespaces. In the following sections describes how to .Net Framework manages the code in compile time and run time.
Microsoft .Net Languages Source Code are compiled into Microsoft Intermediate Language (MSIL). MSIL we can call it as Intermediate Language (IL) or Common Intermediate Language (CIL). Microsoft Intermediate Language (MSIL) is a CPU independent set of instructions that can be converted to the native code. Metadata also created in the course of compile time with Microsoft Intermediate Language (MSIL) and stored it with the compiled code . Metadata is completely self-describing . Metadata is stored in a file called Manifest, and it contains information about the members, types, references and all the other data that the Common Language Runtime (CLR) needs for execution.

The Common Language Runtime (CLR) uses metadata to locate and load classes, generate native code, provide security, and execute Managed Code. Both Microsoft Intermediate Language (MSIL) and Metadata assembled together is known as Portable Executable (PE) file. Portable Executable (PE) is supposed to be portable across all 32-bit operating systems by Microsoft .Net Framework.
During the runtime the Common Language Runtime (CLR)'s Just In Time (JIT) compiler converts the Microsoft Intermediate Language (MSIL) code into native code to the Operating System. The native code is Operating System independent and this code is known as Managed Code , that is, the language's functionality is managed by the .NET Framework . The Common Language Runtime (CLR) provides various Just In Time (JIT) compilers, and each works on a different architecture depends on Operating Systems, that means the same Microsoft Intermediate Language (MSIL) can be executed on different Operating Systems. In the following section you can see how Common Language Runtime (CLR) functions.

Common Language Runtime

The Common Language Runtime (CLR) is an Execution Environment . It works as a layer between Operating Systems and the applications written in .Net languages that conforms to the Common Language Specification (CLS). The main function of Common Language Runtime (CLR) is to convert the Managed Code into native code and then execute the Program. The Managed Code compiled only when it needed, that is it converts the appropriate instructions when each function is called. The Common Language Runtime (CLR) 's Just In Time (JIT) compilation converts Intermediate Language (MSIL) to native code on demand at application run time.
During the execution of the program ,the Common Language Runtime (CLR) manages memory, Thread execution, Garbage Collection (GC) , Exception Handling, Common Type System (CTS), code safety verifications, and other system services. The CLR ( Common Language Runtime ) defines the Common Type System (CTS), which is a standard type system used by all .Net languages. That means all .NET programming languages uses the same representation for common Data Types , so Common Language Runtime (CLR) is a language-independent runtime environment . The Common Language Runtime (CLR) environment is also referred to as a managed environment, because during the execution of a program it also controls the interaction with the Operating System. In the coming section you can see what are the main functions of Common Language Runtime (CLR).
The Common Language Runtime (CLR) is a an Execution Environment . Common Language Runtime (CLR)'s main tasks are to convert the .NET Managed Code to native code, manage running code like a Virtual Machine and also controls the interaction with the Operating System.
Common Language Runtime (CLR) manages Thread executions, Memory Management that is allocation of Objects and Buffers , Garbage Collection (GC) - Clean up the unused Objects and buffers , Exception Handling, Common Type System (CTS) that is all .NET language that conforms to the Common Language Specification (CLS) have the same primitive Data Types, Code safety verifications - code can be verified to ensure type safety, Language integration that is Common Language Runtime (CLR) follow a set of specification called Common Language Specification (CLS) , this will ensure the interoperability between languages, Integrated security and other system services.

.Net Framework Class Library (FCL)

The .Net Framework class library (FCL) provides the core functionality of .Net Framework architecture. The .Net Framework Class Library (FCL) includes a huge collection of reusable classes, interfaces, and value types that expedite and optimize the development process and provide access to system functionality.
The .Net Framework class library (FCL) organized in a hierarchical tree structure and it is divided into Namespaces. Namespaces is a logical grouping of types for the purpose of identification. Framework class library (FCL) provides the consistent base types that are used across all .NET enabled languages. The Classes are accessed by namespaces, which reside within Assemblies. The System Namespace is the root for types in the .NET Framework. The .Net Framework class library (FCL) classes are managed classes that provide access to System Services . The .Net Framework class library (FCL) classes are object oriented and easy to use in program developments. Moreover, third-party components can integrate with the classes in the .NET Framework.

Common Language Specification

Common Language Specification (CLS) is a set of basic language features that .Net Languages needed to develop Applications and Services, which are compatible with the .Net Framework. When there is a situation to communicate Objects written in different .Net Complaint languages, those objects must expose the features that are common to all the languages. Common Language Specification (CLS) ensures complete interoperability among applications, regardless of the language used to create the application.
Common Language Specification (CLS) defines a subset of Common Type System (CTS). Common Type System (CTS) describes a set of types that can use different .Net languages have in common, which ensure that objects written in different languages can interact with each other. Most of the members defined by types in the .NET Framework Class Library (FCL) are Common Language Specification (CLS) compliant Types. Moreover Common Language Specification (CLS) standardized by ECMA.

Common Type System

Common Type System (CTS) describes a set of types that can be used in different .Net languages in common . That is , the Common Type System (CTS) ensure that objects written in different .Net languages can interact with each other. For Communicating between programs written in any .NET complaint language, the types have to be compatible on the basic level .
These types can be Value Types or Reference Types . The Value Types are passed by values and stored in the stack. The Reference Types are passed by references and stored in the heap. Common Type System (CTS) provides base set of Data Types which is responsible for cross language integration. The Common Language Runtime (CLR) can load and execute the source code written in any .Net language, only if the type is described in the Common Type System (CTS) .Most of the members defined by types in the .NET Framework Class Library (FCL) are Common Language Specification (CLS) compliant Types.

Microsoft Intermediate Language

MSIL stands for Microsoft Intermediate Language. We can call it as Intermediate Language (IL) or Common Intermediate Language (CIL). During the compile time , the compiler convert the source code into Microsoft Intermediate Language (MSIL) .Microsoft Intermediate Language (MSIL) is a CPU-independent set of instructions that can be efficiently converted to the native code. During the runtime the Common Language Runtime (CLR)'s Just In Time (JIT) compiler converts the Microsoft Intermediate Language (MSIL) code into native code to the Operating System.
When a compiler produces Microsoft Intermediate Language (MSIL), it also produces Metadata. The Microsoft Intermediate Language (MSIL) and Metadata are contained in a portable executable (PE) file . Microsoft Intermediate Language (MSIL) includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations
Just In Time Compiler
The .Net languages , which is conforms to the Common Language Specification (CLS), uses its corresponding runtime to run the application on different Operating Systems . During the code execution time, the Managed Code compiled only when it is needed, that is it converts the appropriate instructions to the native code for execution just before when each function is called. This process is called Just In Time (JIT) compilation, also known as Dynamic Translation . With the help of Just In Time Compiler (JIT) the Common Language Runtime (CLR) doing these tasks.
The Common Language Runtime (CLR) provides various Just In Time compilers (JIT) and each works on a different architecture depending on Operating System. That is why the same Microsoft Intermediate Language (MSIL) can be executed on different Operating Systems without rewrite the source code. Just In Time (JIT) compilation preserves memory and save time during application initialization. Just In Time (JIT) compilation is used to run at high speed, after an initial phase of slow interpretation. Just In Time Compiler (JIT) code generally offers far better performance than interpreters.

Managed Code

Managed Code in Microsoft .Net Framework, is the code that has executed by the Common Language Runtime (CLR) environment. On the other hand Unmanaged Code is directly executed by the computer's CPU. Data types, error-handling mechanisms, creation and destruction rules, and design guidelines vary between managed and unmanaged object models.
The benefits of Managed Code include programmers convenience and enhanced security . Managed code is designed to be more reliable and robust than unmanaged code , examples are Garbage Collection , Type Safety etc. The Managed Code running in a Common Language Runtime (CLR) cannot be accessed outside the runtime environment as well as cannot call directly from outside the runtime environment. This makes the programs more isolated and at the same time computers are more secure . Unmanaged Code can bypass the .NET Framework and make direct calls to the Operating System. Calling unmanaged code presents a major security risk.

.Net Metadata

Metadata in .Net is binary information which describes the characteristics of a resource . This information include Description of the Assembly , Data Types and members with their declarations and implementations, references to other types and members , Security permissions etc. A module's metadata contains everything that needed to interact with another module.
During the compile time Metadata created with Microsoft Intermediate Language (MSIL) and stored in a file called a Manifest . Both Metadata and Microsoft Intermediate Language (MSIL) together wrapped in a Portable Executable (PE) file. During the runtime of a program Just In Time (JIT) compiler of the Common Language Runtime (CLR) uses the Metadata and converts Microsoft Intermediate Language (MSIL) into native code. When code is executed, the runtime loads metadata into memory and references it to discover information about your code's classes, members, inheritance, and so on. Moreover Metadata eliminating the need for Interface Definition Language (IDL) files, header files, or any external method of component reference.

.Net Assembly

Microsoft .Net Assembly is a logical unit of code, it contains code that the Common Language Runtime (CLR) executes. Assembly is really a collection of types and resource information that are built to work together and form a logical unit of functionality. During the compile time Metadata is created, with Microsoft Intermediate Language (MSIL), and stored in a file called a Manifest . Both Metadata and Microsoft Intermediate Language (MSIL) together wrapped in a Portable Executable (PE) file. Manifest contains information about itself. This information is called Assembly Manifest, it contains information about the members, types, references and all the other data that the runtime needs for execution.
Every Assembly you create contains one or more program files and a Manifest. There are two types program files : Process Assemblies (EXE) and Library Assemblies (DLL). Each Assembly can have only one entry point (that is, DllMain, WinMain, or Main). We can create two types of Assembly, private Assembly and shared Assembly . A private Assembly is used only by a single application, and usually it is stored in that application's install directory. A shared Assembly is one that can be referenced by more than one application. If multiple applications need to access an Assembly, we should add the Assembly to the Global Assembly Cache (GAC).

.Net Assembly Manifest

An Assembly Manifest is a file that containing Metadata about .NET Assemblies. Assembly Manifest contains a collection of data that describes how the elements in the assembly relate to each other. It describes the relationship and dependencies of the components in the Assembly, versioning information, scope information and the security permissions required by the Assembly.
The Assembly Manifest can be stored in Portable Executable (PE) file with Microsoft Intermediate Language (MSIL) code. You can add or change some information in the Assembly Manifest by using assembly attributes in your code. The Assembly Manifest can be stored in either a PE file (an .exe or .dll) with Microsoft Intermediate Language (MSIL) code or in a standalone PE file that contains only assembly manifest information. Using ILDasm, you can view the manifest information for any managed DLL.

.Net Namespaces

Namespaces are the way to organize .NET Framework Class Library into a logical grouping according to their functionality, usability as well as category they should belong to, or we can say Namespaces are logical grouping of types for the purpose of identification.
The .NET Framework Class Library (FCL ) is a large collection of thousands of Classes. These Classes are organized in a hierarchical tree. The System Namespaces is the root for types in the .NET Framework. We can uniquely identify any Class in the .NET Framework Class Library (FCL ) by using the full Namespaces of the class .In .Net languages every program is created with a default Namespaces . Programmers can also create their own Namespaces in .Net languages.

Garbage Collection

The .Net Framework provides a new mechanism for releasing unreferenced objects from the memory (that is we no longer needed that objects in the program) ,this process is called Garbage Collection (GC). When a program creates an Object, the Object takes up the memory. Later when the program has no more references to that Object, the Object's memory becomes unreachable, but it is not immediately freed. The Garbage Collection checks to see if there are any Objects in the heap that are no longer being used by the application. If such Objects exist, then the memory used by these Objects can be reclaimed. So these unreferenced Objects should be removed from memory , then the other new Objects you create can find a place in the Heap.
The reclaimed Objects have to be Finalized later. Finalization allows a resource to clean up after itself when it is being collected. This releasing of unreferenced Objects is happening automatically in .Net languages by the Garbage Collector (GC). The programming languages like C++, programmers are responsible for allocating memory for Objects they created in the application and reclaiming the memory when that Object is no longer needed for the program. In .Net languages there is a facility that we can call Garbage Collector (GC) explicitly in the program by calling System.GC.Collect.


Thread in computer science means a sequence of execution instructions that can run independently , that is a single flow of execution in a process. Thread is like a process, at least one thread exists within each process. Single Thread (normal programs) in computer science means that only one task can execute and at the same time the other tasks have to wait for the completion of the current task like in a queue. Single thread resulted in systems idle time and application performance.
Multithreading allows multiple process to execute concurrently within a single program .That is more than one task in a program can execute at the same time and each thread run independently of its own. If multiple threads can exist within a process, typically share the state information of a process, and share memory and other resources directly. Each thread maintains exception handlers, a scheduling priority, and a set of structures the system uses to save the thread context until it is scheduled.
In multiple threaded programming we can use system's idle time, so it leads improved application performance . Also we can set priority in each Threads . Threads with higher priority are executed in preference to threads with lower priority. It is recommended that you use as few threads as possible, thereby minimizing the use of Operating System resources . Check the following links to see how Multi Threaded applications works in VB.NET .

Friday, May 15, 2009

What is MVC Pattern

The main purpose using MVC pattern is to decouple the GUI from the Data. It also gives the
ability to provide multiple views for the same Data. MVC pattern separates objects in to three
important sections:-
• Model: - This section is specially for maintaining data. It is actually where your business
logic, querying database, database connection etc. is actually implemented.
• Views: - Displaying all or some portion of data, or probably different view of data. View
is responsible for look and feel, Sorting, formatting etc.
• Controller: - They are event-handling section, which affects either the model or the
view. Controller responds to the mouse or keyboard input to command model and view
to change. Controllers are associated with views. User interaction triggers the events to
change the model, which in turn calls some methods of model to update its state to notify
other registered views to refresh their display.
Ok now this was all in theory. Let us look at how in actually ASP.NET we can implement MVC
pattern. During interview with theory question they will be looking at have, you really
implemented MVC or its just talks. Following are the various sections of ASP.NET, which maps
to MVC sections:-
• Model: - This section is represented by Data view, Dataset, Typed Dataset, Business
components, business entity models etc. Now this section can then be tied up to either
windows application or web UI.
• View: - ASPX, ASCX, or windows application UI like data grid etc. form the view part of
• Controller: - In ASP.NET the behind, code is the controller as the events are handled by
that part. Controller communicates both with Model as well as with view.

Thursday, May 14, 2009

Difference between struct and Class

Difference between struct and Class
1. Struct are value type and stored on stack while class are reference type and store on heap.
2. Struct do not support inheritance while class supports inheritance, However struct can implements interface.
3. Struct should be used when you want to use a small data structure while class is better choice for complex data structure.
4. The fourth significant difference between class objects and struct objects refers to constructors. Constructors are supported by structs in the C# language, and you can define constructors for structs in exactly the same manner as you would for classes. If you are not familiar with constructors, they are methods with the same name as the struct or class. However, the only exception with struct constructors is that you are not permitted to define a constructor that takes no arguments.
5. By default, Structure data members are public but class data members are private.
6. In Structure we can’t declare any default constructor explicitly because it provides by .net framework. But in class we can declare default constructor explicitly.

Monday, May 11, 2009

Questions on WinForm and Visual Studio .Net

Questions on WinForm and Visual Studio .Net
What are win form controls? How they are represented in .NET framework class library?

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.

What are the fundamental and common properties of .NET controls?

Almost all the controls have some similar properties like Location, Size, Enabled, Visible, TabIndex, Name, Text, BacKColor, ForeColor, Font, etc. The TabIndex property is very important. It describes the sequence followed by the windows focus when the user presses the Tab button of keyboard

How do I set the tab order of the controls on the form?

To set the tab order of the controls on the form, select View -> Tab Order. This will start a wizard for setting the tab order. You can set the order of tab for the control by just clicking it in the same sequence as of required tab order.

What does it mean by anchoring of controls?

An anchoring is the property of the control to keep a specific distance with a particular edge of the window (or other containing control). You can anchor a control to any edge or side of the window, e.g., left, top, right, bottom, left and top, etc. If a control is anchored to the left of the window, it will keep the constant distance from the left side of the window; even when the window is resized. The constant distance that the control will keep with the window is the distance it has at the form startup or defined by its Location property. In the figure below, the button is anchored to the top edge of the window.
When the window is resized, it shifts itself on the form to keep the same distance from the top, see the figure below:
If we have defined the top and bottom anchoring and the form is resized, the control will resize itself to have the same distance from top and bottom. Consider the figure below; here the button is anchored top and bottom
When the form is resized, the button resizes itself to keep the same distance from top and bottom
The default anchoring of a control is left and top.

How do I set the anchoring property of my controls?

To change the anchoring property of the control, set the Anchor property of the control from the properties window. When you click the Anchor property of the control in the properties window, Visual Studio.NET will show you a tab to set the edges with which you wish to anchor the control

What does it mean by docking of controls?

Docking is the property of the control to attach itself to a particular edge of the window (or other containing control). You can either dock a control to an edge or to fill the available space in the parent control or window. Common examples of docking includes menu bar and toolbars which dock themselves at the top of the window so that they may remain at top regardless of the size and of the window.
In the figure below, we have docked the button to the top of the window
When the control is resized, the control remains stuck to the top of the window
(Does it remind you the famous outlook bar?)
You can define a control to have a fill dock property so that it may fill all the available space in the parent window or parent control. In the figure below, we have docked the tree view control at left and the list view control with fill docking property
When the form is resized, the tree view will remain at left (changing only its height and not width) while the list view will expand itself to the rest of the available space on the form

(Does it remind you the famous Windows Explorer?)
A control is not docked to any edge, by default.
How do I set the docking property of my controls?

To change the docking property of the control, set the Dock property of the control from the properties window. When you click the Dock property of the control in the properties window, Visual Studio.NET will show you a tab to set the edges with which you wish to dock the control
How do I set the width of a ComboBox to fit the contents?
Move through the index items to find the longest item by character length using the MeasureString function. Use the this value as the ComboBox width.
System.Drawing.Graphics g = comboBox1.CreateGraphics();

float maxWidth = 0f;

foreach(object o in comboBox1.Items)


float w = g.MeasureString(o.ToString(), comboBox1.Font).Width;
'checking the combobox for the longest text
if(w > maxWidth)
maxWidth = w;
'setting the width by checking the longest text
comboBox1.Width = (int) maxWidth
How do I set the color and font in a RichEditBox?
Use the SelectionFont and SelectionColor properties to set the font and color of a RichEditBox. The following code will set the "selected text" to a blue-italic-verdana font set.
Note. If no text is selected then any all new text will be blue-italic-verdana within the RichEditBox.


RichTextBox1.SelectionColor = Color.Blue;

RichTextBox1.SelectionFont = new Font ("Verdana", 12, FontStyle.Italic);
How do I browse and read a text file into a TextBox?
You use the OpenFileDialog to implement this functionailty.

using System.Text;
using System.IO;
private void button1_Click(object sender, System.EventArgs e)
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open the text file you wish" ;
ofd.InitialDirectory = "c:\" ;
ofd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;

if(ofd.ShowDialog() == DialogResult.OK)
StreamReader sr = File.OpenText(ofd.FileName);
string s = sr.ReadLine();
StringBuilder sb = new StringBuilder();
while (s != null)
s = sr.ReadLine();
textBox1.Text = sb.ToString();

How to use the Splitter control?

The Splitter control is used to resize other controls. The purpose of this is to save space on the form.
This control can be very useful when you are working with controls both at design time and run time (which are not visible at design time).
How do I place restriction when entering some text in a textbox?
You can restrict a user from entering text against a set pattern. Or you can request the user only to enters certain type of
characters. E.g. Only a single digit number or a double digit number and so on. To control the input, use the KeyPress event like below:
Private Sub TextBox1_KeyPress(ByVal sender As Object,ByVal e As _ System.Windows.Forms.KeyPressEventArgs) Handles

If(e.KeyChar < "10" Or e.KeyChar > "100") Then
MessageBox.Show("Enter Double Digits")
End If
End Sub

How do I access controls on another Form?

To access controls on other WinForms follow the example. This example reads the text in a textbox from other form and displays it in the textbox on the current form.
Open two forms (form1 and form2), add a Command Button and a Textbox to Form1 and a Textbox to Form2.
The following code relates to form1.
Public Class Form1
Inherits System.Windows.Forms.Form
Dim NewWindow As New Form2()

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Text = NewWindow.TextBox1.Text
End Sub

End Class
When you run the code, Both

How can I access a Website/Webpage with a VB.NET LinkLabel control?

To access a Website or a Webpage using a VB.NET application. Drag a LinkLabel control and write the following code in it’s click event.
Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As

End Sub
Upon running the application,click on the Text on the LinkLabel. The website, Yahoo.com will open in a new browser.
How do I add items to a ComboBox and sort them?
The following code shows how to add items to a ComboBox.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

ComboBox1.Items.Add(“United States”)
ComboBox1.Items.Add(“New Zeland”)
End Sub
To sort the items alpahbetically, select the .Sorted property and set it to True.

How do I load a picture into the PictureBox control?

To load a Picture into the PictureBox control drag a PictureBox control and a Command Button from the Toolbox. When you click the Command Button, the picture you specified will be loaded into the Picturebox.
The following code is a demonstration.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Assuming you have a folder named images in C: drive and a gif image in that
End Sub

How do I add a control to windows form at runtime?

To add a control to a Form at Runtime, firstly decide which control is needed. Set all relevent properties and finally use the Controls.Add(controlname) function.
An an example of how to add a TextBox:
Dim tb as TextBox = New TextBox()
'declaring a textbox
tb.Size = New Size(130, 25)
'setting the size for the textbox
tb.Location = New Point( 50, 70)
'setting the location
tb.Text = "Textbox1"
'setting the text
'adding the textbox to the form
How to create an "Explorer style" application in VB.NET?
Displaying all the drives, folders and files in an application like "Explorer" can be done easily in VB.NET. To do this follow these simple instructions:
Open a new project Add a Command Button to the Form. Place the following code in the click event of the command button.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles Button1.Click
Dim expl As New ExplorerStyleViewer()
End Sub

What is a Tooltip control and how should I use it?

A Tooltip is a tag that displays some text when an ojects Mouse Over event is triggered. This is usually a decription of the object or the action that will follow if the object is say for example clicked.
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

How do you test if an attribute exists in the xml document?

String Value="";

if (Node.Attributes["Attribute1"] == null)
// doesn't exist
// exists

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

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

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.

What base class do all Web Forms inherit from?


What is the difference between Debug.Write and Trace.Write? When should each be used?

The Debug.Write call won’t be compiled when the DEBUGsymbol is not defined (when doing a release build). Trace.Write calls will be compiled. Debug.Write is for information you want only in debug builds, Trace.Write is for when you want it in release build as well.

Difference between Anchor and Dock Properties?

Dock Property->Gets or sets which edge of the parent container a control is docked to. A control can be docked to one edge of its parent container or can be docked to all edges and fill the parent container. For example, if you set this property to DockStyle.Left, the left edge of the
control will be docked to the left edge of its parent control. Additionally, the docked edge of the control is resized to match that of its container
Anchor Property->Gets or sets which edges of the control are anchored to the edges of its container. A control can be anchored to one or more edges of its parent container. Anchoring a control to its parent ensures that the anchored edges remain in the same position relative to the edges of the parent container when the parent container is resized.

When would you use ErrorProvider control?

ErrorProvider control is used in Windows Forms application. It is like Validation Control for ASP.NET pages. ErrorProvider control is used to provide validations in Windows forms and display user friendly messages to the user if the validation fails.
If we went to validate the textBox1 should be empty, then we can validate as below
1). You need to place the errorprovide control on the form
private void textBox1_Validating (object sender, System.ComponentModel.CancelEventArgs e)
Private bool ValidateName()
bool bStatus = true;
if (textBox1.Text == “”)
errorProvider1.SetError (textBox1,”Please enter your Name”);
bStatus = false;
errorProvider1.SetError (textBox1,”");
return bStatus;
it check the textBox1 is empty . If it is empty, then a message Please enter your name is displayed.

Can you write a class without specifying namespace? Which namespace does it belong to by default?

Yes, you can, and then the class belongs to global namespace which has no name. For commercial products, naturally, you wouldn’t want global namespace.

You are designing a GUI application with windows and several widgets on it. The user then resizes the app window and sees a lot of grey space, while the widgets stay in place. What’s the problem?

One should use anchoring for correct resizing. Otherwise the default property of a widget on a form is top-left, so it stays at the same location when resized.

How can you save the desired properties of Windows Forms application?

.config files in .NET are supported through the API to allow storing and retrieving information. They are nothing more than simple XML files, sort of like what .ini files were before for Win32 apps.

So how do you retrieve the customized properties of a .NET application from XML .config file?
Initialize an instance of AppSettingsReader class. Call the GetValue method of AppSettingsReader class, passing in the name of the property and the type expected. Assign the result to the appropriate variable.

Can you automate this process?

In Visual Studio yes, use Dynamic Properties for automatic .config creation, storage and retrieval.

My progress bar freezes up and dialog window shows blank, when an intensive background process takes over.

Yes, you should’ve multi-threaded your GUI, with taskbar and main form being one thread, and the background process being the other.

What’s the safest way to deploy a Windows Forms app?

Web deployment: the user always downloads the latest version of the code, the program runs within security sandbox, properly written app will not require additional security privileges.

Why is it not a good idea to insert code into InitializeComponent method when working with Visual Studio?

The designers will likely through it away, most of the code inside InitializeComponent is auto-generated.

What’s the difference between WindowsDefaultLocation and WindowsDefaultBounds?

WindowsDefaultLocation tells the form to start up at a location selected by OS, but with internally specified size. WindowsDefaultBounds delegates both size and starting position choices to the OS.

What’s the difference between Move and LocationChanged? Resize and SizeChanged?

Both methods do the same, Move and Resize are the names adopted from VB to ease migration to C#.

How would you create a non-rectangular window, let’s say an ellipse?

Create a rectangular form, set the TransparencyKey property to the same value as BackColor, which will effectively make the background of the form transparent. Then set the FormBorderStyle to FormBorderStyle.None, which will remove the contour and contents of the form.

How do you create a separator in the Menu Designer?

A hyphen ‘-’ would do it. Also, an ampersand ‘&\’ would underline the next letter.

How’s anchoring different from docking?

Anchoring treats the component as having the absolute size and adjusts its location relative to the parent form. Docking treats the component location as absolute and disregards the component size. So if a status bar must always be at the bottom no matter what, use docking. If a button should be on the top right, but change its position with the form being resized, use anchoring.

How do you trigger the Paint event in System.Drawing?

Invalidate the current form; the OS will take care of repainting. The Update method forces the repaint.

With these events, why wouldn’t Microsoft combine Invalidate and Paint, so that you wouldn’t have to tell it to repaint, and then to force it to repaint?
Painting is the slowest thing the OS does, so usually telling it to repaint, but not forcing it allows for the process to take place in the background.

How can you assign an RGB color to a System.Drawing.Color object?

Call the static method FromArgb of this class and pass it the RGB values.

What class does Icon derive from?

Isn’t it just a Bitmap with a wrapper name around it? No, Icon lives in System.Drawing namespace. It’s not a Bitmap by default, and is treated separately by .NET. However, you can use ToBitmap method to get a valid Bitmap object from a valid Icon object.

Before in my VB app I would just load the icons from DLL. How can I load the icons provided by .NET dynamically?

By using System.Drawing.SystemIcons class, for example System.Drawing.SystemIcons.Warning produces an Icon with a warning sign in it.

When displaying fonts, what’s the difference between pixels, points and ems?

A pixel is the lowest-resolution dot the computer monitor supports. Its size depends on user’s settings and monitor size. A point is always 1/72 of an inch. An em is the number of pixels that it takes to display the letter

Wednesday, May 6, 2009

Difference between .Net Remoting and Web Services

Difference between .Net Remoting and Web Services

1. .Net Remoting can be accessed over various protocols i.e. HTTP, TCP & SMTP but
2. Web Services can be access over HTTP only.

3. NET Remoting provides the fast communication than Web Services when we use the TCP channel and the binary formatter

4. Remoting has support for both stateless and with-state environment, which is achieved using Singleton and Singlecall activation but web services are only stateless.

5. Web services serialize objects through XML contained in the SOAP messages and can thus only handle items that can be fully expressed in XML. .NET Remoting relies on the existence of the common language runtime assemblies that contain information about data types. This limits the information that must be passed about an object and allows objects to be passed by value or by reference.
6. Web services support only the objects that can be serialized but .NET Remoting can provide support to all objects that inherit MarshalByRefObject.
7. Web Services support heterogeneous environments means interoperability across platforms but .Net remoting requires .Net on both server and client end.
8. Web Services are reliable than .Net remoting because Web services are always hosted in IIS.
9. Web Services are ease to create and deploy but .Net remoting is bit complex to program.

.Net Interview Questions

What is the difference between Overload and Override?
Overload is the another version of the same function into the class. There can be different parameters, return type in overload functions (in brief: Same function and different parameters).
Override is entirely overriding the base class function and creating our own version in the child class. Base class and child class function name and return type should be same.

What the way to stop a long running thread ?

What is multi-threading?
It is basically trying to do more than one thing at a time within a process.
There are two main ways of multi-threading which .NET encourages: starting your own threads with ThreadStart delegates, and using the ThreadPool class either directly (using ThreadPool.QueueUserWorkItem) or indirectly using asynchronous methods (such as Stream.BeginRead, or calling BeginInvoke on any delegate).

What’s difference between System.SystemException and System.ApplicationException?
The difference between ApplicationException and SystemException is that SystemExceptions are thrown by the CLR, and ApplicationExceptions are thrown by Applications.

What is CODE Access security?
Code Access Security (CAS), in the Microsoft .NET framework, is Microsoft's solution to prevent untrusted code from performing privileged actions.

It performs following function
1. Defines permissions and permission sets that represent the right to access various system resources.
2. Enables administrators to configure security policy by associating sets of permissions with groups of code (code groups).
3. Enables code to request the permissions it requires in order to run, as well as the permissions that would be useful to have, and specifies which permissions the code must never have.
4. Grants permissions to each assembly that is loaded, based on the permissions requested by the code and on the operations permitted by security policy.
5. Enables code to demand that its callers have specific permissions.
6. Enables code to demand that its callers possess a digital signature, thus allowing only callers from a particular organization or site to call the protected code.
7. Enforces restrictions on code at run time by comparing the granted permissions of every caller on the call stack to the permissions that callers must have.

What is Metadata?
Metadata is the complete way of describing what is in a .NET assembly. Digging into the metadata yields the types available in that assembly, viz. classes, interfaces, enums, structs, etc., and their containing namespaces, the name of each type, its visibility/scope, its base class, the interfaces it implemented, its methods and their scope, and each method’s parameters, type’s properties, and so on.

What is Manifest?
The manifest describes the assembly, providing the logical attributes shared by all the modules and all components in the assembly. The manifest contains the assembly name, version number, locale and an optional strong name that uniquely identifying the assembly.

What is the difference between Namespace and Assembly?
1. It is a Collection of names wherein each name is Unique.
2. They form the logical boundary for a Group of classes.
3. Namespace must be specified in Project-Properties.

1. It is an Output Unit. It is a unit of Deployment & a unit of versioning. Assemblies contain MSIL code.
2. Assemblies are Self-Describing. [e.g. metadata,manifest]
3. An assembly is the primary building block of a .NET Framework application. It is a collection of functionality that is built, versioned, and deployed as a single implementation unit (as one or more files). All managed types and resources are marked either as accessible only within their implementation unit, or by code outside that unit.

What is Managed and Unmanaged code?
Managed Code is what Visual Basic .NET and C# compilers create. It compiles to Intermediate Language (IL), not to machine code that could run directly on your computer. The IL is kept in a file called an assembly, along with metadata that describes the classes, methods, and attributes (such as security requirements) of the code you've created. This assembly is the one-stop-shopping unit of deployment in the .NET world. You copy it to another server to deploy the assembly there—and often that copying is the only step required in the deployment.

Unmanaged code is what you use to make before Visual Studio .NET 2002 was released. Visual Basic 6, Visual C++ 6, heck, even that 15-year old C compiler you may still have kicking around on your hard drive all produced unmanaged code. It compiled directly to machine code that ran on the machine where you compiled it—and on other machines as long as they had the same chip, or nearly the same. It didn't get services such as security or memory management from an invisible runtime; it got them from the operating system. And importantly, it got them from the operating system explicitly, by asking for them, usually by calling an API provided in the Windows SDK. More recent unmanaged applications got operating system services through COM calls.

What is JIT (Just-in-time) Compiler ?
Just-in-time compiler is a compiler used to convert the Commmon Intermediate Language (CIL) code into native code (also called machine code) that is processed by machine.

A little description
While compiling of .NET program, its code is converted into Common Intermediate Language code that is done by Common Language Runtime.
But while executing the program this CIL code is converted into Machine code or Native code that is done by JIT Compiler.

What is the location of Global Assembly Cache on the system?

What's the difference between private and shared assembly?
Private Assembly is used inside an application only and does not have to be identified by a strong name.
Shared Assembly can be used by multiple applications and has to have a strong name.

Can you place two .dll files with the same name in GAC (Global Assembly Cache)?
Yes, provided both have different versions.
GAC is a Folder that contains .dll that have strong name. So we can keep myproject.dll and myproject.dll two files into GAC with different version like and

What is typed dataset ?
A typed dataset is very much similar to a normal dataset. But the only difference is that the sehema is already present for the same. Hence any mismatch in the column will generate compile time errors rather than runtime error as in the case of normal dataset. Also accessing the column value is much easier than the normal dataset as the column definition will be available in the schema.

Can a DataAdapter.Fill method take DataTable as parameter or it works only for DataSet?
It has 5 different overloads and of course it can take DataSet as well as DataTable as parameter to fill data in from database.

Can you assign GridView.DataSource = DataReader()?

What is Property?
A property is a method or pair of methods that are exposed to the outside world as if they are fields.

What is Remoting in .NET?
.NET Remoting offers much more complex functionality including support for passing objects by values or by references, callbacks & multiple objects activation ^ life cycle management policy. In order to use Remoting a client need to build using .NET.
What is application domain?
The primary purpose of application domain is to isolate an application from other application. Win32 process provides isolation but in distinct memory address spaces. This is effective but it is expensive and doesn't scale well. The .NET runtime enforces app domain isolation by keeping control over the use of memory.
All memory in the app domain is managed by the .net runtime so the runtime can ensure that app domain do not access each other's memory. Objects in different application domains communicate either by transporting copies of objects across application domain boundries or by using a proxy to exchange messages.

What is RSS?
RSS (Really Simple Syndication/Rich Site Summary) is a light weight XML format for distributing news headlines or site summary & other contents of the website.

What is Satellite Assembly?
It is a often used to deploy language specific resources for an application. These assemblies work in side-by-side execution because the application has a separate product ID for each language & installed satellite assemblies in a language specific sub-directory.
When uninstalling, the application removes only the satellite assemblies associated within a give language & .NET Framework version.

What is MSIL?
MSIL (Microsoft Intermediate Language) is a CPU-Independent instructions set into which .NET Framework programs are compiled. It contains instructions for loading, storing, initializing and calling methods on objects.

What is CLS?
CLS (Common Language Specification) is a set of constructs or constraints that serves as a guide for library writers and compiler writers.It allows libraries to be fully usable from any language supporting the CLS, and for those languages to integrate with each other. The CLS is a subset of common type system. The common language specifications is also important to application developers wh are writing code that will be used by other developers.

What is CTS?
CTS (Common Type System) is a rich type system, build into the common language runtime that supports the types and operations found in most of the programming languages. The common type system supports the complete implementation of a wide range of programming language.

What does aspx stand for?
Active Server Pages Extension

What is Singleton pattern?
Singleton pattern ensures a class has only one instance & provide a global point of access to it. It is achieved by declaring a static variable for the class & checking for null before actually instantiating it.

Where reference and value types variables are stored?
All reference type variables are stored in heap (Random) and all value types variables are stored in stack (Sequential).

What is StringCollection?
StringCollection is a simple resizable collection of strings
Following function shows how to insert and retrive data into/from StringCollection.
public static string GetStringCollection()
System.Text.StringBuilder strB = new System.Text.StringBuilder();

// Add strings into StringCollection
System.Collections.Specialized.StringCollection strC = new System.Collections.Specialized.StringCollection();
strC.Add("Ram 1");
strC.Add("Ram 2");
strC.Add("Ram 3");
strC.Add("Ram 4");
strC.Add("Ram 5");

// Retrieve string from StringCollection
System.Collections.Specialized.StringEnumerator coll = strC.GetEnumerator();
while (coll.MoveNext())
strB.Append(coll.Current + "");
return strB.ToString();

What is the use of RCW & CCW?
RCW: Runtime Collable Wrapper takes a COM component, wrap it up and allows .NET client to consume it.
CCW: COM Collable Wrapper wraps a .NET object for consumption by COM client

List few ValueTypes variables.
Below are all ValueTypes variables.

String is a value type or reference type?
String is a reference type variable.

When to use String and StringBuilder class?
Use the String class to concat, join or format methods to join multiple items in a single statement.
Use StringBuilder class to create dynamic strings.

Write a function into Javascript that will toggle display a HTML element.
function ShowHide(id)
document.getElementById(id).style.display == '' ? document.getElementById(id).style.display = 'none' : document.getElementById(id).style.display = '';

What is CLR (Common Language Runtime)?
This is an execution engine for .NET Framework application. It provides a number of services including
1. Code Management
2. Application memory isolation
3. Verification of type safety
4. Conversion of IL to native code.
5. Access to meta data
6. Managing memory for managed objects
7. Enforcement of code access security
8. Exception handling, including cross-language exceptions.
9. Inter operation between managed code, COM objects and pre-existing DLLs (Unmanaged code and data)
10. Automation of object layout
11. Support for developer services (profiling, debugging etc.)

Difference between Response.Expires and Response.ExpiresAbsolute?
This property specifies the number of minutes before a page cached in the browser expires ie. if the user returns to the same page before the specified number of minutes the cached version of the page is displayed.
<% Response.Expires = minutes %>

Using this property we can set the date and/or time at which page cached in the browser expires.
<% Response.ExpiresAbsolute=#May 15, 1999 18:00:00# %>

What is boxing and unboxing?
Converting a value type to reference type is called Boxing and Converting reference type of value type is Unboxing.

int i = 1;
object o = i; // boxing
int j = (int) o; // unboxing

What is gacutil.exe?
It's a command to install the assembly into the Global Assembly Cache.

How to use trace in libraray classes (like BAL, DAL)?
Use following code to use Trace.Warn, Trace.Write etc.

What is MVC (Model View Controller) pattern?
The Model-View-Controller (MVC) pattern separates the modeling of the domain, the presentation, and the actions based on user input into three separate classes:

Model. The model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller).

View. The view manages the display of information.

Controller. The controller interprets the mouse and keyboard inputs from the user, informing the model and/or the view to change as appropriate.

What are session management techniques in .NET?
There are three different techniques of managing session in ASP.NET
Session state is stored locally in memory of ASP.NET worker process.

Session state is stored outside ASP.NET worker process and is managed by Windows service. Location of this service is specified by stateConnectionString attribute.

Session state is stored outside ASP.NET worker process in SQL Server database. Location of this database is represented by sqlConnectionString attribute.
Locations of visitors to this page