Friday, 19 October 2007

Ch2, Lesson1 - Navigating the File System.

What are File System Classes?

  • System.IO - Set of classes to manipulate files, directories & drives.
  • file sys classes - informational & utility.
  • Informational - derive from FileSystemInfo base class. -> FileInfo, DirectoryInfo.
  • DriveInfo - not derived from FileSystemInfo.
  • Utility classes - provide static mthds to perform ops - incl File, Directory & Path classes.
  • Path - provides static mthds for manipulating a file system path.
  • FileSystemWatcher - provides mthds for monitoring file system directories for changes.
  • FileSystemWatcher - poss. to get more events generated than can be handled. FileSystemWatcher then throws Error event, which can be captured (by registering for it + turning events on).


Thursday, 18 October 2007

Lesson 4: Converting bet. types.

Conversion in C#
  • narrowing conversion - prohibited.
  • widening conversion - allowed.

Ways to Perform Explicit Conversion

  • System.Convert - bet. types that impl. IConvertible interface.
  • (type) - cast operator - bet. types that define conversion operators.

Boxing/Unboxing

  • boxing - converts a value type to ref type. (e.g. convert int -> Object)
  • unboxing - ref -> value.
  • boxing/unboxing - incur overheads.
  • boxing - occurs on calling virtual mthds that structure inherits from System.Object - e.g. ToString().
  • Best Practices:
    1. Impl. overloads for mthds that accept mult. value types. Better to create mult. overloads than 1 proc taking Object.
  • 2. Use generics instead of accpeting Object args.
  • 3. Override ToString, Equals, GetHash virtual members when defining structures.

How to Implement Conversion in Custom Types

  • conversion operators - for narrowing ( k'word explicit)/widening (k'word implicit) conversions bet. numeric types.
  • Override ToString() to provide conversion to strings, and override Parse() to provide conversion from strings.

Wednesday, 17 October 2007

(Real) Lesson 3: Constructing Classes

What is Inheritance?
  • Inheritance allows one to create new classes from existing ones, and use said derived instance as if one were using the base instance.
  • Derived classes can be used interchangeably. i.e. where a method takes a paramter of a given type, an object of any of its derived types can be passed in.

What is an interface?

  • Interface - aka 'contract'.
  • Defines a common set of 'members' that all classes that implement said interface, must provide.
  • Within the interface declaration, define the members. e.g IDisposable provides the Dispose() mthd, to free up resources. ICloneable - supports copying an object.
  • Classes can implement multiple interfaces.
  • Visual Studio has a shortcut to extract an interface - Refactor -> Extract Interface.

What are Partial Classes?

  • Allows one to split a class definition across multiple source files.
  • Benefit - hides detail. Allows derived class writers to focus on that which is significant.

What are Generics?

  • Part of the .NF type system
  • Enables type-definition while leaving some details unspecified.
  • Instead of specifying the types of parameters or member classes, you allow code that uses your type to specify it. Thus consumer code can tailor a type to its own needs.
  • .NF 2.0 - System.Collections.Generic namespace - incl. Dictionary, Queue, SortedDictionary, SortedList...
  • Above classes have non-generic counterparts in System.Collection - but they offer improved performance and type safety.

Why use Generics?

  • In .NF 1.1 - developers used Object class as generic param, and then cast other classes to/fro Object. Generics offer 2 advanatges over this approach:
  • 1. reduced runtime errors - compiler cannot catch types errors resulting from casting to/fro Object.
  • 2. Improved performance - casting requires 'boxing & unboxing' which slows performance. Generics doesn't require casting or boxing.

How to Create a Generic Type

class Gen

{

public T t;

public U u;

public Gen(T _t, U _u)

{

t = _t;

u = _u;

}

}

  • The consuming code will determine the types of T & U.
  • Limitation in creating a generic type/class - code valid only if it will compile for every possible constructed instance. Thus you are limited to the capabilities of the base Object class.

How to Consume a Generic Type

  • When you consume, you must specify the types for any generics used.

Constraints

  • Generics would be v.limited if one could only write code that would compile for any consuming class, because we would then be limited to the capabilities of base Object class.
  • Constraints - overcome this limitiation.
  • Constraints - place requirements on the types that consuming code can sub for generic.
  • 4 types of constraint:

1. Interface - Only allow types that impl. specific interface(s) to use generic.

2. Base class - Only allow types that match/inherit from a specific base class to use gen.

3. Constructor - Requesires types that use gen. to implement a parameterless constructor.

4. Ref. or value type - requires types that use gen. to be either a ref. or value type.

class CompGen

where T : IComparable

{

.

.

.

public T Max()

{

if( t2.CompareTo()t1) <>

return t1;

}

}

Events - what is an event?

  • Event - a msg sent by a object to signla the occurance of some action.
  • event sender - obj that raises the event.
  • event receiver - obj that captures/responds to the event.

What is a Delegate?

  • Acts as an intermediary bet event sender class & receiving obj.
  • delegate - a class that holds a ref to a mthd.
  • delegate class - unlike other classes, it has a signature. And it holds refs to mthds that match its signature.
  • delegate decl. - supplies signature of the delegate.
  • std signature of an event handler delegate - no ret val., 1st param type Object - refers to instance that raises event. 2nd param derived from EventArgs - holds event data.
  • public delegate void AlarmEventHandler(object sender, EventArgs e);
  • If event generates data - 2nd param custom type derived from EventArgs.
  • associate event with mthd that will handle event - add instance of the delegate to the event.

How to respond to an Event

  • 1. Create mthd to respond to event. mthd must match delegate signature.
  • 2. Add event handler - to indicate which mthd should receive events.

How to raise an Event

  • 1. create a delegate - public delegate void MyEventHandler(object sender, EventArgs e);
  • 2. create an event member - public event MyEventHandler MyEvent;
  • 3. Invoke the delegate within a mthd when need to raise event:

What are attributes?

  • Attributes describe a type, method or property in a way that can be programmatically queried ~ 'reflection'. Use attributes to:
  • 1. specify security priveleges for a class - e.g. needing to read a particular file. Runtime will thus throw an exception <>
  • Describe an assembly - title, description...




Thursday, 13 September 2007

Lesson 3: Compressing Streams

Compression - useful in real-world projects to save space or bandwidth. .NF supports 2 new stream classes that can compress data.
  • GZIP & DEFLATE - 2 mthds inside .NF. Use industry-std compression algorithms. No intellectual-property issues.
  • size limit - can compress upto 4GB of uncompressed data.
  • said comp. mthds exposed by .NF as GZipStream() & DeflateStream().
  • gzip or DEFLATE? - GZIP allows for headers for xtra info. Thus if internal use DefalteStream - slightly smaller but if distributing externally use GZIP.
  • GZipStream() - allows comp.

How to Compress Data with a Compression Stream

  • Compression streams don't write to a resource (e.g. a file, memory) - they write to other streams.
  • typical scenario - read an existing file & write to a new compressed version of the file.
  • GZipStream compStream = new GZipStream(destFile, CompressionMode.Compress) - a compression stream wraps the stream that contains (or will contain) compressed data.

Wednesday, 12 September 2007

lesson 2: Using Common Ref Types II

Understanding Readers & Writers

  • TextReader/TextWriter - abstract classes fro mwhich StreamReader/Writer are derived.
  • StringReader/Writer - to read/write to/fro in-memory strings.
  • StringWriter uses a 'StringBuilder', so it is very efficient at creating ever larger strings.
  • BinaryReader/BinaryWriter - for handling binary data to/from streams (i.e. binary files).
  • long number = reader.ReadInt64(); byre[] bytes = reader.ReadBytes(4);...
  • MemoryStream class - func. to create in-memory streams.
  • When use MemoryStream? Do time-intensive work inthe MemoryStream and then open the dest. file, flush the data to it, and close the file quickly.
  • BufferedStream - to wrap streams to improve performance by buffering reads & writes thro the stream. Writing out data to a stream directly does not perform very well. BufferStream wraps another stream object, to allow for writes to happen to a buffer. Only when the buffer is flushed does the data get pushed into the underlying stream.

Monday, 3 September 2007

lesson 2: Using Common Ref Types.

Ref Types Vs Value Types

  • Ref variable - holds the address of data rather than the data itself.
  • Assigning one ref. var to another - doesn't copy the data - merely creates 2nd copy of ref to same data.
  • 2500 built-in ref types - everything NOT derived from System.ValueType

Strings/StringBuilder

  • Immutable - cannot change - System.String.
  • Avoid temporary strings - s = "a"; s+= "qwerty"; - 2 strings created, of which only the last will have a ref. 1st garbage collected. Avoid unnecessary garbage collection here by using String class's Concat(), Join() & Format() mthds. Or use StringBuilder class to create mutable strings.
  • StringBuilder class - can span multiple stmts.

Create/Sort Arrays

  • int[] ar = {3,1,2};
  • Sort using static mthd - Array.Sort(ar);

Streams (System.IO.Stream)

  • common type - means of reading from/writing to disk.
  • StreamReader/StreamWriter - simplest - enable reading from/writing to txt files.
  • sr.ReadToEnd();

Exceptions

  • Catch block - skipped if no error encountered in try block.
  • define own exceptions - derive from System.ApplicationException.
  • Filtering Exceptions - mutiple catch blocks - runtime will only execute the 1st Catch block with a matching exception. THUS ORDER CATCH BLOCKS FROM MOST-SPECIFIC TO LEAST SPECIFIC.
  • Finally{} - runs whether an exception occured or not.
  • All code in try/catch blocks.

Monday, 20 August 2007

70-536 - Ch1 - Lesson 1 - Using Value types.

  • .NET Framework (.NF) - an integral Windows component.
  • Value types (VT) - simplest types in .NF.
  • Contain their data directly - no ref to data stored elsewhere.
  • Instances of VT stored on stack.
  • 3 general VTs: built-in types, user-defined types, enumerations. Each is derived from System.ValueType.

Built-in VTs

  • Base types, provided by .NF. Other types are built from these.
  • Optimizing performance - runtime optimizes perf. of Int32 & UInt32. For F.P use Double.
  • VTs function as objects - you can call methods on them (e.g. ToString() ).
  • In .NT, all types are derived from System.Object.

Declaring VTs

  • declare symbol as instance of that type.
  • VTs - implicit constructor - declaring them instantiates the type automatically. (No ''new' keyword).
  • Constructor assigns a default value to new instance (e.g. o or null).
  • Best practice - explicitly initialize within declaration - bool b = false;
  • C# is case-sensitive.
  • Nullable - new type in .NF 2.0 - allows one to determine whether a value has been assigned or not.
  • Nullable b = null;
  • Shorthand - bool? b = null;
  • HasValue and Value members - if (b.HasValue) ... else ...;

Creating User-Defined Types

  • UDFs - structures/structs.
  • structs - composite of other types - easier to work with related data.
  • example - System.Drawing.Point.
  • explicit construction - System.Drawing.Point p = new System.Drawing.Point(2,3);
  • define own structures ~ struct keyword.
  • Class/Struct - former created on heap & is ref type, latter created on stack & is VT.

Creating Enumerations

  • Enums - related symbols that have fixed values.
  • Use to provide a list of choices to developers using your class.
  • E.g. - enum Titles : int { Mr, Ms, Mrs, Dr };
  • Use when developers consuming your types must choose from a limited set of choices for a value.

---------------------------

Structs

  • struct - UDT. A lightweight class.
  • similar - constructors, methds, fields, properties, operators,...
  • diffs - dont support inheritance (cant inherit from any other class + implicitly sealed), or destructors. Class ref type, struct VT.
  • structs - use only for types that are small, simple, and similar in behaviour and characteristics to built-in types.
  • structs - > efficient in arrays, <>
  • structs - can implement mult. interfaces.
  • diffs - no custom default (i.e parameterless) constructor. Also cannot init. an instance fld in a struct (e.g. private int xVal = 50; )
  • structs - can create without 'new' - though not recommended - more difficult to read.
  • struct - override ToString() - prevents boxing. (e.g. when passing -> WriteLine() ).