PG - MCA - Computer Applications - 31524 MCA VB - NET - 8300
PG - MCA - Computer Applications - 31524 MCA VB - NET - 8300
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
Author
Dr. Preety Khatri, Assistant Professor, Institute of Management Studies (IMS), Noida
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.
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 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
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
1.1 OBJECTIVES
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
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.
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
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.
NOTES
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.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
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
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.
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
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
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.
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.
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
Self-Instructional
14 Material
Introduction to
1.8 SELF ASSESSMENT QUESTIONS AND Visual Studio
EXERCISES
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
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
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
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.
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.
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.
Self-Instructional
22 Material
Toolbox
NOTES
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.
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.
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
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.
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.
Self-Instructional
Material 29
Toolbox
NOTES
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
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.
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.
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.
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.
Self-Instructional
34 Material
Toolbox
2.9 FURTHER READINGS
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
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
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.
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
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
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.
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
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.
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
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:
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
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
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.
Self-Instructional
Material 59
Creating Classes
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
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
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.
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.
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
{
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;
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
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();
Self-Instructional
70 Material
Output: Creating Classes
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 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
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.
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.
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.
Self-Instructional
Material 77
Method Snippets
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
Self-Instructional
78 Material
Fields and properties Method Snippets
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;
class ExampleDemo {
public static void Main() {
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;
class ExampleDemo {
public static void Main() {
// Create a new Student object:
Student s = new Student();
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
6.4 SUMMARY
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
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
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.
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.
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);
Console.Writeline(“Debited “ + amount.ToString() +
“ from Customer Checking Account”);
}
public decimal CustomerCurrentBalance { getvalue; setvalue;
}
}
}
Self-Instructional
92 Material
VB Events
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
{
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()
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.
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#).
To use the interface snippet, first type int and then press TAB. The interface
snippet template (in VB) is shown in Figure 7.4.
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
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
Self-Instructional
102 Material
Events
7.10 SELF ASSESSMENT QUESTIONS AND
EXERCISES
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
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.
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.
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.
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.
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.
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.
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?
Self-Instructional
110 Material
Building Projects
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
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.
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?
Self-Instructional
114 Material
Building Projects
NOTES
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
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
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.
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.
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
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.
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.
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.
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.
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
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.
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.
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
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.
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.
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.
In debug mode, you can start the program running which is done by
selecting DebugStart 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
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.
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.
NOTES
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.
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.
Self-Instructional
138 Material
Debugging Methods
NOTES
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.
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
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.
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
Self-Instructional
Material 143
Working with Databases
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
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
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.
Self-Instructional
146 Material
which belongs to the key and then right-click and select Set Primary Key. This is Working with Databases
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
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
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
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.
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.
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
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
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
12.1 OBJECTIVES
Self-Instructional
Material 155
Building Desktop
Applications with WPF 12.2 STARTING A WPF 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.
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
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
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
Self-Instructional
160 Material
Building Desktop
Applications with WPF
NOTES
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
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
12.5 SUMMARY
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.
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.
Self-Instructional
164 Material
Using WPF Controls
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
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
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.
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,
Self-Instructional
Material 169
Using WPF Controls
NOTES
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.
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.
Self-Instructional
Material 173
Using WPF Controls
NOTES
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>
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.
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.
Self-Instructional
Material 179
Using WPF Controls
13.7 FURTHER READINGS
Self-Instructional
180 Material
Creating, Designing and
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
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)
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.
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.
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
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.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
{
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.
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”>
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
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
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.
Self-Instructional
206 Material
Creating, Designing and
Deploying Web
Applications with
ASP.NET MVC
NOTES
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.
Self-Instructional
Material 209
Creating, Designing and
Deploying Web
Applications with
ASP.NET MVC
NOTES
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
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.
Self-Instructional
Material 211
Creating, Designing and
Deploying Web
Applications with
ASP.NET MVC
NOTES
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.
[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
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.
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