Net framework session02

41
In this session, you will learn to: Describe the purpose of collections and collection interfaces Implement the various classes available in the .NET Framework 2.0 Implement generic list types, collections, dictionary types, and linked-list types Implement specialized string and named collection classes Implement collection base classes and dictionary base types Describe the purpose and creation of an assembly Share an assembly by using the Global Assembly Cache Install an assembly by using the Installer, AssemblyInstaller, ComponentInstaller, InstallerCollection, and InstallContext Objectives

Transcript of Net framework session02

Page 1: Net framework session02

In this session, you will learn to:Describe the purpose of collections and collection interfacesImplement the various classes available in the .NET Framework 2.0Implement generic list types, collections, dictionary types, and linked-list typesImplement specialized string and named collection classesImplement collection base classes and dictionary base typesDescribe the purpose and creation of an assemblyShare an assembly by using the Global Assembly CacheInstall an assembly by using the Installer, AssemblyInstaller, ComponentInstaller, InstallerCollection, and InstallContext classes and the InstallEventHandler delegate available in the .NET Framework 2.0

Objectives

Page 2: Net framework session02

What are Collections?Collections are classes used to store arbitrary objects in an organized manner.Types of collections available in .Net Framework are:

Arrays: Are available in the System.Array namespace and can store any type of data.Advanced Collections: Are found in the System.Collections namespace and consist of the following collections:

Non-Generic Collections: With a non-generic collection, you could store multiple types of objects in the collection simultaneously.Generic Collections: When you create an instance of a generic collection, you determine and specify the data type you want to store in that collection.

Examining Collections and Collection Interfaces

Page 3: Net framework session02

What are Collection Interfaces?Collection interfaces specify all the necessary properties and methods for an implementing class to provide the required functionality and behavior of a collection.Every collection class, non-generic or generic, implements at least one or more collection interfaces.

Examining Collections and Collection Interfaces (Contd.)

Page 4: Net framework session02

Create a Flexible Collection of Reference Types by Using ArrayList class

The ArrayList class is defined in the System.Collections namespace.An ArrayList represents a list, which is similar to a single-dimensional array that you can resize dynamically.The ArrayList does not provide type safety.

Working with Primary Collection Types

Dynamic Resizing

Page 5: Net framework session02

The following code snippet creates an ArrayList to store names of countries:ArrayList countries = new ArrayList();

countries.Add("Belgium"); countries.Add ("China"); countries.Add("France");

foreach (string country in countries) { Console.WriteLine (country); }

Working with Primary Collection Types (Contd.)

Page 6: Net framework session02

Manage Collections by Using Stacks and QueuesYou can use Stacks and Queues to store elements when the sequence of storing and retrieving them is an important issue.Stacks follow the last-in-first-out (LIFO) principle while Queues follow the first-in-first-out (FIFO).

Stack

Queue

LIFO

FIFO

Working with Primary Collection Types (Contd.)

Page 7: Net framework session02

The following code example shows the implementation of the Stack class:Stack s1 = new Stack();s1.Push("1"); s1.Push("2"); s1.Push("3");Console.WriteLine("topmost element: " +

s1.Peek()); Console.WriteLine("total elements: " +

s1.Count);while (s1.Count > 0) { Console.Write(" " +

s1.Pop()); }The output of the code example will be:topmost element: 3total elements: 33 2 1

Working with Primary Collection Types (Contd.)

Page 8: Net framework session02

The following code example shows the implementation of the Queue class:Queue q1 = new Queue();q1.Enqueue("1");q1.Enqueue("2");q1.Enqueue("3");Console.WriteLine("topmost element: " +

q1.Peek());Console.WriteLine("total elements: " +

q1.Count);while (q1.Count > 0) { Console.Write(" " + q1.Dequeue());}The output of the code example will be:topmost element: 1total elements: 31 2 3

Working with Primary Collection Types (Contd.)

Page 9: Net framework session02

Enumerate the Elements of a Collection by Using an Enumerator

Iterators are sections of code that return an ordered sequence of values of the same type.They allow you to create classes and treat those as enumerable types and enumerable objects.

Working with Primary Collection Types (Contd.)

Page 10: Net framework session02

Access Reference Types Based on Key/Value Pairs and Comparers

The Comparer class compares two objects to detect if they are less than, greater than, or equal to one another.The Hashtable class represents a collection of name/value pairs that are organized on the basis of the hash code of the key being specified.The SortedList class represents a collection of name/value pairs that are accessible either by key or by index, but sorted only by keys.

Working with Primary Collection Types (Contd.)

Page 11: Net framework session02

The following code example shows the implementation of the Comparer class:string str1 = "visual studio .net";string str2 = "VISUAL STUDIO .NET";string str3 = "visual studio .net";Console.WriteLine("str1 and str2 : " +

Comparer.Default.Compare(str1, str2));Console.WriteLine("str1 and str3 : " +

Comparer.Default.Compare(str1, str3));Console.WriteLine("str2 and str3 : " +

Comparer.Default.Compare(str2, str3));

Working with Primary Collection Types (Contd.)

Page 12: Net framework session02

The following code example creates a new instance of the Hashtable class, named currency:Hashtable currencies = new Hashtable();currencies.Add("US", "Dollar");currencies.Add("Japan", "Yen");currencies.Add("France", "Euro");Console.Write("US Currency: {0}",

currencies["US"]);

Working with Primary Collection Types (Contd.)

Page 13: Net framework session02

The following code example shows the implementation of the SortedList class:SortedList slColors = new SortedList();slColors.Add("forecolor", "black");slColors.Add("backcolor", "white");slColors.Add("errorcolor", "red");slColors.Add("infocolor", "blue");foreach (DictionaryEntry de in slColors){ Console.WriteLine(de.Key + " = " + de.Value);}

Working with Primary Collection Types (Contd.)

Page 14: Net framework session02

Store Boolean Values in a BitArray by Using the BitArray Class

The BitArray class implements a bit structure, which represents a collection of binary bits, 1s and 0s.The Set and Get methods can be used to assign Boolean values to a bit structure on the basis of the index of the elements.The SetAll is used to set the same value for all the elements.

Working with Primary Collection Types (Contd.)

Page 15: Net framework session02

Just a minute

If you place a set of dinner plates, one on top of the other, the topmost plate is the first one that you can pick up and use. According to you, which class follows the same principle?

QueueBitArrayStackHashtable

Answer Stack

Page 16: Net framework session02

Create Type-Safe Collections by Using Generic List TypesThe generic List class provides methods to search, sort, and manipulate the elements of a generic list.The generic List class can be used to create a list that provides the behavior of an ArrayList.

Working with Generic Collections

Page 17: Net framework session02

The following code example shows the implementation of the generic List:List<string>names = new List<string>();names.Add("Michael Patten");names.Add("Simon Pearson");names.Add("David Pelton");names.Add("Thomas Andersen");foreach (string str in names){ Console.WriteLine(str);}

Working with Generic Collections (Contd.)

Page 18: Net framework session02

Create Type-Safe Collections by Using Generic CollectionsThe generic Stack class functions similarly to the non-generic Stack class except that a generic Stack class contains elements of a specific data type.The generic Queue class is identical to the non-generic Queue class except that the generic Queue class contains elements of a specific data type.The generic Queue class is used for FIFO applications.The generic Stack class is used for LIFO applications.

Working with Generic Collections (Contd.)

Page 19: Net framework session02

Access Reference Types Based on Type-Safe Key/Value Pairs

In generic key/value pairs, the key is defined as one data type and the value is declared as another data type.The following classes can be used to add name and value pairs to a collection:

Dictionary: Represents in the value the actual object stored, while the key is a means to identify a particular object.SortedList: Refers to a collection of unique key/value pairs sorted by a key.SortedDictionary: Uses a faster search algorithm than a SortedList, but more memory.

Working with Generic Collections (Contd.)

Page 20: Net framework session02

Create Type-Safe Doubly Linked Lists by Using Generic Collections

With the generic LinkedList class, you can define nodes that have a common data type with each node pointing to the previous and following nodes.With a strongly typed doubly linked list you can traverse forward and backward through the nodes to reach a particular node.

Doubly LinkedList

Working with Generic Collections (Contd.)

Page 21: Net framework session02

Just a minute

What is a doubly linked list?

Answer A collection in which each node points to the previous and following nodes is referred to as a doubly linked list.

Page 22: Net framework session02

What Are Specialized Collections?Specialized collections are predefined collections that serve a special or highly specific purpose.These collections exist in the System.Collections.Specialized namespaceThe various specialized collections available in .Net Framework are:

String classesDictionary classesNamed collection classesBit structures

Working with Specialized Collections

Page 23: Net framework session02

Just a minute

What is a specialized string collection?

Answer A specialized string collection provides several string-specific functions to create type-safe strings.

Page 24: Net framework session02

Create Custom Collections by Using Collection Base Classes

Collection base classes provide the abstract base class for strongly typed non-generic collections.The read-only version of the CollectionBase class is the ReadOnlyCollectionBase class.

Working with Collection Base Classes

Page 25: Net framework session02

Create Custom Dictionary Types by Using Dictionary Base Types

Dictionary base types provide the most convenient way to implement a custom dictionary type.Custom dictionary types can be created by using:

DictionaryBase classDictionaryEntry structure

Working with Collection Base Classes (Contd.)

Page 26: Net framework session02

Just a minute

Categorize the following features into CollectionBase class and the DictionaryBase type?

Helps create custom collectionsHelps create a custom dictionaryProvides the public member CountIs a base collection of key value/pairs

Collection Base class Dictionary Base type

Helps create custom collections Helps create a custom dictionary

Provides the public member Count Is a base collection of key value/pairs

Answer

Page 27: Net framework session02

What Is an Assembly?An assembly is a self-contained unit of code that contains all the security, versioning, and dependency information.Assemblies have several benefits like:

Resolve conflicts arising due to versioning issues.Can be ported to run on multiple operating systems.Are self-dependant.

Working With An Assembly

Page 28: Net framework session02

Create an AssemblyYou can create the following two types of Assemblies.

Single-file assemblies: are self-contained assemblies.Multifile assemblies: store different elements of an assembly in different files.

You can create an assembly either at the command prompt by using command-line compilers or by using an IDE such as Visual Studio .NET 2005.

Working With An Assembly (Contd.)

Types of Assemblies

Single-file Multifile

Page 29: Net framework session02

To create an assembly with the .exe extension at the command prompt, use the following syntax:

compiler command module nameFor example, if you want to compile a code module called myCode into an assembly you can type the following command:

csc myCode.cs

Working With An Assembly (Contd.)

Page 30: Net framework session02

The three most common forms of assemblies are:.dll : A .dll file is an in-process executable file. This file cannot be run independently and is called by other executable files..exe: An .exe file is an out-of-process executable file that you can run independently. An .exe file can contain references to the .dll files that get loaded at run time..netmodule: A .netmodule is a block of code for compilation. It contains only the type metadata and the MSIL code.

Working With An Assembly (Contd.)

Page 31: Net framework session02

What is Global Assembly Cache?The global assembly cache is a system-wide code cache managed by the common language runtime.Any assembly that needs to be shared among other applications is typically installed in the global assembly cache.On the basis of sharing, assemblies can be categorized into two types, private assemblies and shared assemblies.

Sharing an Assembly by Using the Global Assembly Cache

Page 32: Net framework session02

Creating and Assigning a Strong Name to an AssemblyA strong name provides a unique identity to an assembly.For installing an assembly in the global assembly cache, you must assign a strong name to it. You can use Sn.exe provided by the .NET Framework to create and assign a strong name to an assembly. For creating a strong name for an assembly you can open the Visual Studio 2005 Command Prompt and type the following command:

SN -k KeyPairs.snkSN is the command to generate the strong key and Keypairs.snk is the filename where you are storing this key.

Sharing an Assembly by Using the Global Assembly Cache (Contd.)

Page 33: Net framework session02

Deploy an Assembly into the Global Assembly CacheDeploying an assembly in the global assembly cache is necessary when you need to share the assembly with other applications.There are three methods to deploy an assembly into the global assembly cache:

Windows ExplorerGacutil.exeInstallers

The syntax to use Gacutil.exe is gacutil –i/assembly name. The -i option is used to install the assembly into the global assembly cache.

Sharing an Assembly by Using the Global Assembly Cache (Contd.)

Page 34: Net framework session02

What are Assembly Installers?Assembly installers are used to automate the process of installing assemblies.You can create installers either by using:

Visual Studio: Allows you to create four types of installers:Setup projectWeb Setup projectMerge Module projectCAB project

Command Prompt: Enables more flexibility in customizing your assembly installers.

Installing an Assembly by Using Installation Types

Page 35: Net framework session02

Create Custom Installation Applications by Using the Installer Class

The .NET Framework provides the Installer class as a base class to create custom installer classes.To create a custom installer class in your setup code, perform the following steps:

Create a class that is inherited from the Installer class.Implement overrides for the Install, Commit, Rollback, and Uninstall methods.Add RunInstallerAttribute to the derived class and set it to true.Invoke the installer.

Installing an Assembly by Using Installation Types (Contd.)

Page 36: Net framework session02

Install an Assembly by Using the AssemblyInstaller Class

You can use the AssemblyInstaller class to load an assembly and run all its installer classes.The AssemblyInstaller class belongs to the System.Configuration.Install namespace.

Installing an Assembly by Using Installation Types (Contd.)

Page 37: Net framework session02

Copy Component Settings for Runtime InstallationComponentInstaller class that has the ability to let custom installer classes to access information from other running components during the installation process.The installer can access the required information from another component by calling the CopyFromComponent method of the ComponentInstaller class.

Custom Installer Classes

Running Components

Installing an Assembly by Using Installation Types (Contd.)

Page 38: Net framework session02

Manage Assembly Installation by Using Installer Classes

The .NET Framework provides the following Installer classes:

InstallerCollection: Provides methods and properties that the application will require to manage a collection of Installer objects.InstallContext: Maintains the context of the installation in progress.

Installing an Assembly by Using Installation Types (Contd.)

Page 39: Net framework session02

Handle Installation Events by Using the InstallEventHandler Delegate

InstallEventHandler delegate can be used to run custom actions at certain points during the installation process. The various events that can be handled during installation are:

BeforeInstallAfterInstallCommittingCommittedBeforeRollback AfterRollbackBeforeUninstallAfterUninstall

Installing an Assembly by Using Installation Types (Contd.)

Page 40: Net framework session02

In this session, you learned that: Collections are classes in which you store a set of arbitrary objects in a structured manner.Collection interfaces specify all the necessary properties and methods for an implementing class to provide the required functionality and behavior of a collection.Primary or non-generic collection types can be dynamically resized, but do not provide type safety.Stack and Queue classes are helpful for storing a set of objects in a collection where the sequence of adding objects is important.Type-safe doubly linked lists can be created by using generic collections.Specialized collections are predefined collections that serve a special or highly specific purpose.

Summary

Page 41: Net framework session02

Collection base classes provide the abstract base class for strongly typed non-generic collections.An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality.The global assembly cache is a system-wide code cache managed by the Common Language Runtime (CLR).An assembly that is installed in the global assembly cache to be used by different applications is known as a shared assembly. Assembly installer is a utility that help automate installation and uninstallation activities and processes.

Summary (Contd.)