Thursday, June 25, 2009

Chapter 5-Lesson 2

  • Use XML serialization when you need to exchange an object with an application that
    might not be based on the .NET Framework
  • Private members of a class are not serialized in XML. This means only public data is serialized.
  • System.Xml.Serialization namespace is required.
  • Xml serialization does not need [Serializable] attribute on a class. However the class must be public and should have a parameter-less constructor.
  • XmlIgnore Attribute is similar to NonSerialized Attribute.
  • Xml Schema Definition tool (Xsd.exe) is used to generate set of classes that are strongly typed according to a schema.
  • DataSet.WriteXml( )/ReadXml( ) methods may be used to serialize datasets into XML.
  • For other types of collections, use TextWriter, initialize it as a StreamWriter and supply this object to XmlSerializer instead of filename in first argument. Collection could be in second argument of Serialize( ) method.

Monday, June 22, 2009

Chapter 5-Lesson 1

  • Converting Object information into another format is called Serialization.
  • System.Runtime.Serialization namespace is required
  • Items copied to clipboard, Remoting and Web Services are good examples of Serialization
  • For Binary Serialization, we use System.Runtime.Serialization.Formatters.Binary namespace BinaryFormatter class.
  • The terms 'Backward Reference' and 'Forward Reference' are used during Deserialization process when an object being Deserialized refers to another object.
  • If the referenced object is already Deserialized, the Formatter treats it a Backward Reference and completes the reference immediatly.
  • However, if the referenced object is not Deserialized yet, it is treated as a Forward Reference and the Formatter registers a fix-up with the ObjectManager which would later on complete the reference.
  • Serializable attribute allows a custom class object to be serialized by a Formatter. All members (including private ones) are serialized.
  • NonSerialized attribute before any class member would omit it from (De)Serialization process.
  • IDeserializationCallback.OnDeserialization( ) method may then be used to initialize objects which were omitted during (De)Serialization.
  • In situations where after serialization, one adds additional members to a class, deserialization may fail because serialized object would not contain info about that additional field. Therefore, if a class has previously been used for Serialization, its always good to use OptionalField attribute to newly added members for sake of Version Compatibility.
  • If members were removed from a class after some objects were serialized, .NET 2.0 would NOT throw an exception while deserializing (since there would be more info available than requested for deserialization). Older versions on .NET did.
  • If object is serialized so that it would later be read by ONLY .NET based applications, use of BinaryFormatter is preferrable. Otherwise use SOAPFormatter.
  • Using SOAPFormatter requires the project to have a reference to System.Runtime.Serialization.Formatters.Soap.dll which is not included by default in .NET 2.0
  • Use BinaryFormatter for best efficiency and SOAPFormatter for portability.
  • SoapIgnore attribute is used for public members of class which we do not wish to serialized to XML.

Monday, June 15, 2009

Chapter 4-Lesson 5

  • Generic classes are type-safe compared to usual collections.
  • There exists a generic equivalent to almost all the collections discussed in earlier chapters. e.g. ArrayList as List<>, etc.
  • Generic List<> collection allows an overload of Sort( ) method to supply a generic delegate for comparison.
  • One difference between generic Dictionary<> class and its non-generic counterparts is that it does not use DictionaryEntry objects to hold items, instead it uses generic KeyValuePair.
  • Generic LinkedList<> is new in .NET 2.0. It consists of LinkedListNode objects and uses ILinkedListEnumerator.
  • Using foreach on a LinkedList will not return LinkedListNode type objects. Instead it will return objects of type that is used to store value in each LinkedList node. Explaination code on Page 255 of MS Press book.
  • Generic collections support generic interfaces, generic enumerators and generic comparisons for type-safety.
  • Three classes are common to almost all collections in System.Collections namespace (and any of its sub-namespaces), namely, CollectionBase, ReadOnlyCollectionBase and DictionaryBase.
  • From .NET 2.0 onwards, its preferrable to use generic collections than non-generic ones.

Chapter 4-Lesson 4

  • BitArray class stores Boolean values in a resizable list. (Manually resizable using Length property)
  • This class also supports standard operations such as AND, OR, XOR, etc.
  • BitVector32 is a structure. It is not resizable, and is used to manipulate bits of, say an Int32.
  • BitArray does not support Add( ) / Remove( ) methods. We use indexers instead.
  • BitVector32 structure actually stores its value in its Data property which is an Int32. Any changes made to the bits would ultimately change the Data property.
  • BitVector32 works on unsigned integers.
  • Practical usage of BitVector32 include Bit Masking, Bit Packing, etc.
  • Bit Packing allows storage of usual small numbers into one relatively large number to save space. (e.g. instead of using three Int16 numbers, we may pack them into one Int32)
  • StringCollection and StringDictionary are strongly typed.
  • StringCollection works identical to ArrayList, and StringDictionary works identical to HashTable except that both Key and Value must be strings.
  • However, Keys in StringDictionary are case-Insensitive, meaning "fourth" and "Fourth" would lead to same Value.
  • The CollectionsUtil class provides static methods for creating case-insensitive HashTable/SortedList.
  • StringComparer object allows for creating Culture-Invariant collections.
  • The NameValueCollection allows to store multiple Values per Key. Values can be retrieved by using Key or Index.
  • This collection would behave like previous collections when items are added using indexer, but behaves differently (allows multiple Values per Key) when Add( ) method is used.
  • It also supports retriving Value using Index number of Key. If a key has more than one Value, using index would return a comma seperated list.

Sunday, June 14, 2009

Chapter 4-Lesson 3

  • Dictionary classes in .NET framework are used to map a Key to a Value.
  • Useful when creating Lookup tables.
  • Dictionaries can also use indexers.
  • Objects in Dictionaries are typically of type DictionaryEntry, which hold a key and a value.
  • All Dictionary classes derive from IDictionary which in turn derives from ICollection interface.
  • The ContainsKey( )/ContainsValue( ) methods in HashTable are used to know the existance of specific Keys/Values in a HashTable collection.
  • HashTable uses unique Hash values to store Values. So using the same Key for different values over time would retain just the latest because all others would overwrite each other.
  • Hash values are internally integers.
  • When using strings as Key, the string class overrides the GetHashCode( ) and Equals( ) method of the object class to make sure two similar strings in the Key specification get to the same Hash value in the collection (keep in mind strings are by default immutable)
  • Therefore, if we use our objects' reference as Key, we might want to override these methods to make sure two instances with some property similar between them would be treated as the same Key point in the collection. (See Page 214-215 [Fish class example] in MS Press Book)
  • The IComparer interface allows for sorting of objects of a class.
  • We may supply object from a class that implements IEqualityComparer in the constructor of a HashTable. IEqualityComparer provides the same two methods discussed above to provide results of comparison in HashTable. Details on Page 216.
  • HashTable returns items in the order of their Hash Values while traversal.
  • SortedList collection returns objects in the sorted order. Sorting takes place with respect to Key.
  • The indices of the DictionaryEntry objects may change as items are added or removed.
  • HashTable is not good (in performance) for small collections (fewer than ten elements). Instead, use ListDictionary.
  • HybirdDictionary starts as a ListDictionary and, as the data grows converts itself into a HashTable. Usage is same as HashTable.
  • HashTable does NOT allow access to items by index.
  • OrderedList class is used to attain performance of HashTable in large data scenario and at the same time allow the use of index for data items. Therefore it has extra methods that allow for insertion and removal as well as accessinf of data at specific index.

Saturday, June 13, 2009

Chapter 4-Lesson 2

  • Queue collection allows to Enqueue duplicate and null values.
  • Queue is a FIFO collection while Stack is a LIFO collection.
  • Queue supports Enqueue( ) and Dequeue( ) methods.
  • Stack supports Push( ) and Pop( ) methods.
  • Both classes support Peek( ) method.

Chapter 4-Lesson 1

  • Collections are classes that support gathering of data in an orderly manner.
  • SortedList is a name/value pair collection.
  • BitArray is compact collection of Boolean values
  • HybirdDictionary collection uses ListDictionary for small group of items and migrates to Hashtable when data size becomes large.
  • The process when ValueTypes are wrapped up in object type is called Boxing.
  • The AddRange( ) method of ArrayList supports every object that has implemented ICollection interface.
  • Add( ) and AddRange( ) methods add objects at the end of ArrayList. For adding items at specific positions, use Insert( )/InsertRange( ) methods.
  • The Remove( ) method will search for a given object in ArrayList, if found, will delete it, and if not found, will return without throwing Exception.
  • ArrayList supports indexers, so we can use them as arr[2] = "something";
  • For details on IEnumerator and how to use it, refer to MS Press book, Table 4-2 onwards.
  • An alternative to using IEnumerable properties is to use the foreach construct.
  • foreach may be used on any collection that supports IEnumerable.
  • If we know the data type of the items in a specific collection, we may specify that in the foreach loop and it will automatically handle Unboxing.
  • ICollection interface derives from IEnumerable interface. For details refer to MS Press book, Table 4-4 onwards.
  • The CopyTo( ) method of the ICollection ensures that the contents of the collection can be converted into an Array.
  • Simple collections such as ArrayList inherit from IList which in turn derives from ICollection. This adds the capability of methods such as Add( ), Clear( ), Contains( ), etc. and properties such as Item.
  • The Sort( ) method in ArrayList uses Comparer class (which implements ICompaarer). So it also allows us to supply a Comparer object incase we dont wish to use the default.

Friday, June 12, 2009

Chapter 3-Lesson 2

  • Encoding converts byte values into characters.
  • .NET 2.0 supports encoding in UTF-8, UTF-16, UTF-32, ASCII and ANSI/ISO using System.Text.Encoding. In .NET 3.5 its all present in System.Text namespace.
  • Code Pages in .NET Framework include IBM-EBCDIC as well as UTF-7 and UTF-8 standards.
  • The default encoding type in framework is UTF-16.

Chapter 3-Lesson 1

  • Regex class is used to match a string against a Regular Expression.
  • When validating input, one must put the leading carat ( ^ ) to represent beginning of input and dollar ($) sign to represent end of input pattern so as to minimize the risk of human error.
  • The carat (^) would match the expression at the beginning of any line in a multi-line string.
  • Regular Expressions characters are case sensitive, even in VB.NET
  • Tip: Use Verbatim strings (that begin with @ sign) to create regular expressions to avoid problems with back-slashes.
  • Try to learn a few simple Regular Expressions for exam.
  • Asterisk (*) means the preceding character must be present zero or more time, while plus (+) sign represents 1 or more times.
  • To define a certain number of occurrence for a character use {n} notation after the character where n is the number of occurrences.
  • We can also define min-max range for a character using {min,max} notation. We can also leave either as blank.
  • Use question mark to make character optional. And Period (.) to represent reserved space for a single character.
  • Use Table 3-3 in the MS Press book for further information.
  • We may use Back-Referencing (using \k with a named group) to search for repeating characters or groups of characters.
  • Use of RegexOptions.ECMAScript with any other options throws an Exception.

Thursday, June 11, 2009

Chapter 2-Lesson 4

  • In .NET 2.0, there are new types of applications that are meant to be deployed and installed from Web pages called “Click-Once applications” or, sometimes, “Smart-client applications.” These new types of applications are meant to solve deployment of applications across a company or enterprise.
  • Isolated Storage means the application will be able to hold data temoporarily in a system provided secure area.
  • We may create both Application-level data store and User-level data store.
  • IsolatedStorageFile class (and its static methods) is used for this purpose.
  • IsolatedStorageFileStream is derived from FileStream class.
  • Get the appropriate data store for Application/User. Create an IsolatedStorageFileStream object specifying the usual filename, FileMode and the store in which to create the file. Once this is done, its all the same as using a FileStream with StreamReader/StreamWriter.

Chapter 3-Lesson 3

  • Both GZip and DEFLATE compression systems allow compression for a maximum of 4GB data.
  • GZipStream is useful for wider distribution scenario while DeflateStream is useful for relatively smaller size (because it does not include header information)
  • Compression Streams would always wrap the FileStream with compressed data, whether during Compression or Decompression.

Sunday, June 7, 2009

Chapter 2-Lesson 2

  • Most operations with Streams involve the File class
  • StreamReader and StreamWriter classes allow for sequential reading and writing of data.
  • Static methods in the File class are almost identical to the FileInfo class.
  • Simple Create( ) method (or Open, etc) would return a FileStream object where as CreateText( ) method (or OpenText, etc) would return a StreamReader/StreamWriter object.
  • The Directory class provides static methods for routine directory operations.
  • The FileAccess enum provides the possible rights assigned when accessing a file.
  • Using FileAccess.Read would allow read-only access, whereas FileAccess.Write would allow append-only access.
  • The FileMode enum determines whether file would be created or opened or deleted, etc.
  • FileMode.Append can only be used with FileAccess.Write
  • FileMode.Create overwrites any existing file while FileMode.CreateNew throws an exception if file exists.
  • Similarly FileMode.Open would throw an exception if file does not exist but FileMode.OpenOrCreate wont.
  • The Length property of the Stream class returns length of a stream in bytes.
  • The SetLength property will Truncate (shrink) the contents of the stream if new length is lesser than the old one and vice versa.
  • The StreamReader is intended to read the Stream as a string rather than as bytes.
  • The StreamReader class is derived from the abstract TextReader class. StreamWriter derives from TextWriter abstract class.
  • Similarly StringReader/StringWriter inherit from TextReader/TextWriter class. StringWriter uses a StringBuilder.
  • For non-textual data there are BinaryReader/BinaryWriter classes.
  • One use of MemoryStream is like we use datasets for database operations. You may continue to write on a MemoryStream and when you decide to make chages permanent you wirte a MemoryStream to a FileStream. This would lock the actual file for a short period of time reducing accessibility downtime.

Friday, June 5, 2009

Chapter 2-Lesson 1

  • FileInfo.Encrypt( ) method encrypts a file
  • DriveInfo.AvailableFreeSpace( ) may return different value than DriveInfo.TotalFreeSpace( ) depending on disk quotas.
  • All types optical drives (CDROM, DVD, etc) are marked as DriveInfo.CDRom enum value
  • Path.GetFullPath( ) method can be used to resolve relative paths.
  • Path.GetRandomFileName( ) generates a random filename.
  • Given a path, the Path class can be used to extract different pieces of info within the path string (e.g. Filename, extension, directory, root directory, ...) using its methods.

Thursday, June 4, 2009

Chapter 1-Lesson 4

  • Widening conversion means converting from a low precision type to a higher precision type (e.g. from float to double)
  • Narrowing conversion usually requires explicit casting
  • C# prohibits implicit narrowing conversions
  • Boxing converts a value type to a reference type, and unboxing converts a reference
    type to a value type.
  • ToString( ), Equals( ) and GetHash( ) are virtual members of object class

Wednesday, June 3, 2009

Chapter 1-Lesson 2

  • Reference types store addresses of data on Stack
  • Actual data (object) is stored on heap.
  • Garbage collection occurs only when needed.
  • Assigning one reference variable to another doesn’t copy the data. Instead, assigning
    a reference variable to another instance merely creates a second copy of the reference
  • When you modify a reference type, you modify all copies of that reference type.
  • Arrays are reference types.
  • Stream is an abstract class.
  • Immutable objects are those whose value cannot be changed once it is assigned, e.g. string.
  • If we tend to change an immutable object, it will return a new object.
  • The default constructor for StringBuilder class creates 16-bytes buffer in memory.
  • We can create our own Exceptions by deriving from System.ApplicationException class
  • The Finally block runs after the Try block and any Catch blocks have
    finished executing, whether or not an exception was thrown.
  • IConvertable enables a class to be converted to a base (built-in type)
  • Partial classes allow you to split a class definition across multiple source files
  • Using generics doesn’t require casting or boxing, which
    improves run-time performance
  • A delegate declaration is sufficient to define a delegate class
  • EventHandler is a predefined delegate that specifically represents an event handler
    method for an event that does not generate data

Monday, June 1, 2009

Chapter 1-Lesson 1

  • Value types are also objects
  • These include Built-in types, structures and enums
  • Better use Int32 for interger operations and Double for floating point
  • Booleans are 4-byte value types (I thought they used 1-bit)
  • There are nearly 300 value types in .NET
  • Value type vvariables can be declared Nullable ( C# shortcut ?, as in float? amount; )
  • Structures are referred to as User-Defined Types.
  • Value types are stored over Stack in memory
  • Reference types are stored over a Managed Heap in memory.
  • Usually, create structures when requiring instances of size less that 16 bytes that require no inheritance, ploymorphism, etc.
  • The default base-type for enum is int
  • To create enum with another base type we can use enum Days : byte { ... }
  • Enum base type cannot be char