- When interoperating with legacy/UNIX sys.
- r/w files in other languages.
- ASCII - 0-127 - 7-bit byte.
- for languagues other than English - 128-255 - 8-bit byte.
- code pages - ASCII for 0-127, and language specific values for 128-255.
- code page - a list of character codes (code points) in a certain order.
- code pages - support specific languages.
- Windows code pages - 256 code points + zero-based.
- Unicode - a massive code page with 10000+ characters
- stds for encoding Unicode - UTF-16, UTF-8,...
- overloaded Stream constructor - new StreamWriter("abc.txt", false, Encoding.Unicode);
Monday, 29 October 2007
Chapter 3, Lesson 2: Encoding, decoding.
Ch3, lesson 1 - Forming Regular Expressions.
- Text processing - pattern matching, (sub)string extraction, (sub)string replacement.
Pattern Matching
- namespace - System.Text.RegularExpressions.
- statc mthd - System.Text.RegularExpressions.Regex.IsMatch(
, ); - ^,$ - begin, end.
- \b - word boundary.
- \B - match NOT on a \b boundary.
- @ - backslashes are treated literally.
- * >=0
- + >=1
- {n} - repeat previous char n times.
- {n,m} - repeat prev char bet n & m times.
- {n,} - repeat previous char min n times.
- ? - prev. char optional.
- . - single char.
- [] - character class/range - e.g. [0-9] = \d
- \d - numeric digit, \D - non-numeric char - [^0-9]
- \s - white-space char, \S - non-white space char
- \w - word char = [a-zA-Z0-9_], \W - [^a-zA-Z0-9_]
- () - to match group of chars
- (?
pattern) - name a group - to refer to matched data later. - backreferencing - to find repeating groups of characters.
- (?
\w)\k - finds doubled word characters. - \1 - 1st backreference in a reg expr, \2 - 2nd backref in regex,...
- extract matched data - access elts of Match>Groups array.
- Replace substrings using reg expr...
Monday, 22 October 2007
Ch2, lesson 4 - Working with Isolated Storage
- Bad idea to give pgs unfettered access to a computer. THE SANDBOX OF LIMITED SECURITY.
- Q) Where do pgs that need to persist state go?
- A) Isolated Storage (IS). Now pgs can run as least-priveleged users + persist state without having to test whether app has enough rights to save data to the hard drive.
- Main benefit of isolated storage - app will run regardless of whether runing under partial, limited or full-trust.
How to Create a Store
- Before saving to isolated storage, one must determine how to scope the data in the store:
- mthd 1 - Assembly/Machine - creates a store that is specific to the calling assembly & lcl machine. Useful for application-level data.
- mthd 2 - Assembly/User - creates a store that is specific to the calling assembly & current user. Useful for user-level data.
- create assembly/machine store - IsolatedStorageFile machineStore = IsolatedStorageFile.GetMachineStoreForAssembly(); This IS is specific to the assembly that is calling it.
IsolateStorageFileStream
- encapsulates stream to read, write and create files in IS.
R/W
- r/w -> IS like r/w any other data into the file system.
- 1. Create a Store - IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForAssembly();
- 2. Create a Stream - IsolatedStorageFileStream userStream = new IsolatedStorageFileStream("UserSettings.set", FileMode.Create, userStore);
Ch2, lesson3 - Compressing Streams.
- save space or bandwidth by compressing data.
- I/O system - 2 mthds for compressing data: GZIP, DEFLATE.
- both mthds - lmtd to compress 4GB of uncompressed data.
- GZipStream, DeflateStream classes.
- GZipStream Vs DeflateStream - GZIP has header. Header might be useful when decrompressing with gzip tool. If internal - DeflateStream file slightly smaller. If external - gzip, as may need header.
- CompressionStreams - write to another stream, not a resource (e.g. a file or memory).
- CompressionStream - wraps the stream that contains (or will contain) compressed data.
- 1. Open file to be compressed + file to be written to - FileStream sourceFile = File.OpenRead(inFileName);
- 2. wrap outgoing stream - GZipStream compStream = new GZipStream(destFile, CompressionMode.Compress);
- 3. read data from source & feed -> compression stream -
- int theByte = sourceFile.ReadByte();
- while (theByte != -1)
- {
- compStream.WriteByte.((byte)theByte);
- theByte = sourceFile.ReadByte();
- }
Friday, 19 October 2007
Ch2, lesson2 - Reading & Writing Files.
- All stream classes derive from abstract class Stream.
- File class - static mthds for opening (r/w) & creating files.
- File class - can return FileStream obj or StreamReader, StreamWriter.
- FileStream - basic func for opening file streams for reading & writing.
- StreamReader/StreamWriter - easier. Reads stream as string.
- File - Open(), OpenText(), Create(), CreateText(). ...Text() ret StreamReader.
- StringReader/Writer - read to-fro in-memory strings.
- BinaryReader/Writer - handle binary data to/fro streams.
- MemoryStream - to create in-memory streams. Used where need to create a stream before really need to store it.
- MemoryStream - can wrap MemoryStream obj in StreamWriter to write to MemoryStream.
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.
- 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
- 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...