.NET Fundamentals - Pondview Software

Download Report

Transcript .NET Fundamentals - Pondview Software

.NET Fundamentals
February 4, 2004
Week 3
Class Agenda – February 4, 2004
Questions / Homework?
Types (Intrinsic and Reference), Classes, Objects
Class Exercise 1
Collections
Class Exercise 2
Serialization / Deserialization
Class Exercise 3
Procedural vs Object Oriented Programming
Homework Assignment
Questions / Homework ?
• Review Week 2 Homework – mention
problems... code review
• I'm hoping we will cover "exceptions" in more
detail.
• Another thing that I'm in need of help is finding
the vast available resources that are provided.
Like when do you need to use the various
IMPORTS, and all the potential referenceable
classes.
Homework Assignment – Week 2 - Grading
Label on Form and Label Form (5)
Three Names Fields with Correct Labels and Validation (10)
Reset Button (Reset Application) (5)
Create Full Name Button (5)
Display Button (5)
Group Box with Radio Buttons (10)
Horizontal Forward Method (5)
Horizontal Backward Method (5)
Vertical Forward Method (5)
Vertical Backward Method (5)
Uses Full MessageBox to Display Errors (5)
Displays in TextBox (5)
Uses Scroll Bars (5)
Adds 1/2 Name Length to ComboBox (5)
Adjusts Name Length Based on ComboBox Selection (10)
Reset Removes Added Length from ComboBox (5)
Reset Clears ComboBox (5)
Strongly Typed Object Oriented
Programming Environment
Type  Class  Object
In Visual Basic.NET a type is defined by
a class, while the individual instances of
a class are known as objects.
Types and Types in .NET
What is a type?
• Every variable has a type
• A type defines the variables general
properties and behaviors
• A type can be complex like a form class or
simple like an integer.
• Sometimes a type is tangible, like a button
in a window
• Sometimes a type abstract, like a data table
or a thread
Types in .NET
Previously, each programming
language represented data types in its
own way. Now, the common type
system provides every language in
Visual Studio .NET with a consistent
set of data types.
In addition, every data type supports a
minimum set of methods. Because all
languages use the same library of types,
you can call one language from another
without having to convert the type or the
call conventions.
The .NET run-time environment is
designed to be safe and secure. The
.NET run-time environment
enforces strict rules to guarantee the
safety of types.
type-safe code
• Type-safe code is code that accesses types only in
well-defined, allowable ways.
• Type-safe code only accesses memory at fixed
offsets corresponding to actual field members.
• Code that accesses memory at arbitrary offsets
outside the range of memory that belongs to that
object's publicly exposed fields, it is not type-safe.
.NET and type-safe code
• The Common Language Specification defines a set of
programmatically verifiable rules.
• These rules govern the interoperation of types that are
authored in different programming languages.
• These rules also establish requirements for Common
Language Specification compliance.
• Visual Studio .NET languages such as Microsoft Visual
Basic .NET and Microsoft Visual C# .NET comply
with the Common Language Specification.
Type Fundamentals
• All objects in .NET ultimately derive from
System.Object
• This means that every object of every type has a
minimum set of methods
The Public Methods
• Equals - Determines whether two objectinstances
are equal.
• GetHashCode - Serves as a hash function for a
particular type, suitable for use in hashing
algorithms and data structures like a hash table.
• ToString - Returns a string that represents the
current object.
• GetType - Gets the type of the current instance.
• ReferenceEquals - Determines whether the
specified object instances are the same instance.
The Protected Methods
• Methods only seen by derived classes.
• MemberWiseClone - Creates a shallow copy of
the current object. Creates a new instance of the
object and sets the new object’s fields to be
identical to this object’s fields. Returns a
reference to the new object.
• Finalize - Allows an object to attempt to free
resources and perform other cleanup operations
before the object is reclaimed by garbage
collection.
Microsoft .NET supports two
kinds of data types
• Value types. Types that are allocated in a
stack or inline in a structure.
• Reference types. Types that are allocated in
a heap.
Value Types
• Value types store the data directly on the
stack. (simply, a last in first out list).
• You access this data directly.
• To create a copy of the value that is assigned,
you can assign a value type to a variable.
• Value types are not inheritable.
• They are implicitly derived from the
System.ValueType class, which derives from
System.Object.
Value Types
Value types include:
• primitive types
• Enums
• Structures
Primitives
Primitives are the foundation of data types. Primitives are
the lowest types available.
You can identify primitives through keywords, which are
aliases for predefined types in the System namespace. For
example, the int or int32 data type is an alias for the
System.Int32 object.
Because all data types are derived from System.Object,
primitives are actually objects with a set of members that are
available for each type. For example, the int32 data type has
a member named MaxValue.
Primitive Types
- Byte
- Short
- Int16/32/64
- Interger
- Single
- Double
- Decimal
- Boolean
- DateTime
- Char
- String
Of these primitive types, only the String type is a
reference type. All of the other primitive types are
value types.
Enumerators
The Enum keyword is used to declare an
enumeration, a distinct type consisting of a set
of named constants called the enumerator list.
Every enumeration type has an underlying
type, which can be any integral type except
Char.
Enum Statement
• Used at module, class, or structure level to
declare an enumeration and define the
values of its members.
Enum
• An enumeration is a related set of constants. The
enumeration members between the Enum and
End Enum statements are initialized to constant
values. The defined values cannot be modified at
run time. Values can include both positive and
negative numbers, as the following example
shows:
Enum SecurityLevel
IllegalEntry = -1
MinimumSecurity = 0
MaximumSecurity = 1
End Enum
Another Enum Example
Public Enum InterfaceColors
MistyRose
= &HE1E4FF&
SlateGray
= &H908070&
DodgerBlue = &HFF901E&
DeepSkyBlue = &HFFBF00&
SpringGreen = &H7FFF00&
ForestGreen = &H228B22&
Goldenrod
= &H20A5DA&
Firebrick
= &H2222B2&
End Enum
Structure
• The Structure statement can appear only at module,
namespace, or file level. This means you can declare
structures in a source file or inside a module, interface,
or class, but not inside a procedure.
• You can also define one structure inside another, but you
cannot access its members through the outer structure.
Instead, you must declare a variable of the inner
structure's data type.
• Structures can be accessed from anywhere within the
module or class in which they are declared.
Structures
• The Structure data type inherits from the
System.ValueType class.
• A Structure type is a value type that can contain
constructors, constants, fields, methods,
properties, indexers, operators, events, and
nested types.
• A Structure is like a light weight class.
• A Structure is stored on the stack.
Structure
The .NET structure data type is very similar to a
class data type except that a structure data type is a
value type (whereas a class data type is a reference
type).
For increased efficiency, you may want to use
structure data types if you do not need the overhead
of maintaining a reference pointer. However, because
a structure data type is a value type, it is not garbage
collected.
Public Structure Employee
' Public members, accessible throughout declaration region.
Public FirstName As String
Public LastName As String
' Private members, accessible only within the structure itself.
Private HomePhone As Long
Private Level As Integer
Private Salary As Double
Private Bonus As Double
' Procedure member, which can access structure's private members.
Friend Sub CalculateBonus(ByVal Rate As Single)
Bonus = Salary * CDbl(Rate)
End Sub
' Property member to return employee's eligibility.
Friend ReadOnly Property Eligible() As Boolean
Get
Return Level >= 25
End Get
End Property
' Event member, raised when business phone number has changed.
Public Event ChangedWorkPhone(ByVal NewPhone As Long)
End Structure
Reference types
• Reference types store the data on the managed heap and
store a pointer to the data on the stack
• You access the data in reference types through the
reference pointer
• Are collected by the garbage collector when they are no
longer in use.
• Are passed by reference.
• Can be extended by inheritance.
• Can specify Finalizers.
• Reference pointer is type safe.
• A variable of reference type always contains a reference
to a value of that type or a null reference.
Reference types include the
following data types
•
•
•
•
•
String
Array
Class
Interface
Delegate
String
• .NET String data types are invariant.
• Because String data types are read-only after
initialization, you cannot directly modify their
content.
• The String variable contains a pointer to
memory that contains the actual data. Any
modification to the string deallocates the
current memory block and allocates a new
memory block for the new value
StringBuilder
NOTE: If the cost of deallocating and reallocating
string greatly affects performance, you can use the
StringBuilder class in Visual Studio .NET. You
will notice performance benefits at approximately
300 string concatenations.
Array
• Provides methods for creating, manipulating, searching, and sorting
arrays, thereby serving as the base class for all arrays in the common
language runtime.
• All array types implicitly inherit from the System.Array class,
which inherits from System.Object. Arrays are allocated on the
managed heap.
• If all of the dimensions of the array are zero, the array has a length
of zero, and the array is empty.
• In an array reference types are initialized to null, value types are
initialized to the default value for their type (i.e. int members are
initialized to zero). You can initialize arrays during declaration.
• By inheriting from System.Array, each array reference type
automatically inherits a set of System.Array methods and
properties such as Rank, Length, GetLength, and
GetUpperBound.
Class
• A class is a data structure that may contain data members
(such as constants and variables), function members (such
as methods, properties, indexers, operators, events, and
constructors), and nested types.
• Class types support inheritance. Inheritance is a
mechanism whereby a derived class can extend and
specialize a base class.
• Derived classes inherit and can extend the properties and
the methods of the base class. Derived classes can also
override inherited methods with new implementations.
Interface
• An interface is a contract.
• The class or a structure that implements the
interface must adhere to the contract.
• The contract specifies the members that must be
supplied by the class that implements the interface.
• The interface is a list of functions. The interface
contains methods, properties, and events.
• An interface provides no implementation itself.
Delegate
• The delegate reference type is central to the programming
model of the Common Language Runtime (CLR).
• Delegates are classes that hold references to procedures.
• The Delegate reference provides a managed, type-safe
function pointer, which is the delegate type.
• A delegate is derived from the System.Delegate class.
• Delegates are the basis for events.
• The .NET event model uses delegates to bind events to the
methods that are used to handle them. The delegate allows
other classes to register for event notification by
specifying a handler method. When the event occurs, the
delegate calls its bound method.
Boxing and Unboxing
In some cases, you may want to treat an instance of a value type like an
instance of a reference type. Boxing provides this mechanism.
Boxing converts a value type to a reference type by performing the
following steps:
1. Allocates memory on the managed heap to store the value.
2. Copies the value to the managed heap.
3. Stores the reference to the data (address of the object) on the
stack.
Unboxing converts an instance of a reference type back to its original
value type by returning a pointer to the data within a boxed subject.
The pointer does not include the usual overhead that is associated with
a true object.
Boxing
• Here’s what happens when you box a value type:
– Memory is allocated from the managed heap to hold the
value type plus the overhead members.
– The value type’s fields are copied to the newly allocated
memory.
– The address of the object is returned.
– Note that a whole new object is returned – manipulating
the original value type will not change the boxed
reference.
Dim value As Integer = 123
Dim o As Object = value 'box int into an object box
Dim value2 As Integer = CInt(o) 'unbox into value2
Unboxing
• Here’s what happens when a reference type is unboxed
– If the reference is null, a NullReferenceException is thrown
– If the reference does not refer to an object that is a boxed value
of the desired value type, an InvalidCastException is thrown
– A pointer to the value type is returned, which is frequently
copied immediately to another value type.
Dim value As Integer = 123
Dim o As Object = value 'box Integer into an object box
Dim value2 As Long = CLng(o) 'unbox into value2
Casting
There are two types of casting:
• Implicit casting. Implicit casting is transparent to
users. The compiler automatically converts from
one data type to another. The predefined, implicit
conversions always succeed and never cause an
error.
• Explicit casting. Explicit casts are called in the
code. Explicit casts cannot guarantee success and
may lose information if you cast from a larger
type to a smaller type.
Type  Class  Object
In Visual Basic.NET a type is
defined by a class, while the
individual instances of a class are
known as objects.
In Visual Basic.NET Everything
happens within a Class!
Class
• A class is a data structure that may contain data members
(such as constants and variables), function members (such
as methods, properties, indexers, operators, events, and
constructors), and nested types.
• Class types support inheritance. Inheritance is a
mechanism whereby a derived class can extend and
specialize a base class.
• Derived classes inherit and can extend the properties and
the methods of the base class. Derived classes can also
override inherited methods with new implementations.
Class
Classes are declared using the keyword class. It takes the following
form::
[attributes] [modifiers] Class identifier [Inherits classname]
[ class-body]
End Class
where:
– attributes (Optional)
– modifiers (Optional) The allowed modifiers are new, abstract,
sealed, and the four access modifiers.
– identifier The class name.
– class-body Declarations of the class members.
Common Class Members
• fields, which are the variables of the class.
• methods, which implement the
computations and actions that can be
performed by the class.
• properties, which define named
characteristics associated with reading and
writing those characteristics.
Instance versus Static Members
• Instance members are unique to each object
instance and referenced by the object
reference.
• Static members are limited to one copy,
associated with the class type, being
referenced by the class type.
Fields
• A field is a member that represents a
variable associated with an object or class.
• Fields maintain class state
Methods
• A method is a member that implements a
computation or action that can be performed by
an object or class.
• Choose a name for your method based on the
following guidelines.
– Use verbs or verb phrases to name methods
– The first letter in the identifier and the first
letter of each subsequent concatenated word
are capitalized.
Method Arguments
• Appear as local variables within the method
• Method arguments are private by default
Modifiers for Fields or Methods
Term
Description
Public
Accessible to all methods in all
assemblies.
Private
Method is visible only to member
methods within the same class.
Method extends visibility to methods
of derived classes.
Method extends visibility to any class
in the same assembly.
protected or internal
Protected
Internal
Protected Internal
Modifiers for Fields
Term
Description
Static
The field is part of the type’s state,
not the object’s state
Readonly
The field can be written to only in
the constructor.
Modifiers for Methods
Term
Description
Static
Method is associated with the type
itself, not an instance of the type.
The method may not access
instance fields.
Virtual
Most-derived method is called, even
if object is cast to a base type.
Applies only to non-static methods.
New
Method should not override a
virtual method defined by it’s base
type – the method hides the
inherited method. Applies only to
virtual methods
Modifiers for Methods (continued)
Term
Description
Override
Explicitly indicates the method is
overriding as virtual method in it’s
base type. Applies only to virtual
methods.
Abstract
Indicates that a deriving type must
implement the method. Need to
mark the type abstract as well.
Applies only to virtual methods.
Sealed
The derived type cannot override
this method. Applies only to virtual
methods.
Method Overloading
• Method overloading occurs when a class contains two
methods with the same name, but different signatures.
• Use method overloading to provide different methods
that do semantically the same thing.
• Use method overloading instead of allowing default
arguments. Default arguments do not version well and
therefore are not allowed in the Common Language
Specification (CLS). The following code example
illustrates an overloaded String.IndexOf method.
String.IndexOf (String name)
String.IndexOf (String name, int startIndex)
Method Overloading (continued)
• Use default values correctly. In a family of overloaded
methods, the complex method should use parameter names
that indicate a change from the default state assumed in
the simple method. For example, in the following code,
the first method assumes the search will not be casesensitive. The second method uses the name ignoreCase
rather than caseSensitive to indicate how the default
behavior is being changed.
// Method #1: ignoreCase = false.
Type.GetMethod(String name)
// Method #2: Indicates how the default behavior of method #1 is
// being changed.
Type.GetMethod (String name, Boolean ignoreCase)
Properties
(Get and Set accessor)
Get and Set accessor
•
•
•
•
Provides protection for variables in a class
Define the variable as private
Use a get and set accessor to access the variable
The accessor of a property contains the
executable statements associated with getting
(reading or computing) or setting (writing) the
property. The accessor declarations can contain a
Get accessor, a Set accessor, or both.
Example
Public Property LastName()
Get
Return m_LastName
End Get
Set(ByVal Value)
m_LastName = Value
End Set
End Property
Get accessor
• The body of the Get accessor is similar to that of a
method. It must return a value of the property type. The
execution of the Get accessor is equivalent to reading the
value of the field.
• When you reference the property, except as the target of an
assignment, the Get accessor is invoked to read the value
of the property.
• The Get accessor must terminate in a Return or Throw
statement, and control cannot flow off the accessor body.
Set accessor
• The Set accessor is similar to a method that returns void. It
uses an implicit parameter called Value, whose type is the
type of the property. In the following example, a Set
accessor is added to the Name property:
• When you assign a value to the property, the Set accessor
is invoked with an argument that provides the new value.
For example:
• It is an error to use the implicit parameter name (Value) for
a local variable declaration in a Set accessor.
• When accessing a property using the Set accessor, preserve
the value of the property before you change it. This will
ensure that data is not lost if the Set accessor throws an
exception.
Accessors notes
• A property is classified according to the accessors used as
follows:
– A property with a Get accessor only is called a readonly property. You cannot assign a value to a read-only
property.
– A property with a Set accessor only is called a writeonly property. You cannot reference a write-only
property except as a target of an assignment.
– A property with both Get and Set accessors is a readwrite property.
• In a property declaration, both the Get and Set accessors
must be declared inside the body of the property.
Constructors
• Methods called whenever an object is instantiated
• Before the constructor is called, the object points
to undifferentiated memory.
• After the constructor is called, the object points to
valid instance.
• If a constructor is not defined the CLR creates one
for you.
• Member variables are initialized to default values.
• Constructor method name is the same as the class
name.
Constructor (continued)
• If you provide an overloaded Constructor, you
must provide a default constructor, even if it does
nothing.
• Can call the base class constructor using the base
keyword.
• Base class constructor always uses the most
derived type.
• Constructors have no return type
• Typically declared Public
• Arguments are defined just like any other method
Public Sub New()
Throw New ApplicationException("First and Last Name Required")
End Sub
Public Sub New(ByVal fName As String, ByVal lName As String)
If fName = "" Or lName = "" Then
Throw New ApplicationException("First and Last Name Required")
End If
m_FirstName = fName
m_MiddleName = ""
m_LastName = lName
BuildFullName()
End Sub
Public Sub New(ByVal fName As String, ByVal mName As String, ByVal lName As String)
If fName = "" Or lName = "" Then
Throw New ApplicationException("First and Last Name Required")
End If
m_FirstName = fName
m_MiddleName = mName
m_LastName = lName
BuildFullName()
End Sub
Copy Constructor
• Constructor where the argument is another
instance of the object
• Shallow copy – shares address of references
defined in the class
• Deep copy – Duplicates all members
throughout the hierarchy.
Initializers
• Setting member variables (i.e. fields) to
specific values when the object is created.
Private m_Age As Integer = 12
Private m_City as String = "Calais"
Me pointer
• The Me keyword refers to the current instance of
the class.
• Static member functions do not have a Me
pointer.
• The Me keyword can be used to access members
from within constructors, instance methods, and
instance accessors.
• It is an error to refer to Me in a static method,
static property accessor, or variable initializer of
a field declaration.
In Visual Basic.NET a type is
defined by a class, while the
individual instances of a class
are known as objects.
What is an object?
• A class is an abstract model.
• An object is the concrete realization or instance
built on the model specified by the class.
• An object is created in the memory using the
keyword 'new' and is referenced by an identifier
called a "reference".
Creating an Object
Dim myObjRef As MyClass = New MyClass()
In the above, a instance of class MyClass is created
with the variable name of myObjRef .
The New operator
• Allocates memory for the object from the
managed heap
• Initializes the object’s overhead members (the
CLR uses these to manage the object).
– The object’s pointer to the type’s method table.
– A SyncBlockIndex (used to manage access to
the object by multiple thread).
• Calls the type’s instance constructor, passing any
parameters specified. Most languages call the
base class constructor, but this is not mandated by
the CLR.
Object Oriented Programming
The essence of object-oriented
programming is the creation of
new types.
What is an Object?
An object is a software bundle of
related variables and methods.
Software objects are often used to
model real-world objects you find in
everyday life.
Object Oriented Programming
• Where programmers define not only the data type of a data
structure, but also the types of operations (functions) that
can be applied to the data structure. The data structure
becomes an object that includes both data and functions.
• Programmers create relationships between one object and
another. Objects can inherit characteristics from other
objects.
• A principal advantages of object-oriented programming
over procedural programming is that programmers create
modules that do not need to be changed when a new type
of object is added. A programmer simply creates a new
object that inherits many of its features from existing
objects.
Procedural Programming
• Focus on sequential logic flow (i.e. steps in
a procedure, open file, read records,
calculate amount, write record, etc.)
• Focus on verbs (do this, then do this, etc.)
• Use flowcharts to work logic problems
Object Oriented Programming
• Focus on the nouns, the things (i.e.
customer, stockroom, order, etc.)
• Focus on the relationships (i.e. orders for
customer, parts for an order, etc.)
• Verbs are methods (Customer.PlaceOrder,
Part.CheckInventory, etc.)
• Use Object Oriented Modeling Tools
Object Oriented Programming
Languages
For a programming language to be a true OOP
language, the language must meet the following
criteria:
– Abstraction
– Encapsulation
– Polymorphism
– Inheritance
Abstraction
Abstraction manages the complexities of a
business problem by allowing you to identify a set
of objects involved with that business problem.
Encapsulation
Encapsulation hides the internal implementation
of an abstraction within the particular object.
Polymorphism
Polymorphism provides for multiple
implementations of the same method. For
example, different objects can have a save
method, each of which perform different
processing.
Polymorphism
poly  many
morph  forms
• When all derived types from a common
base class provide the same method, with
implementations specific to the derived
class.
• To create polymorphic methods add virtual
to the base class method.
• In the derived class add the word override.
Inheritance
• The OO term for the ability of a type to use
and extend the functionality of a base type.
• A class inherits state and behavior from its
superclass.
• Inheritance provides a powerful and natural
mechanism for organizing and structuring
software programs.
• .NET provides for true implementation
inheritance whereby you can reuse the
implementation of a class.
Implementation Inheritance
• A class can inherit from a superclass, and thereby
the new class derives the implementation of the
methods in the superclass. The new class can also
override some of the methods and extend the
behavior by adding more methods.
• One big advantage of implementation inheritance
is code reuse.
• Unlike classic C++, the CLR (and hence Visual
Basic.NET) does not support multiple
implementation inheritance.
Inheritance
To inherit from is to be a specialized version of –
Derivied Class
• Can not inherit a constructor
• Must implement its own constructor
• Can only access the base constructor by
calling it explicitly
Class Exercise 1
Create a CNameLister Class
Collection Class
The Visual Basic.NET Collection Class
• A collection is a way of grouping a set of related items.
• Many different types of collections exist. Collections are
used in Visual Basic to keep track of many things, such as
all the controls on a form (the Controls collection for
example), and users can create their own collections to
organize and manipulate objects.
• Collections are a good way to keep track of objects that
your application might need to dynamically create and
destroy. The following code fragment shows how you
might use the Add method of a collection object to keep a
list of Widget objects the user has created.
Collection – Sample Code
Public AddressBook As New Collection()
Try
Dim obj As CNameAddress = New CNameAddress()
obj.FirstName = fname
obj.LastName = lname
obj.Street = strt
obj.City = cty
obj.State = state
obj.Zipcode = zip
obj.BuildAddressKey()
AddressBook.Add(obj, obj.adrKey)
ComboBox1.Items.Add(obj.adrKey)
Catch ex As ArgumentException
MessageBox.Show(ex.Message, "Duplicate Key", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Collections in Visual Basic.NET
• In general terms, a collection is a way of grouping and managing
related objects. This simple definition, however, describes a
somewhat complex reality.
• Every form, for example, has a Controls collection. This is an
object that represents all the controls on that form. It allows you
to obtain a reference to a control in the collection by its index, and
to loop through the members of the collection using For
Each...Next statements.
• Visual Basic also provides a Collection class, with which you can
define and create your own collections. Like a form's Controls
collection, the Collection class also provides you with the built-in
functionality to loop through members using For Each...Next and
to reference members by index. Since both are collections, why
then does the following code from a Windows Forms application
generate a compiler error?
Zero-Based and One-Based Collections
• A collection is either zero-based or one-based, depending on what
its starting index is. As you might guess, the former means that the
index of the first item in the collection is zero, and the latter means
that it is one. An example of a zero-based collection is the
Controls collection used in the Form class. An instance of the
Collection object, is an example of a one-based collection.
• One-based collections are more intuitive to use, because the index
ranges from one to Count, where the Count property returns the
number of items in a collection. The index of a zero-based
collection, by contrast, ranges from zero to one less than the Count
property.
• The .NET Framework is standardizing collection as being zerobased. The Visual Basic Collection class is one based primarily for
the purpose of compatibility with previous versions.
Index and Key Values
• Many collections in Visual Basic allow you to access an
item using either a numeric index or a String key, as do
instances of the Visual Basic Collection class. You may
also add items to Collection objects without specifying a
key.
• By contrast, some collections (such as
System.Collections.ArrayList) allow only a numeric
index. These collections provide access to their members
only through the index, and do not allow you to associate
a key.
Adding and Removing Items
• Collections also differ in whether or not you can add
items to them, and if so, how those items are added.
Because the Visual Basic Collection object is a generalpurpose programming tool, it's more flexible than other
collections. It has an Add method for putting items into
the collection, and a Remove method for taking items
out.
Adding Records to a Collection
Try
Dim obj As CNameAddress = New CNameAddress()
obj.FirstName = fname
obj.LastName = lname
obj.Street = strt
obj.City = cty
obj.State = state
obj.Zipcode = zip
obj.BuildAddressKey()
AddressBook.Add(obj, obj.adrKey)
ComboBox1.Items.Add(obj.adrKey)
Catch ex As ArgumentException
MessageBox.Show(ex.Message, "Duplicate Key",
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Removing Records from a Collection
Dim i As Integer
For i = AddressBook.Count To 1 Step -1
AddressBook.Remove(i)
Next
or
For i = AddressBook.Count To 1 Step -1
Dim obj As CNameAddress
obj = AddressBook(i)
AddressBook.Remove(obj.adrKey)
Next
Why loop backwards?
Class Exercise 2
Add a Collection class to the Name
Lister Windows Form Application
Serialization
Serialization
• Serialization is the process of storing the state of an object to a
storage medium.
• During this process, the public and private fields of the object and
the name of the class, including the assembly containing the class,
are converted to a stream of bytes, which is then written to a data
stream. When the object is subsequently deserialized, an exact
clone of the original object is created.
• Why would you want to use serialization? The two most important
reasons are to persist the state of an object to a storage medium so
an exact copy can be re-created at a later stage, and to send the
object by value from one application domain to another. For
example, serialization is used to save session state in ASP.NET and
to copy objects to the Clipboard in Windows Forms. It is also used
by remoting to pass objects by value from one application domain
to another.
Serialization
1. Binary
2. XML and SOAP Serialization
Binary Serialization
• Serialization can be defined as the process of storing the state of an object to a
storage medium. During this process, the public and private fields of the object
and the name of the class, including the assembly containing the class, are
converted to a stream of bytes, which is then written to a data stream. When the
object is subsequently deserialized, an exact clone of the original object is created.
• When implementing a serialization mechanism in an object-oriented environment,
you have to make a number of tradeoffs between ease of use and flexibility. The
process can be automated to a large extent, provided you are given sufficient
control over the process. For example, situations may arise where simple binary
serialization is not sufficient, or there might be a specific reason to decide which
fields in a class need to be serialized. The following sections examine the robust
serialization mechanism provided with the .NET Framework and highlight a
number of important features that allow you to customize the process to meet your
needs.
Binary Formatter – Imports Statement
Imports System.IO
Imports System.Collections
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization
Binary Formatter – Sample Code
Dim obj As CNameAddress
Dim bFormatter As IFormatter = New BinaryFormatter
Dim strm As Stream = New FileStream("datafile.bin", _
FileMode.Create, _
FileAccess.Write, _
FileShare.None)
For i = 1 To AddressBook.Count
obj = AddressBook(i)
bFormatter.Serialize(strm, obj)
Next
strm.Close()
XML and SOAP Serialization
• XML serialization converts (serializes) the public fields and properties of an
object, or the parameters and return values of methods, into an XML stream that
conforms to a specific XML Schema definition language (XSD) document. XML
serialization results in strongly typed classes with public properties and fields that
are converted to a serial format (in this case, XML) for storage or transport.
• Because XML is an open standard, the XML stream can be processed by any
application, as needed, regardless of platform. For example, XML Web services
created using ASP.NET use the XmlSerializer class to create XML streams that
pass data between XML Web service applications throughout the Internet or on
intranets. Conversely, deserialization takes such an XML stream and reconstructs
the object.
• XML serialization can also be used to serialize objects into XML streams that
conform to the SOAP specification. SOAP is a protocol based on XML, designed
specifically to transport procedure calls using XML.
• To serialize or deserialize objects, use the XmlSerializer class. To create the
classes to be serialized, use the XML Schema Definition tool.
XML and SOAP Serialization
Imports System.IO
Imports System.Collections
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization
Dim stream As Stream = File.Open("datafile.soap", _
FileMode.Create)
Dim formatter As New SoapFormatter()
Dim obj As CNameAddress
For i = 1 To AddressBook.Count
obj = AddressBook(i)
formatter.Serialize(stream, obj)
Next
stream.Close()
<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAPENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAPENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAPENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<a1:CNameAddress id="ref-1"
xmlns:a1="http://schemas.microsoft.com/clr/nsassem/NameAddressClass/NameAddressClass%2C%20Versi
on%3D1.0.1495.13907%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull">
<m_LastName id="ref-3">Schopp</m_LastName>
<m_FirstName id="ref-4">Chip</m_FirstName>
<m_Street id="ref-5">472 Sugar Road</m_Street>
<m_City id="ref-6">Bolton</m_City>
<m_State id="ref-7">MA</m_State>
<m_Zipcode id="ref-8">01740</m_Zipcode>
<adrKey id="ref-9">Chip Schopp</adrKey>
</a1:CNameAddress>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAPENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAPENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAPENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
Deserialization
Deserialization – SoapFormatter
Dim fs As New FileStream("DataFile.soap", FileMode.Open)
Try
Dim formatter As New SoapFormatter
While (True)
Dim obj As New CNameAddress
obj = DirectCast(formatter.Deserialize(fs), _
CNameAddress)
AddressBook.Add(obj, obj.adrKey)
ComboBox1.Items.Add(obj.adrKey)
End While
Catch e3 As Xml.XmlException
MessageBox.Show("End of Stream Reached" + vbCrLf +
e3.Message, "Exception Catch", MessageBoxButtons.OK,
MessageBoxIcon.Error)
Finally
fs.Close()
End Try
Deserialize – BinaryFormatter
Dim fsIn As New FileStream("DataFile.bin", FileMode.Open)
Try
Dim bFormatter As New BinaryFormatter
While (True)
Dim obj As New CNameAddress
obj = DirectCast(bFormatter.Deserialize(fsIn), _
CNameAddress)
AddressBook.Add(obj, obj.adrKey)
ComboBox1.Items.Add(obj.adrKey)
End While
Catch e1 As SerializationException
MessageBox.Show("Failed to deserialize. Reason: " & _
e1.Message)
Finally
fsIn.Close()
End Try
Class Exercise 3
Add a logic to serialize and deserialize
the Names collection in the Name
Lister Windows Form Application
Address Book
Homework Assignment