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
}
g.Dispose();
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.Focus();

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)
{
sb.Append(s);
s = sr.ReadLine();
}
sr.Close();
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

TextBox1.KeyPress
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
NewWindow.Show()
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

System.Windows.Forms.LinkLabelLinkClickedEventArgs)Handles_
LinkLabel1.LinkClicked
System.Diagnostics.Process.Start("www.yahoo.com")
End Sub
Upon running the application,click on the Text on the LinkLabel. The website, Yahoo.com will open in a new browser.
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(“India”)
ComboBox1.Items.Add(“Australia”)
ComboBox1.Items.Add(“Sweden”)
ComboBox1.Items.Add(“Spain”)
ComboBox1.Items.Add(“England”)
ComboBox1.Items.Add(“United States”)
ComboBox1.Items.Add(“Russia”)
ComboBox1.Items.Add(“China”)
ComboBox1.Items.Add(“Japan”)
ComboBox1.Items.Add(“New Zeland”)
End Sub
To sort the items alpahbetically, select the .Sorted property and set it to True.

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
PictureBox1.Image=Image.FromFile("C:\images\image.gif")
'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
Me.Controls.Add(tb)
'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()
expl.Show()
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

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

String Value="";

if (Node.Attributes["Attribute1"] == null)
{
// doesn't exist
Value="";
}
else
{
// exists
Value=Node.Attributes["Attribute1"].Value.ToString();
}

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?

System.Windows.Forms.Form

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
control.
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.
E.g
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)
{
ValidateName();
}
Private bool ValidateName()
{
bool bStatus = true;
if (textBox1.Text == “”)
{
errorProvider1.SetError (textBox1,”Please enter your Name”);
bStatus = false;
}
else
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

3 comments:

  1. Hi

    Tks very much for post:

    I like it and hope that you continue posting.

    Let me show other source that may be good for community.

    Source: Project interview questions

    Best rgs
    David

    ReplyDelete
  2. Thanks for the post

    You can find some good Techical Interview Question Answers on in the below link

    Technical Interview Question Database

    Thanks
    Joya

    ReplyDelete
  3. Great work, really appreciate your effort for the information and being enrolled in http://www.wiziq.com/course/46-INTERVIEW-PREPARATION-COURSE-BY-SHIVPRASAD-KOIRALA the OOps, .NET and SQL INTERVIEW Preparation i found your information very helpful.

    ReplyDelete

 
Locations of visitors to this page