0% found this document useful (0 votes)
134 views234 pages

PG - MCA - Computer Applications - 31524 MCA VB - NET - 8300

Uploaded by

VARSHA BHARNE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
134 views234 pages

PG - MCA - Computer Applications - 31524 MCA VB - NET - 8300

Uploaded by

VARSHA BHARNE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 234

ALAGAPPA UNIVERSITY

[Accredited with ’A+’ Grade by NAAC (CGPA:3.64) in the Third Cycle

and Graded as Category–I University by MHRD-UGC]


KARAIKUDI – 630 003

DIRECTORATE OF DISTANCE EDUCATION

Master of Computer Applications


315 24

VISUAL PROGRAMMING
WITH .NET
Semester - II
ALAGAPPA UNIVERSITY
[Accredited with ‘A+’ Grade by NAAC (CGPA:3.64) in the Third Cycle
and Graded as Category–I University by MHRD-UGC]
(A State University Established by the Government of Tamil Nadu)
KARAIKUDI – 630 003

Directorate of Distance Education

Master of Computer Applications


Semester - II
31524

VISUAL PROGRAMMING WITH .NET


Reviewer
Mr. S. Balasubramanian Assistant Professor in Computer Science,
Directorate of Distance Education,
Alagappa University, Karaikudi

Author
Dr. Preety Khatri, Assistant Professor, Institute of Management Studies (IMS), Noida

"The copyright shall be vested with Alagappa University"

All rights reserved. No part of this publication which is material protected by this copyright notice
may be reproduced or transmitted or utilized or stored in any form or by any means now known or
hereinafter invented, electronic, digital or mechanical, including photocopying, scanning, recording
or by any information storage or retrieval system, without prior written permission from the Alagappa
University, Karaikudi, Tamil Nadu.

Information contained in this book has been published by VIKAS® Publishing House Pvt. Ltd. and has
been obtained by its Authors from sources believed to be reliable and are correct to the best of their
knowledge. However, the Alagappa University, Publisher and its Authors shall in no event be liable for
any errors, omissions or damages arising out of use of this information and specifically disclaim any
implied warranties or merchantability or fitness for any particular use.

Vikas® is the registered trademark of Vikas® Publishing House Pvt. Ltd.


VIKAS® PUBLISHING HOUSE PVT. LTD.
E-28, Sector-8, Noida - 201301 (UP)
Phone: 0120-4078900  Fax: 0120-4078999
Regd. Office: 7361, Ravindra Mansion, Ram Nagar, New Delhi 110 055
 Website: www.vikaspublishing.com  Email: [email protected]

Work Order No. AU/DDE/DE1-291/Preparation and Printing of Course Materials/2018 Dated 19.11.2018 Copies - 500
SYLLABI-BOOK MAPPING TABLE
Visual Programming with .NET
Syllabi Mapping in Book

BLOCK 1 : INTRODUCTION
Unit 1: Introduction: What is Visual Studio?-Navigating the Unit 1: Introduction to Visual Studio
Visual Studio-The Menu–Toolbar-Work Area. (Pages 1-15);
Unit 2: Toolbox: Solution Explorer-Status Bar-Managing VS Unit 2: Toolbox
Windows. (Pages 16-35);
Unit 3: Visual Studio Project Types: Windows Projects- Unit 3: Visual Studio
Web Projects-Office Projects-SharePoint Projects-Database Project Types
Projects. (Pages 36-40)

BLOCK 2 : C# AND VB.NET


Unit 4: Basic Syntax: Code Skeleton-The Main Method-The Unit 4: Basic Syntax
Program Class-The First Program Namespace-VS Code (Pages 41-59);
Editor-Class and Member Locators–Bookmarks-Running Unit 5: Creating Classes
Programs-Primitive Types and Expressions-Enums-Branching (Pages 60-77);
Statements-Loops. Unit 6: Method Snippets
Unit 5: Creating Classes: Class Inheritance–Class Snippet- (Pages 78-85)
Writing Methods-Parameters Passing-Returning Data.
Unit 6: Method Snippets: Coding Fields and Properties-
Declaring and Using Properties-The Property Snippet.

BLOCK 3: UNDERSTANDING DELEGATES AND


EVENTS
Unit 7: Events: Delegates-Handler Code-Implementing Unit 7: Events
Interfaces-The Interface Snippet-Applying Arrays and (Pages 86-103);
Generics. Unit 8: Creating and
Unit 8: Creating and Building Projects: Constructing Building Projects
Solutions and Projects-Navigating the Solution Explorer- (Pages 104-110);
Examining Property Settings-Assembly Name-Default Unit 9: Building Projects
Namespace-Target Framework-Output Type. (Pages 111-124)
Unit 9: Building Projects: Startup Object-Icon and Manifest-
Compiling Applications-Rebuilding Solutions/Projects-Cleaning
Solutions/Projects-Managing Dependencies, Compilation
Settings-Navigating with Class View-Using the Class Designer-
Class Designer Code Generation.

BLOCK 4 : DEBUGGING WITH VISUAL STUDIO


Unit 10: Debugging methods: Breakpoints-Stepping Through Unit 10: Debugging Methods
Code–Inspecting Application State-Locals and Autos Windows- (Pages 125-143);
Watch Windows-The Immediate Window-The Call Stack
Window-The Quick Watch Window-Watching Variables with
Pin to Source-Working with IntelliTrace.
Unit 11: Working with Databases: Server Explorer-Creating Unit 11: Working with Databases
a Database-Adding Tables-Relating Tables with Foreign Keys- (Pages 144-154)
Adding Stored Procedures-Configuring Database Options.

BLOCK 5 : BUILDING PROGRAMS WITH VS 2010


Unit 12: Building Desktop Applications with WPF: Unit 12: Building Desktop
Starting a WPF Project-Understanding Layout-Grid Layout- Applications with WPF
StackPanel Layout-DockPanel Layout-WrapPanel Layout- (Pages 155-164);
Canvas Layout. Unit 13: Using WPF Controls
Unit 13: Using WPF Controls: Managing Windows for (Pages 165-180);
Controls-Setting Properties-Handling Events-Coding Event Unit 14: Creating, Designing and
Handlers-Working with Data in WPF-Data Source-Configuring Deploying Web Applications
a ComboBox. with ASP.NET MVC
Unit 14: Reading and Saving Data-Using the DataGrid- (Pages 181-222)
Summary-Creating Web Applications with ASP.NET MVC-
Designing Silverlight Applications-Deploying Web Services with
WCF.
CONTENTS
INTRODUCTION

BLOCK I: INTRODUCTION
UNIT 1 INTRODUCTION TO VISUAL STUDIO 1-15
1.0 Introduction
1.1 Objectives
1.2 Visual Studio Code
1.3 Installing Visual Studio 2010
1.4 Working on Visual Studio 2010
1.4.1 Navigating the Visual Studio 2010 Environment
1.5 Answers to Check Your Progress Questions
1.6 Summary
1.7 Key Words
1.8 Self Assessment Questions and Exercises
1.9 Further Readings
UNIT 2 TOOLBOX 16-35
2.0 Introduction
2.1 Objectives
2.2 The Toolbox
2.3 The Solution Explorer
2.4 Managing vs Windows
2.5 Answers to Check Your Progress Questions
2.6 Summary
2.7 Key Words
2.8 Self Assessment Questions and Exercises
2.9 Further Readings
UNIT 3 VISUAL STUDIO PROJECT TYPES 36-40
3.0 Introduction
3.1 Objectives
3.2 Getting Started with Visual Studio Project Types
3.3 Answers to Check Your Progress Questions
3.4 Summary
3.5 Key Words
3.6 Self Assessment Questions and Exercises
3.7 Further Readings

BLOCK II: C# AND VB.NET


UNIT 4 BASIC SYNTAX 41-59
4.0 Introduction
4.1 Objectives
4.2 Starting a Simple Project and Code Skeleton
4.2.1 The Main Method
4.2.2 The Program Class
4.2.3 First Program Namespace
4.2.4 An Overview of the Visual Studio Code Editor
4.2.5 Class and Member Locators
4.2.6 Bookmarks
4.3 Running Programs
4.3.1 Primitive Types
4.3.2 Expressions
4.3.3 Enums
4.3.4 Branching Statements
4.3.5 Loops
4.4 Answers to Check Your Progress Questions
4.5 Summary
4.6 Key Words
4.7 Self Assessment Questions and Exercises
4.8 Further Readings
UNIT 5 CREATING CLASSES 60-77
5.0 Introduction
5.1 Objectives
5.2 Classes
5.3 Class Inheritance
5.4 Class Snippet and Writing Methods
5.4.1 Parameters Passing and Returning Values
5.5 Answers to Check Your Progress Questions
5.6 Summary
5.7 Key Words
5.8 Self Assessment Questions and Exercises
5.9 Further Readings
UNIT 6 METHOD SNIPPETS 78-85
6.0 Introduction
6.1 Objectives
6.2 Getting Started with Method Snippets
6.2.1 The Property Snippet
6.3 Answers to Check Your Progress Questions
6.4 Summary
6.5 Key Words
6.6 Self Assessment Questions and Exercises
6.7 Further Readings

BLOCK III: UNDERSTANDING DELEGATES AND EVENTS


UNIT 7 EVENTS 86-103
7.0 Introduction
7.1 Objectives
7.2 Introduction to Events
7.3 Delegates
7.3.1 Event, Delegate and Handler Code Completion
7.4 Implementing Interfaces
7.4.1 Creating an Interface
7.4.2 Making Classes Implement the Interface
7.5 The Interface Snippet
7.6 Applying Arrays and Generics
7.7 Answers to Check Your Progress Questions
7.8 Summary
7.9 Key Words
7.10 Self Assessment Questions and Exercises
7.11 Further Readings
UNIT 8 CREATING AND BUILDING PROJECTS 104-110
8.0Introduction
8.1 Objectives
8.2 Constructing Solutions and Projects
8.3 Navigating the Solution Explorer
8.4 Examining Property Settings
8.5 Answers to Check Your Progress Questions
8.6 Summary
8.7 Key Words
8.8 Self Assessment Questions and Exercises
8.9 Further Readings
UNIT 9 BUILDING PROJECTS 111-124
9.0 Introduction
9.1 Objectives
9.2 Startup Object, Icon and Manifest
9.3 Building and Cleaning Projects/Solutions
9.4 Managing Dependencies and Build Order
9.5 Managing Compilation Settings
9.6 Navigating a Project with Class View
9.7 Answers to Check Your Progress Questions
9.8 Summary
9.9 Key Words
9.10 Self Assessment Questions and Exercises
9.11 Further Readings

BLOCK IV: DEBUGGING WITH VISUAL STUDIO


UNIT 10 DEBUGGING METHODS 125-143
10.0 Introduction
10.1 Objectives
10.2 Basic Concept
10.2.1 Setting Breakpoints
10.2.2 Stepping through the Code
10.2.3 Inspecting Application State
10.2.4 Locals and Autos Windows
10.2.5 Watch Windows
10.2.6 The Immediate Window
10.2.7 The Call Stack Window
10.2.8 The Quick Watch Window
10.2.9 Watching Variables with Pin to Source
10.2.10 Working with IntelliTrace
10.3 Answers to Check Your Progress Questions
10.4 Summary
10.5 Key Words
10.6 Self Assessment Questions and Exercises
10.7 Further Readings
UNIT 11 WORKING WITH DATABASES 144-154
11.0 Introduction
11.1 Objectives
11.2 Introduction to Server Explorer
11.2.1 Creating a Database
11.2.2 Adding Tables
11.2.3 Relating Tables with Foreign Keys
11.2.4 Adding Stored Procedures
11.2.5 Configuring Database Options
11.3 Answers to Check Your Progress Questions
11.4 Summary
11.5 Key Words
11.6 Self Assessment Questions and Exercises
11.7 Further Readings

BLOCK V: BUILDING PROGRAMS WITH VS 2010


UNIT 12 BUILDING DESKTOP APPLICATIONS WITH WPF 155-164
12.0 Introduction
12.1 Objectives
12.2 Starting a WPF Project
12.3 Understanding Layout
12.3.1 Grid Layout
12.3.2 StackPanel Layout
12.3.3 DockPanel Layout
12.3.4 WrapPanel Layout
12.3.5 Canvas Layout
12.4 Answers to Check Your Progress Questions
12.5 Summary
12.6 Key Words
12.7 Self Assessment Questions and Exercises
12.8 Further Readings
UNIT 13 USING WPF CONTROLS 165-180
13.0 Introduction
13.1 Objectives
13.2 Managing Windows for Controls
13.2.1 Setting Properties
13.2.2 Handling Events
13.2.3 Coding Event Handlers
13.2.4 Working with Data in WPF
13.2.5 Configuring a Combobox
13.3 Answers to Check Your Progress Questions
13.4 Summary
13.5 Key Words
13.6 Self Assessment Questions and Exercises
13.7 Further Readings
UNIT 14 CREATING, DESIGNING AND DEPLOYING WEB APPLICATIONS
WITH ASP.NET MVC 181-222
14.0 Introduction
14.1 Objectives
14.2 Reading and Saving Data
14.2.1 Using the DataGrid
14.3 ASP.NET MVC
14.3.1 Starting an ASP.NET MVC Project
14.3.2 Building Controllers
14.3.3 Assigning Masterpage Files
14.3.4 Managing Routing
14.3.5 Building an Employee Management Application
14.4 Starting a Silverlight Project
14.4.1 Using Silverlight Controls (Playing Video)
14.4.2 Running Silverlight Out-Of-Browser (OOB)
14.5 Starting a WCF Project
14.5.1 WCF Interfaces
14.5.2 Implementing a WCF Service Contract
14.6 Answers to Check Your Progress Questions
14.7 Summary
14.8 Key Words
14.9 Self Assessment Questions and Exercises
14.10 Further Readings
Introduction
INTRODUCTION

A programming language is an artificial language specifically designed to


NOTES communicate instructions to a machine, particularly a computer. Technically, the
programming languages are used to create programs that control the behaviour of
a machine and/or to express algorithms precisely. The earliest programming
languages predate the invention of the computer and were used to direct the
behaviour of machines, such as Jacquard looms. Since then thousands of different
programming languages have been created, mostly in the computer field, with
many more being created every year. The majority programming languages illustrate
computation in an imperative style, i.e., as a sequence of commands, while some
languages, such as those that support functional programming or logic programming
use alternative forms of description. The description of a programming language is
usually split into the two components of syntax (form) and semantics (meaning).
Visual Basic or VB is considered as a third generation or high level event
driven programming language with Integrated Development Environment (IDE)
specifically developed by Microsoft for its COM (Component Object Model)
programming model and was first released in 1991. A Visual Basic programmer
can design an application using the components provided with Visual Basic itself.
Programming in VB is a combination of visually arranging components or controls
on a form, specifying attributes and actions of those components, and writing
additional lines of code for more functionality. Visual Studio is an integrated
development environment (IDE) used to develop programs, websites, web apps,
web services etc. it uses Microsoft software development platform such as
Windows API, Microsoft Silverlight etc. It can produce both native code and
managed code. Visual studio support 36 languages such as C#, Visual Basic,
C++ etc. This book provides the basic knowledge of using Visual studio and use
code in C# and Visual Basic.
This book, Visual Programming with .NET, follows the SIM format or
the self-instructional mode wherein each unit begins with an ‘Introduction’ to the
topic followed by an outline of the ‘Objectives’. The detailed content is then
presented in a simple and organized manner, interspersed with ‘Check Your
Progress’ questions to test the understanding of the students. A ‘Summary’ along
with a list of ‘Key Words’ and a set of ‘Self Assessment Questions and Exercises’
is also provided at the end of each unit for effective recapitulation.

Self-Instructional
10 Material
Introduction to
BLOCK - I Visual Studio
INTRODUCTION

NOTES
UNIT 1 INTRODUCTION TO
VISUAL STUDIO
Structure
1.0 Introduction
1.1 Objectives
1.2 Visual Studio Code
1.3 Installing Visual Studio 2010
1.4 Working on Visual Studio 2010
1.4.1 Navigating the Visual Studio 2010 Environment
1.5 Answers to Check Your Progress Questions
1.6 Summary
1.7 Key Words
1.8 Self Assessment Questions and Exercises
1.9 Further Readings

1.0 INTRODUCTION

Visual Studio .NET is a Microsoft-integrated development environment (IDE)


which can be used for developing Windows Forms, graphical user interfaces
(GUIs), consoles Web applications and Web services. Visual studio is a collection
of tools that helps to write programs. Text editor is required to write the code and
a command line compiler to run and create an executable application, if visual
studio is not installed. The use of Visual Studio is to mechanize many of the ordinary
tasks which are required to develop applications.
Visual Studio is used to write and manage native code supported by .NET
Framework, Microsoft Windows, Windows CE, Windows Mobile, Microsoft
Silverlight and .NET Compact Framework. The code editor Visual Studio .NET
supports code refactoring and IntelliSense and the Visual Studio .NET integrated
debugger that supports machine-level debugging and source-level debugging. Visual
Studio .NET also consists of built-in tools for example a form designer, which is
used in building GUI applications. A Web designer is a class designer that creates
and develop dynamic web pages and also used to design a schema for supporting
database and for custom libraries also.
Plug-ins can be added at different levels which are used to improve the
functionality, while domain-specific language editors and visual designers are
examples of new tool sets that may be added via these plug-ins. Built-in language
services offer support for different well-known languages (like C#, C++, VB, and
Self-Instructional
Material 1
Introduction to F#), while language services may be installed separately to support languages,
Visual Studio
including M, Python, and Ruby, among other supported languages. There are
various versions of Visual Studio which support different languages. It is a cost-
effective solution for beginners who only need Visual Basic.
NOTES

1.1 OBJECTIVES

After going through this unit, you will be able to:


 Understand the significance of Visual Studio
 Install and navigate through the Visual Studio
 Understand and discuss the various menu options and tools available in
Visual Studio

1.2 VISUAL STUDIO CODE

Visual Studio code is code an editor that combines the source code editor with
powerful developer tooling, for example, IntelliSense code completion with
debugging. It is supported by macOS, Linux, and Windows. Visual Studio Code
consists of built-in support for rich semantic code understanding and navigation,
IntelliSense code completion, and code refactoring.
Visual Studio Code consists of an interactive debugger, with the help of this
the programmer can go through the source code, analyse variables, check status
stacks and execute commands in the console. It works with build and scripting
tools which is used to perform common tasks.
Benefits of using Visual Studio

1. Automatically Generated Code


 You can choose from a large number of projects included in visual studio.
After starting a new project, Visual Studio will automatically produce outline
code which can compile and run immediately. Each project type has project
items that you can add, and project items includes skeleton.
 Visual Studio consists of predefined controls which saves the time to write
your own code (for repetitive tasks).
2. Customizability and Extensibility
 Many parts of the Visual Studio may be customized like layout, editor
options, colours etc. Because of the options which are so widespread, so it
must require to know where and how to find them.

Self-Instructional
2 Material
 If the out-of-the-box VS development environment doesn’t offer a feature Introduction to
Visual Studio
you need, you can write your own macros to automate a series of tasks you
find yourself repeating.
 Customizability and Extensibility provides a better environment to work NOTES
with.
3. Everything at Your Fingertips
 Visual Studio provides a way how to navigate the Visual Studio environment.
It provides better working experience by providing toolbox, a server
explorer, databases, a Solution Explorer, testing utilities, and visual designers.
4. Rapid Coding Experience
It uses snippets to type an abbreviation that expands to a code template. The VS
editor optimizes your coding experience. Much of your code is colorized; you
have IntelliSense, tips that pop up as you type; and keyboard shortcuts for
performing a multitude of tasks. There are a few refactoring features that help you
quickly improve the organization of your code while you’re coding. For example,
the Rename refactoring allows you to change an identifier name where it is defined,
which also changes every place in the program that references that identifier. VS
introduces even more features, such as a call hierarchy, which lets you see the call
paths in your code; snippets, which allow you to type an abbreviation that expands
to a code template; and action lists for automatically generating new code.

1.3 INSTALLING VISUAL STUDIO 2010

In this section, we will discuss about system requirements and how to install, set
up and run the application.
System Requirements
Following are the basic requirements for installing Visual Studio 2010.
 A 32-bit x86 or 64-bit (x64) CPU, at least 1GB RAM, DVD-ROM.
 3GB hard disk space, a 5400 RPM hard disk drive.
 A 1.6 GHz processor, DirectX video at 1280 × 1024 resolution.
Following are the steps to install the Visual Studio:
1. When you start the visual studio set up, then you can see the Microsoft
Visual Studio 2010 window as shown in Figure 1.1. View ReadMe button
shows some guidelines to install the software. Click on Install Microsoft
Visual Studio 2010.

Self-Instructional
Material 3
Introduction to
Visual Studio

NOTES

Fig. 1.1 Microsoft Visual Studio 2010 Setup window

2. After the setup window, there is setup welcome Microsoft Visual Studio
2010 window as shown in figure 1.2. The setup is loading installation
components. This figure shows the installation of Ultimate version. In the
Help Improve Setup section, there is a check box button and if that button
is clicked, then the installer would collect logs produced throughout the
setup process. After the setup is complete then these are directed across
the internet to Microsoft. Under the check box, there is a link that is privacy
statement and this link provides the more information about Microsoft that
is what Microsoft does with setup information. After doing these steps,
click Next.

Fig. 1.2 Setup Welcome Microsoft Visual Studio 2010 Window


Self-Instructional
4 Material
Introduction to
Visual Studio

NOTES

Fig. 1.3 Setup Licensing terms window

3. After the setup components gets loaded, then there comes licensing window
screen as shown in Figure 1.3. The installer must read the Visual Studio
License agreement for the understanding of licencing terms and conditions.
Depending upon the choice of package, the licensing terms may differ. It
may vary based on specific country or region. After ensuring the terms and
conditions, click on check box containing “I have read and accept the license
terms” to proceed for the next step. After that write your name and enter
the license key which comes with your software. If Visual Studio is
downloaded with the help of Microsoft Developer Network (MSDN) then
the installer will spontaneously fill in the product key. After that click Next.

Fig. 1.4 Setup Customization window


Self-Instructional
Material 5
Introduction to 4. After licencing window, there is an option for customizing product installation.
Visual Studio
Figure 1.4 which shows the options to select between full and custom
installation. If you click the Custom option, you will be able to choose
precisely which components should be installed. This is a good opportunity
NOTES to uncheck the items you won’t ever use. If it is your first installation and
you have enough storage, you might want to go through the list and check
everything to take a look at what is available. You can always return to this
installation later and make adjustments.
Figure 1.4 shows in product install path. So, there is an option to change
the location or path to install Visual Studio. After choosing the desired path
to install the visual studio, click on Install button to start the installation and
the installation begins.

Fig. 1.5 Installation Setup Progress Window

5. Visual Studio installer would be required to reboot the computer.

Fig. 1.6 Window set up to restart your computer to complete the installation
Self-Instructional
6 Material
6. After completion of installation process, there comes an option to restart Introduction to
Visual Studio
the computer, as shown in Figure 1.6. Make sure to close applications you
are working on to avoid loss of data and then click Restart Now.

NOTES

Fig. 1.7 Installation Setup Success window

7. When installation completes without any error, you’ll see the Success
window as shown in Figure 1.7. But sometimes some problems occur
during installation. To resolve them, window provides the guidance on
what to do and how to solve this problem. After completion of installation,
the documentation can be install by clicking on Install Documentation
button.

Self-Instructional
Material 7
Introduction to
Visual Studio

NOTES

Fig. 1.8 Checking for service releases

8. Your installation is now almost complete. You can install product


documentation by clicking the Install Documentation button as shown in
Figure 1.7. The initial installation screen that appeared when beginning the
installation will reappear, as shown in Figure 1.8. You should also check for
service releases; not only for the updated functionality to VS, but also
because service releases often include important security updates.

Fig. 1.9 Options for Default Environment choosing window


Self-Instructional
8 Material
9. You are now ready to run VS. You will also require to perform one easier Introduction to
Visual Studio
configuration step, where you will choose your default environment settings,
as shown in Figure 1.9.

NOTES
1.4 WORKING VISUAL STUDIO 2010

After launching the Visual Studio 2010, the screen of Microsoft Visual Studio
2010 appears. This screen shows information about the version of the product.
Also it provides the information about to whom it has been licensed as shown in
figure 1.10.

Fig. 1.10 Visual Studio Installation IDE

The first time you run Visual Studio 2010, you will see the splash screen
only for a short period before you are prompted to select the default
environment settings. It may seem unusual to ask those who haven’t used a
product before how they imagine themselves using it. Because Microsoft has
consolidated a number of languages and technologies into a single IDE. IDE
must account for the subtle (and sometimes not so subtle) differences in the
way developers work.

Self-Instructional
Material 9
Introduction to
Visual Studio

NOTES

Fig. 1.11 Default Environment Settings

Figure 1.11 shows how to select the default environment settings after starting
up the visual studio 2010. Depending on selecting the environment settings, when
you click the Start Visual Studio button you will most likely see a dialog indicating
that Visual Studio is configuring the development environment. Once the process
gets complete, Visual Studio 2010 opens and ready to start work as shown in
Figure1.12.

Self-Instructional
10 Material
Introduction to
Visual Studio

NOTES

Fig. 1.12 Visual Studio 2010 Start-up Window

Before you start building your first application, it is important to take a step
back and look at the components that make up the Visual Studio 2010 IDE.
Menus and toolbars are positioned along the top of the environment and a selection
of sub-windows, or panes, appears on the left, right, and bottom of the main
window area. The main editor space is in the center. Whenever you open a code
file, an XML document, a form, or some other file, it appears in this space for
editing. A new tab is created for every new file so that you can toggle among
opened files. On either side of the editor space is a set of tool windows. These
areas provide additional contextual information and functionality.
In case of the general developer settings, the default layout includes the
Solution Explorer and Class View on the right, and the Server Explorer and Toolbox
on the left. The tool windows on the left are in their collapsed, or unpinned, state.
If you click a tool window’s title, it expands and collapses again when you remove
the cursor. When a tool window is expanded, you see a series of three icons at the
top right of the window, similar to those shown in the left image of Figure 1.13.

Fig. 1.13 Unpinned Tool Window State


Self-Instructional
Material 11
Introduction to If you want the tool window to remain in its expanded, or pinned state, you
Visual Studio
can click the middle icon, which looks like a pin. The pin rotates 90 degrees to
indicate that the window is now pinned. Clicking the third icon, the X, closes the
window. If later you want to reopen this or another tool window, you can select it
NOTES from the View menu. The right image in Figure 1.13 shows the context menu that
appears when the first icon, the down arrow, is clicked. Each item in this list
represents a different way of arranging the tool window. The Float option allows
the tool window to be placed anywhere on the screen, independent of the main
IDE window. It is useful if you have multiple screens because you can move the
various tool windows onto the additional screen, allowing the editor space to use
the maximum screen real estate. Selecting the Dock as Tabbed Document option
makes the tool window into an additional tab in the editor space.
1.4.1 Navigating the Visual Studio 2010 Environment
Visual Studio integrated development environment is also abbreviated as IDE.
Figure 1.14 shows how Visual Studio looks when it is first started. It shows the
parts of the screen and also help to know about how the IDE is organized.

Fig. 1.14 Visual Studio 2010 Start-up Screen

The Menu
Figure 1.14 shows at the very top left there is an option menu bar having options
File, Edit, View, Tools etc. Menu option provides access to recently opened files
and projects. The menu bar is a standard part of windows applications. The cut,
copy, and paste operations comes under Edit menu option and also provide easy
navigation with the help of source code. View menu option provides the access to
all of the tool windows. It has a menu item which consists of more application
windows. The Tools menu contains a grab-bag of functionality; for instance, you
can attach a debugger to see your other programs run, line by line; connect to a

Self-Instructional
12 Material
database for data; set add-ins, macros, and more. One very important menu item Introduction to
Visual Studio
on the Tools menu is Options, which exposes hundreds of settings for customizing
your VS environment. You can use the Test menu to find all of the functionality for
performing unit tests to test your new software one part at a time. This is also
where other editions of VS include access to other types of testing tools. NOTES
The advanced functionality for improving the performance of an application
is done byAnalyse, Architecture, and Team menus .These also provides functionality
like integrating With Microsoft’s Team Foundation Server as well as working with
application architecture.
The Windows and Help menus are alike in case of most of the application
types. The Windows menu permits to deploy the Visual Studio windows and the
Help menu is that where to look and visit to discover the technical documentation
on Visual Studio.
Toolbar
As shown in Figure 1.14, there is an option called toolbar. The toolbar consists of
commonly accessed functionality which is a subset of what is available with the
help of menus. Toolbars are context-sensitive means hiding and showing depending
on what you are doing in Visual Studio. It is easy to display any toolbar using View
toolbar option. You can also customize toolbars and also scrolling to the bottom of
the list by right-clicking the toolbar of your choice. Toolbar customization window
is used to add any feature that you would like to the current toolbar.
Work Area
The work area consists of the start page which is at the centre as shown in Figure
1.14. This work area is used to write code. It also provides the functionality to
work with visual designers. The Start page is separated into two sections i.e.
information and project management.
On the right, the information side of the page consists of resources to help
you get started with Visual studio such as links to the Microsoft Web site,
walkthroughs to help you learn new features and tab which updates with the help
of latest developer news from Microsoft. On the left, the project management side
of the page deals with a quick way to start new projects or work having a list of
newly opened projects.

Check Your Progress


1. What is Visual Studio code?
2. What is the use of interactive debugger?

Self-Instructional
Material 13
Introduction to
Visual Studio 1.5 ANSWERS TO CHECK YOUR PROGRESS
QUESTIONS

NOTES 1. Visual Studio code is code an editor that combines the source code editor
with powerful developer tooling, for example, IntelliSense code completion
with debugging.
2. With the help of an interactive debugger, the programmer can go through
the source code, analyse variables, check status stacks and execute
commands in the console.

1.6 SUMMARY

 Visual Studio .NET is a Microsoft-integrated development environment


(IDE) which can be used for developing Windows Forms, graphical user
interfaces (GUIs), consoles Web applications and Web services.
 Visual Studio is used to write and manage native code supported by .NET
Framework, Microsoft Windows, Windows CE, Windows Mobile,
Microsoft Silverlight and .NET Compact Framework.
 Visual Studio code is code an editor that combines the source code editor
with powerful developer tooling, for example, IntelliSense code completion
with debugging. It is supported by macOS, Linux, and Windows.
 Visual Studio Code consists of an interactive debugger, with the help of this
the programmer can go through the source code, analyse variables, check
status stacks and execute commands in the console.
 The work area consists of the start page which is at the centre. This work
area is used to write code. It also provides the functionality to work with
visual designers.

1.7 KEY WORDS

 Visual Studio: It is an integrated development environment (IDE) by


Microsoft which can be used for developing Windows Forms, graphical
user interfaces (GUIs), consoles Web applications and Web services.
 Visual Studio Code: It is a code editor redefined and optimized for building
and debugging modern web and cloud applications.

Self-Instructional
14 Material
Introduction to
1.8 SELF ASSESSMENT QUESTIONS AND Visual Studio

EXERCISES

Short Answer Questions NOTES

1. Write a note on Visual Studio code.


2. What are the basic requirements for installing Visual Studio 2010?
3. What are the benefits of using Visual Studio?
Long Answer Questions
1. Explain the various steps for installing the Visual Studio 2010.
2. Write a note on the following:
(i) Menu
(ii) Toolbar
(iii) Work area

1.9 FURTHER READINGS

Bronson Gary and David Rosenthal. 2005. Introduction to Programming with


Visual Basic .NET, Burlington, Massachusetts: Jones & Bartlett Learning.
Liberty Jesse. 2003. Programming Visual Basic .NET. Sebastopol, California:
O’Reilly Media, Inc.
Mayo Joe. 2010. Ms Visual Studio 2010. Noida: Tata McGraw-Hill.

Self-Instructional
Material 15
Toolbox

UNIT 2 TOOLBOX
NOTES Structure
2.0 Introduction
2.1 Objectives
2.2 The Toolbox
2.3 The Solution Explorer
2.4 Managing vs Windows
2.5 Answers to Check Your Progress Questions
2.6 Summary
2.7 Key Words
2.8 Self Assessment Questions and Exercises
2.9 Further Readings

2.0 INTRODUCTION

In this unit, you will learn about the toolbox, solution explorer and status bar.
Toolbox is like a tool window available with the help of View menu. The Toolbox
window contains all of the available components for the currently active document
being shown in the main workspace. These can be visual components, such as
buttons and textboxes; invisible, service-oriented objects, such as timers and system
event logs; or even designer elements, such as class and interface objects used in
the Class Designer view.

2.1 OBJECTIVES

After going through this unit, you will be able to:


 Add and arrange the components in the toolbox
 Add projects and items in the Solution Explorer
 Add references to the Solution Explorer
 Expand and collapse Windows
 Show the different types of Windows

2.2 THE TOOLBOX

Microsoft has offered developers true drag and drop placement of elements during
the design of both web and rich client applications. The toolbox which is available
with (Ctrl+Alt+X). The Toolbox window which is shown in the main workspace
holds all of the available components for the currently active document.

Self-Instructional
16 Material
Toolbox

NOTES

Fig. 2.1 A Tool Window (Toolbox)

Every component is represented with its name and icon. This differs from
the old way of displaying the available objects in which the Toolbox was simply a
stacked list of icons that left you guessing as to what some of the more obscure
components were, as shown with the Common Controls group on the right side of
Figure 2.1.You can change the view of each control group individually. Right click
anywhere within the group area and deselect the List View option in the context
menu.
Visual Studio 2010 presents the available components in groups rather than
as one big mess of components. This default grouping enables you to more easily
locate the controls you need, for example, data related components are in their
own Data group.
Regardless of how the components are presented, the way they are used in
a program is usually the same: click and drag the desired component onto the
design surface of the active document, or double - click the component’s entry for
Visual Studio to automatically add an instance.
Visual components, such as buttons and textboxes appear in the design
area where they can be repositioned, resized, and otherwise adjusted via the
property grid. Non - visual components such as the Timer control, appear as
icons, with associated labels, in a non – visual area below the design area as
shown in Figure 2.2.
When you start to build your own components or controls, create a new
tab and go through the process of adding each item. Visual Studio 2010 automatically
interrogates all the projects in your solution.
Figure 2.1 shows at the top left - hand side, there is a group known as
Reference Library Controls have a single component i.e. MyControl.
Reference_Library is the name of a class library which is available and defined in
the same solution and contains MyControl control. If any components or controls
is identified (essentially any class that implements System .ComponentModel.
IComponent or System.Windows.FrameworkElement for WPF), a new tab is
created for that project and the appropriate items are added with a default icon
and class name (in this case MyControl), as shown on the left in Figure 2.1. For

Self-Instructional
Material 17
Toolbox components, this is the same icon that appears in the non - visual part of the design
area when you use the component.

NOTES

Fig. 2.2 Design Area (non-visible area)

To customize how your items appear in the Toolbox, you need to add a 16
x 16 pixel bitmap in the project which works as the control or component. The
next step is to select the newly inserted bitmap in the Solution Explorer and navigate
to the Properties window. Make sure the Build property is set to Embedded
Resource. All you now need to do is attribute your control with the Toolbox
Bitmap attribute. The code in VB as well as C# is given below.
VB
ToolboxBitmap(GetType(MyControl), “MyControlIcon.bmp”)
Public Class MyControl
C#
[ToolboxBitmap(typeof(MyControl), “MyControlIcon.bmp”)]
public class MyControl
This attribute uses the type reference for MyControl to locate the appropriate
assembly to extract the MyControlIcon.bmp embedded resource. Other overloads
of this attribute can use a file path as the only argument. In this case, you don’t
even need to add the bitmap to your project. It is also worth noting that customizing
the Toolbox and designer experience for Windows Presentation Foundation (WPF)
controls uses the notion of a Metadata store instead of attributes. This typically
results in additional assemblies that can be used to tailor the design experience in
both Visual Studio 2010 and Expression Blend.
Self-Instructional
18 Material
Adding Components in Toolbox Toolbox

Sometimes, you will find that a particular component is not present in the lists
displayed in the Toolbox. Most of the .NET components are already present, but
some are not. For example, the WebClient class component is not displayed in the NOTES
Toolbox by default. Managed applications can also use COM components in
their design. Once added to the Toolbox, COM objects can be used in much the
same way as regular .NET components, and if coded correctly you can program
against them in precisely the same way, using the Properties window and referring
to their methods, properties, and events in code.
To add a component to your Toolbox layout, right -click anywhere within
the group of components you want to add it to and select Choose Items. After a
moment, you are presented with a list of .NET Framework components as shown
in Figure 2.3.

Fig. 2.3 A List of .NET Framework Components

Scroll through the list to locate the item which you want to add to the Toolbox
and select the corresponding checkbox. You can add multiple items at the same
time by selecting each of them before clicking the OK button. You can also remove
items from the toolbox by deselecting them from the list.
If you are finding it difficult to locate the item you need, you can use the
Filter box which filters the list based on name, namespace, and assembly name.
On rare conditions the item may not be listed at all. This can happen with
nonstandard components such as ones that you build yourself or that are not
registered in the Global Assembly Cache (GAC). You can still add them by using
the Browse button to locate the physical file on the computer. Once you have
Self-Instructional
Material 19
Toolbox selected and deselected the items you need, click the OK button to save them to
the Toolbox layout. WPF components, COM components, Silverlight Components
can also be added in the same way. To view the list of available items, switch over
to the relevant tab in the dialog window and appropriately registered COM
NOTES components to add. Again, use the Browse button to search controls which may
not appear in the list.
Arranging Components in Toolbox
Toolbox items are in alphabetical order by default that enables you to locate
unfamiliar items. However, if you are only using a handful of components and
avoiding to continuously scroll up and down. You can create (groups of controls)
and move existing object types around. Repositioning an individual component
is easy. Locate it in the Toolbox and click and drag it to the new location.
When you are happy with where it is, release the mouse button and the
component will move to the new spot in the list. You can move it to a different
group in the same way by just keep dragging the component up or down the
Toolbox until you have located the right group. These actions work in both
List and Icon views.
To copy the component from one group to another, rather than moving it,
hold down the Ctrl key as you drag, and the process will duplicate the control so
that it appears in both groups. To create a new group in the Toolbox, Right click
anywhere in the toolbox area and then select the Add Tab command. A new blank
tab will be added to the bottom of the Toolbox with a prompt for you to name it.
To change the name of a component, right click the component’s entry in
the Toolbox and select the Rename Item command. An edit field will appear inline
in place of the original caption, enabling you to name it however you like it even
with special characters.
By default, controls are added to the Toolbox according to their class names.
This means you end up with some names that are difficult to understand, particularly
if you add COM controls to your Toolbox. Visual Studio 2010 enables you to
modify a component’s name to something more understandable.
If you are confused with components in unusual groups and lost sight of
where everything is, you can choose Reset Toolbox from the same right click
context menu. This restores all of the groups in the toolbox to their original states,
with components sorted alphabetically and in the groups in which they started.
When you first start Visual Studio 2010, the items within each group are
arranged alphabetically. However, after moving items around, you may find that
they’re in a bewildering state and decide that you simply need to start again. All
you have to do is right click anywhere within the group and select the Sort Items
Alphabetically command.

Self-Instructional
20 Material
Toolbox
2.3 THE SOLUTION EXPLORER

Visual Studio 2010 uses the concept of a solution to tie everything together whenever
you create or open an application or for that matter just a single file. Typically, a NOTES
solution is made up of one or more projects, each of which in turn can have
multiple items associated with it. Earlier these items were typically just files but
increasingly projects are made up of items that may consist of multiple files, or in
some cases no files at all.
The Solution Explorer tool window (Ctrl+Alt+L) provides a convenient
visual representation of the solution, projects, and items as shown in Figure 2.4.
You can see three projects presented in a tree: a C# WPF application, a C# WCF
service library, and a VB class library.
Each project has an icon associated with it that typically indicate the type of
project and the language in which it is written. There are some exceptions like
setup projects that don’t have a language because the font is bold faced, so one
node is mainly noticeable. It shows that this project is the start-up project. To
change the start-up project, right - click the project you want to nominate and
select Set as StartUp project. It is also possible to nominate multiple projects as
start-up projects via the Solution Properties dialog.

Fig. 2.4 Solution Explorer Tool Window

You can see that the My Project node is actually made up of multiple files,
which hold settings, resources, and information about the assembly. In this expanded
view, you can see all the files and folders contained under the project structure.
Unfortunately, if the file system changes, the Solution Explorer does not automatically

Self-Instructional
Material 21
Toolbox update to reflect these changes. The second button, Refresh can be used to make
sure you are seeing the correct list of files and folders.
The toolbar across the top of the Solution Explorer enables you to customize
NOTES the way the contents of the window appear to you, as well as giving you shortcuts
to the different views for individual items. For example, the first button Show All
Files expands the solution listing to display the additional files and folders as shown
in Figure 2.5.
The Solution Explorer toolbar is contextually aware with different buttons
shown which depends on what type of node is selected. Where a folder not
enclosed in the project is selected and the other buttons (from Figure 2.4) are not
visible. In short, these buttons when visible can be used to view code or open the
designer, which displays both the design and xaml views. Figure 2.5 shows the
Class Diagram button.

Fig 2.5 Shortcuts to the Different Views for Individual Items

Some Common Tasks


In addition to providing a convenient way to manage projects and items, the
Solution Explorer has a dynamic context menu that gives you quick access to
some of the most common tasks such as building the solution or individual
projects, accessing the build configuration manager, and opening files. Figure 2
.6 shows how the context menu varies depending on which item is selected in
the Solution Explorer.

Self-Instructional
22 Material
Toolbox

NOTES

Fig. 2.6 The context menu of Solution Explorer

The first items in the left hand and center menus relate to building either
the entire solution or the selected project. But in some cases, selecting Build is
the most efficient option because it only builds projects that have changed.
However, in some cases you may need to force a Rebuild which builds all
dependent projects regardless of their states. If you want to remove all the
additional files that are created during the build process, you can invoke Clean.
This option can be useful if you want to package your solution in order to e-mail
it to someone. You might not want to include all the temporary or output files
that are created by the build.
For most items in the Solution Explorer, the first section of the context
menu is similar to the right hand menu in Figure 2.7. The default Open and
Open With items allow you to determine how the item will be opened. This is
of particular use when you are working with XML resource files. Visual Studio
2010 opens this file type using the built- in resource editor, but it prevents you

Self-Instructional
Material 23
Toolbox from making certain changes and doesn’t support all data types you might
want to include using the Open With menu item. In that case, you can use the
XML editor.

NOTES
Adding Projects and Items in the Solution Explorer
The most common actions carried out in the Solution Explorer are like addition,
renaming, removal of projects and items. If you want to add a new project to an
existing solution, then you select Add àNew Project (from the context menu off
the Solution node).
As shown in Figure 2.7, that has undergone a few minor changes since
previous versions of Visual Studio. The Project templates can be searched and
sorted. The pane on the right side displays information about the selected project
such as type of project and its description.

Fig. 2.7 Adding Projects in the Solution Explorer

In the Installed Templates hierarchy on the left of the Add New Project
dialog, the templates are primarily arranged by language and then by technology.
The templates includes office project types, enabling you to build both application
and document level add-ins for most of the office products.
Though the office add-ins still make use of Visual Studio Tools for Office
(VSTO), this is built onto Visual Studio 2010 instead of being an additional installer.
There are also tabs for Online Templates and Recent Templates. The Online
Templates can be sorted and searched in the same way as Installed Templates,

Self-Instructional
24 Material
although the sort criteria has been extended to include creation date, ratings, and Toolbox

downloaded frequency.
The other thing you will notice in this dialog is the ability to select different
framework versions. If you have existing projects and don’t want to have to migrate NOTES
forward to the new version of the .NET Framework then you can still immediately
take advantage of the new features such as improved IntelliSense. The alternative
is to have both Visual Studio 2010 and a previous version installed in order to
build projects for earlier framework versions. The framework selection is also
included in the search criteria, limiting the list of available project templates to
those that are compatible with the selected .NET framework version.
One of the worst and most poorly understood features in Visual Studio is
the concept of a Web Site project. It is distinct from a Web Application project
which can be added via the aforementioned Add New Project dialog. To add a
Web Site project, you need to select Add ª’ Web Site from the context menu off
the Solution node. This displays a dialog similar to the one shown in Figure 2.8,
where you can select the type of web project to be created. In most cases, this
simply determines the type of default item that is to be created in the project.

Fig. 2.8 To Add New Web Site

You will need to start adding items once you have a project. You can do this
via the Add context menu item off the project node in the Solution Explorer. The
first submenu, New Item, launches the Add New Item dialog as shown in Figure
2.9.

Self-Instructional
Material 25
Toolbox

NOTES

Fig. 2.9 To Add New Item

Returning to the Add context menu, you will notice a number of predefined
shortcuts such as User Control and Class. These do little more than bypass the
stage of locating the appropriate template within the Add New Item dialog. The
Add New Item dialog is still displayed because you need to assign a name to the
item being created.
Adding References to the Solution Explorer
Visual Studio 2010 supports reusable components using the references for a
project. If you enlarge out any project then you will analyse a number of .NET
Framework libraries such as System. Core and System that required to be
referenced by a project in order to be built.
A reference allows the compiler to resolve type, property, method names,
and field back to the assembly where they are defined. If you want to reuse a class
from a third - party library, or even your own .NET assembly, you need to add a
reference to it via the Add Reference context menu item on the project node of the
Solution Explorer.
When you launch the Add Reference dialog (shown in Figure 2.10), Visual
Studio 2010 interrogates the local computer, the Global Assembly Cache, and
your solution in order to present a list of known libraries that can be referenced.
This includes both .NET and COM references that are separated into different
lists, as well as projects and recently used references. In previous versions of
Visual Studio, this dialog was notoriously slow to load. If the component, you
Self-Instructional
26 Material
need to reference isn’t present in the appropriate list then you can choose the Toolbox

Browse tab, which enables you to locate the file containing the component directly
in the file system. By initially loading the list of projects within your solution and
presenting that as the default tab, lazy loading the content for the remaining tabs
then this dialog displays almost instantly. NOTES
As in other project - based development environments going back as far as
the first versions of VB, you can add references to projects contained in your
solution, rather than adding the compiled binary components. The advantage to
this model is that it is easier to debug into the referenced component and ensure
that you are running the latest version of all components, but for large solutions this
may become unwieldy.

Fig. 2.10 To Add References

Adding Service References to Solution Explorer


The other type of reference that the Solution Explorer provides is service references.
In previous versions of Visual Studio, it was referred to as web references. But
there is now a more generic Add Service Reference menu item with the advent of
the Windows Communication Foundation (WCF). It invokes the Add Service
Reference dialog, which you can see in Figure 2.11. In our example, the drop-
down feature of the Discover button has been used to look for Services in Solution.
Unfortunately, this dialog is another case of Microsoft of not understanding the
usage pattern properly. Though the dialog itself is resizable, the status response
message area is not, making it hard to read any errors generated. Luckily, if any
errors are thrown while Visual Studio 2010 attempts to access the service
Self-Instructional
Material 27
Toolbox information, it provides a hyperlink that opens the Add Service Reference Error
dialog. This generally gives you enough information to resolve the problem.
In the lower left-hand corner of Figure 2.11, there is an Advanced button.
The Service Reference Settings dialog enables you to customize which types are
NOTES
defined as part of the service reference. By default, all local system types are
assumed to match those being published by the service. If this is not the case, you
may want to adjust the values in the Data Type area of this dialog.
There is also an Add Web Reference button in the lower left-hand corner of
the Service Reference Settings dialog, which enables you to add more traditional
.NET Web service references. This might be important if you have some limitations
or are trying to support intersystem operability.

Fig. 2.11 Add Service Reference

Status Bar
The Status bar provides information about what is happening with Visual Studio at
the current time. When you work with VS, the Status bar changes in a context-
sensitive way to give you information specific to the task you are working on. For
example, the editor displays line, column, and other information pertaining to the
status of the editor.

Self-Instructional
28 Material
Toolbox
2.4 MANAGING VS WINDOWS

Window title bars consists of a set of three icons i.e. Window Position (down
arrow), Close (cross) and Maximize/Restore Down (window). In Figure 2.12, NOTES
which shows the Solution Explorer with these three icons (on its title bar at the
top-right corner).
The Window Position allows you to treat the window as Dock, Float, Dock
As Tabbed Document, Auto Hide, and Hide. You can expand a window to fill the
entire work area or allow the window to be resized and float freely around the
work area with the Maximize/Restore Down icon. In the docked position, the
Maximize/Restore Down icon becomes a pin that can be used to pin the window
open or allow it to slide shut. The Close icon allows you to close a window. The
following sections describe how to use these title icons to manipulate these windows
through expanding and collapsing, docking, floating, tabbing, and closing and
opening.

Fig. 2.12 Window title bar icons

Expanding and Collapsing Windows


Hovering over the Toolbox tab will expand the Toolbox and display a set of three
icons (in the title bar of the Toolbox window): Hide (pin), Window Position (down
arrow) and Close (cross).

Self-Instructional
Material 29
Toolbox

NOTES

Fig. 2.13 Expanded Toolbox

If you move the carat away from the Toolbox, the Toolbox will collapse
and turn back into a tab on the left side of the screen. For any collapsed window,
such as the Toolbox, you can expand that collapsed window and click the Hide
(pin) icon to pin the window, which will make the window layout similar to the
Solution Explorer. Figure 2.14 shows the pinned window; the pin in the Hide icon
(above the Auto Hide tooltip) is vertical and you no longer see the Toolbox tab in
the left margin.
Clicking the Hide icon on any expanded window will cause the window to
collapse and display as a tab, similar to the Toolbox. Another way to collapse a
window is by selecting the Auto Hide option on the Window Position (down
arrow) menu.
Docking Windows
The Dock option shows the window in an open docked position which is similar
to the Solution
Explorer. You can move a docked window to some position in the work
area. Select its title bar and drag the window out of its current position, in case, to
move a docked window.

Self-Instructional
30 Material
Toolbox

NOTES

Fig. 2.14 Pinned Toolbox

Fig. 2.15 Dragging a window for docking

As shown in Figure 2.15, there is a visual set of icons shown over the
workspace, representing the docking zones (where you can move the window
to). The shadow of the window will show the new location every time you drag a
window into a docking zone. While dropping the window into the docking zone
results that moving the window from its old docking zone into the new docking
zone.

Self-Instructional
Material 31
Toolbox Floating Windows
The Float option allows windows to appear anywhere in the VS IDE, where you
can move them at will. By selecting the floating window’s title bar, you move a
NOTES floating window and move the carat to the new location (where you want the
window to be). Otherwise, you can double-click on the title bar. Figure 2.16
shows the Toolbox floating over other windows.

Fig. 2.16 Floating a window

Tabbed Windows
An example of using the Dock As Tabbed Document option is the Start page. Any
window set as Dock As Tabbed Document will appear as a new tab in the work
area. For example, consider if the Toolbox is set as Dock As Tabbed Document
then it would become a tabbed document in the same group as the Start window
(as shown in Figure 2.17).
If you want to change a window from a tabbed document then select the
tab and drag the window ahead of the other documents, making it a floating window.

Fig. 2.17 Tabbed document windows


Self-Instructional
32 Material
Closing and Opening Windows Toolbox

Clicking the Close icon on a window title bar will close the window. Alternative
method to close the window is by selecting the Hide option from the Window
Position icon menu. Reopening a window depends on type of window it means, NOTES
Visual Studio or Project Item. If the window is from Visual Studio then you can
come back to the View menu and after that select the window you required to
open.

Check Your Progress


1. How you will add a component in the Toolbox?
2. What does a reference provide to the compiler?
3. What are the three icons of Window title bars?

2.5 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. To add a component to your Toolbox layout, right -click anywhere within


the group of components you want to add it to and select Choose Items.
2. A reference allows the compiler to resolve type, property, method names,
and field back to the assembly where they are defined.
3. Window title bars consists of a set of three icons i.e. Window Position
(down arrow), Close (cross) and Maximize/Restore Down (window).

2.6 SUMMARY

 Toolbox is like a tool window available with the help of View menu. The
Toolbox window contains all of the available components for the currently
active document being shown in the main workspace.
 Microsoft has offered developers true drag and drop placement of elements
during the design of both web and rich client applications.
 Visual Studio 2010 presents the available components in groups rather than
as one big mess of components. This default grouping enables you to more
easily locate the controls.
 To add a component to your Toolbox layout, right -click anywhere within
the group of components you want to add it to and select Choose Items.
 Toolbox items are in alphabetical order by default that enables you to locate
unfamiliar items.
 The Solution Explorer tool window (Ctrl+Alt+L) provides a convenient
visual representation of the solution, projects, and items.
Self-Instructional
Material 33
Toolbox  The toolbar across the top of the Solution Explorer enables you to customize
the way the contents of the window appear to you, as well as giving you
shortcuts to the different views for individual items.
 Visual Studio 2010 supports reusable components using the references for
NOTES
a project. If you enlarge out any project then you will analyse a number of
.NET Framework libraries such as System. Core and System that required
to be referenced by a project in order to be built.
 The Status bar provides information about what is happening with Visual
Studio at the current time.
 Window title bars consists of a set of three icons i.e. Window Position
(down arrow), Close (cross) and Maximize/Restore Down (window).
 The Dock option shows the window in an open docked position which is
similar to the Solution Explorer.
 The Float option allows windows to appear anywhere in the VS IDE, where
you can move them at will.

2.7 KEY WORDS

 Status Bar: It provides information about what is happening with Visual


Studio at the current time.
 Float Option: It allows windows to appear anywhere in the VS IDE, where
you can move them at will.

2.8 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer Questions


1. Discuss the addition of components in the toolbox.
2. What is the need of adding references to the Solution Explorer?
3. How you will add service references to Solution Explorer?
4. What does Status Bar provides?
5. Discuss the use of float, Tabbed and dock Windows.
Long Answer Questions
1. How you will arrange components in Toolbox?
2. What are the features of Solution Explorer?
3. Explain how you will add projects and items in the Solution Explorer.

Self-Instructional
34 Material
Toolbox
2.9 FURTHER READINGS

Bronson Gary and David Rosenthal. 2005. Introduction to Programming with


Visual Basic .NET, Burlington, Massachusetts: Jones & Bartlett Learning. NOTES
Liberty Jesse. 2003. Programming Visual Basic .NET. Sebastopol, California:
O’Reilly Media, Inc.
Mayo Joe. 2010. Ms Visual Studio 2010. Noida: Tata McGraw-Hill.

Self-Instructional
Material 35
Visual Studio Project
Types
UNIT 3 VISUAL STUDIO PROJECT
TYPES
NOTES
Structure
3.0 Introduction
3.1 Objectives
3.2 Getting Started with Visual Studio Project Types
3.3 Answers to Check Your Progress Questions
3.4 Summary
3.5 Key Words
3.6 Self Assessment Questions and Exercises
3.7 Further Readings

3.0 INTRODUCTION

In this unit, you will work with various types of projects of visual studio. Visual
studio 2010 provides various templates to develop code and files that are required
to start developing applications. It also provides various project types based on
languages such as C# and visual basic. It also lets you create your own project
types.

3.1 OBJECTIVES

After going through this unit, you will be able to:


 Check the various types of available projects
 Discuss about the various types of projects

3.2 GETTING STARTED WITH VISUAL STUDIO


PROJECT TYPES

Visual Studio 2010 includes a plethora of project types which make it easy to
form applications with templates. To check for the available projects, select File
 New  Project, as shown in Figure 3.1. It shows that you can create a new
Web site, open a wizard that creates a new project from existing files or by open
a file for editing. Figure 3.1 also shows the selecting a New Project with the help
of the File menu.

Self-Instructional
36 Material
Visual Studio Project
Types

NOTES

Fig. 3.1 Using file menu for selecting a new project

Figure 3.2 demonstrate how to select a new project window by selecting


File  New  Project. The New Project window displays that there are
different projects which are used to select from Web, Office, Cloud and Reporting,
including Windows, SharePoint, Silverlight, WCF, Test and Workflow. But some
of the project types don’t appear in Figure 3.2. But if you scroll down the templates
list in the New Project window, then you will see them. In our case, it displays the
appearance for C# projects, but there are also similar projects for other
programming languages including VB, C++ (pronounced as see-plus-plus) and
F# (pronounced as f-sharp).

Fig. 3.2 New project window


Self-Instructional
Material 37
Visual Studio Project Windows Projects
Types
Selecting Windows Projects will show you a list of project types which may be
created for desktop applications including Windows Forms, Windows Presentation
NOTES Foundation (WPF), and Console. The console applications are used for building
applications which don’t require graphical user interface (GUI) and are generally
used for creating utilities that administrators can write scripts with or for writing a
quick test for your program. The console applications are used while learning VB
and C# languages.
Other windows projects include Windows Services which are applications
that are always on and run as a service in the background without a GUI, Class
Libraries for holding reusable code often referred to as middleware, and Control
Libraries for holding graphical controls that can be dragged-and-dropped from
the Toolbox onto a visual designer within VS.
Web Projects
Web projects consists of ASP.NET, Web Services, Server Controls and Dynamic
Data. The web project like ASP.NET allows you to write an application which is
hosted by a Web server like internet Information Server (IIS) and runs in a Web
browser. A Server Control project allows you to build a library of GUI controls
and these GUI controls can be dragged-and-dropped onto the design surface of
a Web page in Visual Studio. Web Services which we can call from the internet
are reusable components. The Web Services is that which uses ubiquitous protocols
to enable code from any platform to call them, and enabling integration among
heterogeneous computing systems. A quick way to build a working website is
done with the help of dynamic data projects which is based on an existing database
schema.
Office Projects
The developers have been writing Visual Basic for Applications (VBA) programs
to automate Microsoft Office applications. An Office project allows you to
automate office applications with the help of .NET through different languages like
C#, Visual Basic. It also consists of supported office applications like, PowerPoint,
Excel, InfoPath, Word, Project Outlook and Visio.
Sharepoint Projects
SharePoint technology is used for building portal-style Web applications. It is
associated with managing workgroup collaboration and Office applications. In
order to create and run SharePoint projects, the computer you use to run VS will
need to be running one of Microsoft’s server platforms, such as Server 2008.
SharePoint does not run on Windows 7, Vista, or Windows XP.

Self-Instructional
38 Material
Database Projects Visual Studio Project
Types
Database projects includes a SQL Server project type that provides close
integration with SQL Server. It is used for building .NET code and runs inside of
SQL Server. For example, consider you can write functions and stored procedures NOTES
and in Visual Basic or C# or VB. This ensures to have the advantage of the .NET
Framework in your code. With a single mouse click, Visual Studio makes it easy
to deploy your code to SQL Server.

Check Your Progress


1. What are the steps to check for the available projects?
2. What constitute the web projects?

3.3 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. To check for the available projects, select File  New  Project.


2. Web projects consists of ASP.NET, Web services, server controls and
dynamic data.

3.4 SUMMARY

 Visual studio 2010 provides various templates to develop code and files
that are required to start developing applications.
 Visual Studio 2010 includes a plethora of project types which make it easy
to form applications with templates. To check for the available projects,
select File  New  Project.
 Selecting Windows Projects will show you a list of project types which
may be created for desktop applications including Windows Forms,
Windows Presentation Foundation (WPF), and Console.
 Web projects consists of ASP.NET, Web Services, Server Controls and
Dynamic Data. The web project like ASP.NET allows you to write an
application which is hosted by a Web server like internet Information Server
(IIS) and runs in a Web browser.
 SharePoint technology is used for building portal-style Web applications, it
is associated with managing workgroup collaboration and Office
applications.
 Database projects includes a SQL Server project type that provides close
integration with SQL Server. It is used for building .NET code and runs
inside of SQL Server.
Self-Instructional
Material 39
Visual Studio Project
Types 3.5 KEY WORDS

 SharePoint: It is a web-based collaborative platform that integrates


NOTES with Microsoft Office. It is primarily sold as a document management and
storage system, but the product is highly configurable and usage varies
substantially among organizations.
 Windows Communication Foundation (WCF): It is a platform for building
service-oriented applications. It can be used to send data as asynchronous
messages from one service endpoint to another.

3.6 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer Questions


1. What are the different types of web projects?
2. How you will check the available projects in visual studio?
Long Answer Questions
1. What are Windows projects in VS?
2. Write a note on the various types of project in VS.

3.7 FURTHER READINGS

Bronson Gary and David Rosenthal. 2005. Introduction to Programming with


Visual Basic .NET, Burlington, Massachusetts: Jones & Bartlett Learning.
Liberty Jesse. 2003. Programming Visual Basic .NET. Sebastopol, California:
O’Reilly Media, Inc.
Mayo Joe. 2010. Ms Visual Studio 2010. Noida: Tata McGraw-Hill.

Self-Instructional
40 Material
Basic Syntax
BLOCK - II
C# AND VB.NET

NOTES
UNIT 4 BASIC SYNTAX
Structure
4.0 Introduction
4.1 Objectives
4.2 Starting a Simple Project and Code Skeleton
4.2.1 The Main Method
4.2.2 The Program Class
4.2.3 First Program Namespace
4.2.4 An Overview of the Visual Studio Code Editor
4.2.5 Class and Member Locators
4.2.6 Bookmarks
4.3 Running Programs
4.3.1 Primitive Types
4.3.2 Expressions
4.3.3 Enums
4.3.4 Branching Statements
4.3.5 Loops
4.4 Answers to Check Your Progress Questions
4.5 Summary
4.6 Key Words
4.7 Self Assessment Questions and Exercises
4.8 Further Readings

4.0 INTRODUCTION

In this unit, you will learn about the program code skeleton, main method, VS
code editor and bookmarks. Code skeleton means the basic syntax/structure on
which the most programs are written. Main method is the entry and exit point of a
program whenever a program executes it starts with the main method. Bookmarks
allows you to navigate code quickly without manual navigation. You will also learn
about the primitive data types, expressions, branching statements and loops. Branching
statements are used to alter the flow of control of a program. Loops are required to
execute the same instruction multiple time based on the conditions.

4.1 OBJECTIVES

After going through this unit, you will be able to:


 Understand the code skeleton in C# and VB
 Understand the role of main method in the program
Self-Instructional
Material 41
Basic Syntax  Define program class and namespace in program
 Understand the need of bookmarks
 Discuss the primitive data types and expressions
NOTES  Explain the various types of branching statements and loops

4.2 STARTING A SIMPLE PROJECT AND CODE


SKELETON

You have learnt that a console application is very simple and allows you to read
and write text from and to the command prompt window. Figure 4.1 shows the
starting of a simple new project.

Fig. 4.1 New project window

To start a new project, first open Visual Studio and then select File  New
 Project. The new project window will open. Select Console Application as the
program type. After that set the program name to MyFirstProgram and specify
a location of your choice where the project will be stored. Additional features of
the New Project window consists of the ability to specify the .NET Framework
version, icon size options, a search capability, sorting options.
Figure 4.1 shows the version of .NET framework having the set of languages,
class libraries, runtime etc. it is the platform supported by the visual studio. Visual
studio allows multiple versions of the .NET Framework including different versions
2.0, 3.0, 3.5, and 4.0. Visual Studio will compile your code against the version
you choose. When you click the OK button, it will produce a Console application
project in the programming language (as shown in Figure 4.2).

Self-Instructional
42 Material
The Solution Basic Syntax

Figure 4.2 contains a solution and this is a container for multiple projects. Under
the solution is the FirstProgram project and the project items comes under this
project includes settings and files. NOTES

Fig. 4.2 The Solution Explorer: A Console Application

A project consists of various types of project items and each project items
into a project depend on the project type. For example, there are project items
that are part of a WPF application but wouldn’t be part of a console application.
Examining the Code Skeleton
You can see a file named Program.cs on running the New Project Wizard for a
Console application which consists of skeleton code (in editor). VS will create
skeleton code using built-in templates for most project types. This code can be
edited and removed. Example 4.1 shows the sample skeleton code.
Example 4.1 The Code Skeleton
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FirstProgram
{
class Program
{
Self-Instructional
Material 43
Basic Syntax static void Main(string[] args)
{
}
}
NOTES
}
VB
Module Module1
Sub Main()
End Sub
End
The skeleton code shows about basic structure of Visual Studio and new
Console application. It is the basic code to start writing your program. This program
doesn’t contains any special code of program but this program will in fact run and
then end itself. In C# code, the braces are used to define a block. Whereas the
VB code, consists of Sub and Module with corresponding End identifier to indicate
the boundaries of a block.
4.2.1 The Main Method
Main method is the entry point of the applications. Whenever the application is
started, it the main method which is invoked. The application may be console
application or window application. The keyword main is used to declare the main
function or method. The code skeleton shown in Example 4.1 shows the innermost
block is Static void main( string [] args) which is the main method for that
code. Similarly, sub main () is the main method in VB applications. It can
also be stated that Main is an area or place where the computer starts transferring
control to your program.
In C#, begin and end of the Main method is defined by curly braces.
Whereas in VB, the starting of Main is done with Sub and ended with End Sub. In
C#, the methods may return values, like text, numbers or other types of values
and the type of thing they can return is specified by you right before the method
name. Alternatively, In case of VB language, a Function returns a value but a Sub
does not.
The return type of the main method is void, when it is not returning any
value. The parameter passed to the method is args defined as array of strings. This
parameter holds all of the parameters passed to this program from the command
line. The static keyword is a modifier that says there will only be a single
instance of this method for the life of the program. The keyword public is
access modifiers which means the compiler can execute this from anywhere.
Visual Basic uses the term shared, which has the same meaning as static.
Modules are inherently shared. All module methods must be shared. Therefore,
the VB Main method is shared.
Self-Instructional
44 Material
4.2.2 The Program Class Basic Syntax

A class is like a blueprint of objects that defines the properties, field, events, methods
etc. it encapsulates the various variables of distinct data types, methods based on
your need. The code skeleton given below shows that class contains the main NOTES
method in it.
C#
class Program
{
// Main Method omitted for brevity

}
VB
Module Module1
‘ Main omitted for brevity
End Module
Visual Studio uses Module as the default object type for a new project. So
in case of VB, you can interchange Module with Class. The Program class consists
of Main method and other methods can be added to the Program class.
4.2.3 First Program Namespace
A namespace is used to make class names unique and unambiguous. The
namespaces are like adding a middle name and surname to your first name. A
namespace name precedes the class name, middle name and surname follow your
first or given name.
A namespace helps in organizing the code. It also helps you find things in
other programmers’ code, which helps to form libraries of code. Programmers
finds it easier to find what they need. We can say that the .NET platform has a vast
class library which is organized into namespaces and assemblies. The main .NET
namespace is System, which has multiple sub-namespaces. Namespaces are also
used to differentiate between classes which have the same name in different libraries.
The syntax given below illustrate the concept of namespace.
C#
Namespace FirstProgram
{
// Program class omitted for brevity
}
VB
Namespace FirstProgram
Public Class Customer
End Class
End Namespace
Self-Instructional
Material 45
Basic Syntax You can put multiple classes inside the namespace. A VB module must be
stated at the global level. It means that a namespace that you create can’t be
added to a namespace that you create.

NOTES 4.2.4 An Overview of the Visual Studio Code Editor


Figure 4.3 shows the Visual Studio Code Editor with the Console application
skeleton code from the Example 4.1.

Fig. 4.3 Visual studio code editor

4.2.5 Class and Member Locators


At the top of the editor, there are two drop-down lists i.e. class locator and member
locator which are used for navigating through the code. If you have multiple classes
in your file, you can use the class locator from the drop-down list on the left to
select the class you want to find.
However, there is Visual Studio wizards which spontaneously generate
code and place many classes in the same file. If you want to find a specific class
and study about what the automatically generated code is doing. In that case,
the class locator is very useful. On the top right, the member locator drop-down
list is there, which consists of other members and a list of methods for the class
selected in the class locator. Selecting a member bases the editor to move you
to the first line of that class member. Whenever you find yourself scrolling from
end to end in a large file, then the member locator will help to discover what
you’re looking quickly. The vertical bar on the left side of the editor is called the
indicator margin, where you’ll see icons for features such as bookmarks and
debug breakpoints.

Self-Instructional
46 Material
4.2.6 Bookmarks Basic Syntax

Figure 4.4 shows a bookmark on the line for the program class. When, you are
working with multiple locations or multiple documents inside the same document
then bookmarks allows you to navigate code quickly without manual navigation. NOTES
Table 4.1 lists the shortcut keys of Bookmark.
Table 4.1 Shortcut keys of Bookmark

KEY CODE MEANING

CTRL-B, T Toggle a bookmark on or off

CTRL-B, N Move to next bookmark

CTRL-B, P Move to previous bookmark


CTRL-B, C clear all bookmarks
CTRL-W, B Open the Bookmarks window

Fig. 4.4 Bookmark window

CTRL-W, B command is used to open the bookmark window as shown in


Figure 4.4. It allows you to manage bookmarks throughout your application. The
bookmark has the same toolbar which look like in Visual Studio when the editor
window is active. Inside the Bookmark list, there is an option through which you
can check to make a bookmark active or inactive.
In case, if the bookmark is inactive then the previous and next navigation
will not stop at the bookmark. By clicking the name twice, you can change the
name of the bookmark. File Location and Line Number shows you where the
bookmark is located.

Check Your Progress


1. Write a note on main method.
2. Define class.
3. What is the use of bookmarks?
Self-Instructional
Material 47
Basic Syntax
4.3 RUNNING PROGRAMS

The program can be run in Visual Studio with or without debugging. Debugging is
NOTES defined as the process of locating and removing errors in your code. If the program
is running with debugging, then the break points can be set easily. If the program is
not running with debugging, it will allows you to run the application and also avoiding
any breakpoints that may have been set.
To run the program without debugging, select Debug  Start and then
press CTRL-F5 which will run the Command Prompt window. The output “Hello’
will be printed.
To run the program with debugging, select Debug  Start Debugging and
then press F5. You can use a Console.ReadKey statement which is below
Console.WriteLine that will keep the window open till you press any key. The
code of the updated Main method is given below:
C#
static void Main(string[] args)
{
Console.WriteLine(“Hello from Visual Studio 2010!”);
Console.ReadKey();
}
VB
Sub Main()
Console.WriteLine(“Hello from Visual Studio 2010!”)
Console.ReadKey()
End Sub
After pressing the F5 Key, the output will be “Hello”.
4.3.1 Primitive Types
Primitive data types are the built-in data types which can be used to build other
data types called as non-primitive data types. Variables can hold values which can
be manipulated during the execution of a program. There are various types of
variables and type specifies specify about what kind of data the variable can have.
Table 4.2 shows the various primitive data types.
Table 4.2 Primitive types

VB C# .NET DESCRIPTION
Byte Byte Byte 8-bit unsigned integer
SByte Sbyte Sbyte 8-bit unsigned integer
Short Short Int 16 16-bit signed integer
Uint16 Ushort Uint16 16-bit unsigned integer
Integer Int Int32 32-bit signed integer
Self-Instructional
48 Material
Uint32 Unit Uint32 32-bit unsigned integer Basic Syntax
Long Long Int64 64-bit signed integer
Uint64 Ulong Uint64 64-bit unsigned integer
Single Flat Single 32-bit floating point
Double Double Double 64-bit floating point NOTES
Boolean Bool Boolean True or false
Char char Char 16-bit Unicode character
Decimal decimal Decimal 96-bit decimal
String string String String of Unicode characters

The code below shows how to declare a 32-bit signed integer in VB as well
as in C#.
C#
int age1;
Int32 age2;
VB
Dim age1 as Integer
Dim age2 as Int32
C# code uses int and VB uses Integer for a 32-bit signed integer as their
built-in type definitions. The .NET type is the same in both C# and VB languages.
4.3.2 Expressions
Expressions are grouping of operators, variables, referencing other class members.
For example, consider a mathematical expression as given below:
C#: int result = 2 + 4 * 5;
VB: Dim result As Int32 = 2 + 4 * 8
The expression 2 + 4 * 5 consists of the operators + (addition) and *
(multiplication). The output of the expression will be 22 because expressions use
standard algebraic precedence.
The order of operations can be modified using parentheses. For example:
C#: int result = (2 + 4) * 5;
VB: Dim result As Int32 = (2 + 4) * 8

Here because of parenthesis, the values of 2 and 4 are added, which gives
the value 6. This 6 is multiplied by 5 and the output will be 30.
Ternary and Immediate If Operators
VB immediate if operators and C# ternary operators allows you to test a condition
which will return a value subject on whether the condition is true or false. The
code given below shows how an immediate if operator and ternary operator
work.
Self-Instructional
Material 49
Basic Syntax C#
Int bankAccount = 0;
String accountString = bankAccount == 0 ? “checking” :
“savings”;
NOTES
VB
DIM accountString As String =
If(bakkAccount = 0, “checking”, “saving”)
Conditional statement shows that while running the program check if
bankAccount is equal to 0 or not. If the condition is true, then the first expression
will execute. While, if the condition is false, the second expression will execute.
4.3.3 Enums
An enum allows you to specify the set of values which are easy to read in code.
For example, the code below create an enum that lists of StudentInfo, like Passed,
failed, Average.
Open a new file by right-clicking the project to create an enum. Select
Add  New Item  Code File and then call the file StudentInfo.cs (or
Studentinfo.vb).
C#
Public enum StudentInfo
{
Passed,
Failed,
Average
}
VB
Enum StudentInfo
Passed
Failed
Average
End Enum
C#
StudentInfo Details = StudentInfo.Passed;
Sting message =
Details = = StudentInfo.Passed ?
“Student Info is Passed” :
“Student Info is Failed” :
VB
Dim Details As StudentInfo = StudentInfo.Passed
Dim message =
Self-Instructional
50 Material
IIF (Details = StudentInfo.Passed, Basic Syntax
“Student Info is Passed” ,
“Student Info is Failed” )
4.3.4 Branching Statements NOTES
A branching statement allows the flow of execution to jump on a different part of
the code. For example, consider the case of marks of the student to check whether
student is passed or failed. To check if marks are greater than 40 the student is
passed or if marks are less than 40, it means the student is failed. So there are two
primary types of branching statements used which are: if and switch (Select Case
in VB).
Expressions
If statements allow you if the specified condition values to true at runtime then it
perform an action. Consider an example, prints a statement to the console if the
contents of variable result is greater than 25.
Example 4.2 Prints a statement to the console if value is greater than 25.
C#
if (result > 25)
{
Console.WriteLine(“result is > 25”);
}
VB
If result > 25 Then
Console.WriteLine(“Result is > 25”)
End If
In C#, the curly braces are mandatory when you want two or more
statements to run, but sometimes curly braces are optional if there is only have one
statement to run. So here the condition must estimate to either a Boolean true or
false. When the if condition is false then the else clause will executes.
Syntax:

Consider an example which is a part of If statement. The example, shows


the usage of else statement.

Self-Instructional
Material 51
Basic Syntax Example 4.3 To check whether the result is greater than or less than equal to 25
using if-else statement.
C#
NOTES if (result > 25)
{
Console.WriteLine(“result is > 25”);
}
else
{
Console.WriteLine(“result is <= 25”);
}
VB
If result > 25 Then
Console.WriteLine(“Result is > 25”)
Else
Console.WriteLine(“Result is <= 25”)
End If
Switch/Select Statements
A switch statement is a type of multi-way branch control mechanism used to allow
the value of a variable or expression to change the control flow of program
execution. Consider the following example depending on the value of a name
variable that will perform different actions.
Example 4.4 Illustrating the concept of switch/select statements.
C#
var name = “Amit”;
switch (name)
{
case “Priya”:
Console.WriteLine(“Name is Priya”);
break;
case “”:
Console.WriteLine(“Name is Amit”);
break;
default:
Console.WriteLine(“Unknown Name”);
break;
}
VB
Dim name As String = “Amit”
Select Case name
Self-Instructional
52 Material
Case “Priya” Basic Syntax
Console.WriteLine(“Name is Priya”)
Case “Amit”
Console.WriteLine(“Name is Amit”)
NOTES
Case Else
Console.WriteLine(“Unknown name”)
End Select
In case of C#, there is the keyword switch with the value being evaluated
in parentheses. When the case statement matches the switch value then the code
will be executed. When there isn’t a match then the default case will be executed.
The switch snippet is given below.

The program stops executing the switch statement when the compiler finds
a break statement.
Switch Statement Snippets
There are two states for switch statement snippets: a minimal switch statement and
an expanded switch with enum cases. In case of minimal switch statement, start by
typing sw and then press TAB. When you press ENTER, then the snippet will
expand to a switch statement as shown below:

switch (name)
{
default:
break;
}

Same in case of VB, which works similar to the C# switch. For these type
of statements, first type Se and then press TAB as shown below.

Self-Instructional
Material 53
Basic Syntax 4.3.5 Loops
Quite often we have to perform the same operation a number of times. We need
to repeat the same operation with one or more of the values changed, which is
NOTES known as loop or iteration. There are different types of loops like while, do,
for, for each.
for Loop
It allow you to specify the number of times to execute a block of statements.
Consider the following example.
Example 4.5 Usage of for Loop
C#
for (int i = 0; i < 3; i++)
{
Console.WriteLine(“i = “ + i);
}
Here, i is a variable of type integer, the loop will continue to execute given
that i is less than 3, and i will be incremented by one every time after the loop
executes. The condition, i < 3, is calculated before the loop executes, and if the
condition evaluates to false then the loop will not execute.
VB
For i As Integer = 0 To 2
Console.WriteLine(“i = “ & i)
Next
Here, For loop initializes i as an integer and recapping three times from
0 to 2.
foreach Loops
This loop is used to iterate over the elements of the collection that may be an array
or a list. It executes for each element present in the array. It is necessary to enclose
the statements of foreach loop in curly braces {}. The following example
illustrates the concept of foreach loop.
Example 4.6 foreach loop on an array of strings.
C#
string[] people = { “Amit”, “Priya”, “John” };
foreach (var person in people)
{
Console.WriteLine(person);
}

Self-Instructional
54 Material
VB Basic Syntax

Dim people = {“Amit”, “Priya”, “John” }


For Each person As String In people
Console.WriteLine(person)
NOTES
Next
Here, people is an array of strings that consists of three specific strings of
text. Only three times the block of the loop will execute, once for each item in the
array.
While Loops
In C#, a while loop will permits a block of code to execute as long as specified
condition is true. Consider the code given below that does a countdown of numbers.
C#
int count = 3;
while (count > 0)
{
Console.WriteLine(“count: “ + count);
count—;
}
VB
Dim count As Integer = 3
While count > 0
Console.WriteLine(“count: “ & count)
count -= 1
End While
The while loop executes given that count is greater than 0. Here in this
example, count have the value 3 and so it will be decrement by one each time with
the help of the loop.
To generate a while loop snippet, first type wh and then press TAB key.
Following screenshots shows the C# snippet and VB snippet.
while loop snippet template in C#

Self-Instructional
Material 55
Basic Syntax while loop snippet template in VB

NOTES

do Loops
If you want the code in the loop to execute at least one time then use a do loop.
The code below shows the use of do loop.
Example 4.7 The usage of Do Loop (A simple menu that obtains user input).
string response = “”;
do
{
Console.Write(“Press ‘Q’ and Enter to break: “);
response = Console.ReadLine();
} while (response != “Q”);
While using the do loop snippet, first type do and then press TAB key.
Following screenshots shows the C# snippet and VB snippet.
C#

VB

Check Your Progress


4. What are primitive data types?
5. What is a branching statement?
Self-Instructional
56 Material
Basic Syntax
4.4 ANSWERS TO CHECK YOUR PROGRESS
QUESTIONS

1. Main method is the entry point of the applications. Whenever the application NOTES
is started, it the main method which is invoked. The application may be
console application or window application. The keyword main is used to
declare the main function or method.
2. A class is like a blueprint of objects that defines the properties, field, events,
methods etc. it encapsulates the various variables of distinct data types,
methods based on your need.
3. Bookmarks allows you to navigate code quickly without manual navigation.
4. Primitive data types are the built-in data types which can be used to build
other data types called as non-primitive data types.
5. A branching statement allows the flow of execution to jump on a different
part of the code.

4.5 SUMMARY

 VS will create skeleton code using built-in templates for most project types.
This code can be edited and removed.
 The skeleton code shows about basic structure of Visual Studio and new
Console application. It is the basic code to start writing your program. This
program doesn’t contains any special code of program but this program
will in fact run and then end itself.
 Main method is the entry point of the applications. Whenever the application
is started, it the main method which is invoked. The application may be
console application or window application. The keyword main is used to
declare the main function or method.
 A class is like a blueprint of objects that defines the properties, field, events,
methods etc. it encapsulates the various variables of distinct data types,
methods based on your need.
 A namespace is used to make class names unique and unambiguous. The
namespaces are like adding a middle name and surname to your first name.
A namespace name precedes the class name, middle name and surname
follow your first or given name.
 When, you are working with multiple locations or multiple documents inside
the same document then bookmarks allows you to navigate code quickly
without manual navigation.
 The program can be run in Visual Studio with or without debugging.
Debugging is defined as the process of locating and removing errors in your
Self-Instructional
Material 57
Basic Syntax code. If the program is running with debugging, then the break points can
be set easily. If the program is not running with debugging, it will allows you
to run the application and also avoiding any breakpoints that may have
been set.
NOTES
 Primitive data types are the built-in data types which can be used to build
other data types called as non-primitive data types.
 An enum allows you to specify the set of values which are easy to read in
code.
 A branching statement allows the flow of execution to jump on a different
part of the code.
 A switch statement is a type of multi-way branch control mechanism used
to allow the value of a variable or expression to change the control flow of
program execution.
 Quite often we have to perform the same operation a number of times. We
need to repeat the same operation with one or more of the values changed,
which is known as loop or iteration.

4.6 KEY WORDS

 Operators: The symbols which represent various computations (such as


addition, subtraction, etc.) performed on various data-items.
 Expression: Formed by a combination of variables, constants and
operators that represents a computation.
 Statement: An instruction given to the computer to perform a specific action.

4.7 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer Questions


1. What is namespace?
2. Write the syntax for creating the namespace.
3. What is an expression?
4. Write a note on enum.
Long Answer Questions
1. Write and explain the code skeleton in C# and VB.
2. What is the significance of namespace? Write the syntax for creating a
namespace.
Self-Instructional
58 Material
3. What are the different primitive data types? Basic Syntax

4. Write the syntax for creating the enum.


5. Explain the different types of branching statements and loops along with
their syntax. NOTES

4.8 FURTHER READINGS

Bronson Gary and David Rosenthal. 2005. Introduction to Programming with


Visual Basic .NET, Burlington, Massachusetts: Jones & Bartlett Learning.
Liberty Jesse. 2003. Programming Visual Basic .NET. Sebastopol, California:
O’Reilly Media, Inc.
Mayo Joe. 2010. Ms Visual Studio 2010. Noida: Tata McGraw-Hill.

Self-Instructional
Material 59
Creating Classes

UNIT 5 CREATING CLASSES


NOTES Structure
5.0 Introduction
5.1 Objectives
5.2 Classes
5.3 Class Inheritance
5.4 Class Snippet and Writing Methods
5.4.1 Parameters Passing and Returning Values
5.5 Answers to Check Your Progress Questions
5.6 Summary
5.7 Key Words
5.8 Self Assessment Questions and Exercises
5.9 Further Readings

5.0 INTRODUCTION

In this unit, you will learn about the classes, inheritance and methods. A class is a
user-defined data type that binds data and the functions/methods that operate on
the data together in a single unit. Like other user-defined data types, it also needs
to be defined before using its objects in the program. A class serves as a template
that provides a layout common to all of its instances, known as objects. That is, a
class is only a logical abstraction that specifies what data and functions its objects
will have, whereas objects are the physical entities through which those data and
functions can be used in a program. Inheritance is the most important concept of
object-oriented programming that provides the opportunity to reuse the code. A
class inherits the methods and properties of other class. The class that inherits the
other class is derived class while the class from which it is inherited is called as
base class.

5.1 OBJECTIVES

After going through this unit, you will be able to:


 Define and create classes
 Understand the significance of inheritance
 Create and use the class snippet
 Write methods
 Declare and pass parameters to methods and handle the return value

Self-Instructional
60 Material
Creating Classes
5.2 CLASSES

A class definition starts with the keyword class followed by the class name; and
the class body enclosed by a pair of curly braces. With the help of classes, you NOTES
can also create your own types which you can instantiate and create objects with.
Class Syntax
To generate a new custom class definition, right-click the project, then select Add
 Class. Set name of the class as Student as shown in Example 5.1.
Example 5.1 Creating a Student class
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FirstProgram
{
public class Student
{
public string FirstName;
}
}
VB
Public Class Student
Public Dim FirstName As String
End Class
Here, the class have a field i.e. FirstName. A field is a variable in a class
that holds information which is specific to that class.
Consider another example which tells about how to instantiate an object of
type Student. Here the code is inside the main method.
Example 5.2 Code using the Student class
C#
Student stu = new Student();
stu.FirstName = “Amit”;
VB
Dim stu As New Student
stu.FirstName = “Amit”
Here, stu is a variable of type Student. The new Student () (in C#) or new
Student (in VB) clause creates a new instance of Student and this new instance is
Self-Instructional
Material 61
Creating Classes being allocated to stu. The FirstName field of that particular instance of Student is
allocated a string value of “Amit”.
Example 5.3 write a program in C# that creates a class Box having parameter
length, breadth and height and print the volume of the box.
NOTES
C#
using System;
namespace BoxApplication {
class Box {
public double length; // Length of a box
public double breadth; // Breadth of a box
public double height; // Height of a box
}
class Boxtester {
static void Main(string[] args) {
Box Box1 = new Box(); // Declare Box1 of type
Box
Box Box2 = new Box(); // Declare Box2 of type
Box
double volume = 0.0; // Store the volume of a
box here

// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;

// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;

// volume of box 1
volume = Box1.height * Box1.length *
Box1.breadth;
Console.WriteLine(“Volume of Box1 : {0}”,
volume);

// volume of box 2
volume = Box2.height * Box2.length *
Box2.breadth;
Console.WriteLine(“Volume of Box2 : {0}”, volume);

Self-Instructional
62 Material
Console.ReadKey(); Creating Classes
}
}
}
NOTES
VB
Module mybox
Class Box
Public length As Double ‘ Length of a box
Public breadth As Double ‘ Breadth of a box
Public height As Double ‘ Height of a box
End Class
Sub Main()
Dim Box1 As Box = New Box() ‘ Declare Box1 of
type Box
Dim Box2 As Box = New Box() ‘ Declare Box2 of
type Box
Dim volume As Double = 0.0 ‘ Store the volume
of a box here

‘ box 1 specification
Box1.height = 5.0
Box1.length = 6.0
Box1.breadth = 7.0

‘ box 2 specification
Box2.height = 10.0
Box2.length = 12.0
Box2.breadth = 13.0

‘volume of box 1
volume = Box1.height * Box1.length * Box1.breadth
Console.WriteLine(“Volume of Box1 : {0}”, volume)

‘volume of box 2
volume = Box2.height * Box2.length * Box2.breadth
Console.WriteLine(“Volume of Box2 : {0}”, volume)
Console.ReadKey()
End Sub
End Module

Self-Instructional
Material 63
Creating Classes Output: when the code executes, the result will be as
follows:
Volume of Box1 : 210
Volume of Box2 : 1560
NOTES
5.3 CLASS INHERITANCE

Inheritance facilitates a class to acquire the properties and functionality of the


existing class. The new class depicts the acquired properties and behaviour of the
existing class as well as its own unique properties and behaviour. Inheritance allows
code reusability. This implies that it facilitates classes to reuse existing code. The
new class acquires members of the old class that are already tested and debugged.
Hence, inheritance saves time and also increases reliability. When one class can
reuse the features of another class that is known as inheritance. For example,
consider a child class can be inherited from a parent class. The following example
will create a Geniusstudent class that derives from the Student class. To create this
class, first right-click the project and then select Add àClass. Allocate the name
the class as Geniusstudent. Example 5.4 shows the new class and modifications
for implementing inheritance.
Example 5.4 Genuisstudent inheriting the student class.
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FirstProgram
{
public class Cashier : Student
{
}
}
VB
Public Class Geniusstudent
Inherits Student
End Class
The C# inheritance relationship is indicated by the colon after the Student
identifier which is followed by the class being derived from i.e. Student. Whereas
in case of VB, on a new line, there is a keyword inherits which is followed by the
class being derived from.

Self-Instructional
64 Material
Example 5.5 Code using Inheritance Creating Classes

C#
Geniusstudent gn = new Geniusstudent();
gn.FirstName = “John”; NOTES
VB
Dim gn As New Geniusstudent
gn.FirstName = “John”
Geniusstudent does not have a field FirstName. Here, Geniusstudent is a
specific kind of Student. You can add a new field to new Geniusstudent class. An
instance of the Student class would not be capable to contain this information.

Check Your Progress


1. Define class.
2. How you will generate a new custom class definition?
3. Define inheritance.

5.4 CLASS SNIPPET AND WRITING METHODS

Using class snippet you can create a new class file by right-clicking the project
and then select Add  New Item  Code File. Write the name of the file as
Student. You can also add the class snippet by type cl and then press TAB.

Fig. 5.1 C# class snippet template

To create a class snippet, you have to type in the class name and then press
Enter.
Writing Methods
Methods are the blocks of code referred by the name that can be invoked anywhere
in the program simply by its name. Methods are also known as procedures,
functions and subroutines. A method consists of one or more statements. The
main reason to create methods includes the ability to modularize your code or
group a common operation, isolate complex operations in one place which that
can be reused in multiple places.
Self-Instructional
Material 65
Creating Classes Example 5.6 Declaring and using a Method
C#
using System;
NOTES using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FirstProgram
{
class Program
{

static void Main(string[] args)


{
MessageDisplay msgDspy = new MessageDisplay();
msgDspy.DisplayMessageInstance();
}
}
C#: (MessageDisplay.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FirstProgram
{
class MessagePrinter
{
public static void DisplayMessageStatic()
{
Console.WriteLine(“This is a static method.”);
}
public void DisplayMessageInstance()
{
Console.WriteLine(“This is an instance method.”);
}
}
}
VB
Module Module1
Sub Main()
MessageDisplay.DisplayMessageShared()
Self-Instructional
66 Material
Dim msgDspy As New MessageDisplay() Creating Classes
msgDisplay.DisplayMessageInstance()
End Sub
End Module
NOTES
VB (MessageDisplay.vb)
Public Class MessageDisplay
Public Shared Sub DisplayMessageShared()
Console.WriteLine(“This ia a shared method.”)
End Sub
Public Sub DisplayMessageInstance()
Console.WriteLine(“This is an instance method.”)
End Sub
End Class
There are two different types of methods, instance and static. Shared
methods are similar as static in case of VB. DisplayMessageStatic is the static
method having a public access modifier which means that any other code by using
the containing class, MessageDisplay will be capable to use the method.
If you didn’t include the public access modifier, the method would be private
by default and only the code residing within the MessageDisplay class would be
able to use that method. DisplayMessageStatic has a keyword void. It means that
this method does not return a value.
Within the method block, there is Console.WriteLine statement. The
statement below shows how DisplayMessageStatic (in VB) is called (repeats
from Example 5.6).
C#
Program.DisplayMessageStatic();
VB
MessageDisplay.DisplayMessageShared()
5.4.1 Parameters Passing and Returning Values
You have to pass parameters when a method with parameters is called. Following
are the three ways of passing parameters to a method.
1. Value parameters: In this case the method copies the actual value of an
argument into the formal parameter of the function. The changes made to
the parameter in a function have no effect on the argument.
2. Reference parameters: In this case the method copies the reference to
the memory location of an argument into the formal parameter. The changes
made in the parameter affects the actual arguments.
3. Value parameters: This method helps in returning more than one value.

Self-Instructional
Material 67
Creating Classes Example 5.7: Write a program in which the values are passed to method by value
for swapping.
using System;
namespace CalculatorApplication {
NOTES
class NumberManipulator {
public void swap(int x, int y) {
int temp;

temp = x; /* save the value of x */


x = y; /* put y into x */
y = temp; /* put temp into y */
}
static void Main(string[] args) {
NumberManipulator n = new NumberManipulator();

/* local variable definition */


int a = 100;
int b = 200;

Console.WriteLine(“Before swap, value of a : {0}”, a);


Console.WriteLine(“Before swap, value of b : {0}”, b);

/* calling a function to swap the values */


n.swap(a, b);

Console.WriteLine(“After swap, value of a : {0}”, a);


Console.WriteLine(“After swap, value of b : {0}”, b);

Console.ReadLine();
}
}
}

Output:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200

Self-Instructional
68 Material
The output shows that there is no change in the values but they have changed Creating Classes

inside the function.


A reference parameter holds a reference to a memory location of a variable.
A new storage location is not created for these parameters whenever you pass the
NOTES
parameter by reference. They represent the same memory location as the actual
parameters that are supplied to the method. ref keyword is used to declare the
reference parameters.
Example 5.8: Write a program in which the values are passed to method by
reference for swapping.
using System;
namespace CalculatorApplication {
class NumberManipulator {
public void swap(ref int x, ref int y) {
int temp;

temp = x; /* save the value of x */


x = y; /* put y into x */
y = temp; /* put temp into y */
}
static void Main(string[] args) {
NumberManipulator n = new NumberManipulator();

/* local variable definition */


int a = 100;
int b = 200;

Console.WriteLine(“Before swap, value of a : {0}”, a);


Console.WriteLine(“Before swap, value of b : {0}”, b);

/* calling a function to swap the values */


n.swap(ref a, ref b);

Console.WriteLine(“After swap, value of a : {0}”, a);


Console.WriteLine(“After swap, value of b : {0}”, b);

Console.ReadLine();
}
}
}

Self-Instructional
Material 69
Creating Classes Output:
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
NOTES
After swap, value of b : 100
Here, values have changed inside the swap function and change is reflected
in the main function.
Only one value from a function can be returned using a return statement.
You can return two values from a function using output parameters. Output
parameters are similar to reference parameters, except that they transfer data out
of the method rather than into it. Consider the following example that returns the
values from the function.
Example 5.9: Function returning the values.
using System;
namespace CalculatorApplication {
class NumberManipulator {
public void getValue(out int x ) {
int temp = 5;
x = temp;
}
static void Main(string[] args) {
NumberManipulator n = new NumberManipulator();

/* local variable definition */


int a = 100;

Console.WriteLine(“Before method call, value of a :


{0}”, a);

/* calling a function to get the value */


n.getValue(out a);

Console.WriteLine(“After method call, value of a :


{0}”, a);
Console.ReadLine();
}
}
}

Self-Instructional
70 Material
Output: Creating Classes

Before method call, value of a : 100


After method call, value of a : 5
The variable passed for the output parameter need not be assigned a value. NOTES
Output parameters are useful when you need to return values from a method
through the parameters without assigning an initial value to the parameter.
Function Returning Value in VB
In VB, a function can return a value in two ways which are given below.
 By using the return statement
 By assigning the value to the function name
Example 5.10: FindMax function returning the maximum value.
Module myfunctions
Function FindMax(ByVal num1 As Integer, ByVal num2 As
Integer) As Integer
‘ local variable declaration */
Dim result As Integer

If (num1 > num2) Then


result = num1
Else
result = num2
End If
FindMax = result
End Function
Sub Main()
Dim a As Integer = 100
Dim b As Integer = 200
Dim res As Integer

res = FindMax(a, b)
Console.WriteLine(“Max value is : {0}”, res)
Console.ReadLine()
End Sub
End Module
Output:
Max value is : 200

Self-Instructional
Material 71
Creating Classes Param Arrays
You are not always known to the number of arguments passed as parameter at the
time of declaring a function or sub-procedure. In that case param arrays are useful.
NOTES Example 5.11: To demonstrates the concept of param arrays.
Module myparamfunc
Function AddElements(ParamArray arr As Integer()) As
Integer
Dim sum As Integer = 0
Dim i As Integer = 0

For Each i In arr


sum += i
Next i
Return sum
End Function
Sub Main()
Dim sum As Integer
sum = AddElements(512, 720, 250, 567, 889)
Console.WriteLine(“The sum is: {0}”, sum)
Console.ReadLine()
End Sub
End Module
Output:
The sum is: 2938
Passing Arrays as Function Arguments
An array can be passed as a function argument in VB.Net.
Example 5.12: An array is passed as function argument.
Module arrayParameter
Function getAverage(ByVal arr As Integer(), ByVal size
As Integer) As Double
‘local variables
Dim i As Integer
Dim avg As Double
Dim sum As Integer = 0

For i = 0 To size - 1
sum += arr(i)
Next i
avg = sum / size
Self-Instructional
72 Material
Return avg Creating Classes
End Function
Sub Main()
‘ an int array with 5 elements ‘
NOTES
Dim balance As Integer() = {1000, 2, 3, 17, 50}
Dim avg As Double
‘pass pointer to the array as an argument
avg = getAverage(balance, 5)
‘ output the returned value ‘
Console.WriteLine(“Average value is: {0} “, avg)
Console.ReadLine()
End Sub
End Module
Output:
Average value is: 214.4
Subs
Sub procedures are procedures that do not return any value. The Sub statement
is used to declare the name, parameter and the body of a sub procedure.
Passing Parameters by Value
By default the parameters is passed by value. In this case new storage location is
created for each formal parameter. The values of actual arguments are copied into
them. The changes to the formal parameters does not affect the actual arguments.
The ByVal keyword is used to declare the parameters by value.
Example 5.13: Passing parameters by value.
Module paramByval
Sub swap(ByVal x As Integer, ByVal y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()
' local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '

Self-Instructional
Material 73
Creating Classes swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
NOTES
End Sub
End Module

Output:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
Passing Parameters by Reference
The ByRef keyword is used to declare the parameters by reference.
Example 5.14: Passing parameters by reference.
Module paramByref
Sub swap(ByRef x As Integer, ByRef y As Integer)
Dim temp As Integer
temp = x ‘ save the value of x
x = y ‘ put y into x
y = temp ‘put temp into y
End Sub
Sub Main()
‘ local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Console.WriteLine(“Before swap, value of a : {0}”,
a)
Console.WriteLine(“Before swap, value of b : {0}”,
b)
‘ calling a function to swap the values ‘
swap(a, b)
Console.WriteLine(“After swap, value of a : {0}”,
a)
Console.WriteLine(“After swap, value of b : {0}”,
b)
Console.ReadLine()
End Sub
End Module

Self-Instructional
74 Material
Output: Creating Classes

Before swap, value of a : 100


Before swap, value of b : 200
After swap, value of a : 200
NOTES
After swap, value of b : 100

Check Your Progress


4. What is a method?
5. What happened when the values are passed by value to a method?

5.5 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. A class is a user-defined data type that binds data and the functions/methods
that operate on the data together in a single unit. Like other user-defined
data types, it also needs to be defined before using its objects in the program.
2. To generate a new custom class definition, right-click the project, then select
Add  Class.
3. Inheritance facilitates a class to acquire the properties and functionality of
the existing class. The new class depicts the acquired properties and
behaviour of the existing class as well as its own unique properties and
behaviour. Inheritance allows code reusability.
4. Methods are the blocks of code referred by the name that can be invoked
anywhere in the program simply by its name. Methods are also known as
procedures, functions and subroutines.
5. When the parameters are passed by value the method copies the actual
value of an argument into the formal parameter of the function. The changes
made to the parameter in a function have no effect on the argument.

5.6 SUMMARY

 A class definition starts with the keyword class followed by the class name;
and the class body enclosed by a pair of curly braces.
 To generate a new custom class definition, right-click the project, then select
Add  Class.
 Inheritance facilitates a class to acquire the properties and functionality of
the existing class. The new class depicts the acquired properties and

Self-Instructional
Material 75
Creating Classes behaviour of the existing class as well as its own unique properties and
behaviour. Inheritance allows code reusability.
 Using class snippet you can create a new class file by right-clicking the
project and then select Add  New Item  Code File.
NOTES
 Methods are the blocks of code referred by the name that can be invoked
anywhere in the program simply by its name. Methods are also known as
procedures, functions and subroutines.
 A reference parameter holds a reference to a memory location of a variable.
A new storage location is not created for these parameters whenever you
pass the parameter by reference. They represent the same memory location
as the actual parameters that are supplied to the method.
 Only one value from a function can be returned using a return statement.
You can return two values from a function using output parameters. Output
parameters are similar to reference parameters, except that they transfer
data out of the method rather than into it.

5.7 KEY WORDS

 Class: a user-defined data type that binds properties and methods that
operate on the data together in a single unit.
 Inheritance: A process of deriving a new class from an already existing
class in such a way that the new class inherits all the members of the already
existing class.

5.8 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer Questions


1. Write the syntax for creating a class.
2. Discuss how you will add the class snippet.
3. Write the syntax for declaring the method.
Long Answer Questions
1. Define a class to represent a bank account of 10 customers. The class
contains four data members’ name of the depositor, account number, type
of account (S for savings and C for current), and balance amount. In addition,
the class contains member functions to perform the following tasks:
(i) To initialise data members
(ii) To deposit money
Self-Instructional
76 Material
(iii) To withdraw money after checking the balance (minimum balance is Creating Classes

1000)
(iv) To display the data members
2. Explain how inheritance facilitates code reusability. NOTES
3. Explain the various ways of passing the values to method with the help of
suitable programs.

5.9 FURTHER READINGS

Bronson Gary and David Rosenthal. 2005. Introduction to Programming with


Visual Basic .NET, Burlington, Massachusetts: Jones & Bartlett Learning.
Liberty Jesse. 2003. Programming Visual Basic .NET. Sebastopol, California:
O’Reilly Media, Inc.
Mayo Joe. 2010. Ms Visual Studio 2010. Noida: Tata McGraw-Hill.

Self-Instructional
Material 77
Method Snippets

UNIT 6 METHOD SNIPPETS


NOTES Structure
6.0 Introduction
6.1 Objectives
6.2 Getting Started with Method Snippets
6.2.1 The Property Snippet
6.3 Answers to Check Your Progress Questions
6.4 Summary
6.5 Key Words
6.6 Self Assessment Questions and Exercises
6.7 Further Readings

6.0 INTRODUCTION

You have already learnt that the code snippets are the readymade code snippets
that you can quickly insert in your code. In this unit, you will learn about the
method snippets, fields and properties. Method snippets are not available in C#
but VB provides snippet template. You will also learn how to use property snippet.

6.1 OBJECTIVES

After going through this unit, you will be able to:


 Use method snippet
 Define fields and properties
 Shows the property snippet

6.2 GETTING STARTED WITH METHOD


SNIPPETS

C# doesn’t have snippets for writing methods whereas VB have snippets. VB


function snippet template is given below.

Self-Instructional
78 Material
Fields and properties Method Snippets

Properties are named members of classes, structures, and interfaces. Member


variables or methods in a class or structures are called Fields. Properties are an
extension of fields and are accessed using the same syntax. They NOTES
use accessors through which the values of the private fields can be read, written
or manipulated.
Properties do not name the storage locations. Instead, they have accessors
that read, write, or compute their values. For example, let us have a class named
Student, with private fields for age, name, and code. We cannot directly access
these fields from outside the class scope, but we can have properties for accessing
these private fields.
Accessors
The accessor of a property contains the executable statements that helps in getting
(reading or computing) or setting (writing) the property. The accessor declarations
can contain a get accessor, a set accessor, or both. For example:
// Declare a Code property of type string:
public string Code {
get {
return code;
}
set {
code = value;
}
}

// Declare a Name property of type string:


public string Name {
get {
return name;
}
set {
name = value;
}
}

// Declare a Age property of type int:


public int Age {
get {
return age;

Self-Instructional
Material 79
Method Snippets }
set {
age = value;
}
NOTES
}
The following example code demonstrates use of properties.
using System;
namespace tutorialspoint {
class Student {
private string code = “N.A”;
private string name = “not known”;
private int age = 0;

// Declare a Code property of type string:


public string Code {
get {
return code;
}
set {
code = value;
}
}

// Declare a Name property of type string:


public string Name {
get {
return name;
}
set {
name = value;
}
}

// Declare a Age property of type int:


public int Age {
get {
return age;
}
set {
age = value;
Self-Instructional
80 Material
} Method Snippets
}
public override string ToString() {
return “Code = “ + Code +”, Name = “ + Name + “,
Age = “ + Age; NOTES
}
}

class ExampleDemo {
public static void Main() {

// Create a new Student object:


Student s = new Student();

// Setting code, name and the age of the student


s.Code = “001”;
s.Name = “Zara”;
s.Age = 9;
Console.WriteLine(“Student Info: {0}”, s);

//let us increase age


s.Age += 1;
Console.WriteLine(“Student Info: {0}”, s);
Console.ReadKey();
}
}
}
When tshe above code is compiled and executed, it produces the following output:
Student Info: Code = 001, Name = Zara, Age = 9
Student Info: Code = 001, Name = Zara, Age = 10
Abstract Properties
An abstract class may have an abstract property, which should be implemented in
the derived class. The following program code illustrates the concept of abstract
class.
using System;

namespace tutorialspoint {
public abstract class Person {
public abstract string Name {

Self-Instructional
Material 81
Method Snippets get;
set;
}
public abstract int Age {
NOTES
get;
set;
}
}
class Student : Person {
private string code = “N.A”;
private string name = “N.A”;
private int age = 0;

// Declare a Code property of type string:


public string Code {
get {
return code;
}
set {
code = value;
}
}

// Declare a Name property of type string:


public override string Name {
get {
return name;
}
set {
name = value;
}
}

// Declare a Age property of type int:


public override int Age {
get {
return age;
}
set {
age = value;
Self-Instructional
82 Material
} Method Snippets
}
public override string ToString() {
return “Code = “ + Code +”, Name = “ + Name + “,
Age = “ + Age; NOTES
}
}

class ExampleDemo {
public static void Main() {
// Create a new Student object:
Student s = new Student();

// Setting code, name and the age of the student


s.Code = “001”;
s.Name = “Zara”;
s.Age = 9;
Console.WriteLine(“Student Info:- {0}”, s);

//let us increase age


s.Age += 1;
Console.WriteLine(“Student Info:- {0}”, s);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following output:
Student Info: Code = 001, Name = Zara, Age = 9
Student Info: Code = 001, Name = Zara, Age = 10
6.2.1 The Property Snippet
Figure 6.1 shows the property snippet. To create a property Snippet, first type
pro and then press TAB.

Fig. 6.1 Property Snippet Template (in C#)

Self-Instructional
Material 83
Method Snippets A C# property snippet template creates an automatic property by default,
whereas the VB snippet template have the get and set accessors as shown below.

NOTES

Check Your Progress


1. Define properties.
2. Define fields.

6.3 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. Properties are named members of classes, structures, and interfaces.


2. Member variables or methods in a class or structures are called Fields.

6.4 SUMMARY

 Properties are named members of classes, structures, and interfaces.


Member variables or methods in a class or structures are called Fields.
 Properties are an extension of fields and are accessed using the same syntax.
 Properties do not name the storage locations. Instead, they have accessors
that read, write, or compute their values.
 The accessor of a property contains the executable statements that helps in
getting (reading or computing) or setting (writing) the property.
 First type pro and then press TAB to create a property Snippet.

6.5 KEY WORDS

 Snippet: It is a programming term for a small region of re-usable source


code, machine code, or text.
 Fields: These are the member variables or methods in a class or structures.
Self-Instructional
84 Material
Method Snippets
6.6 SELF ASSESSMENT QUESTIONS AND
EXERCISES

Short Answer Questions NOTES

1. Write the template code for method snippet.


2. Write the template code of property snippet.
Long Answer Questions
1. What are accessors? Explain with a sample code.
2. Write a code to illustrate the use of abstract class.

6.7 FURTHER READINGS

Bronson Gary and David Rosenthal. 2005. Introduction to Programming with


Visual Basic .NET, Burlington, Massachusetts: Jones & Bartlett Learning.
Liberty Jesse. 2003. Programming Visual Basic .NET. Sebastopol, California:
O’Reilly Media, Inc.
Mayo Joe. 2010. Ms Visual Studio 2010. Noida: Tata McGraw-Hill.

Self-Instructional
Material 85
Events
BLOCK - III
UNDERSTANDING DELEGATES AND EVENTS

NOTES
UNIT 7 EVENTS
Structure
7.0 Introduction
7.1 Objectives
7.2 Introduction to Events
7.3 Delegates
7.3.1 Event, Delegate and Handler Code Completion
7.4 Implementing Interfaces
7.4.1 Creating an Interface
7.4.2 Making Classes Implement the Interface
7.5 The Interface Snippet
7.6 Applying Arrays and Generics
7.7 Answers to Check Your Progress Questions
7.8 Summary
7.9 Key Words
7.10 Self Assessment Questions and Exercises
7.11 Further Readings

7.0 INTRODUCTION

In this unit, you will learn about the events, delegates and how to implement the
interfaces. Event enables a class or object to indicate when a particular action is
occurred. It provides notifications to the client when something happened to the
object. Delegate is a reference variable that holds reference to a method and is
used to implement the events and call-back methods. An interface contains the
methods, properties and events and it depends on the class to implements them.
You will also learn about how to create and apply array and generics.

7.1 OBJECTIVES

After going through this unit, you will be able to:


 Understand the concept of events
 Discuss the need of delegates
 Implement interfaces
 Create and access the arrays
 Define generics
Self-Instructional
86 Material
Events
7.2 INTRODUCTION TO EVENTS

Events are user actions such as key press, clicks, mouse movements, etc., or
some occurrence such as system generated notifications. Applications need to NOTES
respond to events when they occur, for example, interrupts. Events are used for
inter-process communication.
Consider an example of BankAccount. These accounts can be of any type
like savings. If a customer performs an overdraft, the consequences depends on
the type of account is being used. But a generalized account class which may be
used by any bank account type without knowing the overdraft rules. So here,
event is the customeraccount class that will shows the notification whenever an
overdraft occurs. As shown in Example 7.1, if assigned value is less than zero
then the CustomerCurrentBalance property is modified to raise an Event known
as OverDraft.
Example 7.1 To illustrate the use of event.
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FirstProgram
{
class Program
{
private decimal CustomeraccountBalance = 500m;
static void Main(string[] args)
{
Program account = new Program();
account.OverDraft += new EventHandler(account_OverDraft);
account.CustomerCurrentBalance = -1;
Console.ReadKey();
}
public decimal CustomerCurrentBalance
{
getvalue
{
return CustomeraccountBalance;
}
setvalue
{
Self-Instructional
Material 87
Events if (value < 0)
{
if (OverDraft != null)
{
NOTES
OverDraft(this, EventArgs.Empty);
}
}
CustomeraccountBalance = value;
}
}
static void account_OverDraft(object sender, EventArgs
e)
{
Console.WriteLine(“Overdraft Occurred”);
}
public event EventHandler OverDraft;
}
}
VB
Module Module1
Private Dim CustomeraccountBalance As Decimal = 500
Sub Main()
AddHandler OverDraft, AddressOf AccountOverdraft
CustomerCurrentBalance = -1
Console.ReadKey()
End Sub
Public Event OverDraft As EventHandler
Public Sub AccountOverdraft (ByVal sender As Object, ByVal
e As EventArgs)
Console.WriteLine(“Overdraft Occurred”)
End Sub
End Module
In the code given above, there is an event known as OverDraft which is
declared as public. The delegate is EventHandler which describes the communication
contract that must be adhered by any code that wishes to listen for the event to
fire. Inside of if statement, there is CurrentAccountBalance property which have
the setvalue accessor and it determines if value is less than 0.
In C# when an event is equal to null, it means that nothing has subscribed to
be notified by the event—in essence, no other code is listening. However, when
the C# event is not null, then this indicates that some code somewhere has hooked

Self-Instructional
88 Material
up a method to be called when the event fires. That method is said to be listening Events

for the event.


For example, consider the caller has hooked up a method, the event
OverDraft is fired. This check for null is important. If nothing is listening for the
NOTES
event and we raise or fire the event by calling OverDraft, an error would occur at
runtime whenever a value is set into the CurrentAccountBalance property. The
arguments to the C# event mean that the current object, this, and an empty
EventArgs will be passed as the event message to any other methods that were
hooked up to this event.

7.3 DELEGATES

Delegates helps to hook up methods as the receiver to specific events. The delegate
specifies the number of arguments, the allowable signature, and their types, of a
method that is allowed to be hooked up to the event as a listener or handler. For
the OverDraft event, the EventHandler delegate type identifies about the signature
of a method, which can be written as:
C#
public event EventHandler OverDraft;
VB
Public Event OverDraft As EventHandler
The EventHandler class identifies that any methods hooked up to the
OverDraft event. This type of event can define two parameters like, an EventArgs
class and an object of any type. The EventHandler class specify that the method
does not return a value. As shown in Example 7.2, the account_OverDraft method
that matches the predefined EventHandler signature.
Example 7.2 Using Delegates
C#
static void account_OverDraft(object sender, EventArgs
e)
{
Console.WriteLine(“Overdraft Occurred”);
}
VB
Public Sub AccountOverdraft(ByVal sender As Object, ByVal
e As EventArgs)
Console.WriteLine(“Overdraft Occurred”)
End Sub
In C#, the account_OverDraft has two parameters i.e. EventArgs and type
object. The account_OverDraft doesn’t return any value. Example 7.3 explains
how the method account_OverDraft is hooked up to the event OverDraft.
Self-Instructional
Material 89
Events Example 7.3 The account_OverDraft method is hooked up to the OverDraft
event.
C#
NOTES account.OverDraft += new EventHandler(account_OverDraft);
account.CustomerCurrentBalance = -1;
VB
AddHandler OverDraft, AddressOf AccountOverdraft
CustomerCurrentBalance = -1
Here, (in C# code) the += syntax is for assigning a delegate to an event.
The OverDraft is an event and the delegate is a new instance of EventHandler.
The Eventhandler defines the precise message contract and it is delegate type of
OverDraft.
7.3.1 Event, Delegate and Handler Code Completion
In C# to create a delegate or an event, there is Code Completion support for
hooking a delegate up to an event, which also generates the handler method. This
process takes two steps i.e. delegate and handler creation.
For doing this, the initial step is to type the reference to the event consisting
of instance, then type event name, at last type +=. When you type the = sign, then
there is a tooltip symbol like the one as shown in Figure 7.1.

Fig. 7.1 Delegate Assignment Code Completion

Fig. 7.2 Handler Method Creation Code Completion

The tooltip symbol instructing you to type TAB which is used to create a
new delegate instance. If you type TAB and then code completion will pop up
additional tooltip for creating the handler method (as shown in Figure 7.2). You
can also describe interfaces to classes which is used to communicate with them in
a specified way whereas a delegate delivers an interface to a method which define
how to communicate.

Check Your Progress


1. Define events.
2. What is delegate?
Self-Instructional 3. What does delegate specifies?
90 Material
Events
7.4 IMPLEMENTING INTERFACES

Interfaces provides the flexibility to the code. It is useful in case you have group of
classes which may be exchanged at any time. But you have to require to write the NOTES
similar operations for each of these classes. Basically, there is a requirement to
write the code which uses the class (only once). The interface generates a contract
which is required for each of the interchangeable classes. Consider an interface
which states that all classes which implement the interface and this is also having
the methods A and B, it means every class that implements the interface, these
have required A and B property.it is necessary to write the class that contains the
members of the interface and also gives an execution of the interface members.
The classes that implement the interfaces have executable code, but an interface
does not have any executable code.
7.4.1 Creating an Interface
For creating an interface, right-click on the project in Solution Explorer. Then
select Add  New Item and in last, under the language branch in installed templates
select Code and select the Interface item. You can name the Interface
CustomerAccount. Example 7.4 shows how to create an Interface.
Example 7.4 Creating an Interface
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FirstProgram
{
public interface CustomerAccount
{
void Creditaccount(decimal amount);
void Debitaccount(decimal amount);

decimal CustomerCurrentBalance { getvalue; setvalue; }


}
}
VB
Public Interface CustomerAccount
Sub Creditaccount(ByVal amount As Decimal)
Sub Debitaccount(ByVal amount As Decimal)
Property CustomerCurrentBalance As Decimal
End Interface Self-Instructional
Material 91
Events After you’ve added the interface, you’ll need to make modifications to make
the code Match as shown in Example 7.4. Notice that the CustomerAccount
members don’t have an implementation and so appear incomplete because they
have no lines of code. Also, each member doesn’t have a public modifier because
NOTES interface members are implicitly public.
7.4.2 Making Classes Implement the Interface
To create a class, right-click the project in Solution Explorer, then select Add 
New Item, select Code under the language branch in Installed Templates, and
select the Class item. You can name the class as AccountChecking and click Add.
Example 7.5 shows how to make classes that implement the interface.
Example 7.5 Checking classes that implement the interface
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FirstProgram
{
class Checking : CustomerAccount
{
public void Creditaccount(decimal amount)
{
// implement checking logic
CustomerCurrentBalance += amount;
Console.Writeline(“Added “ + amount.ToString() +
“ to Customer Checking Account”);
}
public void Debitaccount(decimal amount)
{
// implement checking logic
CustomerCurrentBalance -= amount;

Console.Writeline(“Debited “ + amount.ToString() +
“ from Customer Checking Account”);
}
public decimal CustomerCurrentBalance { getvalue; setvalue;
}
}
}

Self-Instructional
92 Material
VB Events

Public Class AccountChecking


Implements CustomerAccount
Public Sub Creditaccount(ByVal amount As Decimal)
NOTES
Implements CustomerAccount.
Creditacount
‘ Implement Checking logic
CustomerCurrentBalance += amount
Console.Writeline(“Added “ & amount.ToString() &
“ to Customer Checking Account”)
End Sub
Public Sub Debitaccount(ByVal amount As Decimal)
Implements CustomerAccount.Debitaccount
‘ Implement Checking logic
CustomerCurrentBalance -= amount
Console.Writeline(“Debited “ + amount.ToString() +
“ from Customer Checking Account”)
End Sub
Public Property CustomerCurrentBalance As Decimal
Implements customerAccount.
CustomerCurrentBalance
End Class
Example 7.6 Saving class which implements the CustomerAccount Interface
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FirstProgram
{
class Saving : customerAccount
{
public void Credit(decimal amount)
{
// implement savings logic
CustomerCurrentBalance += amount;
Console.Writeline(“Added “ + amount.ToString() +
“ to Customer Saving Account”);
}

Self-Instructional
Material 93
Events public void Debitaccount(decimal amount)
{
// implement savings logic
CustomerCurrentBalance -= amount;
NOTES
Console.Writeline(“Debited “ + amount.ToString() +
“ from CustomerSaving Account”);
}
public decimal CustomerCurrentBalance { getvalue; setvalue;
}
}
}
VB
Public Class Saving
Implements CustomerAccount
Public Sub Creditaccount(ByVal amount As Decimal)
Implements customerAccount.
CreditAccount
‘ Implement Saving logic
CustomerCurrentBalance += amount
Console.Writeline(“Added “ & amount.ToString() &
“ to Customer Saving Account”)
End Sub

Public Sub DebitAccount(ByVal amount As Decimal)


Implements CustomerAccount.Debitaccount
‘ Implement Saving logic
CustomerCurrentBalance -= amount
Console.Writeline(“Debited “ + amount.ToString() +
“ from Customer Saving Account”)
End Sub
Public Property CustomerCurrentBalance As Decimal
Implements CustomerAccount.CustomerCurrentBalance
End Class
As shown above, it is clear that from Examples 7.5 and 7.6, the
AccountChecking and AccountSaving both implement the CustomerAccount
interface and repeated as follows:
C#
class AccountChecking : CustomerAccount
and
class AccountSaving : customerAccount
Self-Instructional
94 Material
VB Events

Public Class AccountChecking


Implements CustomerAccount
and
NOTES
Public Class AccountSaving
Implements CustomerAccount
Writing Code that Uses an Interface
Consider there are two classes AccountChecking and AccountSaving. Example
7.7 shows how to write the code a single time with interfaces. The following
example runs a payroll by obtaining instances of AccountChecking and
CustomerSaving classes and crediting each class.
Example 7.7 To Process payroll with checking and saving class instances.
C#
Public void ProcessPayrollForAccontCheckingAndSaving
Accounts()
{
Checking[] checkAccounts = GetCheckingAccounts();
foreach (var checkAcct in checkAccounts)
{
checkAcct.Creditaccount(600);
}
Saving[] savingAccounts = GetSavingAccounts();
foreach (var savingAcct in savingAccounts)
{
savingAcct.Creditaccount(600);
}
}
public Checking[] GetCheckingAccounts()

{
Checking[] chkAccts = new Checking[2];
chkAccts[0] = new Checking();
chkAccts[1] = new Checking();
return chkAccts;
}
public Saving[] GetSavingAccounts()
{
int numberOfAccounts = 5;
Saving[] savAccts = new Saving[numberOfAccounts];

Self-Instructional
Material 95
Events for (int i = 0; i < numberOfAccounts; i++)
{
savAccts[i] = new Saving();
}
NOTES
return savAccts;
}
VB
Sub ProcessPayrollForCheckingAndSavingAccounts()
Dim checkAccounts As Checking() = GetCheckingAccounts()
For Each checkAcct In checkAccounts
checkAcct.CreditAccount(600)
Next
Dim savingAccounts As Saving() = GetSavingsAccounts()

For Each savingAcct In savingAccounts


savingAcct.CreditAccount(600)
Next
End Sub
Function GetCheckingAccounts() As Checking()
Dim chkAccts(1) As CheckingAccount
chkAccts(0) = New CheckingAccount()
chkAccts(1) = New CheckingAccount()
Return chkAccts
End Function
Function GetSavingsAccounts() As Saving()
Dim numberOfAccounts As Integer = 5
Dim savAccts(numberOfAccounts) As Saving
For i As Integer = 0 To numberOfAccounts
savAccts(i) = New Saving()
Next
Return savAccts
End Function
Consider another Example 7.8, which consists of both AccountChecking
and AccountSaving implement the same interface that is CustomerAccount. It
shows how to process payroll with the help of Customeraccount Interface.
Example 7.8 To Process payroll through the CustomerAccount Interface.
C#
public void ProcessPayrollForAllAccounts()
{
IAccount[] accounts = GetAllAccounts();
Self-Instructional
96 Material
foreach (var account in accounts) Events
{
account.CreditAccount(800);
}
NOTES
}
public CustomerAccount[] GetAllAccounts()
{
IAccount[] allAccounts = new CustomerAccount[4];
allAccounts[0] = new Checking();
allAccounts[1] = new Saving();
allAccounts[2] = new Checking();
allAccounts[3] = new Saving();
return allAccounts;
}
VB
Sub ProcessPayrollForAllAccounts()
Dim accounts As CustomerAccount() = GetAllAccounts()
For Each account In accounts
account.CreditAccount(800)
Next
End Sub
Function GetAllAccounts() As CustomerAccount()

Dim allAccounts(3) As CustomerAccount


allAccounts(0) = New Checking()
allAccounts(1) = New Saving()
allAccounts(2) = New Checking()
allAccounts(3) = New Saving()
Return allAccounts
End Function
You can call the code from the main () method as shown below:
C#
Program bank = new Program();
bank.ProcessPayrollForAllAccounts();
VB
ProcessPayrollForAllAccounts()
Here, the accounts is an array of CustomerAccount. You can assigns an
instance of the class which implements the interface by using a variable (declared
as the interface type). AccountChecking and AccountSaving implement

Self-Instructional
Material 97
Events CustomerAccount. The GetAllAccounts gives a list of objects which implement
CustomerAccount.
There is a loop that iterate through each CustomerAccount instance known
as CreditAccount.
NOTES
By using the CreditAccount on each instance calling the CreditAccount
method on the runtime AccountChecking or AccountSaving instance. Also observe
that we’ve eliminated the duplication because one algorithm, namely
CustomerAccount.Credit() (in our example), which works on AccountChecking
and AccountSaving.

7.5 THE INTERFACE SNIPPET

To open the interface snippet, first right-clicking in Solution Explorer, then select
Add  New Item  Code File. You can name the file and save with extension
.cs (in C#) and .vb (in VB). Figure 7.3 shows the Interface Snippet Template (in
C#).

Fig. 7.3 Interface Snippet Template (in C#)

To use the interface snippet, first type int and then press TAB. The interface
snippet template (in VB) is shown in Figure 7.4.

Fig. 7.4 Interface Snippet Template (in VB)

7.6 APPLYING ARRAYS AND GENERICS

Whatever code you write will typically need to group objects into a single collection
of that object type. An array is a container which contain zero or many elements
and holds an instance of a specific type.

Self-Instructional
98 Material
Coding Arrays Events

Consider you declare a variable of the array type which instantiate the array to a
particular size.
You can use the array by indexing into the elements. Example 7.9 shows the NOTES
method of coding array (creating and using an array).
Example 7.9 Method of coding array (creating and using an array).
C#
private void ArrayDemo()
{
double[] stats = new double[3];
stats[0] = 1.0;
stats[1] = 1.1;
stats[2] = 1.3;
double sum = 0;
for (int i = 0; i < stats.Length; i++)
{
sum += stats[i];
}
Console.WriteLine(
stats[0] + “ + “ +

stats[1] + “ + “ +
stats[2] + “ = “ +
sum);
}
VB
Sub ArrayDemo()
Dim stats(2) As Double
stats(0) = 1.0
stats(1) = 1.1
stats(2) = 1.2
Dim sum As Double = 0
For i As Integer = 0 To 2
sum += stats(i)
Next
Console.WriteLine(
stats(0) & “ + “ &
stats(1) & “ + “ &
stats(2) & “ = “ &
Self-Instructional
Material 99
Events sum)
End Sub
In C# code, it is clear that the stats variable is denoted as array that is of
type double. By assigning new double [3] to stats, you can instantiate arrays. The
NOTES
stats has three elements having indexes 0, 1, and 2. Similarly in VB, stats as an
array of type double.
Coding Generics
Generics are classes, structures, interfaces, and methods that have placeholders
(type parameters) for one or more of the types that they store or use. Generics
which permits you to write a piece of code. This piece of code work with multiple
types efficiently.
In .NET there is an entire library of generic collections as well as generic
types. Example 7.10 shows how to declare a generic List. The code states the
type of the list like an AccountChecking and then demonstrate how to generate
the generic list. This helps to do operations on the AccountChecking elements of
the generic list.
Example 7.10 To declare a Generic List
C#
private void ListExmp()
{
List<Checking> checkAccts = new List<AccountChecking>();
checkAccts.Add(new AccountChecking());
checkAccts.Add(new AccountChecking());
for (int i = 0; i < checkAccts.Count; i++)
{
Console.WriteLine(checkAccts[i].CustomerCurrentBalance);
}
}
VB
Sub ListExmp()
Dim checkAccts As New List(Of AccountChecking)
checkAccts.Add(New AccountChecking())
checkAccts.Add(New AccountChecking())
For i As Integer = 0 To checkAccts.Count - 1
Console.WriteLine(checkAccts(i).CustomerCurrentBalance)
Next
End Sub
Here the generic List type is denoted as List<T>, where T is a type
placeholder. With the help of this placeholder, you can state any type you want.
Self-Instructional
100 Material
For example, you can create a List<string> for strings or a List<int> for integers, Events

which will be List (Of String) or List (Of Integer) respectively.


Use the Add method to add elements to the List because a list grows
dynamically to accommodate any number of elements. Collections such as List
NOTES
are convenient because they have multiple convenience methods, such as Clear,
Contains, Remove, and more. The System.Collections. Generic namespace has
several other generic collections, like Stack, Dictionary, and Queue etc. Each
generic is modified by exchanging the type parameters with the types you required
to work on.

Check Your Progress


4. How you will create an interface?
5. Write the steps to open an interface snippet.
6. What are generics?

7.7 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. Events are user actions such as key press, clicks, mouse movements, etc.,
or some occurrence such as system generated notifications.
2. Delegate is event handler which describes the communication contract that
must be adhered by any code that wishes to listen for the event to fire.
3. The delegate specifies the number of arguments, the allowable signature,
and their types, of a method that is allowed to be hooked up to the event as
a listener or handler.
4. For creating an interface, right-click on the project in Solution Explorer.
Then select Add  New Item and in last, under the language branch in
installed templates select Code and select the Interface item.
5. To open the interface snippet, first right-clicking in Solution Explorer, then
select Add  New Item  Code File. You can name the file and save with
extension .cs (in C#) and .vb (in VB).
6. Generics are classes, structures, interfaces, and methods that have
placeholders (type parameters) for one or more of the types that they store
or use.

7.8 SUMMARY

 Event enables a class or object to indicate when a particular action is


occurred.
Self-Instructional
Material 101
Events  Delegate is a reference variable that holds reference to a method and is
used to implement the events and call-back methods.
 Events are user actions such as key press, clicks, mouse movements, etc.,
or some occurrence such as system generated notifications.
NOTES
 Delegates helps to hook up methods as the receiver to specific events. The
delegate specifies the number of arguments, the allowable signature, and
their types, of a method that is allowed to be hooked up to the event as a
listener or handler.
 In C# to create a delegate or an event, there is Code Completion support
for hooking a delegate up to an event, which also generates the handler
method. This process takes two steps i.e. delegate and handler creation.
 Interfaces provides the flexibility to the code. It is useful in case you have
group of classes which may be exchanged at any time. But you have to
require to write the similar operations for each of these classes. Basically,
there is a requirement to write the code which uses the class (only once).
 For creating an interface, right-click on the project in Solution Explorer.
Then select Add  New Item and in last, under the language branch in
installed templates select Code and select the Interface item.
 To create a class, right-click the project in Solution Explorer, then select
Add  New Item, select Code under the language branch in Installed
Templates, and select the Class item.
 To open the interface snippet, first right-clicking in Solution Explorer, then
select Add  New Item  Code File. You can name the file and save with
extension .cs (in C#) and .vb (in VB).
 An array is a container which contain zero or many elements and holds an
instance of a specific type.
 Generics are classes, structures, interfaces, and methods that have
placeholders (type parameters) for one or more of the types that they store
or use. Generics which permits you to write a piece of code. This piece of
code work with multiple types efficiently.

7.9 KEY WORDS

 Delegate: It is a reference variable that holds reference to a method and is


used to implement the events and call-back methods.
 Interface: It contains the methods, properties and events but not the
implementation and it depends on the class to implements them.

Self-Instructional
102 Material
Events
7.10 SELF ASSESSMENT QUESTIONS AND
EXERCISES

Short Answer Questions NOTES

1. Write a note on events and delegates.


2. Define interface.
3. Discuss how you will create an interface with an example.
4. Write the steps to open an interface snippet.
5. Write a program that creates and use an array.
Long Answer Questions
1. Write a program to illustrate the use of events.
2. Explain how you will create an event and delegate.
3. How you will create a class and implement the interface? Explain.
4. How you will implement the generics? Explain.

7.11 FURTHER READINGS

Bronson Gary and David Rosenthal. 2005. Introduction to Programming with


Visual Basic .NET, Burlington, Massachusetts: Jones & Bartlett Learning.
Liberty Jesse. 2003. Programming Visual Basic .NET. Sebastopol, California:
O’Reilly Media, Inc.
Mayo Joe. 2010. Ms Visual Studio 2010. Noida: Tata McGraw-Hill.

Self-Instructional
Material 103
Creating and
Building Projects
UNIT 8 CREATING AND BUILDING
PROJECTS
NOTES
Structure
8.0 Introduction
8.1 Objectives
8.2 Constructing Solutions and Projects
8.3 Navigating the Solution Explorer
8.4 Examining Property Settings
8.5 Answers to Check Your Progress Questions
8.6 Summary
8.7 Key Words
8.8 Self Assessment Questions and Exercises
8.9 Further Readings

8.0 INTRODUCTION

In this unit, you will learn about the solution and projects. Visual studio can be
used to build applications/projects having different levels of complexities. You
will also navigate through the solution explorer which provides one of the best
feature that the properties, folders and programs are represented in hierarchical
relationship.

8.1 OBJECTIVES

After going through this unit, you will be able to:


 Construct solutions and projects
 Navigate through the solution explorer
 Explain how to examine the properties

8.2 CONSTRUCTING SOLUTIONS AND PROJECTS

With the help of Visual Studio, you can build applications that range in size and
complexity. You can start a console project which consist of a number of files
having code at the very basic level. In case of higher levels of complexity, there
is a requirement to build enterprise-scale applications which consists of many
projects of different types. These large scale projects have to be structured to
maintain a large teams of developers. The organizing principles of project
organization and solution states that: we have a project inside of a solution. It
means you have to work with only one solution at a time. This solution consists
Self-Instructional
104 Material
of one or more projects. As we know that there are different project types Creating and
Building Projects
which have unique settings and options. But here in this unit, we will start by
creating a console application.
A hierarchical model is used in Visual Studio, and this is used to help and
NOTES
organize the code. This also helps in a project set up and provides flexibility.
Some options like projects and solutions are well defined, but for customizing
the arrangement of files, there is a freedom to add folders which help to meet
your requirements.
Creating a New Project
To open the New Project window, press CTRL + SHIFT + N. Visual Studio
always remember your last project type. This can be beneficial, while creating
multiple projects of the same type. To create a new project, select Console
Application as a project type.
Figure 8.1 shows that the projects in C#, allows you to configure Location,
configure Name, Solution and Solution Name. In C#, the Solution Name field
is the name of the solution and the Name field is the name of the project.

Fig. 8.1 Creating a new project

But in case of multiproject solution, to create a project, type the name


of the project and then write the name for the solution. For example, in Figure
8.1, the project is named as ProjectDemo and the solution is named as
SolutionDemo. The spaces are allowed while giving the names.
While starting the console project, if you start by having a very simple
project. You want to save all project files in the same folder, for this you have
Self-Instructional
Material 105
Creating and to uncheck Create Directory for solution. However, most applications you build
Building Projects
will have multiple projects and leaving this box checked makes more sense
because it maintains consistency between folder and solution organization.
While adding the project into the solution, this project must be put into
NOTES
a separate subfolder. If you check Add To Source Control, VS will open a
window for you to configure source control. Click OK to create the solution.
While starting a new Console project, must require a Name parameter,
(the name of the project to create). As the project created, a window popups
which requests to you about Name, Create Directory, Location, Solution Name
etc.

8.3 NAVIGATING THE SOLUTION EXPLORER

Figure 8.2 shows in the Solution Explorer window that Visual Studio creates a
new project. We know that the Solution Explorer window is where you can find
all of the artifacts of an application. Hierarchical relationships is one of the
feature of the project as shown below.

Fig. 8.2 Solution Explorer Window

Multiple projects and folders can be added to a solution for organising


the projects. For organizing Projects in the Solution Explorer, you have to right-
click the solution name and then select Add  New Project. With the help of
this you can add more projects. You can Add  Existing Project which allows
you to add a project which already exists. A single project can also be shared
with other solutions. For this select Add  New Solution Folder which adds
a folder to a solution.
For organizing projects, you can add a hierarchy of folders to a solution.
If you want your file system layout to match the Solution Explorer layout with
solution folders, you must create the file system folders yourself. To avoid
confusion, remember that it is possible for the physical location of projects to
differ from the Solution Explorer layout. Besides organizing projects, solution
folders are also useful for associating specific artifacts with your project. While
solution folders are not tied to physical file system folders, they are included
with source control providers, such as Visual Source Safe and Team System.
Self-Instructional
106 Material
Another benefit of a solution folder is to contain a copy of an external Creating and
Building Projects
class library (which you built for your project). Because, when other members
of the team check the solution beyond the source control, then they will be
working with the same files and versions.
NOTES
Solution folders can also be used for any type of file, including project
documentation or anything else that you want to keep organized in a single
place. Depending on project type, VS hides various files associated with a
project. The Solution Explorer toolbar has a Show All Files button that will
show these hidden files. If you have the solution selected, all you’ll see is the
Add A New Solution Folder button, so you’ll need to select a project before
the Show All Files button will display.

8.4 EXAMINING PROPERTY SETTINGS

When you first create a project, these settings are organised for common values
for that project type. Each project has associated settings that you can configure.
To meet the requirements, you can modify these settings. As shown in Figure
8.2, each project has a folder named Properties.
When you double-click the Properties, it will open a property setting
window as shown in Figure 8.3. The window represents that there are multiple
tabs and these tabs are associated properties which are grouped to the subject
of each tab.

Fig. 8.3 Examining Property Settings (The Project Properties Window)

Self-Instructional
Material 107
Creating and Based on the project type, you can see additional tabs and out of these
Building Projects
some of the tabs are common in between all projects.
Assembly Name
NOTES The assembly name offers the filename for the project. As shown in Figure 8.3,
there is an Assembly Name which is used to set ProjectDemo. The output will
be a *.exe, because this is a Console application. So here the filename will be
ProjectDemo.exe.
Default Namespace
The default namespace setting defines about the namespace which will be well-
defined repeatedly, in case, if you add a new code file to your project. The
default namespace is the primarily set to the name of your project.
Target Framework
Visual Studio has .NET Framework multi-targeting support, where you can
work with any version of.NET between v2.0 and v4.0. Select the .NET version
you need in the Target Framework combo box. VB includes this option on the
Compile tab when clicking the Advanced Compile Options button. As we know
that there are multiple versions of .NET (on same machine). So you can switch
easily between different projects which uses different .NET versions. This method
is valuable if you are working as a consultant on different projects with different
Versions.
Output Type
An Output type is the type of assembly created when you build your project.
There are three types of output i.e. Console Application, Windows Application
and Class Library. The console application produces a *.exe assembly.

Check Your Progress


1. Write one of the benefit of visual studio for building a project.
2. What does assembly name offers?

8.5 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. With the help of Visual Studio, you can build applications that range in
size and complexity. A hierarchical model is used in Visual Studio, and
this is used to help and organize the code.
2. The assembly name offers the filename for the project.

Self-Instructional
108 Material
Creating and
8.6 SUMMARY Building Projects

 With the help of Visual Studio, you can build applications that range in
size and complexity. NOTES
 A hierarchical model is used in Visual Studio, and this is used to help and
organize the code. This also helps in a project set up and provides
flexibility.
 The projects in C#, allows you to configure Location, configure Name,
Solution and Solution Name.
 Multiple projects and folders can be added to a solution for organising
the projects. For organizing Projects in the Solution Explorer, you have
to right-click the solution name and then select Add  New Project.
With the help of this you can add more projects. You can Add 
Existing Project which allows you to add a project which already exists.
 The assembly name offers the filename for the project.
 The default namespace setting defines about the namespace which will be
well-defined repeatedly, in case, if you add a new code file to your
project.
 An Output type is the type of assembly created when you build your
project.

8.7 KEY WORDS

 Assembly Name: It is simply the name of the compiled file that your
code will be compiled to as either an executable or library.
 Default Namespace: It defines about the namespace which will be
well-defined repeatedly, in case, if you add a new code file to your
project.

8.8 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer questions


1. Discuss the benefits of constructing solution and projects in VS.
2. Write a note on the following:
(i) Assembly name
(ii) Default namespace

Self-Instructional
Material 109
Creating and (iii) Target framework
Building Projects
(iv) Output type
Long Answer questions
NOTES
1. How will you organise the projects using solution explorer?
2. Explain the benefits of solution folders.
3. What are the property settings in solution explorer?

8.9 FURTHER READINGS

Bronson Gary and David Rosenthal. 2005. Introduction to Programming with


Visual Basic .NET, Burlington, Massachusetts: Jones & Bartlett Learning.
Liberty Jesse. 2003. Programming Visual Basic .NET. Sebastopol, California:
O’Reilly Media, Inc.
Mayo Joe. 2010. Ms Visual Studio 2010. Noida: Tata McGraw-Hill.

Self-Instructional
110 Material
Building Projects

UNIT 9 BUILDING PROJECTS


Structure NOTES
9.0 Introduction
9.1 Objectives
9.2 Startup Object, Icon and Manifest
9.3 Building and Cleaning Projects/Solutions
9.4 Managing Dependencies and Build Order
9.5 Managing Compilation Settings
9.6 Navigating a Project with Class View
9.7 Answers to Check Your Progress Questions
9.8 Summary
9.9 Key Words
9.10 Self Assessment Questions and Exercises
9.11 Further Readings

9.0 INTRODUCTION

In this unit, you will learn about the Startup object, rebuilding and cleaning
projects/solutions. Startup objects allows you to start your application in different
configurations. The build includes more than compilation. For example, consider
while writing ASP.NET applications, Visual Studio will generate code based on
the Web controls on the page. This generated code would be compiled with
normal code. So the term build is more accurate than compile. You will also
learn about the managing dependencies and work with Class View.

9.1 OBJECTIVES

After going through this unit, you will be able to:


 Understand the use of startup object
 Build and clean projects/solutions
 Manage dependencies
 Navigate and use the class view

9.2 STARTUP OBJECT, ICON AND MANIFEST

In a Console application, you can add multiple main methods, but at a time only
one main method would be active. The Startup object allows you to specify
which class contains the main method you want to use as the entry point to your
application. The start-up object permits you to start your application in different
configurations.
Self-Instructional
Material 111
Building Projects Icon and Manifest
Clicking the ellipses button on the right of the icon drop-down list, you can
browse an icon file, *.ico, which will appear as your application icon. The
NOTES manifest allows you to identify Microsoft Windows User Access Control (UAC)
Settings. It also support a form of deployment which is called as Click-Once.
A WPF application can be organised from a Web page and that runs
locally on the desktop machine. The manifest defines the Click-Once application
and its deployment and application features. When you broadcast a Click-Once
application, then these manifests are automatically generated. While creating
manifest files, you couldn’t allow to build manually manifest files, but while
creating these files it must consists of the knowledge outside what a beginner’s
guide would include.
In VB, there is a UAC Settings button that allows you to directly modify
the app .manifest file. But for doing this operation, you must have the knowledge
of the operating system UAC settings.
Compiling Applications
On the Build menu, there are several compilation options, it isn’t always intuitive
which option you should use. These options are scoped to either the entire
solution or current project. So in compiling applications, you will learn about
how to build projects and also describes how to rebuild projects.

9.3 BUILDING AND CLEANING PROJECTS/


SOLUTIONS

For building projects or solutions requires that you run the compiler to compile
source code files. The build includes more than compilation. For example,
consider while writing ASP.NET applications, Visual Studio will generate code
based on the Web controls on the page. This generated code would be compiled
with normal code. So the term build is more accurate than compile. During a
normal build, VS will only build the items in a project or solution that are out
of date. The projects having some edits or changes can be rebuilt, but there are
some projects which are untouched can be used again. During normal
development a build is normally the fastest option. You will need to build
everything to make sure you aren’t accidentally working with old code.
Rebuilding Projects/Solutions
A rebuild performs the similar actions as a build, except that it forces the build
of all items belonging to a project or solution. The main cause for a rebuild
consists is to ensure new code that has been written works with existing code.

Self-Instructional
112 Material
If you have been creating a fresh build for organization, then you must be careful Building Projects

about the important items which are built when a normal build doesn’t work.
Before you deploy an application, you’ll want to perform a rebuild to
ensure all of the code builds. Depending on your process, you will want to test
NOTES
the code that was just rebuilt, prior to deployment. The rebuild ensures that the
application you are preparing for deployment is the most current.
Sometimes the normal build doesn’t work properly. There can be lots of
bugs that are related with code which you’ve already written. While Visual
Studio is a great tool which manages dependencies between projects. There are
still complex situations where entire one doesn’t build properly. So the solution
of this problem is to try a rebuild which forces to build on all items of a solution
or project.
A rebuild takes more time to perform, the reason is that all items in a
project have to be rebuilt. If you have a small project, you might not notice the
differences. However, if you have a fairly large solution, with dozens of projects,
a steady pattern of rebuilds throughout the day could affect your productivity.
A rebuild on a project is often not much more work than a build on the project,
but there are probably edge cases where the difference in time would be
noticeable.
So here instead of building the solution, rebuild the solution is most
important. As in case of Visual Studio has upgraded the performance of the
build process. So, you should analyse the performance as a relation between
build and rebuild.
Cleaning Projects/Solutions
A clean operation can remove the project outputs. It consists of *.exe, *.dll or
there can be other items which are formed by the build process. The clean
operation makes ensures that all outputs must be fresh or to obtain a smaller
copy of the project.
Normally, a full rebuild ensures that you have the maximum up-to-date
outputs available. You can also execute a clean operation so that all outputs can
be deleted. It also make sure to execute build to check which outputs were
created. But this method can give you understanding about whether the build on
a solution was consisting of all of the projects.
In some situations, the Visual Studio manages all of your dependencies
for you. But most of the developers sometimes change these dependencies.
Cleaning is a tool to help you know whether a project is really being built from
a practical perspective. It is rare and you could inspect file dates to tell the same
thing, but cleaning is another path you can take.
The main use of clean is to delete outputs from the project which makes
it smaller. To compress a solution or project which requires that the size of the
Self-Instructional
Material 113
Building Projects file should be minimized. The code files can be compress like *.exe or *.dll files
but these files have extra space, even when these files are added to a compressed
file. But, if the clean operation is performed before compressing the files, then
these files can use much less file space.
NOTES
Check Your Progress
1. What does Startup object specify?
2. What is the main difference between build and rebuild project?

9.4 MANAGING DEPENDENCIES AND BUILD


ORDER

A dependency means in which a given project depends on other projects to


operate properly. For example as discussed in previous unit, the ProjectDemo
project references ClassLibraryDemo and also uses the code in
ClassLibraryDemo. So we can say that the ProjectDemo has a dependency on
ClassLibraryDemo.
Visual Studio adds this dependency automatically which is good because
when VS builds your solution, it will keep all projects up-to-date. Visual Studio
manages a tree of dependencies. When you perform a rebuild, then Visual
Studio manages the dependency tree. This also builds all projects which does
not contain dependencies. So, we can say that visual studio builds all projects
which depend on the last set of projects which were rebuilt.
This process continues until the whole solution is rebuilt. At the top of the
tree, all projects reference updated versions of all referenced projects. By right-
clicking a project or the solution in Solution Explorer, you can manually manage
dependencies. Figure 9.1 shows the Project Dependencies window.
From the drop-down list, you can select the project to set dependencies
(in the Project Dependencies window). As shown in Figure 9.1, the ProjectDemo
project has a dependency on ClassLibraryDemo. These types of dependency
is automatically created by Visual Studio.
Project dependencies have direct impact on the build order of a project.
As we know that projects have dependencies upon them and these dependencies
must be built before the depending projects. As shown in Figure 9.1, click on
the Build Order tab from the Project Dependencies window to manage the
order of the build. By right-clicking a project, you could also get to the Build
Order tab in Solution Explorer (as shown in Figure 9.2).

Self-Instructional
114 Material
Building Projects

NOTES

Fig. 9.1 Project Dependencies Window

Fig. 9.2 Project Build Order tab

9.5 MANAGING COMPILATION SETTINGS

The project property pages consists of a tab which is used for compiler settings.
You can fixed compiler settings for individual project. Figure 9.3 shows the C#
compiler options, it means this can be open by double clicking the Properties
folder on a project.
Self-Instructional
Material 115
Building Projects

NOTES

Fig. 9.3 C# Compiler Options

The TRACE and DEBUG compilation constants ensures to use the Trace
and Debug classes, respectively. These are the members of the .NET Framework
System.Diagnostics namespace. You can also build code which depends on
your own custom constants. It can be achieved by adding your particular
constants to the Conditional Compilation Symbols box as a comma separated
list of strings.
C# allows you to write code which is categorised as unsafe. It means you
can use pointers and other features in an unsafe context. As we know that the
unsafe code is still managed code. However, the CLR can’t verify that the code
is safe because unsafe code can contain pointers. This is an advanced feature
and the box is unchecked, ensuring that you must check it to opt in to enable
this type of coding.
All warning messages are associated with a level. By Default, the Warning
level is set to 4 and this consists of all compiler warnings. By doing setting this
to a lower level will suppress the display of all warnings which are at that level
or higher. You can also suppress the specific warnings and this is done by
adding them to a comma-separated list in the Suppress Warnings box.
You really shouldn’t suppress warnings, as this setting could cover up an
error that would be hard to detect otherwise. While building an application, the
program will run if warnings are present. These programs can’t be run if the
compiler come upon with errors. Sometimes the warnings are also important
which you might want to treat them as errors and the Treat Warnings as Errors
section provides you flexibility in holding warning-as-error scenarios.
Under the project folder, the output path of an application defaults to
bin\Debug which is used like bin\Release to release builds and Debug builds.
Checking the XML Documentation file will cause XML Documentation comments
to be extracted from your code into an XML file that you specify. By checking
Self-Instructional
116 Material
this box, it will increases the time of the build process. So that you won’t Building Projects

essentially want to leave it on throughout the Debug builds (when most of


coding is done).
The XML documentation file can be input into third-party tools which
NOTES
automatically build technical documentation. If you were building a .NET
Assembly then you would only check the Register (for COM Interop box) that
was being called from a COM application.
You can turn on the Generate Serialization Assembly to speed up the
serialization process, if you’re doing XML serialization of types in an assembly.
C# has another group of settings on the Build Events tab. The code can be run
before or after the build for each project.
You can set the conditions upon when the build occurs, which could be
always, on a successful build, or only when an update occurs. The build events
have a set of macros you can access that gives you information on the current
build process. On its Compile page (in case of VB), the VB has options which
are specific to the VB compiler as shown in Figure 9.4.

Fig. 9.4 Compile Options Page (VB)

Most of the VB and C# compiler options are similar, except for Option
Explicit, Option Strict, Option Compare, and Option Infer. You can also assign
any type to another by default, but Option Strict, if turned on, will force you
to use code that performs a conversion from a larger type to a smaller type,
often referred to as a narrowing conversion.
Option Infer will allows a variable to assume its type based on what is
being allocated to the variable, rather than declaring the variable type. For
example:
Dim studentName = “John”
Self-Instructional
Material 117
Building Projects In this example, the type of “John” is a String. Here studentName come
to be a string because that is the type of the value being assigned.

NOTES
9.6 NAVIGATING A PROJECT WITH CLASS VIEW

The Class view is the way to work with projects. It allows you to view project
artifacts and solutions with the help of logical layout of the code. In C#, you
can open Class view with the help of pressing CTRL-W or from the View menu
 select Class View. You can open Class view with the help of pressing
CTRL-SHIFT, or select View  Other Windows  Class View. Figure 9.5
shows the Class View window.
In the Class view, there is ordering of nodes that start at the project. It
consists of namespaces or references. It also consists of classes under these
namespaces. Below every class there is Base Types and contains a list of base
classes which are derived from and implemented interfaces for that particular
class. As shown in Figure 9.5, it is clear that selection of the Student class and
this displays the members of the class in the bottom pane.

Fig. 9.5 Class View Window

In the Class View toolbar, you can generate new folders. You can use the
arrows to navigate up or down the hierarchy. You can also select options of
what to display in the hierarchy.
Using the Class Designer
When working with a project, then it can be helpful to have a high-level view
of the project contents. Especially, if someone else has created the project and
Self-Instructional
118 Material
you haven’t worked with that project before. So here comes the use of Class Building Projects

Designer. The Class Designer provides a basic tool to perform some design
yourself.
Class Desinger Visualization NOTES
When you select a project in Solution Explorer, then you can check there is the
Class Designer button appear in the Solution Explorer toolbar. The Class Designer
button appears on the Class View window. Clicking View Class Diagram will
produce a diagram of classes in your solution.
As shown in Figure 9.6, a new file is produced in Visual Studio which is
named as ClassDiagram1.cd and having the visual representation of the code.
It shows that the properties window is open which allows you to view information
about the selected Program class.

Fig. 9.6 Visualizing code with the Class Designer

Here, the Class Details window gives the additional details on the members
of the Program.cs class.
Class Designer Code Generation
The Class Designer allows you to produce code graphically. As shown in Figure
9.6, on the left-hand side, you can see a tab for the Toolbox. There is a group
of images for code items, like Enum, Class, Inheritance etc. It displays the result
of using Toolbox items to improve the existing Figure 9.7. You can see the
Toolbox with options for what type of items you can add to a class diagram.
Each of the Toolbox items matches some type of code that you would normally
write.
In the class diagram, there are some additional items which consists of an
abstract class named as Staff. It also consists of a normal class named Teacher.
Self-Instructional
Material 119
Building Projects Figure 9.7 also shows inheritance relationship, in which the Teacher derives
from Staff.

NOTES

Fig. 9.7 Generating code with the Class Designer

To create a new object, drag-and-drop the object from the Toolbox to


the Class Designer surface; you’ll see an input window similar to Figure 9.8.
In Figure 9.8, the New Abstract Class window is the Class Designer
objects which you can add to a diagram where you fill in the initial data for
naming the class. It also specifying the file the code that would be added to.

Fig. 9.8 Adding a new object to the Class Designer

Not all Toolbox options work this way, though, associations and inheritance
work by selecting the item in the Toolbox, selecting the object where the line
begins in the Class Designer, and dragging the line to the object in the Class
Designer being referenced. The other two places you can modify data are in the
Properties windows and Class Details.

Self-Instructional
120 Material
By clicking the object in Class Designer, you can add members to an Building Projects

object and then adding the member in Class Details. The Properties window is
context-sensitive, displaying about what options are available for whatever you
have selected in the Class Designer.
NOTES
As shown in Figure 9.7, the Teacher class is selected in Class Designer
and the Summary property in the Properties window was filled with a comment.
Figure 9.8 shows how to add a new object to the class designer. Example 9.1
shows the code from the Teacher.cs file that was generated after all of these
actions in the graphical designer.
Example 9.1 Code generated from the Class Designer
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProjectDemo
{
/// <summary>
/// Teaches Classes
/// </summary>
public class Teacher : Staff
{
/// <summary>
/// Grade student papers
/// </summary>
/// <param name=”papers”>Papers to grade</param>
public void GradePapers(List<string> papers)
{
throw new System.NotImplementedException();
}
}
}
VB
‘’’ <summary>
‘’’ Teaches Classes
‘’’ </summary>
Public Class Teacher
Inherits Staff
‘’’ <summary>

Self-Instructional
Material 121
Building Projects ‘’’ Grade student papers
‘’’ </summary>
Public Sub GradePapers(ByVal papers As List(Of String))
End Sub
NOTES
End Class
This example shows the code generated from the Class Designer consists
of the namespace as specified in project properties and default using directives.
The Grade Papers method is the same as specified in the Class Details window
and the class name, Teacher is the same as the visual object in the class
diagram. In the example, there are comment on Teacher as specified in the
Property window.

Check Your Progress


3. What is the default warning level?
4. What is the significance of Class View?

9.7 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. The Startup object allows you to specify which class contains the Main
method you want to use as the entry point to your application. The start-
up object permits you to start your application in different configurations.
2. A rebuild performs the similar actions as a build, except that it forces the
build of all items belonging to a project or solution.
3. By Default, the Warning level is set to 4
4. The Class view is the way to work with projects. It allows you to view
project artifacts and solutions with the help of logical layout of the code.

9.8 SUMMARY

 The Startup object allows you to specify which class contains the Main
method you want to use as the entry point to your application.
 The manifest allows you to identify Microsoft Windows User Access
Control (UAC) Settings. It also support a form of deployment which is
called as Click-Once.
 During a normal build, VS will only build the items in a project or solution
that are out of date.

Self-Instructional
122 Material
 A rebuild performs the similar actions as a build, except that it forces the Building Projects

build of all items belonging to a project or solution. The main cause for
a rebuild consists is to ensure new code that has been written works with
existing code.
NOTES
 A rebuild takes more time to perform, the reason is that all items in a
project have to be rebuilt.
 A clean operation can remove the project outputs. It consists of *.exe,
*.dll or there can be other items which are formed by the build process.
The clean operation makes ensures that all outputs must be fresh or to
obtain a smaller copy of the project.
 Project dependencies have direct impact on the build order of a project.
 The project property pages consists of a tab which is used for compiler
settings. You can fixed compiler settings for individual project.
 All warning messages are associated with a level. By Default, the Warning
level is set to 4 and this consists of all compiler warnings. By doing setting
this to a lower level will suppress the display of all warnings which are
at that level or higher.
 The Class view is the way to work with projects. It allows you to view
project artifacts and solutions with the help of logical layout of the code.
 The Class Designer allows you to produce code graphically.

9.9 KEY WORDS

 Startup Object: It allows you to specify which class contains the main
method you want to use as the entry point to your application.
 Clean Project: It is a utility that cleans VS project directories so you can
quickly upload or email a zip file with your solution.

9.10 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer Questions


1. What is the use of icon and manifest in projects?
2. What is the benefit of rebuild projects/solution over fresh build?
3. What is the effect of project dependencies on build order?

Self-Instructional
Material 123
Building Projects Long Answer Questions
1. Explain the need for cleaning the projects/solution.
2. How you will manage the dependencies in project?
NOTES 3. How you will manage compilation settings in project?
4. Write a detailed note on Class View.

9.11 FURTHER READINGS

Bronson Gary and David Rosenthal. 2005. Introduction to Programming with


Visual Basic .NET, Burlington, Massachusetts: Jones & Bartlett Learning.
Liberty Jesse. 2003. Programming Visual Basic .NET. Sebastopol, California:
O’Reilly Media, Inc.
Mayo Joe. 2010. Ms Visual Studio 2010. Noida: Tata McGraw-Hill.

Self-Instructional
124 Material
Debugging Methods
BLOCK - IV
DEBUGGING WITH VISUAL STUDIO

NOTES
UNIT 10 DEBUGGING METHODS
Structure
10.0 Introduction
10.1 Objectives
10.2 Basic Concept
10.2.1 Setting Breakpoints
10.2.2 Stepping through the Code
10.2.3 Inspecting Application State
10.2.4 Locals and Autos Windows
10.2.5 Watch Windows
10.2.6 The Immediate Window
10.2.7 The Call Stack Window
10.2.8 The Quick Watch Window
10.2.9 Watching Variables with Pin to Source
10.2.10 Working with IntelliTrace
10.3 Answers to Check Your Progress Questions
10.4 Summary
10.5 Key Words
10.6 Self Assessment Questions and Exercises
10.7 Further Readings

10.0 INTRODUCTION

In this unit, you will learn about how to use the Visual Studio debugger, which
is used to fix problems by setting breakpoints, stepping through code, and
inspecting program state. There is also the development-time tools to inspect
the structure of your code. You will also learn how to set, customize and
manage the breakpoints. Further, you will learn about many ways to see the
values of variables are in your code and the different tools available for inspecting
your code.

10.1 OBJECTIVES

After going through this unit, you will be able to:


 Understand the significance of call hierarchy
 Create, customize and manage breakpoints
 Step through the code
 Discuss the use of various windows in VS like local, autos, call stack etc.
Self-Instructional
Material 125
Debugging Methods
10.2 BASIC CONCEPT

Consider an example below that shows a console application, similar to all of


NOTES the applications created in previous units. You create a console project by
selecting File  New  Project. Then select the Console Application project
and also gives the project a name, and generate the project by clicking OK.
Example 10.1 calculate a discount for a customer, which is based on a special
discount percentage for that customer and what that customer ordered.
Example 10.1 To calculate a discount for customer.
C#: Program.cs
using System;
namespace DebugAndTestDemo
{
class Program
{
static void Main()
{
Customer cust = new Customer();
cust.Discount = .1m;
Order ord = new Order();
ord.AddItem(5.00m);
ord.AddItem(2.50m);
cust.Order = ord;
decimal discount = cust.GetOrderDiscount();
Console.WriteLine(“Customer Discount: {0}”, discount);
Console.ReadKey();
}
}
}
C#: Customer.cs
namespace DebugAndTestDemo
{
class Customer
{
public decimal Discount { get; set; }
public Order Order { get; set; }
public decimal GetOrderDiscount()
{

Self-Instructional
126 Material
return Order.Total * Discount; Debugging Methods
}
}
}
NOTES
C#: Order.cs
using System.Collections.Generic;
namespace DebugAndTestDemo
{
class Order
{
private List<decimal> orderItems = new List<decimal>();
public decimal Total
{
get
{
decimal amount = 0;
foreach (var item in orderItems)
{
amount = amount + item;
}
return amount;
}
}
public void AddItem(decimal amount)
{
orderItems.Add(amount);
}
}
}
VB: Module1.vb
Module Module1
Sub Main()
Dim cust As Customer = New Customer()
cust.Discount = 0.1D
Dim ord As Order = New Order()
ord.AddItem(5D)
ord.AddItem(2.5D)
cust.Order = ord
Dim discount As Decimal = cust.GetOrderDiscount()

Self-Instructional
Material 127
Debugging Methods Console.WriteLine(“Customer Discount: {0}”, discount)
Console.ReadKey()
End Sub
End Module
NOTES
VB: Customer.vb
Class Customer
Property Discount As Decimal
Property Order As Order
Function GetOrderDiscount() As Decimal
Return Order.Total * Discount
End Function
End Class
VB: Order.vb
Class Order
Private orderItems As New List(Of Decimal)
Public ReadOnly Property Total() As Decimal
Get
Dim amount As Decimal = 0
For Each item In orderItems
amount = amount + item
Next
Return amount
End Get
End Property
Sub AddItem(ByVal item As Decimal)
orderItems.Add(item)
End Sub
End Class
The above code shows that this program is very sophisticated. In the
Main method, there are two objects that is Customer and Order. Here you can
see that the Discount property on cust is set to .1(10%), which indicates that
each instance of Customer may have unique discount amount, which could be
useful if you wanted to reward good shopping habits. You can see the instantiation
of Order and subsequent calls to AddItem on the object reference ord.
The Customer class has an Order property and this code is passes to
Order instance, ord. This program calculates the total economic discount that
a customer have to receive for that Order and which is done by calling the
GetOrderDiscount method on the Customer instance. It also returns the calculated
discount amount which is to be subsequently displayed on the console. Essentially,
we created a pair of object instances that is cust and ord, gave the object

Self-Instructional
128 Material
instances the data they needed, and told the object instances to do some work Debugging Methods

for us.
The result is a special discount monetary amount for a given customer
which is based on the customer’s items ordered. All of the code in the Main
NOTES
method is at the first level of the call hierarchy. The properties and methods in
Customer and Order are at the second level of the hierarchy. There is a Total
property and an AddItem method, where the AddItem adds the item parameter
to the orderItems collection. Total iterates through the orderItems collection,
first calculating then returning the sum of all items.
Here, every class which is used has a different purpose, which is related
to how it is named. The reason of using the class helps to select what methods
and data that class will have. The class Customer has Discount and
GetOrderDiscount and the Order class has Total and AddItem. Every object
communicates with other objects cooperating to perform a task.
For example, it is Customer’s duty to calculate a discount. The reason is
that the Customer class identifies what the discount should be. Though, Customer
have to communicate with Order because here the Order is the only object
which knows about the order items. The customer also calculates the total.
Development-Time Code Tools
One of the new features of VS 2010 is Call Hierarchy that allows you to see
what code calls a method and which methods are being called by your code.
It offers different things about code and it also consists of the impact of a
change, degree of reuse, and potential importance of a routine. Consider an
example, as shown in Figure 10.1, where the GetOrderDiscount method is the
called code and the Main method is the call site.

Fig. 10.1 Call Hierarchy Window


Self-Instructional
Material 129
Debugging Methods From the perspective of reuse, different call sites to a method which
indicates that the method is relatively generic and reusable. While a low number
of call sites might not indicate that the reusability of a method. A large number
of call sites may also indicate that a change to a method can have a significant
NOTES impact. Looking at the number of call sites that a method has could be informative
from the perspective of passing different values or seeing how many changes
will be required in called methods.
Now, let’s look at how call hierarchy works. First, remember that call
hierarchy is context-sensitive, meaning that whatever code in the editor has
focus defines your point of view. The point of view for this example will be the
GetOrderDiscount method in the Customer class, and we want to see the call
sites of GetOrderDiscount and what statements inside of GetOrderDiscount are
call sites. To use call hierarchy, either right click the GetOrderDiscount method
in the editor and select View Call Hierarchy, or select GetOrderDiscount in the
editor and press CTRL-K, T. VS shows the Call Hierarchy window in Figure
10.1.
The Call Hierarchy window displays Calls To and Calls From for the
GetOrderDiscount method. Calls From is a list of statements inside
GetOrderDiscount that are call sites for other class membersCalls From is a list
of statements within GetOrderDiscount that are call sites for other class members.
As shown in Figure 10.1, the drop-down list at the top left, with My
Solution selected. It shows that how far-off the Call Hierarchy will look to find
Calls To and Calls from call sites. The options are Current Project, My Solution,
and Current Document etc. When you view Call Hierarchy, then the selected
item is added to the list. To delete an item from the list, you can use the
Remove Root button. The Toggle Details Pane button represents and hides the
Details pane. This displays the code and location of the call site.
As you can see In Figure 10.1, when the Main method is selected, this
indicates the call to GetOrderDiscounts off the cust instance of Customer. You
can double-click any call site in the Call Hierarchy to direct to the location of
the call site in the editor. The Call Hierarchy demonstrate that all of the possible
paths which can be taken with the help of a particular point in code. While
debugging, you required to view the running state of an application which is at
a particular point in time.
Configuring Debug Mode
By default, Visual Studio build projects with Debug mode enabled. It also
identifies project settings which makes it possible to debug your application.
The Visual Studio toolbar shows that the current configuration settings will
displays the Debug and Release configurations. The Release configuration

Self-Instructional
130 Material
describes settings for your program which you want to use, when you organize Debugging Methods

it for production. The custom configuration allows you to set project properties.
The Debug configuration is selected in the toolbar, then double-click the
properties folder of your project and click the Build tab (as shown in Figure
NOTES
10.2). It indicates that optimizations are turned off and both DEBUG and
TRACE and are defined. The compiler will perform extra processing on the
code, in case, when optimizations are turned on. This makes it smaller and
faster and varying the structure of the code.

Fig. 10.2 Build (C#) and Compile (VB) Properties tab

The build of your application will produce different files which are suitable
for debugging. If you want to view these files then right-click the solution 
project  folder in Solution Explorer and then select Open Folder in Windows
Explorer.
As shown in Figure 10.3, navigate to the bin\Debug folder. You will find
four files i.e. two for the applications and two for the support running in the
debugger. Here the DebugAndTestDemoCS.exe is the executable console
application. A symbol file *.pdb shows that it helps synchronize the identifiers
in your code with the executable file and it will be easier to step over code with
the Visual Studio debugger.

Self-Instructional
Material 131
Debugging Methods

NOTES

Fig. 10.3 Debug Output Folder

There are two files with vshost in their name like a *.vshost file creates
your application load faster while debugging. It provides you the ability to test
your application with the help of various security configurations. This also provides
you to calculate expressions while debugging.
In the above Figure, the vshost files are used for debugging. You should
not organize them with your application because these files can have extra
space and not serve a purpose. Open the properties page and then click the
Debug tab as shown in Figure 10.4. Here, you can see that the Platform is set
to x86 and the configuration is set to Debug. Depending on the CPU you are
building the application on, the platform target can be Any CPU, x86, x64, or
Itanium.

Self-Instructional Fig. 10.4 Debug Properties


132 Material
Your Active solution platform may show as Active, if you’re running Debugging Methods

Visual Studio on a 64-bit operating system. The Start Action section of the
Debug tab regulates that how the debugging session begins.
Mostly, you only use the Start Project for a desktop application. The
NOTES
property pages automatically run in a browser and change for Web applications.
You can add a space-separated list of values for command-line arguments. If
you are constructing an application which is required to be run from a command
window or from a command script. It is very helpful to debug and test specific
command-line configuration.
You can then read the values you’ve entered into the Command Line
Arguments text box. By reading them from the args array passed to the Main
method. A working directory is the root location where your program reads and
writes files. By default, this location is bin\Debug for Debug configurations and
bin\Release for Release configurations. You can change the working directory
location by putting a file path in the Working Directory property box.
In Remote Machine, you can debug an application which is executing on
a remote machine. But you are required to install remote debugging software on
the remote machine. The Visual Studio has the capability to debug unmanaged
code like the code which is written in C++ and that code can communicates
directly with the operating system.
Visual Studio allows you to open SQL Server stored procedures, set a
breakpoint and also step through the stored proc code for debugging. If you
need to debug stored procedures, make sure you have to check this box.
Figure 10.5 shows different debugging options.

Fig. 10.5 Debugging Options

Self-Instructional
Material 133
Debugging Methods Figure 10.5 shows various options which allows you to configure debugging.
The main difference between Options settings and Project settings is that the
project settings are for that one project, but with Options settings you can
change the settings for all projects.
NOTES
10.2.1 Setting Breakpoints
Breakpoints are the places where you want the program to automatically pause
from running. It is same like while watching a movie with your home DVD or
Blu-ray player, you push the pause button. Once your program stops on your
breakpoint, then you will be able to accomplish debugging tasks. It could be
viewing the values of variables at the program state. It also evaluates the
expressions, then works on editing code and continuing execution.
Creating A Breakpoint
To create a breakpoint, you required to open a project and open a code file
in the editor. In the Visual Studio editor, you can see on the left side, there are
margin and when you click in this margin, then Visual Studio will set a breakpoint
on the matching code statement. In code, by clicking a statement which gives
it the focus and then pressing F9 sets a breakpoint too. As shown in Figure
10.6, you can see there is a red dot in the margin and the matching statement
emphasized in red.

Fig. 10.6 Creating a Breakpoint

In debug mode, you can start the program running which is done by
selecting DebugStart Debugging press F5. The breakpoint line will turn

Self-Instructional
134 Material
yellow, when the program hits the breakpoint and on the red dot, there will be Debugging Methods

a yellow arrow in the margin.


Customizing a Breakpoint
You can customize the program and stop executing which is based on different NOTES
criteria such as hit count, conditions, and more. To see what else is available,
set a location breakpoint and then right-click the dot in the margin to view the
context menu. Table 10.1 describes each of the breakpoint options available
from the breakpoint context menu.
Table 10.1 Options from the Breakpoint Context Menu

Options Meaning
Condition Allows you to enter an expression that can cause the program to
stop if either the expression identifies true or the value of a variable
has changed.
Delete Breakpoint It removes the Breakpoint
Hit Count Makes the program break on that line every time and after a
number of times the line has executed, when the count is a multiple
of a number or when the number of hits is greater than or equal to
a number.
Disable/Enable It disable or enable a Breakpoint
Breakpoint
Location This is set when you click in the margin.
Filter The Breakpoint will only be hit for any combination of machine,
process or thread choice that you set.
When Hit Sets a tracepoint that prints a message to the output window.
Hit Count It makes the program break on that line every time, after a number
of times the line has executed.

Managing Breakpoints
In your project, the breakpoints can be set across different locations. These
breakpoints can be managed in a central location and which can be done by
selecting Debug  Windows  Breakpoints as shown in Figure 10.7.

Fig. 10.7 Breakpoints Window

With the help of Search box you can filter breakpoints. The Columns box
helps to provide focus on what the search applies to. On the toolbar, the export
Self-Instructional
Material 135
Debugging Methods and import buttons allows to save and recover breakpoints to and from an
XML file.
When you double-click any breakpoint, then you move to a location in
the editor where the breakpoint is set. After setting the breakpoint, you can go
NOTES
with the code to see what the execution flow of the program is.
10.2.2 Stepping through the Code
It is the process of executing one or more lines of code and these are executed
in a controlled manner. Table 10.2 shows the stepping operations through the
code.
Table 10.2 Step Operations

Operation Explanation
Step Into Specific When the current line is on a method call, a step into will move control
to the first line of the method being called and execution will pause
there.
Step Over Executes the code in the current line and moves to the next line of
code where it again pause, waiting for the instruction.
Run to Cursor Sometimes you want to execute a block of code and stop at a certain
line. You could set another breakpoint and run until you it the
breakpoint. To do this right click the line and select Run to Cursor.
Step Out If you are in a method, you can move back to the caller by performing
a Step Out operation. Perform a Step Out by selecting Debug Step
Out, pressing SHIFT-F11, or clicking the Step Out button on the
toolbar.
Set Next Statement You can skip forward and backward over multiple lines of code
without executing the skipped code.

10.2.3 Inspecting Application State


Application state is the values of variables in your code and information that
specifies about what the program is doing. You can perform a Step Out by
selecting Debug  Step Out, pressing SHIFT-F11, or clicking the Step Out
button on the toolbar. When you are debugging the code, then it must be take
care to view application state. You must compare what is happening to what
you expected to happen.
10.2.4 Locals and Autos Windows
The Locals and Autos windows display you the variables in your system at the
current breakpoint. Locals provides you a list of all variables that the current
statement can access. The Autos window displays the variables from the current
and previous lines.
You can open the Locals and Autos windows using Debug  Windows
Menu, when your Visual Studio debug session is active and paused at a
breakpoint. Figure 10.8 shows that the Locals window displays all of the
variables in scope for the Main method.
Self-Instructional
136 Material
Debugging Methods

NOTES

Fig. 10.8 Locals Window

Fig. 10.9 Autos Window

Notice that the Autos window provides a more fine-grained view of both
variables and the properties of objects from the current and previous lines. You
would want to use Autos for a more targeted view of what is currently happening
in the code.
10.2.5 Watch Windows
A Watch window allows you to create a custom list of variables to watch. In
the Watch window, you can drag and drop variables or type a variable name
from the editor. This is done by selecting Debug  Windows  Watch, which
will show a list of four Watch windows. Figure 10.10 displays a Watch window
with a variable.

Fig. 10.10 Watch Window

The Locals and Autos windows can sometimes become crowded with
too many variables and slow you down as your code gets more complex,
especially when the variables you’re interested in are at the bottom of the list
or so far apart that you must scroll between them. The main advantage of the
Watch window is that you can drill down into an object to show a value without

Self-Instructional
Material 137
Debugging Methods increasing the tree view. For example, as shown in Figure 10.10, type
cust.Order.Total to see the output of the Totals property of the Order property
of the cust instance.
By double-click the current value, you can edit the values of your variables
NOTES
and properties in this window. When these value changes, it changes the color
from black to red.
10.2.6 The Immediate Window
The Immediate window allows you to type in variable names and lots of other
types of statements. You can open the immediate window by selecting Debug
 Windows. You can access immediate window through which it may open
automatically during debugging at the bottom-right side of Visual Studio.
Figure 10.11 shows that the Immediate window has three statements,
which consists of execute a method, read a property, or evaluate an expression.

Fig. 10.11 Immediate Window

10.2.7 The Call Stack Window


At the design time, the Call Hierarchy window provides a view of the code.
While debugging, there is the Call Stack window which is previously open on
the right-bottom of Visual Studio in a tab next to the immediate window.
Depending upon your initial Visual Studio environment setup, you can open this
window and from the top menu bar, this can be done by selecting Debug 
Windows Call Stack.
From Main, you can view the current execution path of the application
to where your current line of execution is. Figure 10.12 displays the Call Stack
window. In the Call Stack window, there is the GetOrderDiscount method. In
the Call Stack window, by double-click another method you will move to the
call site where a given method was called.

Self-Instructional
138 Material
Debugging Methods

NOTES

Fig. 10.12 Call Stack Window

10.2.8 The Quick Watch Window


The Quick Watch window allows you to quickly view an expression. When
writing the expression, it provides the Intellisense and also permits to revaluate
the expression. This add the expression to a Watch window. You can access
the Quick Watch window by selecting Debug  Quick Watch or by pressing
CTRL-D, Q.

Fig. 10.13 Quick Watch Window

Figure 10.13 displays the Quick Watch window in use. It shows the
results of calculation in the Value area. The Value area contains the current
expression.
10.2.9 Watching Variables with Pin to Source
While debugging, you can hover over any variable to see its value, but when
you move the mouse away, the tooltip with the value goes away. The Pin To
Source feature goes a step further by displaying the value all the time. To use
Self-Instructional
Material 139
Debugging Methods Pin To Source, right-click the variable and select Pin To Source. Alternatively,
you can hover over the variable in the debugger and click the push-pin that
shows with the tooltip.
Once you’ve pinned a value, you can continue debugging and scroll back
NOTES
up to the variable to read its current value. In addition to seeing the value, you
can add a comment by clicking the chevron that appears when you hover over
the pinned value.

Fig. 10.14 A Pinned Value

10.2.10 Working with IntelliTrace


The IntelliTrace window gives you a view of all the changes which have been
occurred in an application in a debugging session. The IntelliTrace window
shows every step of the debugging session.
You can set the view for Diagnostic Events or Call View, through the
IntelliTrace toolbar. Diagnostic events allows you to filter by Category or Thread.
By clicking each of the items of the IntelliTrace window, it allows you to view
application state as shown in Figure 10.15.

Self-Instructional Fig. 10.15 The Debug History Window


140 Material
If you stepped over a statement that changed the value of a variable then Debugging Methods

IntelliTrace could be useful. Figure 10.15 displays the highlighted event. It


allows you to view Call Stack or Locals. The IntelliTrace is used to inspect
IntelliTrace log files which would be produced by another developer. You can
access IntelliTrace options by selecting Tools  Options  IntelliTrace. It will NOTES
create a log file that exists as long as Visual Studio is running. When Visual
Studio stops, then the log file is deleted. The location of the log file is on the
Advanced branch of IntelliTrace in Tools  Options.

Check Your Progress


1. What is the use of call hierarchy?
2. What are breakpoints?
3. What is application state?

10.3 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. Call Hierarchy allows you to see what code calls a method and which
methods are being called by your code. It offers different things about
code and it also consists of the impact of a change, degree of reuse, and
potential importance of a routine.
2. Breakpoints are the places where you want the program to automatically
pause from running.
3. Application state is the values of variables in your code and information
that specifies about what the program is doing.

10.4 SUMMARY

 Visual Studio debugger is used to fix problems by setting breakpoints,


stepping through code, and inspecting program state.
 One of the new features of VS 2010 is Call Hierarchy that allows you
to see what code calls a method and which methods are being called by
your code. It offers different things about code and it also consists of the
impact of a change, degree of reuse, and potential importance of a routine.
 By default, Visual Studio build projects with Debug mode enabled. It also
identifies project settings which makes it possible to debug your application.
The Visual Studio toolbar shows that the current configuration settings
will displays the Debug and Release configurations.
 Breakpoints are the places where you want the program to automatically
pause from running.
Self-Instructional
Material 141
Debugging Methods  In your project, the breakpoints can be set across different locations.
These breakpoints can be managed in a central location and which can
be done by selecting Debug  Windows | Breakpoints.
 Application state is the values of variables in your code and information
NOTES
that specifies about what the program is doing.
 The Locals and Autos windows display you the variables in your system
at the current breakpoint.
 A Watch window allows you to create a custom list of variables to
watch.
 The Immediate window allows you to type in variable names and lots of
other types of statements.
 The Quick Watch window allows you to quickly view an expression.
 The IntelliTrace window gives you a view of all the changes which have
been occurred in an application in a debugging session.

10.5 KEY WORDS

 Breakpoints: These are the places where you want the program to
automatically pause from running.
 Watch Window: It allows you to create a custom list of variables to
watch.
 Quick Watch Window: This window allows you to quickly view an
expression.

10.6 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer Questions


1. Discuss the significance of call hierarchy window.
2. What does Debug and Release configurations describes?
3. What are breakpoints? Discuss their advantages.
4. What do you understand by stepping through the code?
5. Write the note on the following:
(i) Watch window
(ii) Immediate window
(iii) Call stack window
(iv) Quick stack window
Self-Instructional
142 Material
Long Answer Questions Debugging Methods

1. How you will create, customize and manage the breakpoints? Explain.
2. What are the various options from the Breakpoint Context Menu?
3. Explain the various step operations. NOTES

4. What does locals and autos window provides?


5. What is the need for IntelliTrace? Explain.

10.7 FURTHER READINGS

Bronson Gary and David Rosenthal. 2005. Introduction to Programming with


Visual Basic .NET, Burlington, Massachusetts: Jones & Bartlett Learning.
Liberty Jesse. 2003. Programming Visual Basic .NET. Sebastopol, California:
O’Reilly Media, Inc.
Mayo Joe. 2010. Ms Visual Studio 2010. Noida: Tata McGraw-Hill.

Self-Instructional
Material 143
Working with Databases

UNIT 11 WORKING WITH


DATABASES
NOTES
Structure
11.0 Introduction
11.1 Objectives
11.2 Introduction to Server Explorer
11.2.1 Creating a Database
11.2.2 Adding Tables
11.2.3 Relating Tables with Foreign Keys
11.2.4 Adding Stored Procedures
11.2.5 Configuring Database Options
11.3 Answers to Check Your Progress Questions
11.4 Summary
11.5 Key Words
11.6 Self Assessment Questions and Exercises
11.7 Further Readings

11.0 INTRODUCTION

In this unit, you will learn about the working with databases. Visual Studio provides
different types of tools for working with databases. But Visual C# Express and
Visual Basic Express are the free express versions of Visual Studio and these
don’t have this built-in support. But, you can go to MSDN and from there you can
download the free SQL Server Express. This SQL server is used for database
work alongside the Express versions.

11.1 OBJECTIVES

After going through this unit, you will be able to:


 Open the server explorer
 Create and manipulate the database
 Use various options of configuring database

11.2 INTRODUCTION TO SERVER EXPLORER

To start working with databases in visual studio, first you have to start Visual
Studio and then open Server Explorer by clicking View  Server Explorer or
pressing CTRL-ALT-S.

Self-Instructional
144 Material
Working with Databases

NOTES

Fig. 11.1 Server Explorer

Server Explorer permits you to work with databases like SharePoint and
servers. These databases provides you the access to different types of services
for handling an operating system. For example it consists of Performance Counters,
Event Logs, and Services.
During development in Visual Studio, it is very suitable to be able to access
these services, like if you required to restart an operating system service, then you
can do it rapidly. The Data Connections (as shown in Figure 11.1) have a list of
databases which can be selected and work with.
Initially, you must add connections yourself and the list will be empty. This
can be done by right-clicking Data Connections and configuring the database
settings. So, here you can find out that the process of connecting to an existing
database is similar to the task for creating a database.
11.2.1 Creating a Database
As we know that, with the help of Visual Studio Standard and higher, there is no
requirement for external tools which are used to create a simple database because
there is built-in support for getting started. There are advanced situations arises
where a database administrator required to use the SQL Server tools. These SQL
server tools are used to create the database themselves. Sometimes, you can
create the database yourself to get started.

Fig. 11.2 Create New SQL Server Database Window Self-Instructional


Material 145
Working with Databases If you want to create a database then in Server Explorer right-click Data
Connections and select
Create New SQL Server Database. Figure 11.2 shows Create New SQL
NOTES Server Database Window. Here, the server name is laptop-nvb9jiqo which depends
on your system server name. The server name laptop-nvb9jiqo represents the
name for the SQL Server Express database. The Server names can be different
which is based on the location of the server.
The authentication can be done using any of the two ways i.e. SQL Server
and Windows. We are taking the simplest one that is Windows authentication.
Here the local database created and there is another database already created. It
is built on a server at another location.
11.2.2 Adding Tables
Figure 11.3 shows a database that holds data for customers, orders details and
order. To create a table in a database in Server Explorer, you have to right-click
the Tables branch and then select Add New Table.
The Table Designer permits you to configure the data type (like integer,
date, float, or character) and add columns. Figure 11.3 displays a table having
two columns, CustomerID having data type int and Name of data type is nvarchar
(50). You have to make sure that the Null is unchecked for each column to avoid
errors in code.

Fig. 11.3 Customer Table

Here, CustomerID is a primary key. It is created by right-clicking the column


and then selecting Set Primary Key. You can press CTRL and click on each column

Self-Instructional
146 Material
which belongs to the key and then right-click and select Set Primary Key. This is Working with Databases

the case only if you needed a composite key.


If you want to set the primary key, then you have to make the key number
auto-increment. It will help to have a unique value for every record you insert. NOTES
Figure 11.3 shows that the Column Properties has scrolled down to the Identity
Specification property and theCustomerID is selected. You can enlarge the Identity
Specification property and this is done by selecting the arrow on the left. You can
change the value of the “Is Identity” to Yes using the drop-down arrow on the right
which is No by default. It will enable the Identity Increment. The identity increment
identifies the number to add for each new record. The identity Seed specifies
about what the first number will be.
When you set the Identity Increment then the result is that the first record
added to the table will have a CustomerID having the value 1. Similarly the
succeeding records having CustomerID with the values 2, 3, 4 and so on. The
CustomerID value in each record generates a unique value and this value specifies
the record. It will make easy to program data applications.
Click the Save button on the toolbar after completion of creating the table.
You can also name the table as Customer. You can add data to the Customer table
after opening the database in server explorer. Figure 11.4 shows how to add data
to tables.

Fig. 11.4 Adding data to a table

You are required to enter the name in the Name column. It not required to
enter values in the CustomerID column as it gets auto-increment.
In case of complex databases, you can have multiple tables. For example,
in MyShop database, a Customer has an Order. A new table is required named as
Order having fields OrderID (primary key), OrderDate and CustomerID as shown
in Figure 11.5.

Self-Instructional
Material 147
Working with Databases

NOTES

Fig. 11.5 Order Table

You can see the Description in the Column Properties for the CustomerID
field that is FK (foreign key) to Customer. This foreign key is used to create a
relationship between a parent table and a child table.
11.2.3 Relating Tables with Foreign Keys
The FK (Foreign keys) permits you to create a relationship between two tables.
Here, we are taking the relationship between two tables i.e. Customer and Order
where Customer is the parent and Order is the child table.
The rule is that one record in Customer could have multiple records in
Order. The customers can have zero or more orders. The foreign key which is
used to accomplish the relationship between Customer and Order. If you want to
create the foreign key relationship, then right-click on the CustomerID column in
the Order table and select Relationships.
You can click Add, and select the Tables and Columns Specific property.
After that click the ellipses button which acts on the far right of your selection until
you first click “Tables And Columns Particular” below in the Foreign Key
Relationships dialog window. Figure 11.7 shows the Tables and Columns window
(when open).

Self-Instructional
148 Material
Working with Databases

NOTES

Fig. 11.6 Handling a Foreign Key Relationship

Fig. 11.7 Organising a Foreign Key Relationship

You can select Customer by drop-down menu of primary key table. This
spontaneously selects the primary key that is CustomerID. In Foreign Key Table,
there is an OrderID which is the primary key of the order table. You have to
Select OrderID and then change it to CustomerID as the foreign key column.
After that you can click OK to exit. Click Close to complete creation of the
foreign key relationship.
Self-Instructional
Material 149
Working with Databases To save the new foreign key relationship, click Save as shown in Figure
11.8. You can add a few records to the Order table, but make sure that the
CustomerID should match an existing CustomerID in the Customer table because
of the foreign key relationship.
NOTES

Fig. 11.8 Foreign Key Relationship Save Warning Message

You might want best structure of database and relationships while working
with multiple tables. You can use the database diagrams while maintaining this
relationship. If you want to create a database diagram, then under the database in
Server Explorer, right-click the Database Diagrams folder and click Add New
Diagram. When you receive an information message then click yes that displays
about the creation of objects for database diagramming. In the Add Table window,
select multiple rows, press the CTRL key. Figure 11.9 shows the database diagram.

Fig. 11.9 A Database Diagram


Self-Instructional
150 Material
The database diagram displays information about tables, relationships and Working with Databases

columns. You can use this window to add new tables and relationships. When you
want to create a new table Right-click the design surface, then select Add Table
and after that you can use the Visual Designer to organize the table.
NOTES
To create a foreign key relationship, in the child table, click the foreign key
column, then drag the carat to the parent table. Drop the carat on the primary key
of the parent table. After completion of the above steps, complete the database
diagram and also give a name to the database diagram.
The database diagram has some features like, printing, navigation and multiple
diagrams. You can click the symbol with the four arrow heads at the lower right-
hand corner of the database diagram, in case, when you have a database diagram
larger than the screen size. Now you have to move the mouse to speedily navigate
through the document.
Multiple diagrams can be added to the Database Diagrams folder which
permits you to have multiple different views for your convenience.
11.2.4 Adding Stored Procedures
A stored procedure is code is written in SQL. It is saved as part of a database.
The stored procedure is a method stored in the database itself. If you want to add
a stored procedure in Server Explorer, Right-click on the Stored Procedure folder
for the database and select Add New Stored Procedure.
There will be an editor with skeleton code for a stored procedure. You can
alter the code so that it recovers all of the data from the Customer table as shown
in Example 11.1. After complete alteration of the template code, click Save. You
can see that the stored procedure appear in the Stored Procedures folder of the
database in Server Explorer.
Example 11.1: Using Stored Procedure
CREATE PROCEDURE GetCustomers
AS
declare @cust_count int
select @cust_count = count(*) from Customer
if @cust_count > 0
begin
select [Name] from Customer
end
return
The code given above shows that @cust_count is a variable named. It runs
a select statement to allocate the number of customers, count (*), to @cust_count.
Consider if the value of @cust_count is larger than 0, it means there are the stored
procedure queries and the customers for customer names. When you want to
implement this stored procedure, you have to right-click the stored procedure in
Self-Instructional
Material 151
Working with Databases the database in Server Explorer and click Execute. The output is shown below
which is similar to the following if there are records in the customer table.
Running [dbo].[GetCustomers].
Name
NOTES
Meg
Joe
May
No rows affected.
(3 row(s) returned)
@RETURN_VALUE = 0
Finished running [dbo].[GetCustomers].
You can also manipulate the stored procedure in Visual Studio. If you want
to debug, then set a cut-off point on any line in the stored procedure and in Server
Explorer, right-click the stored procedure and click Alt + F5.
11.2.5 Configuring Database Options
Visual Studio has various database configuration settings and that can be viewed
with the help of Tools  Options menu and selecting Database Tools as shown in
Figure 11.10.

Fig. 11.10 Using Database Tools Options

Visual Studio does not permits you to save a change in foreign key to existing
tables. But, by de-selecting “Prevent saving changes that require table re-creation”,
you can save changes in foreign key to an existing table.

Self-Instructional
152 Material
Working with Databases

Check Your Progress


1. What are the two ways to log on to the server while creating a database?
2. Write some of the features of database diagram. NOTES

11.3 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. You can log on to server using one of the two ways:


(i) Window authentication
(ii) SQL server authentication
2. The database diagram has some features like, printing, navigation and multiple
diagrams. You can click the symbol with the four arrow heads at the lower
right-hand corner of the database diagram, in case, when you have a
database diagram larger than the screen size.

11.4 SUMMARY

 Visual Studio provides different types of tools for working with databases.
 If you want to create a database then in Server Explorer right-click Data
Connections and select Create New SQL Server Database.
 The authentication can be done using any of the two ways i.e. SQL Server
and Windows.
 To create a table in a database in Server Explorer, you have to right-click
the Tables branch and then select Add New Table.
 The Table Designer permits you to configure the data type (like integer,
date, float, or character) and add columns.
 The FK (Foreign keys) permits you to create a relationship between two
tables.
 You can use the database diagrams while maintaining this relationship. If
you want to create a database diagram, then under the database in Server
Explorer, right-click the Database Diagrams folder and click Add New
Diagram.
 The database diagram displays information about tables, relationships and
columns. You can use this window to add new tables and relationships.
 The database diagram has some features like, printing, navigation and multiple
diagrams. You can click the symbol with the four arrow heads at the lower

Self-Instructional
Material 153
Working with Databases right-hand corner of the database diagram, in case, when you have a
database diagram larger than the screen size.
 A stored procedure is code is written in SQL. It is saved as part of a
database. The stored procedure is a method stored in the database itself.
NOTES

11.5 KEY WORDS

 Primary Key: It is a field in a table which uniquely identifies each row/


record in a database table.
 Foreign Key: It is an attribute of one relation whose values are required to
match those of the primary key of some relation.

11.6 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer Questions


1. Discuss the process of adding the tables in a database.
2. What is the use of Table Designer?
3. How you will create the database diagram?
Long Answer Questions
1. How you will create a database? Explain.
2. Explain how you will relate the two tables using the foreign key.
3. Describe the usage of stored procedure with the help of an example.

11.7 FURTHER READINGS

Bronson Gary and David Rosenthal. 2005. Introduction to Programming with


Visual Basic .NET, Burlington, Massachusetts: Jones & Bartlett Learning.
Liberty Jesse. 2003. Programming Visual Basic .NET. Sebastopol, California:
O’Reilly Media, Inc.
Mayo Joe. 2010. Ms Visual Studio 2010. Noida: Tata McGraw-Hill.

Self-Instructional
154 Material
Building Desktop
BLOCK - V Applications with WPF
BUILDING PROGRAMS WITH VS 2010

NOTES
UNIT 12 BUILDING DESKTOP
APPLICATIONS WITH WPF
Structure
12.0 Introduction
12.1 Objectives
12.2 Starting a WPF Project
12.3 Understanding Layout
12.3.1 Grid Layout
12.3.2 StackPanel Layout
12.3.3 DockPanel Layout
12.3.4 WrapPanel Layout
12.3.5 Canvas Layout
12.4 Answers to Check Your Progress Questions
12.5 Summary
12.6 Key Words
12.7 Self Assessment Questions and Exercises
12.8 Further Readings

12.0 INTRODUCTION

Windows Presentation Foundation (WPF) is a .NET technology which is used for


building desktop applications. The output of making a WPF application is an *.exe
file. You can run this file directly on the computer. You can organise and run the
*.exe file on any other computer which has .NET installed. You can improve a
graphical user interface (GUI) in WPF. It makes easier for users to work with the
program. In this unit, you will learn about WPF controls, like TextBox, Button etc.
You will also learn how to build a WPF GUI with the Visual Studio Designer.
XAML is an XML format which Silverlight and WPF use to outline a GUI.

12.1 OBJECTIVES

After going through this unit, you will be able to:


 Start a WPF project
 Work with different types of layout

Self-Instructional
Material 155
Building Desktop
Applications with WPF 12.2 STARTING A WPF PROJECT

To start a WPF Project, open the New Project windowselect WPF


NOTES Applicationfill in the project name, location, and solution name. For example
consider there are large number of customers who buy products from MyShop as
shown in Figure 12.1. It displays the new WPF application in Visual Studio which
also consists of a Designer, a Toolbox and a Solution Explorer.
The Designer allows you to lay out the UI of the application. It is divided
into two sections i.e. Design section and XAML section. The Design surface allows
to visually work with controls and layouts of those controls. With the help of
XAML editor, you can work with XML representation of the controls on the
design surface. The Design and XAML are related because a change in one causes
a change in the other. Like, if you add a Button to the Design, then the result will
be the XML representation of that Button in the XAML.
The Toolbox consists of different controls, like user interface (UI) elements.
For example, you can drag and drop Button and Textbox onto the Designer.

Fig. 12.1 Starting a new WPF Application Project

In the same way, if you add a TextBox element to the XAML, then the
result will be a visual representation of that TextBox in Design. There are different
controls for controlling the windows. Both Design and XAML have zoom controls.

Self-Instructional
156 Material
On Design the zoom tool is a slider which is displays in the upper-left corner. Building Desktop
Applications with WPF
Similarly zoom for XAML is represented like drop-down control in the lower-left
corner. You can also zoom by clicking either Design or XAML and moving the
mouse wheel.
NOTES
At the upper right of XAML editor, you can switch between vertical and
horizontal splits of the window. You can also click the chevron to breakdown the
XML. Below the chevron the splitter icon allows you to split the XAML editor
into two if you drag it down.
The up-down arrow between the Design and XAML tabs allows you to
switch sides so that each panel shows where the other was.

12.3 UNDERSTANDING LAYOUT

A layout defines how you can position and size controls on a screen. WPF controls
and Windows have a Content property which accepts a single control. In some
cases, such as a Button control, the content can be text. However, many situations
call for the ability to lay out multiple controls.
WPF consists of different layout controls, including StackPanel, Grid,
WrapPanel, DockPanel, and Canvas. In Visual Studio, you will generate a window
with a Grid as the layout control. The Grid can be replaced with any other layout
control that suits your needs.
12.3.1 Grid Layout
Visual Studio adds a Grid whenever you start a new WPF project. A Grid is
arrangement of controls that allows you to create a set of rows and columns which
hold other controls. With the help of Visual Designer, you can add rows and columns
to a Grid (by clicking in the middle of a window) in design view.
Figure 12.2 displays a column being added to a Grid. The thin vertical line
in the middle of the window is a new border between two columns. When you
click the window, you can check that there are two thick borders on the left and
top of the window. Visual Studio draws a vertical line that moves left and right as
you run your mouse along the top border. You can do the same with the left
border, adding rows to the Grid. This is a very quick way to add rows and columns
to a Grid.

Self-Instructional
Material 157
Building Desktop
Applications with WPF

NOTES

Fig. 12.2 Adding Columns and Rows to a Grid

The arrow in the Grid border allows you to reposition the column or row
border. You can remove the column or row border by selecting the arrow in the
Grid border and dragging the arrow off the window.
After you have generated rows and columns, you can add more
customizations which describe how much space the column or row can take.
Figure 12.3 shows that there are three sizing customizations: weighted, fixed and
auto. Hover over the column or row border so that to set each of these options.
Visual Studio shows a sizing panel over the left column design border as shown in
Figure 12.3.
On the left side, there is a diamond icon displays which means fixed and the
size will stay the same. As shown in Figure below, in the middle is a weighted
proportion, there is asterisk icon, where the size stays the same in relation to the
other columns.

Self-Instructional
158 Material
Building Desktop
Applications with WPF

NOTES

Fig. 12.3 Row and Column Sizing Options

You can see there is rightmost icon i.e. auto which means the size will vary
according to whatever space leftovers after the other column’s sizes are set. You
can use these sizing options to experiment with the help of layout which you want
when you add content to your Grid.
As shown in Figure 12.3, there are number in the Grid border for each row
and Column and these numbers shows the size in pixels for each row and column
they appear upon. There is the Properties window on the right, where you can
customize and select the Column and Row collections.
12.3.2 StackPanel Layout
When you want to outline controls each on top of the other, like a stack, then a
stack panel layout is used. A StackPanel is used by dragging the StackPanel control
from the Toolbox onto the design surface.

Self-Instructional
Material 159
Building Desktop
Applications with WPF

NOTES

Fig. 12.4 Using a StackPanel Layout

The StackPanel can be used as a primary layout, which is done by selecting


the grid that is added (by default) to a new project and also delete the Grid. As
shown in Figure 12.4 which displays a StackPanel that consists of various button
controls.
In Figure 12.4, the StackPanel will always arrange these controls as one
after the other. The StackPanel can also displays controls horizontally. This can be
done by changing the Orientation property,as shown in the Properties window.
12.3.3 DockPanel Layout
Visual Studio allows you to dock windows inside the borders of the application
and this help to organize the screen so that you can use different tools at one time.
You can outline the controls the same way with the DockPanel control. This
can be done by dragging and dropping a DockPanel control from the Toolbox to
theWindow in the design surface.
You could remove the default Grid also. The DockPanel modifies with a
Height and a Width, and this modification can be done by selecting the DockPanel
and opening the Properties window and then clearing the Height and Width
properties.

Self-Instructional
160 Material
Building Desktop
Applications with WPF

NOTES

Fig. 12.5 Using the DockPanel Layout

Deleting the Height and Width properties allows the DockPanel to expand
and cover the whole window. Figure 12.5 displays a DockPanel with Label controls
in every docking position.
When you drag and drop a control on the design surface of a DockPanel,
then by default the control will take the center position. This can be done by
opening the Properties window and then set the DockLayout.Dock property.
When you add a new Control, it will become the center control. The
additional control will dock to the side of the DockPanel which is identified in the
Dock property.
12.3.4 WrapPanel Layout
Whenever controls naturally follow each other in sequence and continue wrapping
on new lines, you can use a WrapPanel. Figure 12.6 displays various CheckBox
controls in a WrapPanel.

Self-Instructional
Material 161
Building Desktop
Applications with WPF

NOTES

Fig. 12.6 Using the WrapPanel Layout Control

Figure 12.6 shows that how you can outline a group of controls to fill an
available space. In the case of the CheckBox controls, the alignment of the
WrapPanel is set to Horizontal (by Default).
If the number of Check Box controls fills the horizontal row then the left
over Check Boxes wrap to the next row. This is because CheckBox controls
sizes are the same, so you have the uniform layout and it is easier than trying to do
the same thing with other layout or a Grid control.
12.3.5 Canvas Layout
There are times when you might want to perform explicit layout of controls. The
canvas Layout can be used, if you were building a drawing program or a
diagramming application, or if you want to specify the location of controls. Figure
12.7 displays different controls on a Canvas layout.
The Ellipse and Rectangle controls were dragged and dropped from the
Toolbox onto the Canvas control. The properties in the Properties window are
Canvas.Top, Canvas.Left, Width, and Height which represents the entire positioning
of the selected Ellipse control.

Self-Instructional
162 Material
Building Desktop
Applications with WPF

NOTES

Fig. 12.7 Using the Canvas Layout Control

Check Your Progress


1. What is WPF?
2. Define layout.

12.4 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. Windows Presentation Foundation (WPF) is a .NET technology which is


used for building desktop applications.
2. A layout defines how you can position and size controls on a screen.

12.5 SUMMARY

 Windows Presentation Foundation (WPF) is a .NET technology which is


used for building desktop applications. The output of making a WPF
application is an *.exe file.
 To start a WPF Project, open the New Project windowselect WPF
Applicationfill in the project name, location, and solution name.
 The Designer allows you to lay out the UI of the application. It is divided
into two sections i.e. Design section and XAML section.

Self-Instructional
Material 163
Building Desktop  The Design surface allows to visually work with controls and layouts of
Applications with WPF
those controls. With the help of XAML editor, you can work with XML
representation of the controls on the design surface.
 A layout defines how you can position and size controls on a screen.
NOTES
 WPF consists of different layout controls, including StackPanel, Grid,
WrapPanel, DockPanel,and Canvas.

12.6 KEY WORDS

 Layout: It is the way in which the parts of something are arranged or laid
out.
 Grid: It is arrangement of controls that allows you to create a set of rows
and columns which hold other controls.

12.7 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer Questions


1. Write a note on WPF.
2. What are the two sections of designer?
Long Answer Questions
1. What are the different types of layouts in WPF?
2. Write a note on Grid layout.

12.8 FURTHER READINGS

Bronson Gary and David Rosenthal. 2005. Introduction to Programming with


Visual Basic .NET, Burlington, Massachusetts: Jones & Bartlett Learning.
Liberty Jesse. 2003. Programming Visual Basic .NET. Sebastopol, California:
O’Reilly Media, Inc.
Mayo Joe. 2010. Ms Visual Studio 2010. Noida: Tata McGraw-Hill.

Self-Instructional
164 Material
Using WPF Controls

UNIT 13 USING WPF CONTROLS


Structure NOTES
13.0 Introduction
13.1 Objectives
13.2 Managing Windows for Controls
13.2.1 Setting Properties
13.2.2 Handling Events
13.2.3 Coding Event Handlers
13.2.4 Working with Data in WPF
13.2.5 Configuring a Combobox
13.3 Answers to Check Your Progress Questions
13.4 Summary
13.5 Key Words
13.6 Self Assessment Questions and Exercises
13.7 Further Readings

13.0 INTRODUCTION
In this previous unit, you have learnt about the WPF projects and various layout.
WPF consists of different controls to build user interfaces. In this unit, you will
learn about different controls like containers, text, selection, information, decorators
and shapes.

13.1 OBJECTIVES

After going through this unit, you will be able to:


 Manage windows for controls
 Set properties and create event handlers
 Work with data in WPF

13.2 MANAGING WINDOWS FOR CONTROLS

When you work with controls, you have four different windows to work with i.e.
Solution Explorer, Toolbox, Properties and Designer. Table 13.1 shows the
Windows for working with Controls.
Table 13.1 Managing Windows for Controls

WINDOW KEYSTROKE MENU


Solution Explorer CTRL-W, L View Solution Explorer
ToolBox CTRL-W, X ViewToolBox
Properties Window CTRL-W, P ViewProperty Window
Designer SHIFT-F7 Double click *.xaml file in Solution Explorer
Self-Instructional
Material 165
Using WPF Controls You can see the available controls on the Toolbox from the table which are
divided into panels. The top panel is common WPF controls and this makes it
easy to find the controls you use the most. The WPF Controls tab consists of the
whole list of WPF controls. The Designer can be open by double-clicking a *.xaml
NOTES file in Solution Explorer. Select the control in the Toolbox, which is used to add a
control to the Designer and then drag the control onto the Designer. Figure 13.1
which displays a Button that has been dragged and dropped on the Designer
window.

Fig. 13.1 Adding a Control to the Visual Studio Designer

In Figure 13.1, there is a toolbox with the Button control selected. The
Designer displays a Button control and that can be dragged and dropped. Below
the Designer, the Button control appears in the XAML for this window. In the
XAML, the attributes of the Button control match the properties in the Properties
window.
13.2.1 Setting Properties
The Properties window displays different methods to configure a control. For
button controls, you want to change the Content property to make sense for
the text on the button. Here, the purpose of using the button is to allow the
user to create a new order for a customer. So, set the Content property to
New Order.
13.2.2 Handling Events
Events can be handled with the help of Events tab at the top of the Properties
window. Figure 13.2 displays the contents of the Events tab Controls have
literally dozens of events that allow you to manage their behaviour in the
application.

Self-Instructional
166 Material
You can double-click any of the events to handle an event in the Properties Using WPF Controls

window. Visual Studio will wire up that event to a handler method with a default
name.. The handler for the Click event can be implemented and this is done by
double-clicking the Click event in the Properties window Events tab. When you
double-click, VS opens a file named MainWindow.xaml.cs. Assuming you are NOTES
working with the window named as MainWindow.xaml. It is also known as a
code-behind file where you can add event handlers. In MainWindow.xaml.cs,
Visual Studio creates a skeleton method that is used to handle the Button Click
event.

Fig. 13.2 Handling Events (Properties window Events Tab)

Example 13.1: A WPF Code-Behind File


C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

Self-Instructional
Material 167
Using WPF Controls using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
NOTES
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ControlsCS
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs
e)
{
}
}
}
VB
Class MainWindow
Private Sub Button1_Click(
ByVal sender As System.Object,
ByVal e As System.Windows.RoutedEventArgs)
Handles Button1.Click
End Sub
End Class
The Click event handler is created in the method button1_Click. Essentially,
when a user clicks on the button named button1, this handler will be called.
In the XAML, Visual Studio also adds the method to the Button control as
an attribute. The code of XAML given below is independent of programming
language (whether you are coding in C# or VB).
<Button Content=”Button” Height=”23"
HorizontalAlignment=”Left” Margin=”76,43,0,0"
Self-Instructional
168 Material
Name=”button1" VerticalAlignment=”Top” Width=”75" Using WPF Controls
Click=”button1_Click” />
On the top left of the Properties window, there is the ID of the control and
can be changed from button1 to some meaningful name. For example, if the purpose
NOTES
of the button is to create a new order for a customer, you can name the button
NewOrderButton. You can now delete the event handler which is assigned to the
Click event of the Button. Figure 13.3 displays these changes in the Properties
window. Now, the event handler and ID are more readable.
The control has a new ID after the event handler is removed. Double-click
the Click event again. Example 13.2 shows the code to create a new event handler.
Example 13.2: To Create a new event handler
C#
private void button1_Click(object sender, RoutedEventArgs
e)
{
}
private void NewOrderButton_Click(object sender,
RoutedEventArgs e)
{
}
VB
Class MainWindow
Private Sub Button1_Click(
ByVal sender As System.Object,
ByVal e As System.Windows.RoutedEventArgs)
End Sub
Private Sub NewOrderButton_Click(
ByVal sender As System.Object,

ByVal e As System.Windows.RoutedEventArgs) Handles


NewOrderButton.Click
End Sub
End Class

Self-Instructional
Material 169
Using WPF Controls

NOTES

Fig. 13.3 Readable button ID and event handler name

13.2.3 Coding Event Handlers


A user clicks a button to open a window. So, the first task should be to add a new
window. For that open Solution Explorer, then right-click the project (you’re
working with) , after that select Add à New Item àchoose Window (WPF) and
name the window NewOrder.xaml, and then click Add. These steps will create a
new window opened in the Designer. Example 13.3 shows the coding event
handlers.
Example 13.3: Using coding event handlers
C#
public partial class NewOrder : Window
{
public NewOrder()
{

Self-Instructional
170 Material
InitializeComponent(); Using WPF Controls
}
}
VB
NOTES
Public Class NewOrder
End Class
Here, the class in this code is named NewOrder. You can instantiate classes
and call their methods. This method is used to open this window from the
NewOrder_Click event handle of the MainWindow.
You can populate the window just by dragging and dropping controls. For
example the Button in MainWindow.xaml.cs, go back to the NewOrderButton_
Click event handler and add the code in Example 13.4.
Example 13.4: Using coding event handlers (instantiating classes)
C#
private void NewOrderButton_Click(object sender,
RoutedEventArgs e)
{
NewOrder newOrd = new NewOrder();
newOrd.Show();
}
VB
Private Sub NewOrderButton_Click(
ByVal sender As System.Object,
ByVal e As System.Windows.RoutedEventArgs)
Handles NewOrderButton.Click
Dim newOrd As New NewOrder
newOrd.Show()
End Sub
You can call the Show method to open the window and run the program by
pressing F5.
13.2.4 Working with Data in WPF
Binding is the method of retrieving and populating the data to and from controls. In
this section, you will learn about how to show data in your user interface and how
to perform create, read, update, and delete (CRUD) operations via WPF.
Before you can bind to data in the window, you need a data source to work
with data. Consider the order and customer table with their fields.

Self-Instructional
Material 171
Using WPF Controls The Order table has the following fields:
 CustomerID, int
 Location, varchar(50)
NOTES  OrderID, int, primary key, auto-increment
 OrderDate, datetime
 Amount, money
The Customer table has the following fields:
 Name, nvarchar(50)]
 CustomerID, int, primary key, auto-increment
 Income, money
 Age, int
 Birthday, datetime
To add the data source for binding, open the NewOrder window in the
Designer, and select Data àAdd New Data Source menu. This opens the Choose
a Data Source Type window as shown in Figure 13.4.
You can connect to a data source in different ways i.e. can be connected
directly to the database,
With the help of a Web service, an object, or with SharePoint. Figure 13.5
shows how to select the Data Objects window.

Fig. 13.4 Choosing a New Data Source


Self-Instructional
172 Material
Check the box which is next to each object which you want to bind in your Using WPF Controls

application on selecting the Data Objects window. Figure 13.5 shows the Customer
and Order objects. It will configure the data source for use in the application if you
click on the Finish. As shown in Figure 13.6, you can outlook data sources by
NOTES
selecting Data à Show Data Sources.
The Data Sources window allows you to create controls on a form which
are bound to each field of a data source. As shown in Figure 13.6, in the Data
Sources window, both Customer and Object are listed with their fields. The icons
define what type of control should be related with each data field.
If you don’t want a default control type for a field then you can change it by
selecting the field. You can also select another control type from the drop-down
list as shown in Figure 13.7.

Fig. 13.5 Selecting Data Objects

Self-Instructional
Material 173
Using WPF Controls

NOTES

Fig. 13.6 Data Sources Window

Fig. 13.7 Changing the Control Type for a Field

Self-Instructional
174 Material
In Figure 13.7, the CustomerID is changed to a ComboBox to provide the Using WPF Controls

user the option of choosing a customer from a list for a new order, instead of
typing in an ID number.
If you want to create a new order form with controls bound to order data,
NOTES
then in the Data Sources window, Select the Order object and then drag and drop
the order onto the Designer of the NewOrder window. Figure 13.8 displays this
new window. It shows how Visual Studio added a Grid layout with a row for each
field and two columns in the Order table.
In our example, the CustomerID is a ComboBox and the OrderDate is a calendar.
As we know that Visual Studio allows to put spaces between the words in the
labels. The code given below shows adding controls to the Designer. Visual Studio
added the following CollectionViewSource control to the NewOrder window’s
XAML:
<Window.Resources>
<CollectionViewSource x:Key=”orderViewSource”
d:DesignSource=”{d:DesignInstance my:Order,
CreateList=True}” />
</Window.Resources>

Fig. 13.8 Controls Bound with the Help of a Data Source

Here, we need to know the name of the CollectionViewSource, which is


orderViewSource. We need to add an Order object to the CollectionViewSource
so that the controls which are bound to it have a place to save data that the user
enters. Press F7 to see the code that Visual Studio added to the Window Loaded
event handler as shown in Example 13.5.

Self-Instructional
Material 175
Using WPF Controls Example 13.5: Window Loaded Event Handler
C#
private void Window_Loaded(object sender, RoutedEventArgs
e)
NOTES
{
System.Windows.Data.CollectionViewSource
orderViewSource =
((System.Windows.Data.CollectionViewSource)
(this.FindResource(“orderViewSource”)));
// Load data by setting the
//CollectionViewSource.Source property:
// orderViewSource.Source = [generic data source]
}
VB
Private Sub Window_Loaded(
ByVal sender As System.Object,
ByVal e As System.Windows.RoutedEventArgs) Handles
MyBase.Loaded
Dim OrderViewSource As
System.Windows.Data.CollectionViewSource
= CType(Me.FindResource(“OrderViewSource”),
System.Windows.Data.CollectionViewSource)
‘Load data by setting the CollectionViewSource.Source
property:
‘OrderViewSource.Source = [generic data source]
End Sub
The skeleton code above gets a reference to OrderViewSource. The
commented portion of the code suggests how you might populate that control.
However, we are not interested in populating OrderViewSource with data because
the purpose of this screen is to insert a new record. Instead, the proper approach
is to bind an empty object. In addition to assigning a blank Order object to
OrderViewSource, we need to populate the ComboBox that holds the list of
customers and their IDs. The following code is a revision to the Window_Loaded
event handler that assigns a blank Order object to the OrderViewSource and
binds customers to the ComboBox holding customers.
C#
private void Window_Loaded(object sender, RoutedEventArgs
e)
{
var orderViewSource =
FindResource(“orderViewSource”) as CollectionViewSource;
Self-Instructional
176 Material
orderViewSource.Source = Using WPF Controls
new List<Order>
{
new Order
NOTES
{
OrderDate = DateTime.Now
}
};
customerIDComboBox.ItemsSource =
from cust in new MyShopDataContext().Customers
select cust;
}
VB
Private Sub Window_Loaded(
ByVal sender As System.Object,
ByVal e As System.Windows.RoutedEventArgs) Handles
MyBase.Loaded
Dim OrderViewSource As CollectionViewSource =

CType(FindResource(“OrderViewSource”),
CollectionViewSource)
OrderViewSource.Source =
New List(Of Order) From
{
New Order With
{
.OrderDate = DateTime.Now
}
}
CustomerIDComboBox.ItemsSource =
From cust In New MyShopDataContext().Customers
End Sub
This code shows how to assign an order to orderViewSource .It also
describes about populating customerIDComboBox with customers.
13.2.5 Configuring a Combobox
ComboBox and ListBox are more complex controls to configure because both
these controls have a few different properties and these must be set to make sure
that whatever is selected can be read and correctly referenced back to the original
data source.

Self-Instructional
Material 177
Using WPF Controls The previous example assigns the results of a LINQ query for Customer
objects to the customerIDComboBox. You must specify which property of
Customer must display, which property of Customer maps to Order, and which
property of Order to bind the selected item to. To do this binding, open the
NOTES NewOrder.xaml file in the Designer, select the combo box, and set the properties
as specified in Table13.2.
The code given below in XAML displays the results of the settings which
should be used in the Properties window.
<ComboBox DisplayMemberPath=”Name”
SelectedValue=”{Binding Path=CustomerID}”
SelectedValuePath=”CustomerID”
Grid.Column=”1" Grid.Row=”1"
Height=”23" HorizontalAlignment=”Left”
Margin=”3" Name=”customerIDComboBox”
VerticalAlignment=”Center” Width=”120">
</ComboBox>
Table 13.2 Properties of ComboBox for Data Binding

PROPERTY EXPLANATION
SelectedValuePath You need to associate the selected Customer with the
order being created. SelectedValuePath is the name
of the Customer object key, which is CustomerID in
given example.
DisplayMemberPath The Name property from each Customer object
bound to the combo box.
ItemSource It holds the collection of objects which will appear in
combo box. There are two properties, one for the key
of object being displayed. And another for display
the object.
SelectedValue It is a binding to the property of the Order that will
be set with the key from the selected Customer.

Check Your Progress


1. What are the various windows that are available, when you are working
with controls?
2. Define binding in WPF.

13.3 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. When you are working with controls, you have four different windows to
work with i.e. Solution Explorer, Toolbox, Properties and Designer.
Self-Instructional
178 Material
2. Binding is the method of retrieving and populating the data to and from Using WPF Controls

controls.

13.4 SUMMARY NOTES


 When you working with controls, you have four different windows to work
with i.e. Solution Explorer, Toolbox, Properties and Designer.
 The WPF Controls tab consists of the whole list of WPF controls. The
Designer can be open by double-clicking a *.xaml file in Solution Explorer.
Select the control in the Toolbox, which is used to add a control to the
Designer and then drag the control onto the Designer.
 Events can be handled with the help of Events tab at the top of the Properties
window.
 Binding is the method of retrieving and populating the data to and from
controls.
 The Data Sources window allows you to create controls on a form which
are bound to each field of a data source.

13.5 KEY WORDS

 Event: It is an action or occurrence detected by a program.


 Windows Presentation Foundation (WPF): It is a graphical subsystem
by Microsoft for rendering user interfaces in Windows-based applications.

13.6 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer Questions


1. What are various managing windows for controls?
2. How you will set the properties of a control?
3. Discuss the process of adding a data source.
Long Answer Questions
1. Write the code for creating an event handler.
2. How you will instantiate classes in coding the event handler?
3. How you will configure a ComboBox?

Self-Instructional
Material 179
Using WPF Controls
13.7 FURTHER READINGS

Bronson Gary and David Rosenthal. 2005. Introduction to Programming with


NOTES Visual Basic .NET, Burlington, Massachusetts: Jones & Bartlett Learning.
Liberty Jesse. 2003. Programming Visual Basic .NET. Sebastopol, California:
O’Reilly Media, Inc.
Mayo Joe. 2010. Ms Visual Studio 2010. Noida: Tata McGraw-Hill.

Self-Instructional
180 Material
Creating, Designing and

UNIT 14 CREATING, DESIGNING Deploying Web


Applications with
ASP.NET MVC
AND DEPLOYING WEB
NOTES
APPLICATIONS WITH
ASP.NET MVC
Structure
14.0 Introduction
14.1 Objectives
14.2 Reading and Saving Data
14.2.1 Using the DataGrid
14.3 ASP.NET MVC
14.3.1 Starting an ASP.NET MVC Project
14.3.2 Building Controllers
14.3.3 Assigning Masterpage Files
14.3.4 Managing Routing
14.3.5 Building an Employee Management Application
14.4 Starting a Silverlight Project
14.4.1 Using Silverlight Controls (Playing Video)
14.4.2 Running Silverlight Out-Of-Browser (OOB)
14.5 Starting a WCF Project
14.5.1 WCF Interfaces
14.5.2 Implementing a WCF Service Contract
14.6 Answers to Check Your Progress Questions
14.7 Summary
14.8 Key Words
14.9 Self Assessment Questions and Exercises
14.10 Further Readings

14.0 INTRODUCTION
In this unit, you will learn about the using the DataGrid for data representation,
Model View Controller (MVC), work with Silverlight projects and deploy web
services with WCF. DataGrid control displays the fields of a data source as columns
in a table. Each row in the control represents a record in the data source. The
ASP.NET MVC is a web application framework developed by Microsoft that
implements the model–view–controller pattern for building web applications.

14.1 OBJECTIVES
After going through this unit, you will be able to:
 Work with DataGrid
 Explain the purpose of MVC
Self-Instructional
Material 181
Creating, Designing and  Use Silverlight project to create a website
Deploying Web
Applications with  Implement a WCF service contract
ASP.NET MVC

NOTES 14.2 READING AND SAVING DATA

You have to save the order when a user clicks ‘Save’ and for this you have to add
a Button control to the form and set its Content property to Save. You can also set
its Name property to SaveButton.
Example 14.1: Using Click Event Handler
C#
priv ate vo i d Sa ve B u tt on _C l ic k (ob j ect s e n der ,
RoutedEventArgs e)
{
CollectionViewSource orderViewSource =
FindResource(“orderViewSource”) as CollectionViewSource;
List<Order> ordList =
orderViewSource.Source as List<Order>;
Order ord = ordList.FirstOrDefault();
var ctx = new MyShopDataContext();
ctx.Orders.InsertOnSubmit(ord);
ctx.SubmitChanges();
MessageBox.Show(“Order Saved!”);
}
VB
Private Sub SaveButton_Click(
ByVal sender As System.Object,
ByVal e As System.Windows.RoutedEventArgs)
Handles SaveButton.Click
Dim OrderViewSource As CollectionViewSource =
CType(FindResource(“OrderViewSource”),
CollectionViewSource)

Dim ordList As List(Of Order)


ordList = CType(OrderViewSource.Source, List(Of Order))
Dim ord As Order
ord = ordList.FirstOrDefault()
Dim ctx As New MyShopDataContext

ctx.Orders.InsertOnSubmit(ord)
ctx.SubmitChanges()
Self-Instructional
182 Material
MessageBox.Show(“Order Saved!”) Creating, Designing and
Deploying Web
End Sub Applications with
ASP.NET MVC
Before the SaveButton_Click event handler ends, it displays a message
box to the user and also having a status message, Order Saved. There are several
NOTES
overloads of MessageBox class has of the Show method which allows you to
identify buttons, icons etc.
14.2.1 Using the DataGrid
DataGrid is the best option for working with data that can be shown with multiple
rows and columns. To show data in a Grid, you can build off the data source
which is being created in the preceding example. First open the Data Source
window by selecting Data à Open Data Sources. Consider the example in the
previous unit which shows the CustomerID as a ComboBox.
You might want to change CustomerID to a TextBox by clicking on
CustomerID for the Order object in the Data Sources window and selecting
TextBox. Change the control type of Order from a form to a Grid by selecting the
combo box for the Order object in the Data Sources window and selecting the
DataGrid option.
Open the MainWindow .xaml file in the Designer and drag and drop Order
from the Data Sources window to the Designer. You can add another button and
also set its Name property to UpdateButton. You have to set its Content property
to Update.
Figure 14.1 shows the resize and move controls and form. Example 14.2
shows that it added a CollectionViewSource to the window, when adding the
Order to the Designer in Visual Studio. The Window_Loaded event handler
provides the Order data to display in the Grid.

Fig. 14.1 Displaying Information in a Grid


Self-Instructional
Material 183
Creating, Designing and Example 14.2: To display in the Grid the Window_Loaded event handler
Deploying Web
Applications with C#
ASP.NET MVC
private MyShopDataContext m_ctx = new MyShopDataContext();
NOTES private void Window_Loaded(object sender, RoutedEventArgs
e)
{
CollectionViewSource orderViewSource =
FindResource(“orderViewSource”) as CollectionViewSource;
orderViewSource.Source =
from ord in m_ctx.Orders
select ord;
}
VB
Dim m_ctx As New MyShopDataContext
Private Sub Window_Loaded(
ByVal sender As System.Object,
ByVal e As System.Windows.RoutedEventArgs)
Handles MyBase.Loaded
Dim OrderViewSource As CollectionViewSource =
CType(FindResource(“OrderViewSource”),
CollectionViewSource)
OrderViewSource.Source =
From ord In m_ctx.Orders
Select ord
End Sub
Here in the above Example, the MyShopDataContext, m_ctx, is a field
which is outside of the Window_Loaded method handler. As shown in Figure
14.1, there is an Update button on the form and by double-clicking it formed
Click event handler that saves changes like deletes or updates, to the Grid as
shown in Example 14.3.
Example 14.3: By Using Click Event Handler that saves changes like deletes or
updates
C#
private void UpdateButton_Click(object sender,
RoutedEventArgs e)
{
m_ctx.SubmitChanges();
MessageBox.Show(“Updates and Deletes Saved!”);
}

Self-Instructional
184 Material
VB Creating, Designing and
Deploying Web
Private Sub UpdateButton_Click( Applications with
ASP.NET MVC
ByVal sender As System.Object,
ByVal e As System.Windows.RoutedEventArgs)
NOTES
Handles UpdateButton.Click
m_ctx.SubmitChanges()
MessageBox.Show(“Updates and Deletes Saved!”)
End Sub
You can add new row and also modify the cells of existing rows while
running the program .By selecting the row, you can also delete a row with the help
of pressing DELETE key on the keyboard. After doing these changes to the Grid
then click Update. This can call the UpdateButton_Click event handler.

14.3 ASP.NET MVC

The essential information required to be successful with ASP.NET MVC is the


Model View Controller pattern. In MVC, there are three different objects i.e. the
View, Controller and Model. Table 14.1 shows the purpose of each MVC object.
With the help of these three objects, it easier to write good programs which may
be used in future for adding new features or fixing bugs.
Table 14.1 Purpose of MVC Objects

MVC OBJECT PURPOSE


View Each MVC application has a user interface
which shows information to a user and permits
the user to input data.
Model The model is made up of business data and
objects.
Controller A controller orchestrates the activities of an
application. When a user makes a request for
your application, ASP.NET MVC invokes a
Controller.

As you know that there are variation of the relationship between View,
Model and Controller. Figure 14.2 displays the Controller references to the Model
and the View. Since the Controller is handling the operation of the application. The
Controller executes in response to a user request. So, we can say that the Controller
is also responsible for coordinating activity between the View and Model. As
shown in Figure 14.2, the request goes from Controller to View and Model. There
is also a connection established from View to Model. Here the Controller
references the Model. The View references the Model because the View must
bind data to the user interface and required to know what data is available.

Self-Instructional
Material 185
Creating, Designing and The Model does not reference the Controller or the View. The Model is an
Deploying Web
Applications with object which grasps data and any other members which help to handle that data,
ASP.NET MVC like as methods for performing validation. For an ASP.NET MVC operation, a
usual sequence of operations starts with a request to a Controller.
NOTES

Fig. 14.2 Relationship between Controller, View and Model

The Controller will be working with the Model and also perform the actions
requested. The Controller will provides the Model to a View and also run the
View. The View will shows Model data and act together with the user for any
screen operations. Based on the user interaction with the View, there can be more
requests will be made to a Controller to repeat this process.
14.3.1 Starting an ASP.NET MVC Project
You have to open the New Project window to start with ASP.NET MVC project
in Visual Studio. This is done by selecting File à New à Project. It will creates an
ASP.NET MVC 2 Web Application project named MyShopCS (MyShopVB
for VB). Figure 14.3, which displays the new project in Solution Explorer.
Visual Studio with working code creates several folders which are discussed below:
 The Model, View, and Controller folders which grasp the code for the
MVC Models, Views, and Controllers, respectively.
 The App_Data folder is planned which allows you to ship a local database
with your application. It is also perfect for small programs and also where
you can use the free SQL Express database.
 CSS is a standardized language for defining blueprint and look of a Web
site.
The Content folder is that where you add any Cascading Style Sheets (CSS)
files.

Self-Instructional
186 Material
Creating, Designing and
Deploying Web
Applications with
ASP.NET MVC

NOTES

Fig. 14.3 A new ASP.NET MVC Project


The Scripts folder consists of JavaScript files. It also have the ASP.NET
AJAX client libraries and the jQuery. JavaScript supports to make Views more
co-operating and may be more operative in providing an interactive user experience.
The web.config file holds configuration information, like database connection
strings and also consists of more items which you do not required to hard-code
into the application.
The Global.asax file hold code that runs at different periods throughout the
application life cycle.
The code produced by the New Project Wizard will run, and to execute the
application you have to press F5. This will displays a screen as shown in Figure
14.4. Click OK when you see a screen that asks if you want program to run in
debug mode. This will change the web.config file to allow debugging. This is the
one which you required while developing applications.

Fig. 14.4 Running the Default Code (an ASP.NET MVC Project)
Self-Instructional
Material 187
Creating, Designing and 14.3.2 Building Controllers
Deploying Web
Applications with
ASP.NET MVC As shown in Figure 14.3, the MVC project has a Controllers folder. Controller
classes usually exist in in the Controllers folder. It also displays two files i.e.
NOTES AccountController.cs and HomeController.cs, in the
Controllers folder. Example 14.4 shows the contents of the
MainController.cs file.
Example 14.4: MainController Class
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MyShopCS.Controllers
{
[HandleError]
public class MainController : Controller
{
public ActionResult Index()
{
ViewData[“Message”] = “Hello, Welcome to ASP.NET MVC!”;
return View();
}
public ActionResult About()
{
return View();
}
}
}
VB
<HandleError()> _
Public Class MainController
Inherits System.Web.Mvc.Controller
Function Index() As ActionResult
ViewData(“Message”) = “Hello, Welcome to ASP.NET MVC!”
Return View()
End Function
Function About() As ActionResult
Return View()

Self-Instructional
188 Material
End Function Creating, Designing and
Deploying Web
End Class Applications with
ASP.NET MVC
Example 14.4 shows how closely ASP.NET MVC is bound to conventions.
Here the class name is MainController. The ASP.NET MVC uses to recognize
NOTES
which classes are controllers. The methods in the class are identified as actions in
ASP.NET MVC. You must keep an eye on are all conventions of using the
Controllers folder for a Controller, appending the class name with Controller, and
existing actions.
For ASP.NET MVC, the important part of the URL is /Home/About. Home
is the name of the Controller, and ASP.NET MVC appends Controller to the
URL name, looking for the HomeController class located physically in the Controller
folder, that is why it’s important to ensure you create files in the proper locations.
About is an action corresponds to the About method. The call to View in the
about method will displays a View.
Looking Inside a View
Figure 14.4 shows the View in the browse and displaying the message. Example
14.5 shows the Hypertext Markup Language (HTML) code of the View
demonstrating the message.
Example 14.5: HTML code of the View
<%@ Page Language=”C#”
MasterPageFile=”~/Views/Shared/Site.Master”
Inherits=”System.Web.Mvc.ViewPage” %>
<asp:Content ID=”indexTitle”
ContentPlaceHolderID=”TitleContent”
runat=”server”>
Home Page
</asp:Content>
<asp:Content ID=”indexContent”
ContentPlaceHolderID=”MainContent”
runat=”server”>
<h2><%= Html.Encode(ViewData[“Message”]) %></h2>
<p>
To learn more about ASP.NET MVC visit
<a href=”http://asp.net/mvc”
title=”ASP.NET MVC Website”>
http://asp.net/mvc
</a>.
</p>
</asp:Content>

Self-Instructional
Material 189
Creating, Designing and There is a Page directive with a join of Content containers in the code. The
Deploying Web
Applications with Page directive identifies a MasterPage and also inherit attributes. A MasterPage is
ASP.NET MVC an isolated file which hold common HTML. This could be displays on all pages of
a site.
NOTES
14.3.3 Assigning Masterpage Files
You know that there are different sites on the Web which consists of different
pages. They involves menu, footers, header and sidebars. The first time you have
to change the common elements, you need to visit every page.
You have to visit every page when you want to change the common elements.
The MasterPages allows you to identify the common content in one Place. Example
14.6 shows the HTML code of the MasterPage created with the help of ASP.NET
MVC.
Example 14.6: Master page HTML code
<%@ Master Language=”C#”
Inherits=”System.Web.Mvc.ViewMasterPage” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title>
<asp:ContentPlaceHolder ID=”TitleContent”
runat=”server” />
</title>
<link href=”../../Content/Site.css”
rel=”stylesheet” type=”text/css” />
</head>
<body>
<div class=”page”>
<div id=”header”>
<div id=”title”>
<h1>My MVC Application</h1>
</div>
<div id=”logindisplay”>
<% Html.RenderPartial(“LogOnUserControl”); %>
</div>
<div id=”menucontainer”>
<ul id=”menu”>
<li>
<%= Html.ActionLink(“Home”, “Index”, “Home”)%>

Self-Instructional
190 Material
</li> Creating, Designing and
Deploying Web
<li> Applications with
<%= Html.ActionLink(“About”, “About”, “Home”)%> ASP.NET MVC

</li>
NOTES
</ul>
</div>
</div>
<div id=”main”>
<asp:ContentPlaceHolder ID=”MainContent” runat=”server”
/>
<div id=”footer”>
</div>
</div>
</div>
</body>
</html>
Example 14.7: Contents of a Partial View (Master Page)
<%@ Control Language=”C#”
Inherits=”System.Web.Mvc.ViewUserControl” %>
<%
if (Request.IsAuthenticated) {
%>
Welcome <b><%= Html.Encode(Page.User.Identity.Name) %></
b>!
[ <%= Html.ActionLink(“Log Off”, “LogOff”, “Account”) %>
]
<%
}

else {
%>
[ <%= Html.ActionLink(“Log On”, “LogOn”, “Account”) %> ]
<%
}
%>
Example 14.7 displays the contents of a Partial View. There is if statement
and the language syntax is enclosed by <% and %> binding symbols. Here in the
Request object, IsAuthenticated property tells whether the current user is logged
in, and the logic guarantees the suitable message displays.

Self-Instructional
Material 191
Creating, Designing and 14.3.4 Managing Routing
Deploying Web
Applications with
ASP.NET MVC ASP.NET MVC have a routing system which compares the URLs to controllers
with actions. It has parameters which are passed to the actions. While accessing
NOTES the new ASP.NET MVC project, there is a default file known as Global.asax
which is the default routing. There is an Application_Start event which is in contained
with Global.asax file. Example 14.8 shows how to manage and setup the routing.
Example 14.8: Managing and Setting up Routing
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MyShopCS
{
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
routes.MapRoute(
“Default”, // Route name
“{controller}/{action}/{id}”, // URL with parameters
new {
controller = “Home”,
action = “Index”,
id = “” } // Parameter defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
}
VB
‘ Note: For instructions on enabling IIS6 or IIS7 classic
mode,
‘ visit http://go.microsoft.com/?LinkId=9394802
Public Class MvcApplication
Self-Instructional
192 Material
Inherits System.Web.HttpApplication Creating, Designing and
Deploying Web
Shared Sub RegisterRoutes(ByVal routes As RouteCollection) Applications with
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”) ASP.NET MVC

‘ MapRoute takes the following parameters, in order:


NOTES
‘ (1) Route name
‘ (2) URL with parameters
‘ (3) Parameter defaults
routes.MapRoute( _
“Default”, _
“{controller}/{action}/{id}”, _
New With
{
.controller = “Home”, .action = “Index”, .id = “”
}
)
End Sub
Sub Application_Start()
AreaRegistration.RegisterAllAreas()
RegisterRoutes(RouteTable.Routes)
End Sub
End Class
14.3.5 Building an Employee Management Application
In this section, we will use the ASP.NET MVC concepts and also learn about
how to build an application which displays, adds, modifies and deletes customer’s
related data.
Creating a Repository
A repository is a class which accomplishes operations like create, read, and update
etc. Example 14.9 displays a repository for working with employee objects. You
can build the repository by right-clicking the Models folder and then select 
Add  Class and name the class Employee Repository. Here, we assumes
that you’ve created a LINQ to SQL *.dbml, named MyShop.
Example 14.9: A repository for working with employee data
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MyShopCS.Models
{
Self-Instructional
Material 193
Creating, Designing and public class Employee Repository
Deploying Web
Applications with {
ASP.NET MVC private MyShopDataContext m_ctx
= new MyShopDataContext();
NOTES
public int InsertCustomer(Employee emp)
{
m_ctx.Customers.InsertOnSubmit(cust);
m_ctx.SubmitChanges();
return emp. Employee ID;
}
public void UpdateEmployee (Employee emp)
{
var currentEmp =
(from currEmp in m_ctx.Employee
where currEmp.EmployeeID == emp.EmployeeID
select currEmp)
.SingleOrDefault();
if (currentEmp != null)
{
currentEmp.Age = emp.Age;
currentEmp.Birthday = emp.Birthday;
currentEmp.Income = emp.Income;
currentEmp.Name = emp.Name;
}
m_ctx.SubmitChanges();
}
public Employee GetEmployee(int empID)
{
return
(from emp in m_ctx.Employees
where emp.EmployeeID == empID
select emp)
.SingleOrDefault();
}
public List<Employee> GetEmployees()
{
return
(from emp in m_ctx.Employees
select emp)
.
Self-Instructional
194 Material
ToList(); Creating, Designing and
Deploying Web
} Applications with
public void DeleteEmployee(int empID) ASP.NET MVC

{
NOTES
var employee =
(from emp in m_ctx.Employees
where emp.EmployeesID == empID
select emp)
.SingleOrDefault();
m_ctx.Employees.DeleteOnSubmit(employee);
m_ctx.SubmitChanges();
}
}
}
VB
Public Class EmployeeRepository
Private m_ctx As New MyShopDataContext
Public Function InsertEmployee(
ByVal emp As Employee) As Integer
m_ctx.Employees.InsertOnSubmit(emp)
m_ctx.SubmitChanges()
Return emp.EmployeeID
End Function
Public Sub UpdateEmployee(ByVal emp As Employee)
Dim currentEmp =
(From currEmp In m_ctx.Employees
Where currEmp.EmployeeID = emp.EmployeeID
Select currEmp).SingleOrDefault()
If Not currentEmp Is Nothing Then
With currentEmp
.Age = emp.Age
.Birthday = emp.Birthday
.Income = emp.Income
.Name = emp.Name
End With
m_ctx.SubmitChanges()
End If
End Sub
Public Function GetEmployee(ByVal empID As Integer) As
Employee
Self-Instructional
Material 195
Creating, Designing and Dim employee =
Deploying Web
Applications with (From emp In m_ctx.Employees
ASP.NET MVC Where emp.EmployeeID = empID
Select emp).SingleOrDefault()
NOTES
Return employee
End Function
Public Function GetEmployees() As List(Of Employee)
Dim employees =
(From emp In m_ctx.Employees
Select emp).ToList()
Return employees
End Function
Public Sub DeleteEmployee(ByVal empID As Integer)
Dim employee =
(From emp In m_ctx.Employees
Where emp.EmployeeID = empID
Select emp).SingleOrDefault()
m_ctx.Employees.DeleteOnSubmit(employee)
m_ctx.SubmitChanges()
End Sub
End Class
Creating an Employee Controller
Figure 14.5 displays about creating an employee controller. This can be done by
right-click the Controllers folder and then select Add àController àpress CTRL-
M and name the file EmployeeController.

Fig. 14.5 Creating a new controller

Displaying an Employee List


Example 14.10 displays the Index action method of the EmployeeController. It
also displays a list of employees.

Self-Instructional
196 Material
Example 14.10: A controller for displaying a list of employees Creating, Designing and
Deploying Web
C# Applications with
ASP.NET MVC
public ActionResult Index()
{ NOTES
var employees =
new EmployeeRepository()
.GetEmployees();
return View(employees);
}
VB
Function Index() As ActionResult
Dim empRep As New EmployeeRepository
Dim employees As List(Of Employee)
employees = empRep.GetEmployees()
Return View(employees)
End Function
Example 14.11: An Employee View List
<%@ Page Title=”” Language=”C#”
MasterPageFile=”~/Views/Shared/Site.Master”
Inherits=”System.Web.Mvc
.ViewPage<IEnumerable<MyShopCS.Models.Employee>>” %>
<asp:Content ID=”Content1"
ContentPlaceHolderID=”TitleContent”
runat=”server”>
Index
</asp:Content>
<asp:Content ID=”Content2"
ContentPlaceHolderID=”MainContent”
runat=”server”>
<h2>Index</h2>
<table>
<tr>
<th></th>
<th>
EmployeeID
</th>
<th>
Name
</th>
<th>
Self-Instructional
Material 197
Creating, Designing and Age
Deploying Web
Applications with </th>
ASP.NET MVC <th>
Birthday
NOTES
</th>
<th>
Income
</th>
</tr>
<% foreach (var item in Model) { %>
<tr>
<td>
<%= Html.ActionLink(“Edit”, “Edit”,
new { id=item.EmployeeID }) %> |
<%= Html.ActionLink(“Details”, “Details”,
new { id=item.EmployeeID })%>
</td>
<td>
<%= Html.Encode(item.EmployeeID) %>
</td>
<td>
<%= Html.Encode(item.Name) %>
</td>
<td>
<%= Html.Encode(item.Age) %>
</td>
<td>
<%= Html.Encode(String.Format(“{0:g}”,
item.Birthday)) %>
</td>
<td>
<%= Html.Encode(String.Format(“{0:F}”,
item.Income)) %>
</td>
</tr>
<% } %>
</table>
<p>
<%= Html.ActionLink(“Create New”, “Create”) %>
</p> </asp:Content>
Self-Instructional
198 Material
Example 14.12: View for adding a new Employee Creating, Designing and
Deploying Web
<%@ Page Title=”” Language=”C#” Applications with
ASP.NET MVC
MasterPageFile=”~/Views/Shared/Site.Master”
Inherits=”System.Web.Mvc.ViewPage<MyShopCS.Employee>” %>
NOTES
<asp:Content ID=”Content1"
ContentPlaceHolderID=”TitleContent”
runat=”server”>
Create
</asp:Content>
<asp:Content ID=”Content2"
ContentPlaceHolderID=”MainContent”
runat=”server”>
<h2>Create</h2>
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<div class=”editor-label”>
<%= Html.LabelFor(model => model.EmployeeID) %>
</div>
<div class=”editor-field”>
<%= Html.TextBoxFor(model => model.EmployeeID) %>
<%= Html.ValidationMessageFor(
model => model.EmployeeID) %>
</div>
<div class=”editor-label”>
<%= Html.LabelFor(model => model.Name) %>
</div>
<div class=”editor-field”>
<%= Html.TextBoxFor(model => model.Name) %>
<%= Html.ValidationMessageFor(
model => model.Name) %>
</div>
<div class=”editor-label”>
<%= Html.LabelFor(model => model.Age) %>
</div>
<div class=”editor-field”>
<%= Html.TextBoxFor(model => model.Age) %>
<%= Html.ValidationMessageFor(
model => model.Age) %>
</div>

Self-Instructional
Material 199
Creating, Designing and <div class=”editor-label”>
Deploying Web
Applications with <%= Html.LabelFor(model => model.Birthday) %>
ASP.NET MVC </div>
<div class=”editor-field”>
NOTES
<%= Html.TextBoxFor(model => model.Birthday) %>
<%= Html.ValidationMessageFor(
model => model.Birthday) %>
</div>
<div class=”editor-label”>

<%= Html.LabelFor(model => model.Income) %>


</div>
<div class=”editor-field”>
<%= Html.TextBoxFor(model => model.Income) %>
<%= Html.ValidationMessageFor(
model => model.Income) %>
</div>
<p>
<input type=”submit” value=”Create” />
</p>
</fieldset>
<% } %>
<div>
<%=Html.ActionLink(“Back to List”, “Index”) %>
</div>
</asp:Content>
Example 14.13: Methods for modifying the employee’s data
C#
// GET: /Employee/Edit/5
public ActionResult Edit(int id)
{
Employee emp =
new EmployeeRepository()
.GetEmployee(id);
return View(emp);
}
//
// POST: /Employee/Edit/5
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Employee emp)
Self-Instructional
200 Material
{ Creating, Designing and
Deploying Web
try Applications with
{ ASP.NET MVC

new EmployeeRepository()
NOTES
.UpdateEmployee(emp);
return RedirectToAction(“Index”);
}
catch
{
return View();
}
}
VB
‘ GET: /Employee/Edit/5
Function Edit(ByVal id As Integer) As ActionResult
Dim empRep As New EmployeeRepository
Dim emp As Employee
emp = empRep.GetEmployee(id)
Return View(emp)
End Function

‘ POST: /Employee/Edit/5
<HttpPost()> _
Function Edit(ByVal id As Integer, ByVal emp As Employee)
As ActionResult
Try
Dim empRep As New EmployeeRepository
empRep.UpdateEmployee(emp)
Return RedirectToAction(“Index”)
Catch
Return View()
End Try
End Function
In the get Edit action method, you need to add a reference to the current
record, indicated by the id being passed in, and pass that reference to the View for
display. The post Edit action method accepts the modified customer and passes it
to the repository for update in the database.

Self-Instructional
Material 201
Creating, Designing and Deleting an Employee Record
Deploying Web
Applications with
ASP.NET MVC Example 14.14 shows the Delete Controller method for deleting a record.
Example 14.14: The Delete Controller Method (Deleting an employee record)
NOTES C#
//
// GET: /Employee/Delete/5
public ActionResult Delete(int id)
{
new EmployeeRepository()
.DeleteEmployee(id);
TempData[“Result”] = “Employee Deleted.”;
return RedirectToAction(“Index”);
}
VB

‘ GET: /Employee/Delete/5
Function Delete(ByVal id As Integer) As ActionResult
Dim empRep As New EmployeeRepository
empRep.DeleteEmployee(id)
TempData(“Result”) = “Employee Deleted.”
Return RedirectToAction(“Index”)
End Function
Example 14.15: Deleting an employee record (HTML View)
C#
... content removed
<h2>Index</h2>
<p>
<% if (TempData[“Result”] != null)
{ %>
<label><%= Html.Encode(TempData[“Result”].ToString() )%>
</label>
<% } %>
</p>
<table>
... content removed
<% foreach (var item in Model) { %>
<tr>
<td>
<%= Html.ActionLink(“Edit”, “Edit”,
Self-Instructional
202 Material
new { id=item.EmployeeID }) %> | Creating, Designing and
Deploying Web
<%= Html.ActionLink(“Delete”, “Delete”, Applications with
new { id=item.EmployeeID })%> ASP.NET MVC

</td>
NOTES
... content removed
VB:
... content removed
<h2>Index</h2>
<p>
<% If Not TempData(“Result”) Is Nothing Then %>
<label>
<%= Html.Encode(TempData(“Result”).ToString())%>
</label>
<% End If%>
</p>
<p>
<%= Html.ActionLink(“Create New”, “Create”)%>
</p>
<table>
... content removed
<% For Each item In Model%>
<tr>
<td>
<%=Html.ActionLink(“Edit”, “Edit”,
New With {.id = item.EmployeeID})%> |
<%=Html.ActionLink(“Delete”, “Delete”,
New With {.id = item.EmployeeID})%>
</td>
... content removed

14.4 STARTING A SILVERLIGHT PROJECT

Select a Silverlight application in the New Project window. When you set up the
project having name and folder, then Visual Studio shows alternative window for
configuring the Silverlight application as shown in Figure 14.6.
Silverlight provides you the option to build a Web site at the same time you
create the Silverlight application. You are also required to host your Silverlight
application on a Web page. There is an alternate web technology based on
ASP.NET web forms. So, you can see the New Web project type set to ASP.NET
MVC Web Project. Click OK to create the Silverlight application (see Figure
14.7).
Self-Instructional
Material 203
Creating, Designing and
Deploying Web
Applications with
ASP.NET MVC

NOTES

Fig. 14.6 Creating a new Silverlight Application

Fig. 14.7 A new Silverlight Project

Self-Instructional
204 Material
Comparable to WPF applications, the Silverlight applications start with an Creating, Designing and
Deploying Web
App.xaml file and a MainPage.xaml file. The App.xaml runs to modify the application Applications with
and MainPage .xaml consists of the display page. The Silverlight DemoCS ASP.NET MVC
TestPage.html performs the same function as the SilverlightDemoCSTestPage.aspx
holding Silverlight. Example 14.16 shows the contents of the test page and how it NOTES
hosts the Silverlight application.
Example 14.16: Introducing a Silverlight application on a web page.
<%@ Page Language=”C#” AutoEventWireup=”true” %>
<!DOCTYPE html PUBLIC
“-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title>SilverlightDemoCS</title>
<style type=”text/css”>
// css styles omitted
</style>
<script type=”text/javascript” src=”Silverlight.js”></
script>
<script type=”text/javascript”>
function onSilverlightError(sender, args) {
// error handling code omitted
}
</script>
</head>
<body>
<form id=”form1" runat=”server” style=”height:100%”>
<div id=”silverlightControlHost”>
<object data=”data:application/x-silverlight-2,”
type=”application/x-silverlight-2"
width=”100%” height=”100%”>
<param name=”source”
value=”ClientBin/SilverlightDemoCS.xap”/>
<param name=”onError” value=”onSilverlightError” />
<param name=”background” value=”white” />
<param name=”minRuntimeVersion” value=”3.0.40818.0" />
<param name=”autoUpgrade” value=”true” />
<a
href=”http://go.microsoft.com/fwlink/
?LinkID=149156&v=3.0.40818.0"
style=”text-decoration:none”>
Self-Instructional
Material 205
Creating, Designing and <img src=”http://go.microsoft.com/fwlink/?LinkId=161376"
Deploying Web
Applications with alt=”Get Microsoft Silverlight”
ASP.NET MVC style=”border-style:none”/>
</a>
NOTES
</object>
<iframe id=”_sl_historyFrame”
style=”visibility:hidden;height:0px;width:0px;border:0px”>
</iframe>
</div>
</form>
</body>
</html>
Example 14.16 displays an object tag that hosts the Silverlight application
and this tag contains different parameters (as shown in Table 14.2).
Table 14.2 Object Tag Parameters

Parameter Description
Background Sets the control background.
Source As shown in Figure 14.6, there is a ClientBin folder in the
ASP.NET MVC Web application project. When the
Silverlight project builds, Visual Studio will take the output of
that project place it into the ClientBin folder. The output of a
compiled Silverlight project is a *.xap file, which is the same
as a compressed *.zip file, but with a different name.
Silverlight loads the *.xap file into the browser at runtime and
runs the application.
minRuntimeVersion States theta the user must have v3.0.40818.0 or later of the
Silverlight plug-in-for this application to run.
autoUpgrade If the user does not have the minimum version (as specified in
minRuntimeVersion), setting this to true will prompt the user
to begin the upgrade process.

14.4.1 Using Silverlight Controls (Playing Video)


Silverlight consists of strong multimedia support with the help of streaming audio
and video. It consists of various Toolbox which have controls and these controls
helps to make easy to host videos. Figure 14.8 displays how to design a screen
that displays a video.

Self-Instructional
206 Material
Creating, Designing and
Deploying Web
Applications with
ASP.NET MVC

NOTES

Fig. 14.8 To Design a Screen that Displays a Video

Example 14.17: Playing and Stopping a Video


C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace SilverlightDemoCS
{
public partial class MainPage : UserControl
{

Self-Instructional
Material 207
Creating, Designing and public MainPage()
Deploying Web
Applications with {
ASP.NET MVC InitializeComponent();
VideoPlayer.AutoPlay = false;
NOTES
}
private bool m_isPlaying = false;
private void StartStopButton_Click(
object sender, RoutedEventArgs e)

{
if (m_isPlaying)
{
VideoPlayer.Stop();
StartStopButton.Content = “Start”;
m_isPlaying = false;
}
else
{
VideoPlayer.Play();
StartStopButton.Content = “Stop”;
m_isPlaying = true;
}
}
}
}
VB
Partial Public Class MainPage
Inherits UserControl
Public Sub New()
InitializeComponent()
VideoPlayer.AutoPlay = False
End Sub
Dim m_isPlaying As Boolean = False
Private Sub StartStopButton_Click(
ByVal sender As System.Object,
ByVal e As System.Windows.RoutedEventArgs)
If (m_isPlaying) Then
VideoPlayer.Stop()

Self-Instructional
208 Material
StartStopButton.Content = “Start” Creating, Designing and
Deploying Web
m_isPlaying = False Applications with
Else ASP.NET MVC

VideoPlayer.Play()
NOTES
StartStopButton.Content = “Stop”
m_isPlaying = True

End If
End Sub
End Class
14.4.2 Running Silverlight Out-Of-Browser (OOB)
A new capability of Silverlight is running out-of-browser, meaning that the users
can load your application onto the desktop without requirement to visit the hosting
site. In Figure 14.9, you can see a window and also shows the implementation of
OOB. This can be accessed by opening the Silverlight application properties by
double-clicking the Properties folder in Solution Explorer.

Fig. 14.9 Silverlight Properties

Self-Instructional
Material 209
Creating, Designing and
Deploying Web
Applications with
ASP.NET MVC

NOTES

Fig. 14.10 Out-of-Browser Settings

To enable OOB, first check the box “Enable running application out of the
browser” and after that click the Out-Of-Browser Settings button to shows the
window shown in Figure 14.10. It allows you to set information for the application,
the size it will take when running and different sized icons which Windows will
display.
After saving the OOB settings, run the application. Now the user can right-
click the application which is running in the browser and then select Install
SilverlightDemoCSApplication onto the Computer as shown in Figure 14.11.

Self-Instructional
210 Material
Creating, Designing and
Deploying Web
Applications with
ASP.NET MVC

NOTES

Fig. 14.11 Choosing OOB

Figure 14.12 shows that both options are checked. When you click OK,
the Silverlight produces a Start menu item and adds the application to the desktop
(as shown in Figure 14.13). After starting the application, it will run in a window
instead of the browser.

Fig. 14.12 Choosing OOB Deployment Options

Self-Instructional
Material 211
Creating, Designing and
Deploying Web
Applications with
ASP.NET MVC

NOTES

Fig. 14.13 Executing an OOB Application

14.5 STARTING A WCF PROJECT

To start a new WCF project, press CTRL-SHIFT-N and then select WCF Service
Library. You can name the project as WcfDemo as shown in Figure 14.14.

Fig. 14.14 A WCF Service Library Project

14.5.1 WCF Interfaces


The actual implementation will be provided by classes that implement the interface.
Any application wishing to use a Web service have to make calls to the Web
Self-Instructional
212 Material
service which is based on what is stated in the contract. Example 14.18 shows a Creating, Designing and
Deploying Web
WCF service interface. Applications with
ASP.NET MVC
Example 14.18: A WCF Service Interface
using System; NOTES
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WcfDemoCS
{
// NOTE: You can use the “Rename” command on the
// “Refactor” menu to change the interface name
// “IService1” in both code and config file together.
[ServiceContract]
public interface IEmployeeService
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract
(CompositeType composite);
// TODO: Add your service operations here
}
// Use a data contract as illustrated in the sample
// below to add composite types to service operations
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = “Hello “;
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
Self-Instructional
Material 213
Creating, Designing and get { return stringValue; }
Deploying Web
Applications with
ASP.NET MVC set { stringValue = value; }
}
NOTES
}
}
VB
‘ NOTE: You can use the “Rename” command on the
‘ context menu to change the interface name “IService1”
‘ in both code and config file together.
<ServiceContract()>
Public Interface IEmployeeService
<OperationContract()>
Function GetData(ByVal value As Integer) As String
<OperationContract()>
Function GetDataUsingDataContract(
ByVal composite As CompositeType) As CompositeType
‘ TODO: Add your service operations here
End Interface
‘ Use a data contract as illustrated in the sample below
‘ to add composite types to service operations
<DataContract()>
Public Class CompositeType
<DataMember()>
Public Property BoolValue() As Boolean
<DataMember()>
Public Property StringValue() As String
End Class
14.5.2 Implementing a WCF Service Contract
The code of implementing a WCF service contract implementation is given in
Example 14.19.
Example 14.19: A WCF service contract implementation
C#
[ServiceContract]
public interface IEmployeeService
{
[OperationContract]
Employee GetEmployee(int empID);
[OperationContract]
Self-Instructional
214 Material
List<Employee> GetEmployees(); Creating, Designing and
Deploying Web
[OperationContract] Applications with
int InsertEmployee(Employee emp); ASP.NET MVC

[OperationContract]
NOTES
void UpdateEmployee(Employee emp);
[OperationContract]
void DeleteEmployee(int empID);
}
VB
<ServiceContract()>
Public Interface IEmployeeService
<OperationContract()>
Function GetEmployee(ByVal empID As Integer) As Employee
<OperationContract()>
Function GetEmployees() As List(Of Employee)
<OperationContract()>
Function InsertEmployee(ByVal emp As Employee) As Integer
<OperationContract()>
Sub UpdateEmployee(ByVal emp As Employee)
End Interface
Example 14.20: A WCF Service Implementation
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WcfDemoCS
{
public class EmployeeService : IEmployeeService
{
public Employee GetEmployee(int empID)
{
var ctx = new MyShopDataContext();
var employee =
(from emp in ctx.Employees
where emp.EmployeeID == empID
select emp)
.SingleOrDefault();
Self-Instructional
Material 215
Creating, Designing and return employee;
Deploying Web
Applications with }
ASP.NET MVC public List<Employee> GetEmployees()
{
NOTES
var ctx = new MyShopDataContext();
return
(from emp in ctx.Employees
select emp)
.ToList();
}
public int InsertEmployee(Employee emp)
{
var ctx = new MyShopDataContext();
ctx.Employees.InsertOnSubmit(emp);
ctx.SubmitChanges();
return emp.EmployeeID;
}
public void UpdateEmployee(Employee emp)
{
var ctx = new MyShopDataContext();
var employee =
(from cst in ctx.Employees
where cst.EmployeeID == emp.EmployeeID
select cst)
.SingleOrDefault();
if (employee != null)
{
employee.Age = emp.Age;
employee.Birthday = emp.Birthday;
employee.Income = emp.Income;
employee.Name = emp.Name;
ctx.SubmitChanges();
}
}
public void DeleteEmployee(int empID)
{
var ctx = new MyShopDataContext();
var employee =
(from cst in ctx.Employees
where cst.EmployeeID == empID
Self-Instructional
216 Material
select cst) Creating, Designing and
Deploying Web
.SingleOrDefault(); Applications with
if (employee != null) ASP.NET MVC

{
NOTES
ctx.Employees.DeleteOnSubmit(employee);
ctx.SubmitChanges();
}
}
}
}
VB
‘ NOTE: You can use the “Rename” command on the context
‘ menu to change the class name “Service1” in both code
‘ and config file together.
Public Class EmployeeService
Implements IEmployeeService
Public Function GetEmployee(ByVal empID As Integer) As
Employee
Implements IEmployeeService.GetEmployee
Dim ctx As New MyShopDataContext
Dim employee =
(From emp In ctx.Employees
Where emp.EmployeeID = empID
Select emp).SingleOrDefault()
Return employee
End Function
Public Function GetEmployees() As List(Of Employee)
Implements
IEmployeeService.GetEmployees
Dim ctx As New MyShopDataContext
Return (From emp In ctx.Employees
Select emp).ToList()
End Function
Public Function InsertEmployee(ByVal emp As Employee) As
Integer
Implements IEmployeeService.InsertEmployee
Dim ctx = New MyShopDataContext
ctx.Employees.InsertOnSubmit(emp)
ctx.SubmitChanges()
Return emp.EmployeeID
End Function
Self-Instructional
Material 217
Creating, Designing and Public Sub UpdateEmployee(ByVal emp As Employee)
Deploying Web
Applications with Implements IEmployeeService.UpdateEmployee
ASP.NET MVC Dim ctx As New MyShopDataContext
Dim employee = (From cst In ctx.Employees
NOTES
Where cst.EmployeeID = emp.EmployeeID
Select cst).SingleOrDefault()
If Not (employee Is Nothing) Then
With employee
.Age = emp.Age
.Birthday = emp.Birthday

.Income = emp.Income
.Name = emp.Name
End With
ctx.SubmitChanges()
End If
End Sub
Public Sub DeleteEmployee(ByVal empID As Integer)
Dim ctx As New MyShopDataContext
Dim employee = (From cst In ctx.Employees
Where cst.EmployeeID = empID
Select cst).SingleOrDefault()
If Not (employee Is Nothing) Then
ctx.Employees.DeleteOnSubmit(employee)
ctx.SubmitChanges()
End If
End Sub
End Class
Example 14.21: An application using a Web Service
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EmployeeConsole.EmployeeService;
namespace EmployeeConsole
{
class Program
{
static void Main()
Self-Instructional
218 Material
{ Creating, Designing and
Deploying Web
var svc = new EmployeeServiceClient(); Applications with
var newEmp = new Employee ASP.NET MVC

{
NOTES
Age = 36,
Birthday = new DateTime(1974, 8, 22),
Income = 56000m,
Name = “Venus”
};
var newEmpID = svc.InsertEmployee(newEmp);
Console.WriteLine(“New Employee ID: “ + newEmpID);
Employee emp = svc.GetEmployee(newEmpID);
Console.WriteLine(“New Employee: “ + emp.Name);
emp.Income = 49000m;
svc.UpdateEmployee(emp);
Employee updatedEmp = svc.GetEmployee(emp.EmployeeID);
Console.WriteLine(“Economic Adjustment: “ + emp.Income);
svc.DeleteEmployee(updatedEmp.EmployeeID);
//Employee[] employees = svc.GetEmployees();
List<Employee> employees = svc.GetEmployees();
Console.WriteLine(“\nAll Employees:\n”);
foreach (var empItem in employees)
{
Console.WriteLine(empItem.Name);
}
Console.ReadKey();
}
}
}
VB
Imports EmployeeConsoleVB.EmployeeService
Module Module1
Sub Main()
Dim svc = New EmployeeServiceClient
Dim newEmp = New Employee
With newEmp
.Age = 36
.Birthday = New DateTime(1974, 8, 22)
.Income = 56000
.Name = “Venus”
Self-Instructional
Material 219
Creating, Designing and End With
Deploying Web
Applications with Dim newEmpID As Integer
ASP.NET MVC newEmpID = svc.InsertEmployee(newEmp)
Console.WriteLine(“New Employee ID: “ & newEmpID)
NOTES
Dim emp As New Employee
emp = svc.GetEmployee(newEmpID)
emp.Income = 49000
svc.UpdateEmployee(emp)
Dim updatedEmp As Employee
updatedEmp = svc.GetEmployee(emp.EmployeeID)
Console.WriteLine(“Economic Adjustment: “ & emp.Income)
svc.DeleteEmployee(updatedEmp.EmployeeID)
Dim employees As List(Of Employee)
‘Dim employees As Employee()
employees = svc.GetEmployees()
End Sub
End Module

Check Your Progress


1. What are the three objects of MVC?
2. What is a model in MVC?
3. What does Silverlight provides?

14.6 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. There are three different objects of MVC i.e. the View, Controller and
Model.
2. The Model is an object which grasps data and any other members which
help to handle that data, like as methods for performing validation.
3. Silverlight provides you the option to build a Web site at the same time you
create the Silverlight application.

14.7 SUMMARY

 DataGrid is the best option for working with data that can be shown with
multiple rows and columns.
 In MVC, there are three different objects i.e. the View, Controller and
Model.
Self-Instructional
220 Material
 The Model is an object which grasps data and any other members which Creating, Designing and
Deploying Web
help to handle that data, like as methods for performing validation. Applications with
ASP.NET MVC
 Controller classes usually exist in in the Controllers folder. It also displays
two files i.e. AccountController.cs and HomeController.cs, in the Controllers
NOTES
folder.
 Silverlight provides you the option to build a Web site at the same time you
create the Silverlight application. You are also required to host your Silverlight
application on a Web page.
 A new capability of Silverlight is running out-of-browser, meaning that the
users can load your application onto the desktop without requirement to
visit the hosting site.

14.8 KEY WORDS

 DataGrid: It is an architecture or set of services that gives individuals or


groups of users the ability to access, modify and transfer extremely large
amounts of geographically distributed data.
 Model View Controller: It is a web application framework developed
by Microsoft for building web applications.

14.9 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer Questions


1. Discuss the purpose of MVC objects.
2. What are the various folders that are created while working with MVC
projects?
3. How you will set the Silverlight properties?
4. Write a code for implementation of WCF service contract.
Long Answer Questions
1. How you will read and save data using DataGrid?
2. Explain the relationship between MVC objects.
3. Explain how you will create an application in MVC.
4. Create an application in Silverlight project.

Self-Instructional
Material 221
Creating, Designing and
Deploying Web 14.10 FURTHER READINGS
Applications with
ASP.NET MVC
Bronson Gary and David Rosenthal. 2005. Introduction to Programming with
NOTES Visual Basic .NET, Burlington, Massachusetts: Jones & Bartlett Learning.
Liberty Jesse. 2003. Programming Visual Basic .NET. Sebastopol, California:
O’Reilly Media, Inc.
Mayo Joe. 2010. Ms Visual Studio 2010. Noida: Tata McGraw-Hill.

Self-Instructional
222 Material
Master of Computer Applications
31524
VISUAL PROGRAMMING WITH .NET
Semester - II

VISUAL PROGRAMMING WITH .NET


ALAGAPPA UNIVERSITY
[Accredited with ’A+’ Grade by NAAC (CGPA:3.64) in the Third Cycle Master of Computer Applications
and Graded as Category–I University by MHRD-UGC]
KARAIKUDI – 630 003

DIRECTORATE OF DISTANCE EDUCATION

You might also like