Tuesday, 27 November 2007

Chapter 11, lesson 2: Using Declarative Security to Protect Assemblies.

Because CAS can restric permissions given to an app., you must write apps to run in a partially trusted security context.

Use declarative CAS demands - ensure that assm has all necessary permissions but none that it does not require.

Reasons to use CAS Assm Decl

  • To ensure that the runtime will never run your app without granting access to all required resources - if user attempts to run app and CAS security policy does not grant a required permission, an exception is thrown. Use SecurityAction.RequestMinimum - to declare all CAS perms required by app.
  • To create a sandbox for app to ensure an attacker does not manipulae it to access unintended resources - use CAS decl to reduce your assms

Classes for CAS Permissions

  • For each type of resource (e.g. files/folders, printers, network access,...) that can be restricted by CAS there is a .NF class.
  • Permission Attribute classes - inherit from CodeAccessSecurityAttribute class.
  • Action property - specifies how the runtime will interpret the permission. Set to...
  • 1) SecurityAction.RequestMinimum - requires a perm. for assm to run. If assm lacks specified perm then runtime throws exception.
  • 2) SecurityAction.RequestOptional -
  • 3) SecurityAction.RequestRefuse -
  • NOTE: CAS is significant only for partially trusted assmebles. The runtime completely ignores CAS decl for fully trusted assemblies.
  • combine RequestMinimum and RequestOptional - for non-negotiable permissions for 1 thing, but nothing else required.
  • UIPermission, Unrestricted = true - for debugging + RequestOptional.

Friday, 23 November 2007

Chapter 11, lesson 1: Understanding Code Access Security.

Code Access Security (CAS) - enables users to control permissions that individual apps have. Developers thus have to create apps that work with restricted permissions.

Can also use CAS as a developer - by restricting which calers can use your code + forcibly limiting your app to a restricted permission set.

---
  • What is CAS - a security system that aloows administrators + developers to control application authorization.
  • can control auth to following resources: file sys., registry, printers, event logs, sending web requests, whether app can make DNS requests.
  • CAS can only be applied to managed apps - ones that use the .NF runtime. Unmanaged apps limitied only by O.Ss role-based security (RBS).
  • CAS identifies and assigns permissions to apps rather than to people.
  • CAS IDs assembiles ~ evidence.
  • evidence - location where assm is stored, a hash of assm code, assm signature.
  • An assembly's evidence determine which code group it belongs to.
  • code groups - grant an assm a permission set.
  • evidence - info that runtime gathers about an assm to determine which code group it belongs to e.g. folder or web site that it runs from, digitial signatures. It's info that provs identity and describes an assm as deserving a certain level of trust.
  • types of evidence - appn dir (in whcih assm resides), hash of assm, publisher (their digitial signature thus IDs software developer), Site (from which assm was downloaded), Strong Name, URL (from where downloaded).
  • host evidence - describes assm origin.
  • assm evidence - custom user or develoer-provided evidence.
  • Permission - a CAS access control entry e.g. File Dialog - determines whether an assm can prompt user with the Open dialog box. There exist 19 permissions. You can add custom permissions.
  • Permission set - CAS ACL - a group of permissions that apply to apps falling under a particular group. (e.g. LocalIntranet Zone contains more permissions that Internet). .NF has 7 default permission sets.
  • code groups - authorization devices that associate assm with permission sets. Membership to a code group is not set manually - it is determined by the evidence that you specify as the code group's membership condition.
  • Internet_Zone code group - membership condition - host presents Zone evidence + Zone evidence IDs assm as being in Internet zone.
  • A code group must be associated with a permission set.
  • You can only specify only a single type of evidence and a single permission set for a code group.
  • An assm can be a member of mult. code groups.
  • union of permsiions - assm will receive perms as union of all code grps.
  • security policy - a logical grouping of code groups and permission sets.
  • security policy - allow administrators to configure CAS settings at 4 lvls: Enterprise, Machine, User, App Domain.
  • Enterprise Security Policy - configured ~ Active directory svc.
  • Intersection of the permission sets - rutime evalutes Enterprise, Machine & User levels separately, and grants assm minimum set of perms.
  • .NF Configuration Tool - to grant/restrict an assm perms: 1. Evaluate assm to determine which code grps it is a member of, 2. eval assm to det. perms it will be assigned, 3. adding new perm sets, 4. adding mew code groups, 5. increasing an assm's trust.
  • CAS wokrs on top of OS security - if CAS grants an assm access to write to a folder but the user running the assm does not have that perm, then assm cannot write.
  • CAS Policy Tool - caspol.exe - to examine/modify machine/user/enterprise-lvl code access policies.

chapter 10, lesson 4: Detecting Management Events.

.System.Management namespace - tools to monitor + manage the system, devices and apps ~ WMI technology.

Enumerating Management Objects
  • DirectoryObjectSearcher obj - to programatically access resources ~ WMI.
  • mimics SQL.
  • To execute query:
    1. ConnectionOptions (UserName, Password). 2. instance of DirectoryObjectSearcher, 3. Instance of ManagementScope obj - set path 4. Instance of ObjectQuery obj., 5. ManagementObjectCollection = DirectoryObjectSearcher.Get()
  • enumerating logical drives - specify target - e.g. Win32_LogicalDisk.
  • enumerating network adapters - Win32_NetworkConfiguration - new ManagemmentObjectSearcher("SELECT * FRO MWin32_NetworkConfiguration");
  • enumerating windows services - Win32_Service - ManagementObjectCollection AllObjects = DemoSearcher.Get();

Wednesday, 21 November 2007

chapter 10, lesson 3: Monitoring Performance.

...for fixing perf probs like slow/sluggish UI, network access, db connectivity,...

  • Process class - can ref O.S process running ol local or remote machine.
  • Enumerating processes -
  • 1) GetCurrentProcess(),
  • 2) GetProcessById() - if process not found, ArgumentException thrown.
  • 3) GetProcessByName(),
  • 4) GetProcesses() - ArgumentException the 'catch-all' exception out of the set that could be couaght here.
  • PerformanceCounter class - for comparing baseline measurements against current measurements.
  • There exist built-in perf counters - dont reinvent the wheel!
  • CounterCreationData class - a container obj of props needed for PerformanceCounter obj.
  • PerformanceCounterCategory class - manage/manipulate PerformanceCounter objs + their categories. (See if given perf counter exists and if not, create it).

chapter 10, lesson 2: debugging and tracing.

Debug, Debugger classes - more efficient than stepping through code - less time consuming.

Debugger Class
  • enables comm with a debugger app.
  • Break() - equiv of setting bk'pt manually.
  • Log() - posts info to the attached Debugger, if present. To listener objs attached to debugger.
  • Listener - DefaultTraceListener - take Log mthds and write as text to specified target.

Debug Class

  • more granularity than Debugger.
  • Assert() - for true/false conditions - if condition isn't true it will break into the debugger automatically.
  • in release build no debug commands are compiled in so no perf degredation.
  • Fail() - doesn't use an evaluation - simply breaks at offending line and outputs failure msg.
  • Write(), WriteIf()...

Debug Attributes

  • DebuggerBrowsable attr - [DebuggerBrowsable(DebuggerBrowsableState.Never)]
  • DebuggerDisplay - configure top line for class in Locals window.
  • DebuggerHidden - stops bk'pt being set inside anything it decorates.

Monday, 19 November 2007

chapter 10, lesson 1: logging events.

  • create an event log - EventLog class. 1 or 2 actions, then use static mthds, else create instance.
  • writing - EventLog.WriteEntry() -
  • built-in logs - Aplication, Security, System logs.
  • iterate thro entries - Entries property - contains EventLogEntry properties.

Chapter 9, Lesson 4: Configuration Management.

... e.g. specifying what vers of runtime app needs, or telling app what db to connect to.

Getting/Storing settings
  • ConfigurationManager class - retrieves config settings.
  • ConfigurationManager.appSettings - exposes AppSettings.
  • ConfigurationManager.ConnectionStrings - exposes conn strings
  • ConfigurationManager.GetSection(\
    ) - rets Object.
  • ConfigurationManager.Save/SaveAs - provided... 1) ConfigurationSection.SectionInformation.ForceSave = true; 2) filename: AppName.exe.config.

Implementing Config Interfaces

  • ConfigurationSection class - replaces the deprecated IConfigurationSectionHandler interface.
  • 1) Create section in config file - decl + impl outside of all other config elts, 2) retrieve section programatic\lly - ConfigurationSectionGroupCollection gps = config.SectionGroups;
  • how to handle section? create class that impl IConfigurationSectionHandler, and impl. Create() mthd. The retrieve using ConfigurationManager.GetSection, as above.

.NF 2.0 mthd, without impl config int - r/w directly from custom config section.

  • 1) Create section in config file - decl + impl as above, 2) use ConfigurationClass as base class from which to derive classes to consume these values.

Chapter 9, Lesson 3: Using the .NF Config Tool.

...a visual tool to manage most aspects of assm config.

  • luanch it - under Admin Tools.
  • Manage the assm cache - 1) view assm in GAC, 2) add string-named assm to GA.C
  • Manage Configured Assm - 1) view configured assm, 2) Configure an assm.
  • Manage Individual Apps - 1) adding app to configure.
  • Configre an assm - Binding Policy - chnage binding redirections (switching release vers), Codebases - Security Settings

Thursday, 15 November 2007

Chapter 9, Lesson 2: Creating an Installer.

  • Setup and Deployment project types do not cover all scenarios - then create custom installer, using Installer class.
  • Such custom insallers can then be used as part of S&D proj., or installed ~ InstallUtil.exe

Using Base Installer

  • 1) derive class from base Installer.
  • 2) Override Install, Comit, Rollback, Uninstall mthds.
  • 3) Add RunInstallerAttribute to derived class, and set runInstaller param to true.
  • 4) Put derived class in assm with app to install.
  • 5) Invoke installers - i) InstallUtil.exe, ii) AssemblyInstaller/ComponentInstaller for programtic equiv.
  • 6) InstallEventHandler delegate - to facilitate Commit - wire-up Committing, Committed events in constructor.
  • 7) Installers property - ret. an instance of InstallerCollection. Can add mult. installers to a single assm. - mult. installers that do mult. things.

Chapter 8, lesson 3: Creating Windows Services.

  • WS - runs an assembly in the background without any user interaction. Run in own user session.
  • WS - can be automatically started on reboot, even if user does not log on.
  • 1. Cannot be debugged in VS. Must install, start, then attach debugger to service's process.
  • 2. Must create installation component for service apps - they install + register the svc on the server + create entry for svc with Windows Svc Control Manager.
  • 3. runs in a different 'window station' than the interactive station of the logged-on user. No dialog boxes + raise errors to event log, not UI.
  • 4. run in own security context. svc running under system account has more privileges than one under user account.

Creating a Service Project

  • There exists a Wisndows Svc app template in VS.
  • inherits from ServiceBase class.
  • OnStart, OnStop.
  • Add installers - 'Add Installer link in VS' - adds class with 2 - one to install process...

Implementing a Svc

  • ServiceBase.ServiceName property - set. ServiceName not friendly name - used by O.S. Must be unique.
  • OnStart - must not loop as has to return to O.S.
  • OnPause, OnContinue, OnShutdown. Optional.

Create an Install Project for a Service

  • Cannot simply run a svc exe. Must be installed <>
  • ServiceInstaller class - defines svc desc., display name, svc name, and start type.
  • ServiceProcessInstaller class - defines svc acc. settings. Security context set ~ Account property - 1. LocalService - nonprivileged user, 2. NetworkService - can authenticate to another comp on network, 3. LocalSystem - unlimited privileges, presents computer's credentials to any remote server.
  • VS automatically generates both above classes.

Wednesday, 14 November 2007

Chapter 8, lesson 2: Configuring Application Domains.

Configre app domains to create customized envs for assemblies.
Most important application - restricting permissions to reduce risks associated with security vulnerabilities.

Use App Domain to launch assm with limited privileges
  • Restricting permissions of an app domain greatly reduces the risk that an assm you call will perform some malicious action.
  • Defense-in-depth - providing multiple levels of protection.

Using 'Evidence' to configure App Domains

  • Code Group - a logical grouping of code that has a specified condition for membership

Chapter 8, lesson 1: Creating Application Domains.

assembly - defn - a software component that support plug-and-play. A .NET assembly is a deployable unit. An assmebly is a logical DLL oe EXE and a manifest is a detailed description (metadata) of an assembly.

  • Application Domain - a logical container. Allows mult. assemblies to run within a single process, but prevents them from accessing other assemblies' memories.
  • App Domain - like a process - separate memory spaces + access to resources.
  • App Domain - more efficient than processes - allow mult. assemblies to run in separate app domains, without overhead of launching separate processes.
  • App domains - keep assemblies separate within a single process
  • .NF - manages app domains. O.S - manages processes.
  • Create an App Domain - AppDomain d = AppDomain.CerateDomain("NewDomain");
  • Load Assembly into an App Domain -
  • 1) AppDomain d = AppDomain.CreateDomain("NewDomain");
  • 2) d.ExecuteAssembly("Assembly.exe");
  • Unload an App Domain - AppDomain.Unload(d); - individual assemblies cannt be unloaded.

Tuesday, 13 November 2007

Chapter 7, lesson 3: Asynchronous Programming Model (APM).

  • APM - allowing some portions of code to run on separate threadds.
  • Many classes support APM - supply BeginXXX and EndXXX. e.g. FileStreamBeginRead(), EndRead(). Allows asynch. execution of mthds.
  • EndXXX() - calling this blocks until asynch work is complete.
  • Rendevous Models - informs when to call EndXXX(). 3 models - Wait-Until-Done, polling, callback.
  • wait-until-done:
  • 1) strm.BeginRead(buffer,0,buffer.Length,null,null); - null for last 2 args as not Callback.
  • polling:
  • 1) while (!result.IsCompleted){//do work here Thread.Sleep(100);}
  • callback model:
  • 1) Create new AsyncCallback delegate (on another thread) when operation is complete - strmBeginRead(buffer,o,buffer.Length,new AsyncCallback(CompleteRead),strm);
  • ThreadPool - built-in, and can be used in many situations where might expect to to create own threads.
  • 1) WaitCallback workItem = new WaitCallback(WorkWithParameter);
  • 2) ThreadPool.QueueUserWorkItem()
  • ThreadPool - faster - threads reused + saves expensive setup costs. As threads become available, the thread pool posts new work to the thread.
  • change threa pool thread limits - 1) thread starvation, 2) startup thread speed.

Chapter 7, lesson 2: Sharing Data.

  • We can share data bet. multiple threads.
  • multithreading - multiple thredas might be interrogating our objs simult.
  • Interlocked.Increment - adds 1 to value as atomic operation.
  • Interlocked Class - only works with small number of .NET types.

Syncronization Locks

  • Synch locks - to allow one to synch. access to objects in .NET. Can synch access to your own classes + treat larger sections of code as atomic.
  • deadlocks - be careful!!

Other Synch. Mthds.

  • ReaderWriterLock class - lock access to readers and writers separately - allow mult. concurrent readers but only a sinlge writer.
  • To acquire a reader lock:
  • 1) Instance of ReaderWriterLock class - to be shared across any threads.
  • 2) try/catch block - catch ApplicationException - where acquisition of reader lock fails.
  • 3) acquire lock - ReaderWriterLock.AcquireReaderLock.
  • 4) try/finally - to hold any read code. thread-safe read in try, release lock in finally.
  • To acquire a wrtier lock - analogous.

  • Windows kernel objs - Mutex, Semaphore, Event.
  • Much slower than using Monitor.
  • When to use?:
  • 1) Mutex - allows synch. across AppDomain and process boudaries.
  • 2) Semaphore - throttles access to a resource to a set no. of threads.
  • 3) Event - provides a way to notify mult. threads - across AppDomain and process boundaries - that some event has occurred.

  • Mutex
  • 1) create instance of Mutex to be shared across any threads - Mutex m = new Mutex();
  • 2) WiatOne - to wait until lock is available.
  • 3) try/finally - try - do thread-safe work - finally - release lock.

Monday, 12 November 2007

Chapter 7, lesson 1: Threading.

Threading - performing multiple operations concurrently.

  • Thread class - to create + start threads.
  • ThreadState enumeration - e.g. ThreadState.Aborted.
  • create a thread - 1) create mthd which will run on thread - ret. void, no param.
  • 2) wrap mthd in ThreadStart delegate - ThreadStart operation = new ThreadStart(dispatcher);
  • 3) create thread - Thread theThread = new Thread(operation);
  • 4) start thread - theThread.Start();
  • Thread.Sleep - allows other threads to perform work.
  • Join() - makes app wait until a thread has completed.
  • ParamterizedThreadStart delegate - mthd signature has single param of type Object. Ret. void. In dispatcher(), test that obj passed in is of expected type.

Stopping Threads

  • Thread.Abort() - where dispatcher() doesn't catch ThreadAbortExeception(), thread stops at line currently executing when main thread calls Abort. Inconsistent termination point, irrespective of whether exception is caught.
  • BeginCriticalRegion, EndCriticalRegion - A critical region is a section of code that must be executed as if it were a single stmt. Any attempt to abort while within a critical region will have to wait until completion.

Execution Cnotext

  • Each thread has data associated with it - Security info (IPrincipal + thread ID), localization settings (e.g. culture thread is running in), txn info.
  • This contexct info is usually propogated to new threads.
  • default - execution context flows to helper threads.
  • ExecutionContext.SuppressFlow - can stop this - increases perf.

Chapter 6, Lesson 3 - Formatting Text & adding to images.

Adding Text to Graphics
  • Cretae Graphics obj.
  • Create Font obj. - e.g. Font f = new Font("Arial",12,FontStyle.Bold);
  • Create Brush obj. (to describe how text will be filled) OR provide System.Drawing.Brushes property - Graphics g = this.CreateGraphics(); Font f = new Font("Arial",40,FontStyle.Bold); g.DrawString("Hello",f,Brushes.Blue,10,10);

Wednesday, 7 November 2007

Chapter 6, Lesson 2 - Working with Images.

To display, create & modify images.

  • System.Drawing.Image
  • abstract class.
  • to create, load, modify, save .BMP, .JPG, .TIF files.
  • Bitmap Class - inherits from Image - for still images.
  • MetaFile Class - inherits from Image - for animated images.
  • Bitmap.GetPixel() - Returns a Color obj describing a particular pixel in the image.
  • Bitmap.SetPixel() - ...to a specific colour.
  • display an image in a form #1 - 1) load it - Image.FromFile(), 2) create a PictureBox control, 3) set image obj to background - pictureBox1.BackgroundImage = i;
  • display an image in a form #2 - 1) new Bitmap(); 2) .CreateGraphics(); 3) DrawImage().
  • create a new, blank picture - create instance of Bitmap class that does not require an existing image.
  • Edit new image - Bitmap.SetPixel or Graphics.FromImage().
  • icons -

Chapter 6, Lesson 1 - Drawing Graphics.

UI - brushes, pens, colours, fonts
lines, circles, shapes.

System.Drawing Namespace
  • circles, lines, create charts, edit/resize pics.
  • Graphics class - most used - mths for drawing to display device.
  • Pen class - draw lines & curves.
  • Brush class (abstract) - fills interiors of shapes.
  • PictureBox class - use in Windows Forms apps to display image as part of UI.
  • System.Drawing structures - Color, Point, Rectangle, Size.
  • Specify location of control - set control's Location property using Point structure - button1.Location = new Point(10,10);
  • Specify size of control - set control's Size property using Size structure - button1.Size = new Size(30,30);
  • Specify colour - Color structure -> ForeColor/BackColor.
  • Specify custom colour - Color.FromArgB() -> ForeColor/BackColor.
  • To draw on form/control - 1) create Graphics obj - System.Windows.Forms.Control.CreateGraphics(), 2) create Pen obj, 3) call member of Graphics class to draw on control. e.g. g.DrawLine(p,1,1,100,100);
  • endcaps - ends of a line.
  • Pens - can customiize Color + Size of Pen, and also Pattern (p.DashStyle = DashStyle.Dot) and Endcaps (StartCap/EndCap).
  • Filling shapes - most Graphics Draw mthds have corresponding Fill mthds, that require Brush instead of Pen.

Tuesday, 6 November 2007

Chapter 5, lesson 3: Custom Serialization.

Custom Serialization - process of controlling the serialization/deserialization of a type.
use: serialization compatibility - ability to serialize/deserialize between versions of a type without breaking core functionality of type. (e.g. vers. n+1 needs to be able to deserialize objs of vers n).

Custom Serialization
  • override default serialization built-in to .NF - impl. ISerializable interface + apply Serializable attr to class.
  • when? 1) when value of member variable is invalid after deserialization, 2) when class to serialize is marked with Serializable attr. + has declarative or imperative security.
  • how impl. ISerializable interface? impl. GetObjectData() - for during serialization - special constructor - during deserialization. SerializationInfo obj - AddValue() - add variables to be serialized as name/value pairs.
  • respond to serialization events - to alter obj <> (de)serialization. Mthd must 1) accept StreamingContext object, 2) ret. void, 3) be decorated with attr. that you want to intercept.
  • StreamingContext structure - provides info re. the destination of a serialized object, toclasses that impl. ISerializable interface.

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.
  •