34
Visual Studio 2008 Community Training By Mohamed Saleh [email protected] www.jordev.net www.geeksconnected.com/mohamed

Module 1: Introduction to .NET Framework 3.5 (Material)

Embed Size (px)

DESCRIPTION

Module 1: Introduction to .NET Framework 3.5 Jordan .NET User Group - Community Material. Mohamed Saleh

Citation preview

Page 1: Module 1: Introduction to .NET Framework 3.5 (Material)

Visual Studio 2008 Community Training

By

Mohamed Saleh

[email protected]

www.jordev.net

www.geeksconnected.com/mohamed

Page 2: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

2

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

Table of Contents

Official Community Material License 3

Module Overview 4

.NET Frameworks Versions Misconception 5

Visual Studio 2008 Multi-Targeting Support 6

Lab 1: Working with Multi-Targeting Feature 7

Debugging .NET Framework Source Code 12

Lab 2: Enabling And Using The Source Server Support 15

Microsoft .NET Framework 3.5 Library 18

Lab 3: Using MSBuild 3.5 New Features 20

Introducing The Collection Type HashSet<T> 24

Lab 4: Using the HashSet<T> Type 26

Summary 33

References 34

Page 3: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

3

Official Community Material License

While every precaution has been taken in the preparation of this document, Jordev assumes no responsibility for

errors, omissions, or for damages resulting from the use of the information herein.

This disclaimer statement, presented on this page, is an integral part of this document. Should this page of the

document, in its electronic or printed formats, be lost, deleted, destroyed or otherwise discarded, this disclaimer

statement applies despite the consequences.

© 2008 Jordev.NET. All rights reserved.

The names of actual companies and products mentioned herein may be the trademarks of their respective owners.

Page 4: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

4

Module Overview

This module describes the new development features available in Visual Studio 2008

and .Net Framework 3.5 including multi-targeting support, some of the new .NET

Framework libraries, and the C# 3.0 language enhancements.

This module introduces you to the new multi-targeting feature which allows the

developer to use one environment to build projects for many versions of the

framework, and walks you through the new assemblies added to the Framework

which empower the developers in building the applications very easily and quickly.

Objectives:

After completing this module, you will be able to:

Explain the Framework versions misconception.

Explain how VS 2008 can be used to target multiple versions of the Framework.

Using VS 2008 to debug the .NET Framework Source Code.

Explain the usage of the new libraries available in the .NET Framework 3.5.

Examining the MSBuild 3.5 Schema.

Using the new generic collection type HashSet.

Page 5: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

5

.NET Frameworks Versions Misconception

Visual Studio 2008 Ships with the .NET Framework 3.5, there is been some confusion and

misconception about what is .NET Framework 3.5 and 3.0, because the Framework 3.5 is not

a replacement for the .NET 2.0 and 3.0.

The .NET Framework 3.0 and 3.5 extends the enhancements and the libraries of .NET

Framework 2.0, the .NET 2.0 comes with a lot of changes especially into the Common

Language Runtime (CLR), the .NET 3.0 was known as the WinFX which was an extension to

the .NET 2.0 which contains Windows Workflow Foundation (WF), Windows

Communication Foundation (WCF), Windows Presentation Foundation (WPF), and Windows

CardSpace. This means that .NET 3.5 and .NET 3.0 are just an additive libraries and

enhancements to the .NET Framework 2.0.

The .NET Framework 3.5 includes the .NET Framework 3.0 SP1 which includes the .NET

Framework 2.0 SP1, so no need to download separate frameworks, which makes the Visual

Studio 2008 single unified development environment for multiple versions of the .NET

Framework.

Page 6: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

6

Visual Studio 2008 Multi-Targeting Support

Overview:

The multi-targeting feature allows the developer to specify the required .NET Framework

version in the same version of the Visual Studio. This allows the developers to continue

develop projects that were created in Visual Studio 2005 without the need to add new .NET

Framework dependencies.

Supported .NET Frameworks Versions:

Visual Studio 2008 lets you target the following .NET Framework Versions:

.NET Framework 2.0: Included in Visual Studio 2005.

.NET Framework 3.0: Included in Windows Vista. Contains WPF (Windows

Presentation Foundation), WWF (Windows Workflow Foundation), WCF (Windows

Communication Foundation), and WCS (Windows CardSpace).

.NET Framework 3.5: Included in Visual Studio 2008.

.NET Framework Version 1.1 Support:

The Visual Studio 2008 multi-targeting doesn’t support the work with .NET Framework

Version 1.0 or 1.1 because there was a significant Common Language Runtime (CLR)

changes between .NET 1.x and the newer versions.

Although the supported versions are three different versions of .NET Framework, but all the

supported versions are based on the same Common Language Runtime (CLR) Version 2.0

that was included in Visual Studio 2005.

Page 7: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

7

Lab 1: Working with Multi-Targeting Feature

After completing this lab, you will be able to:

Creating Projects target different .NET Framework Versions.

Upgrading and Downgrading the Projects Frameworks Versions using Application Tab.

Upgrading and Downgrading the Projects Frameworks Versions using the XML-Based

Projects Files.

Examining the effects of the multi-targeting feature on the project templates, references,

controls, and compiler settings.

To use the multi-targeting feature in Visual Studio 2008

1. Start Microsoft Visual Studio 2008.

2. On the File menu, point to New and then click Project.

3. In the New Project dialog box, select a language, and then select Windows in the

Project Types box.

4. In the Templates box, select Visual C# Windows Forms Application.

5. In the top-right corner of the New Project dialog box, click in the Target Framework

combo box and select the .NET Framework version 3.5

Page 8: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

8

6. Change the Target Framework combo box to .NET Framework 2.0, the Visual Studio

will automatically filter the project templates to show only the templates supported by

.NET Framework Version 2.0 (excluding the WPF project templates)

Page 9: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

9

7. Change the Target Framework combo box to .NET Framework 3.5, click OK and then

continue to create your project as usual.

8. On the Solution Explorer tab, expand the References node, you will see the following

.NET 3.5 new assemblies: (we will deal with these assemblies deeply in the next

modules)

1. System.Core

2. System.Data.DataSetExtenstions

3. System.Xml.Linq

Changing the Framework version of the project

1. Right-click the project in the Solution Explorer and then click Properties.

2. On the Application tab, Go to the Target Framework drop-down list; click a .NET

Framework Version 2.0.

3. The Visual Studio will reload the project to let the affects of changing the Framework

Version taking the suitable effects.

Page 10: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

10

4. If you try to compile the current project, you may receive error messages because your

project contains references to earlier or later assembly versions, to resolve these

errors, you must remove/modify the references manually.

5. To see the missed references in our case, on the Solution Explorer tab expand the

References node, you will see the missed references highlighted, just Right-click the

missed assemblies and choose Remove from the pop-up menu.

Adding References to upper version of .NET Framework

On the Solution Explorer tab, right-click the References node, and choose Add

Reference, you will see the Assembly the .NET Framework 2.0 Non supported

assemblies grayed out and cannot be added to the current project.

Page 11: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

11

Changing the Framework version manually

1. Right-click the project in the Solution Explorer tab and then choose Unload Project.

2. Right-click the project again, and choose Edit.

3. You will see the XML definition of the project file, under the PropertyGroup section

change the value of TargetFrameworkVersion to v3.5, then choose Save from the

File Menu.

4. On the Solution Explorer tab, Right-click the Project and choose Reload Project.

5. Open the project Properties and you will see the Target Framework changed to .NET

Framework 3.5.

Page 12: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

12

Debugging .NET Framework Source Code

Overview:

Microsoft Released part of the .NET Framework Library source code under the Microsoft

Reference License, which allows the developers and architects to read the code, debug it, and

learn the best practices and patterns used in the implementation of it.

This feature is supported by configuring the Visual Studio 2008 (Express Editions are not

supported) to connect with the Microsoft Reference Source Server which contains symbols

for many products and libraries. These symbols will help the Visual Studio to download the

required source file when the developer debugs it.

Microsoft Symbol Server and Microsoft Reference Source Server:

Symbol Information allows the developers to have better debugging sessions because it

provides information and footprints of the functions that are contained in the executables and

dynamic libraries.

Microsoft Symbol Server provides access to the symbol files of Microsoft Windows Server

2003, Windows XP, Windows 2000 operating system, and other Microsoft products.

Microsoft Reference Source Server differs than the Symbol Server; the Reference Source

Server includes the symbols and source code of the .NET Framework, which allows the

developer to load the correct symbols, binaries and sources during the debugging sessions.

Actually when debugging unmanaged code “native code, the Symbols indentifies the function

name and the offset base but in the managed code scenario the function names are available

Page 13: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

13

during the debugging without any need for the PDB files. Microsoft Reference Source Server

Provides the PDB files which contains URLs to the source code of the functions and classes.

The Available .NET Framework Libraries source code:

Microsoft Reference Source Server currently contains the symbols/source for the following

a ssemblies:

No. Assembly Name Namespaces

1. Mscorlib.dll Microsoft Common Language Runtime

Library including:

Win32 API(s)

System Generics and Collections

System Runtime Libraries

System Security

System Diagnostics and IO

System Reflection and Threading

2. System.dll Microsoft CSharp

System.Net.*

System.ComponentModel.*

System.Web

System.Media

System.Runtime.*

3. System.Data.dll Microsoft Active Data Object .NET Library

4. System.Drawing.dll System.Drawing

System.Drawing.Design

System.Drawing.Drawing2D

System.Drawing.Imaging

System.Drawing.Internal

System.Drawing.Printing

System.Drawing.Text

5. System.Web.dll System.Web

System.Web.Administration

System.Web.Caching

System.Web.Compilation

System.Web.Configuration

System.Web.Configuration.Common

System.Web.Configuration.Internal

System.Web.DataAccess

System.Web.Handlers

System.Web.Hosting

System.Web.Mail

System.Web.Management

System.Web.Profile

System.Web.Security

Page 14: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

14

System.Web.SessionState

System.Web.UI

System.Web.UI.Adapters

System.Web.UI.HtmlControls

System.Web.UI.WebControls

System.Web.UI.WebControls.Adapters

System.Web.UI.WebControls.WebParts

System.Web.Util

6. System.Web.Extensions.dll Microsoft ASP.NET AJAX Toolkit

7. System.Windows.Forms.dll System.Resources

System.Windows.Forms

System.Windows.Forms.Design

System.Windows.Forms.Layout

System.Windows.Forms.PropertyGridInternal

System.Windows.Forms.VisualStyles

8. System.Xml.dll System.Xml

System.Xml.Schema

System.Xml.Serialization

System.Xml.Serialization.Advanced

System.Xml.Serialization.Configuration

System.Xml.XPath

System.Xml.Xsl

9. PresentationCore.dll Microsoft Windows Presentation Foundation

10. Microsoft.VisualBasic.dll Microsoft Visual Basic Runtime

Microsoft Reference License:

Microsoft Released part of the .NET Framework Library source code under the Microsoft

Reference License, which means “use of the software within your company as a reference, in

read only form, for the sole purposes of debugging your products, maintaining your products,

or enhancing the interoperability of your products with the software, and specifically excludes

the right to distribute the software outside of your company.” , so nobody can edit or modify

the source code.

Microsoft Visual Studio 2008 QFE Hotfix:

In order to use this feature, the Visual Studio QFE (Quick Fix Engineering) Hotfix must be

installed which addresses a performance problem when stepping through the downloaded

source code.

For more information check the following link:

https://connect.microsoft.com/VisualStudio/Downloads/DownloadDetails.aspx?DownloadID

=10443&wa=wsignin1.0

Page 15: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

15

Lab 2: Enabling And Using The Source Server Support

After completing this lab, you will be able to:

Enable the Source Server Support during the debugging session in Visual Studio.

Debugging and stepping into.NET Framework library source code.

Enabling Source Server Support in Visual Studio 2008

1. Start Microsoft Visual Studio 2008.

2. On the Tools menu, click Options and then expand the Debugging node, and click

General.

3. In the right settings panel, uncheck Enable Just My Code, and check Enable source

server support.

Page 16: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

16

4. Select the Symbols option in the right setting panel

5. In the Symbols Page, set the symbol file location:

http://referencesource.microsoft.com/symbols

6. Choose a directory in your hard drive to be the Symbol’s Cache Location.

7. Check the option “Search the above locations only when symbols are loaded manually”.

Debugging into the .NET Framework Library Source Code

1. Start Microsoft Visual Studio 2008.

2. On the File menu, point to New and then click Project.

3. In the New Project dialog box, select a language, and then select Windows in the

Project Types box.

4. In the Templates box, select Visual C# Windows Forms Application.

5. In the Solution Explorer, Expand Form1.cs node, and then double click

Form1.Designer.cs.

6. In the Form1.Designer.cs Code View, Set a breakpoint in the last line of Dispose

Function to break when the user close the Form .

Page 17: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

17

7. Press F5 to run the project, and then close the running form.

8. Visual Studio will hit the breakpoint, and then go to the Call Stack Window

(CTRL+ALT+C).

9. In the Call Stack Window, Right click the third call Frame, and then click Load

Symbols.

10. After the Visual Studio downloads the required symbols and source code, double click

again the third call frame.

11. The Visual Studio will open the source code of the System.Windows.Forms.Form,

and now you can step into it.

Page 18: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

18

Microsoft .NET Framework 3.5 Library

What’s New in the .NET Framework 3.5:

Microsoft adds new major enhancements to the .NET Framework Library including:

Microsoft Build Engine 3.5 (MSBUILD):

Microsoft Build Engine 3.5 now supports the Multi-targeting Feature, building projects

concurrently in the Multi-Processor Machines which accelerate the projects building, and

the extensive support for logging which provide a smart way in customizing reports of

build errors, warnings, messages, and events.

CSharp and Visual Basic Compilers Enhancements:

The new enhanced CSharp and Visual Basic compilers are now supporting many new

language features such as Automatic implemented properties, Objects Initializers,

Anonymous Types, Extension Methods, Expression Trees, Lambda Expressions, and a lot

of new techniques that add more productivity in programming.

Language Integrated Query (LINQ):

The new Microsoft Baby which is a new easier data access techniques that allows the

developer to access many kind of data (arrays, collections, SQL data, Datasets, XML,

etc…) easily and smoothly using a SQL-Like syntax.

Common Language Runtime Enhancements (CLR):

The CLR uses the same model of CLR version 2.0 but some new improvements have

been introduced such as the new light HashSet collection type, the Garbage Collector

(GC) Latency Mode that allows the developer to adjust the time of GC work, supporting

Page 19: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

19

the new type ThreadPool, the new TimeZone type which allows the developer retrieve

any time zone defined in the registry, and a lot of new types.

Applications Extensibility (Add-Ins Programming):

The developers now can build extensible applications by using the new architectural

model Add-Ins that allows the application to host new add-ins.

Networking Enhancements:

Peer-to-peer applications can be built easily through the System.Net.PeerToPeer

Namespace.

Security Enhancements:

The new Cryptography Next Generation (CNG) classes provide a managed

implementation many Cryptography algorithms such as ECDiffieHellmanCng and

ECDsaCng, in addition to some enhancements over the reflection security model.

The New Reference Assemblies Location:

The .NET Framework 3.5 assemblies are now located in:

\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\

At Runtime, the references components will be loaded from the GAC (Global Assembly

Cache), at Design Time the mentioned location can be used to find the required assemblies

for referencing.

Page 20: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

20

Lab 3: Using MSBuild 3.5 New Features

Objectives:

This lab introduces you the multi-targeting feature of the XML-based build platform of

Microsoft .NET and the Multiple Processor support feature.

After completing this lab, you will be able to:

Create a simple project files based on the new MSBuild 3.5 schema.

Targeting a specific .NET Framework using the ToolsVersion Attribute.

Using the new Multi-Processor support feature.

Using Multi-Targeting Feature in Build Definitions

Creating the Project Definition File:

1. Start Microsoft Visual Studio 2008.

2. Choose File -> New -> File, and then select XML File from the General category and

click Open.

3. In the Visual Studio XML Editor type the following code:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

<!-- Creating Item Collection Contains the Source code files for the project -->

<ItemGroup>

<Compile Include="Module01BuildSample.cs"/>

</ItemGroup>

<!-- Defining the Logical Build Entry Pointy-->

Page 21: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

21

<Target Name="Build">

<Csc Sources="@(Compile)"/>

</Target>

</Project>

4. Choose File -> Save As. In the “Save as type” dropdown list, choose “All Files

(*.*)”. In the “File Name” Text Box, type C:\Labs\Module01Lab03\Lab03.csproj,

and click Save.

Creating C# Source File:

5. Choose File -> New -> File, and then select Visual C# Class from the General

category and click Open.

6. In the Visual Studio Code Editor replace the content with the following code:

using System;

namespace GeeksConnected.VS2008Training.Lab03

{

public class MSBuildMultiTargeting

{

static void Main()

{

Console.WriteLine("MSBuild 3.5 Multi-Targeting Feature.");

}

}

}

7. Choose File -> Save As. In the “File Name” Text Box, type

C:\Labs\Module01Lab03\Module01BuildSample.cs, and click Save.

Building the Project Definition:

8. Open Visual Studio 2008 Command Prompt from the Start -> Programs ->

Microsoft Visual Studio 2008 -> Visual Studio Tools.

9. On the Command Prompt change the directory to C:\Labs\Module01Lab03 and then

type MSBuild Lab03.csproj, the project will be built automatically.

10. Run the generated Lab03.exe.

Using .NET Framework 3.5 Features:

11. In Visual Studio Open the Module01BuildSample.cs File.

12. In the Visual Studio Code Editor replace the content with the following code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace GeeksConnected.VS2008Training.Lab03

{

Page 22: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

22

public class MSBuildMultiTargeting

{

internal class Person

{

// Auto Implemented Properties...

public Int32 ID { get; set; }

public string Name { get; set; }

public string Job { get; set; }

public string Company { get; set; }

}

static void Main()

{

Console.WriteLine("MSBuild 3.5 Multi-Targeting Feature.");

var Employees = new List<Person>

{

new Person{ID = 1,Name="Omar", Job="Software Engineer",

Company = "GeeksConnected"},

new Person{ID = 2, Name = "Sami", Job = "Quality

Assurance", Company = "Great Package"},

new Person{ID= 3,Name = "Muhanad", Job = "Team Leader",

Company = "Estarta"},

new Person{ID= 4,Name = "Ammar", Job = "Graphics

Designer", Company = "Beat"},

new Person{ID= 5,Name = "Salim", Job = "Project

Coordinator", Company = "GeeksConnected"}

};

var query = from p in Employees where p.Company ==

"GeeksConnected" select p.Name;

string[] names = query.ToArray();

foreach (string s in names)

{

Console.WriteLine(s);

}

Console.ReadKey();

}

}

}

13. Open Visual Studio 2008 Command Prompt, and build the project file using

MSBuild.

14. You will get the following error:

Module01BuildSample.cs(3,14): error CS0234: The type or namespace name

'Linq' does not exist in the namespace 'System' (are you missing an assembly

reference?)

This error occurred because the program reference to Linq assembly - which is part of

.NET Framework 3.5 - and the current project build definition didn’t use the toolset

version 3.5 which help the MSBuild to find the required assemblies.

15. To fix this problem add the attribute ToolsVersion="3.5" to the Project node, like

the following:

Page 23: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

23

<Project ToolsVersion="3.5"

xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

<!-- Creating Item Collection Contains the Source code files for the project -->

<ItemGroup>

<Compile Include="Module01BuildSample.cs"/>

</ItemGroup>

<!-- Defining the Logical Build Entry Pointy-->

<Target Name="Build">

<Csc Sources="@(Compile)"/>

</Target>

</Project>

16. Build the project and run the generated exe file.

Configuring and Using Parallel Project Builds in Visual Studio:

1. Start Microsoft Visual Studio 2008.

2. On the Tools menu, click Options and then expand the Projects and Solutions node,

and click Build and Run.

3. In the right settings panel, write in the text box behind maximum number of parallel

project builds the number of CPUs in your workstation.

4. Now, Create New Solution and add another project to the current solution, and build the

solution by pressing F6.

You can build the projects parallel using the /maxcpucount switch with MBuild utility

like the following:

MSBuild Lab03.csproj /maxcpucount:3

Page 24: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

24

Introducing The Collection Type HashSet<T>

Type Information:

Fully Qualified Name System.Collections.Generic.HashSet

Assembly System.Core.dll

Overview:

HashSet is the only new collection type in .NET Framework 3.5, which provides high

performance set operations.

Hashset is an unordered collection contains unique elements, and provides standard

collection operations (Add, Remove, Contains,...) in addition to the Standard Set Operations

such as (Union, Intersect, Except,…). The HashSet Capacity increases automatically as

elements are added to the object.

Standard Set Operations:

HashSet provides the following operations:

Method Name Description

Union Create a new Set contains the combination of all items in

two sets.

Intersect Create a new Set contains the common items between the

two sets.

UnionWith Modifies the current Set to contain the combination of all

items in two sets.

Page 25: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

25

IntersectWith Modifies the current Set to contain the common items

between the two sets.

ExcepWith Modifies the current Set to Remove all the elements in the

specified collection.

Except Create a new Set contains the non-common elements

between the two Sets.

IsSubsetOf Determine if the current Set is sub set of the specified Set.

IsSupersetOf Determine if the current Set is super set of the specified

Set.

IsProperSubsetOf Determine if the current Set is proper sub set of the

specified Set.

IsProperSupersetOf Determine if the current Set is proper super set of the

specified Set.

Proper Subset:

A subset lacking at least one member of its superset. Set A is a proper subset of set B if all

members of A are members of B, but at least one member of B is not a member of A.

Proper Superset:

A superset having at least one more member in addition of its subset members. Set A is a

proper superset of set B if all members of B are members of A, but at least one member of A

is not a member of B.

Page 26: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

26

Lab 4: Using the HashSet<T> Type

Objectives:

This lab introduces you the new generic collection type HashSet and its standard operations.

After completing this lab, you will be able to:

Using a highly performance generic collections type “the HashSet class”.

Manage the Set collection items by using the Add and Remove Operations.

Iterate through the elements of the set collection.

Applying the standard set operations like the Intersection, Union, Except.

Examining the subsets, supersets, proper subsets, and proper supersets.

Scenario In this exercise, you will create a form that allows the user to enter student names for two

courses, the course students will be displayed in separate ListBox, total of student number in

each list will be displayed in a Label, and the user will be able to perform the set standard

operations (Union, Intersection, and Exception) and display the results into different

ListBox, and he will be able to check if the two courses students SuperSet, SubSet, Proper

SuperSet, or Proper SubSet.

The high levels tasks for this exercise are:

Create the HashSet Operations form.

Design the interface of the form.

Page 27: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

27

Create a method named DisplayTotals to display the total number of the students into the

ListBox(s) and HashSet(s) after any operation.

Add code to do the basic Set operations (Add, Remove, Clear).

Add code to do the standard set operations (Intersection, Union, Except).

Add code to do the SuperSet and SubSet checking between the two courses sets.

The screenshot below shows the proposed layout of this form:

Tasks Supporting Information

1. Start Visual Studio 2008, and

Create New Visual C# Windows

Forms Application.

Save the Solution and Project under the folder

C:\Labs in the name

C:\Labs\Module01Lab04\Lab04.csproj.

2. Specify properties for the main

form.

The title bar of the form must contain the text “HashSet Operations.”

The form must appear in the center of the screen when opened.

The initial size of the form must be 571 pixels wide

Page 28: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

28

and 605 pixels The form name must be frmMain.

3. Add the Controls to the form. A. Add 3 Listboxes to form, and then set properties for each of the controls as follows: ListBox 1 Name: lstCourse1Students ListBox 2 Name: lstCourse2Students ListBox 3 Name: lstSetOperations

B. Add 4 Labels above the Courses Students

Listboxes, and then set properties for each of the controls as follows: Label 1 Name: lblCourse1

Label 1 Text: Course 1 Label 2 Name: lblCountCourse1 Label 2 Text: 00 Label 3 Name: lblCourse2 Label 3 Text: Course 2 Label 4 Name: lblCountCourse2 Label 4 Text: 00

C. Add 2 Text Boxes under the Courses List Boxes,

and then set properties of each of the controls as follows: TextBox 1 Name: txtStudentCourse1

TextBox 2 Name: txtStudentCourse2

D. Add 2 Labels above the Text Boxes, and then set properties for each of the controls as follows: Label 1 Name: lblStudentCourse1 Label 1 Text: Student Name: Label 2 Name: lblStudentCourse2 Label 2 Text: Student Name:

E. Add 6 Buttons under the TextBoxes, and then set

properties for each of the controls as follows:

Button 1 Name: btnAddStudentCourse1 Button 1 Text: Add Button 2 Name: btnRemoveStudentCourse2 Button 2 Text: Remove Button 3 Name: btnClearCourse1 Button 3 Text: Clear Button 4 Name: btnAddStudentCourse2 Button 4 Text: Add Button 5 Name: btnRemoveStudentCourse2 Button 5 Text: Remove Button 6 Name: btnClearCourse2 Button 6 Text: Clear

F. Add 5 Labels under the Buttons, and then set

properties for each of the controls as follows: Label 1 Name: lblSetTotalCourse1Title Label 1 Text: Course 1 Set Total: Label 2 Name: lblCountSet1 Label 2 Text: 00 Label 3 Name: lblSetTotalCourse2Title Label 3 Text: Course 2 Set Total: Label 4 Name: lblCountSet2 Label 4 Text: 00 Label 5 Name: lblSetOperationsTitle

Label 5 Text: Set Operations

G. Add 7 Buttons beside the “Set Operations” ListBox, and then set properties for each of the controls as follows: Button 1 Name: btnUnion Button 1 Text: Union Button 2 Name: btnIntersect

Page 29: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

29

Button 2 Text: Intersection Button 3 Name: btnExcept Button 3 Text: Except Button 4 Name: btnSuperSet

Button 4 Text: Is SuperSet? Button 5 Name: btnSubSet Button 5 Text: Is SubSet? Button 6 Name: btnProperSubSet Button 6 Text: Is Proper SubSet? Button 7 Name: btnProperSuperSet Button 7 Text: Is Proper SuperSet?

Now attach the code to the events of the designed controls as follows:

1. Create new instances of the HashSet Type at the form level scope:

//Creating instances of Students Sets...

HashSet<string> setStudentsCourse1 = new HashSet<string>();

HashSet<string> setStudentsCourse2 = new HashSet<string>();

2. Create new Method to display the total of the students in the list and the created sets then

to display it into the labels:

private void DisplayTotals()

{

//Displaying the count of students in the ListBox and HashSet in Course 1.

lblCountCourse1.Text = lstCourse1Students.Items.Count.ToString();

lblCountSet1.Text = setStudentsCourse1.Count.ToString();

//Displaying the count of students in the ListBox and HashSet in Course 2.

lblCountCourse2.Text = lstCourse2Students.Items.Count.ToString();

lblCountSet2.Text = setStudentsCourse2.Count.ToString();

}

3. Add code to the events of the form controls as follows:

private void btnAddStudentCourse1_Click(object sender, EventArgs e)

{

string strStudentName = txtStudentCourse1.Text.Trim();

if (strStudentName.Length > 0 )

{

//Adding the Student Name to The ListBox and HashSet.

setStudentsCourse1.Add(strStudentName);

lstCourse1Students.Items.Add(strStudentName);

DisplayTotals();

}

}

private void btnAddStudentCourse2_Click(object sender, EventArgs e)

{

string strStudentName = txtStudentCourse2.Text.Trim();

if (strStudentName.Length > 0)

{

//Adding the Student Name to The ListBox and HashSet

setStudentsCourse2.Add(strStudentName);

lstCourse2Students.Items.Add(strStudentName);

Page 30: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

30

DisplayTotals();

}

}

private void btnClearCourse1_Click(object sender, EventArgs e)

{

lstCourse1Students.Items.Clear();

setStudentsCourse1.Clear();

DisplayTotals();

}

private void btnClearCourse2_Click(object sender, EventArgs e)

{

lstCourse2Students.Items.Clear();

setStudentsCourse2.Clear();

DisplayTotals();

}

private void btnRemoveStudentCourse1_Click(object sender, EventArgs

e)

{

if (lstCourse1Students.SelectedItem != null)

{

string strSelectedStudent =

lstCourse1Students.SelectedItem.ToString();

setStudentsCourse1.Remove(strSelectedStudent);

lstCourse1Students.Items.Remove(lstCourse1Students.SelectedItem);

DisplayTotals();

}

}

private void btnRemoveStudentCourse2_Click(object sender, EventArgs

e)

{

if (lstCourse2Students.SelectedItem != null)

{

string strSelectedStudent =

lstCourse2Students.SelectedItem.ToString();

setStudentsCourse2.Remove(strSelectedStudent);

lstCourse2Students.Items.Remove(lstCourse2Students.SelectedItem);

DisplayTotals();

}

}

private void btnUnion_Click(object sender, EventArgs e)

{

//Clearing the Set Operations List...

lstSetOperations.Items.Clear();

//Executing the Union Operation over the two course sets..

Page 31: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

31

HashSet<string> setStudents = new HashSet<string>();

setStudents = setStudentsCourse1;

setStudents.UnionWith(setStudentsCourse2);

foreach (string strStudentName in setStudents)

{

lstSetOperations.Items.Add(strStudentName);

}

}

private void btnIntersect_Click(object sender, EventArgs e)

{

//Clearing the Set Operations List...

lstSetOperations.Items.Clear();

//Executing the Intersection Operation over the two course sets..

HashSet<string> setStudents = new HashSet<string>();

setStudents = setStudentsCourse1;

setStudents.IntersectWith(setStudentsCourse2);

foreach (string strStudentName in setStudents)

{

lstSetOperations.Items.Add(strStudentName);

}

}

private void btnExcept_Click(object sender, EventArgs e)

{

//Clearing the Set Operations List...

lstSetOperations.Items.Clear();

//Executing the Except Operation over the two course sets..

HashSet<string> setStudents = new HashSet<string>();

setStudents = setStudentsCourse1;

setStudents.ExceptWith(setStudentsCourse2);

foreach (string strStudentName in setStudents)

{

lstSetOperations.Items.Add(strStudentName);

}

}

private void btnSuperSet_Click(object sender, EventArgs e)

{

MessageBox.Show(setStudentsCourse1.IsSupersetOf(setStudentsCourse2).T

oString());

}

private void btnSubSet_Click(object sender, EventArgs e)

{

MessageBox.Show(setStudentsCourse1.IsSubsetOf(setStudentsCourse2).ToS

tring());

}

private void btnProperSubSet_Click(object sender, EventArgs e)

Page 32: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

32

{

MessageBox.Show(setStudentsCourse1.IsProperSubsetOf(setStudentsCourse

2).ToString());

}

private void btnProperSuperSet_Click(object sender, EventArgs e)

{

MessageBox.Show(setStudentsCourse1.IsProperSupersetOf(setStudentsCour

se2).ToString());

}

4. Run the application by pressing F5, and test the application by entering some data and

performing the Set Operations.

Page 33: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

33

Summary

The Visual Studio 2008 gives developers a single development environment to target multi-

framework versions, in addition to source server support which provides the ability to debug

into the source code of the Framework. The .Net Framework 3.5 provides many new libraries

that covers a wide variety of business required functionalities and features. The new MSBuild

engine come with many features such as multi-targeting and the support of building projects

parallel in the multi-processor workstation, the new collection type HashSet provides the

ability to perform the standard set operations such as Union, Intersection ,etc… with high

performance.

The next several modules provide you with the coverage of different areas in .NET

Framework 3.5 and Visual Studio 2008 like C# 3.0 Enhancements, Linq, and ASP.Net 3.5

new features. Using the information in this module and your new Visual Studio 2008

development environment, you should be able to follow along with the samples and start

mastering the .NET Framework 3.5.

Page 34: Module 1: Introduction to .NET Framework 3.5 (Material)

MODULE 1: INTRODUCTION TO VISUAL STUDIO 2008 AND .NET FRAMEWORK 3.5

34

References

1. Microsoft Site (http://www.microsoft.com)

2. Microsoft Developer Network (http://msdn.microsoft.com)

3. Shawen Burke’s Blog (http://blogs.msdn.com/sburke/default.aspx)

4. Scott Guthrie’s Blog (http://weblogs.asp.net/scottgu/)

5. Scott Hanselman’s Blog(http://www.hanselman.com/)