Tuesday, 6 November 2007

Chapter 5, lesson 2: XML Serialization.

XML - can store docs, pictures, music, ...

XML Serialization
  • System.Xml.Serialization for r/w XML files.
  • Objs (incl. custom objs) <-> XML files. + transmit objs bet. computers ~ Web Services.
  • When XML Serialization? - when sending obj -> non-.NF-based app + do not need to serialize private members.
  • greater interoperability - XML is a text-based file std - all dev envs handle processing XML files.
  • more admisistrator friendly - viewed/edited ~ text-editor.
  • XML can only serialize public data - not private.
  • cannot serialize obj graphs - only objs.
  • Serialize - 1) create a stream to hold serialized output. 2) constr. XmlSerializer, 3) XmlSerializer.Serialize().
  • Deserialize - 1) Create stream to read serialized input, 2) XmlSerializer, 3) XmlSerializer.Deserialize().
  • custom XML serializable class - 1) specify class as public, 2) specify all members that must be serialized as public, 3) create a parameterless constructor. (private + protected members will be skipped).
  • XML Schema - defines the structure of an XML document.
  • when 2 apps exchange XML files, you need an XML schema.
  • XML Schema - if have one, run XML Schema Def Tool (xsd.exe) to produce class that is strongly typed to the schema. When an instance of such a class is serialized, the generated XML adheres to the XML schema. This makes it simple to create apps that interoperate with standards-based Web svcs.
  • serialize a dataset - as per serializing an obj

Chapter 5, lesson 1: Serializing Objects.

serialization - store data in objects (-> binary, SOAP, XML docs which can then be stored/transferred/retrieved).

Problem: Need to store contents of object to a file? Send an object -> another process? Transmit object across network?

Solution: Will need to convert data -> another format. This is serialization.

Serialization
  • System.Runtime.Serialization.
  • serialize/deserialize - store/transfer/re-create.
  • Serialize an Object - 1) create stream obj to hold serialized output, 2) create BinaryFormatter obj, 3) BinaryFormatter.Serialize().
  • Deserialize an Object - 1) create stream object to read the serialized output, 2) create BinaryFormatter obj, 3) create new obj to store deserialized data, 4) BinaryFormatter.Deserialize().
  • Serialize/deserialize custom classes - Serializable attribute.
  • disable serialization of specific members - [NonSerialized] public decimal total;
  • here 'total' member will not be initialized on deserialization. To automatically init. non-serialized member - IDeserializationCallback interface. Impl. IDeserializationCallback.OnDeserialization().
  • Version compatiblity tools - 1) 'custom serialization', 2) OptionalField attr - added to newly added members that might cause version compatibility probs. Leaves member's value as null if wasn't serialized, rather than throwing an exception. Initialize optinoal members ~ OnDeserialization() callback mthd.
  • Serialization format #1 - BinaryFormatter - most efficient way to serialize objs that will be read only by .NF-based apps.
  • Serialization format #2 - SoapFormatter - XML-bsaed formatter - better for transmitting across network or where read by non-.NF-based app.

Monday, 5 November 2007

Chapter 4, Lesson 5 - Generic Collections.

problem with ArrayList: it doesn't know what type of object users might want to store, so it simply stores instances of Object. This introduces runtime errors (e.g. casting to int in a foreach loop).

solution: generics - a collection class that supports basic colln interfaces (ICollection, IEnumerable), which uses ArrayList to collect items, Add() and indexer so that they are strongly-typed to a type specified by user. MyList myIntList = new MyList();

  • ArrayList -> List<> - Add, indexer, foreach for iterating - type-safe based on generic type param.
  • Sort() - new overload with generic delegate - public delegate int Comparison ( T x,T y )

Generic Dictionary Class

  • Hashtable, ListDictionary, OrderedDictionary, NameValueCollection -> Dictionary<>
  • specift type of key and value.
  • can use indexer.
  • Does not use DictionaryEntry obj to hold key/value pair. Use KeyValuePair instead.

Chapter 4, Lesson 4 - Using Specialized Collections.

Problem: ArrayList, Sequence Lists, And Dictionary classese can be used to store any object. However often leads to having to cast objects on retrieval from the collection.

Answer: System.Collection.Specialized - collns that are meant to work with specific types of data.

BitArray
  • Resizeable colln that stores bools.
  • supports std bit-lvl ops.
  • constructor - specify size, and then chang size ~ Length property.
  • does not support Add() or Remove().
  • default value of bits - false.
  • set individual bits ~ indexer.
  • Can perform ops on 2 BitArray objs of same size.

BitVector32

  • Purpose - to aid in manipulating bits in a 32-bit integer.
  • not resizeable.

BitVector32 & Bit Masks

  • All ops on BitVector32 structure actually change the value of the integer within the structure itself.
  • Data property - gets the stored integer.
  • CreateMask() - static

BitVector32 & Bit Packing

  • taking several smaller numbers & packing them into 1 large number.
  • often done to decrease storage of small numbers.
  • create sections in structure - CreateSection().

StringCollection

  • simple, dynamically sized collection that can only store strings.
  • Working with it is virtually identical to using ArrayList.
  • no casting on retrieval + will generate compile error it try to insert non-string.

StringDictionary

  • Like HashTable - but both key + value are strings.
  • keys are case-insensitive by default.

CollectionsUtil - case-insensitive collns of strings

  • Creating case-insentitive dictionary collns is so common, there are 2 shortcuts:
  • CollectionsUtil.CreateCaseINsensitiveHashtable().
  • CollectionsUtil.CreateCaseInsensitiveSortedList().

NameValueCollection Class

  • like StringDictionary - keys + values are strings.
  • Allows mult. values per key
  • can be retrieved by index as well as key.

Friday, 2 November 2007

Chapter 4, lesson3: Dictionaries.

Dictionaries - opposite end of spectrum to sequental lists. Stores key/value pairs, to allow lookup of values based on key.

Hashtable

  • Add() - specify key, specify value.
  • Indexer - key in the indexer, and then assign value.
  • retrieval - ~ indexer.
  • DictionaryEntry - derived from ICollection - a container containing Key and Value. foreach( DictionaryEntry entry in ) .Value;
  • Object.GetHashCode() - returns an int that uniquely identifies the object.
  • Hashtable - allows only unique hashes of keys, not unique keys.
  • Two strings with same text have same hash, even though they are diff. instances.
  • Hashtable - tests for equality by testing the hash codes of keys. If equal, it will then call Equals mthd, to see whether 2 objs are indeed equal.
  • Consider overriding - GetHashCode, Equals. Thus one can change a class to provide equality.
  • ...and if changing the class to provide equality is difficult? e.g. if want to store strings as keys?? - provide equality OUTSIDE the class.
  • equality OUTSIDE the class - hashtable can use a class that calculates equality.
  • Hashtable - overloaded constructor accepts instance of IEqulaityComparer interface as arg.
  • IEqualityComparer - impl. GetHashCode(), Equals(). Mthds allow the Comparer Class to handle equality re. keys, instead of relying on the key class to supply them.
  • iterating over a hashtable - returns item sin order of their hsah value.
  • If need sorting use SortedList...
SortedList
  • SortedLIst - a dictionary class.
  • can access stored items in order.
  • supports key/value access by index.
  • performs sorting as items are added.
  • Can supply a Comparer class to constructor to control how sorting is performed.

ListDictionary

  • Use like hashtable but for small (<10)>
  • If colln will fluctuate bet large & small, use HybridDictionary.
  • OrderedDictionary - like a hashtable except it allows access to items by index.

Chapter 4, lesson2: Working with Sequential Lists.

Sequential lists - a colln of objects that is to be dealt with as one, rather than accessed individually. Having access to the middle of the list is of little use here.

Queue

  • FIFO structure - putting items in + taking them out.
  • Enqueue, Dequeue, Count, Peek.
  • Enqueue - can add nulls, so cannot test result of Dequeue or peek, to test for empty - use Count.

Stack

  • Push, Pop, Cout, Peek.

Chapter 4, lesson1: Collecting Data Items.

  • collections - classes used for grouping, managing, iterating over related objects.
  • challenge - to discern the right colln to use in a specific situation.

ArrayList

  • A simple, resizeable, unordered, index-based colln of objs of any type.
  • adding/removing items - designed for these operations.
  • adding - can add objects that exist as variabls, created inline, and even value types. Value types will implicitly firstly be wrapped in a obj ref. - i.e. boxed.
  • AddRange - adding from an array or another collection. Supports adding a range of items from any object that supports ICollection interface.
  • Add/AddRange - add to end of ArrayList.
  • Insert/InsertRange - insert at specific positions.
  • Use Indexer to set at a position - however not same as Insert - it overwrites.
  • Remove, RemoveRange, RemoveAt.
  • Contains, IndexOf, Clear - if Contains(myString), then IndexOf(myString), RemoveAt(index) else Clear().

ArrayList - iterating

There are several mths to iterate over items in an ArrayList.

  • numeric indexer - for x = 0 to colln.Count - colln[x]
  • IEnumerable - ArrayList supports this interface which allows use of Enumerator to access list - GetEnumerator() returns an IEnumerator interface, which provides mechanism - MoveNext() - for iterating in fwd direction.
  • IEnumerator - colln.GetEnumerator(); while(enum.MoveNext()) - enum.Current;
  • foreach - enumerates a colln. Can be used on any colln that support IEnumerable.

Interfaces in Collections

  • ICollection - derived from IEnumerable - implemented in the API of most colln classes.
  • ICollection.CopyTo - easy way to copy contents -> Array.
  • IList - derived from ICollection - exposes mthds to get at items.

Sorting - colln.Sort();

  • Sort works by using Comparer class to perform comparison.
  • Comparer class - default implementation that supports IComparer interface.
  • IComparer - impl. Compare() - takes 2 objs & returns an int that represents the result.
  • Sort - allows one to specify diff obj which implements IComparer.
  •