• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/284

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

284 Cards in this Set

  • Front
  • Back
System.SByte
Bytes:1 Range:-128 to 127
System.Byte
Bytes:1 Range: 0 to 255
System.Int16
Bytes:2 Range: -32768 to 32767
Used for Interoperation and other specialized uses (short)
short
Bytes:2 Range: -32768 to 32767
Used for Interoperation and other specialized uses (System.Int16)
System.Int32
Bytes:4 Range:-2147483648 to 2147483647

Used for Whole numbers and counters (int)
int
Bytes:4 Range:-2147483648 to 2147483647

Used for Whole numbers and counters (System.Int32)
What are valid key lengths for the RijindaelManaged symmetric cryptography class?
128 through 256 bits in 32-bit increments.
What are valid key lengths for the DES symmetric cryptography class?
56 bits
What are valid key lengths for the TripleDES symmetric cryptography class?
156 bits which only 112 bits are effectively used for encryption.
How do you retrieve a list of supported code pages?
EncodingInfo[] ei = Encoding.GetEncodings();
foreach(EncodingInfo e in ei)
Console.WriteLine("{0}: {1}, {2}", e.CodePage, e.Name, e.DisplayName);
AssemblyAlgorithmIdAttribute
Used to specify which hash algorithm to use when reading file hashes in the assembly mainifest.

[assembly: AssemblyAlgorithmId(AssemblyHashAlgorithm.MD5)]
AssemblyCompanyAttribute
Used to specify the company that produced the assembly.

[assembly: AssemblyCompany("Proseware, Inc.")]
AssemblyConfigurationAttribute
Used to specify which configuration is used for the assembly such as "DEBUG" or "RELEASE".

[assembly: AssemblyConfiguration("DEBUG")]
AssemblyCopyrightAttribute
Used to specify the copyright information for the assembly.

[assembly: AssemblyCopyright("Copyright @Proseware, Inc. 2006")]
AssemblyInformationalVersionAttribute
Used to specify a version that is used just for informational purpose. Runtime never uses it.
AssemblyKeyFileAttribute
Used to specify the path to a key file to use to sign (or strongly name) this assembly.

[assembly: AssemblyKeyFile("../key.snk")]
AssemblyTitleAttribute
Used to specify a title for this assembly in the manifest.

[assembly: AssemblyTitle("Proseware.Framework.DataLayer")]
AssemblyTrademarkAttribute
Used to specify any trademark information about this assembly.

[assembly: AssemblyTrademark("Proseware@")]
AssemblyVersionAttribute
Used to specify the version of the assembly. The assembly version is made up of four elements followed by a period.

<major version>.<minor version>.<build number>.<revision>

The build number and revision number can be replaced with an asterisk for an autogenerated number. You cannot use an asterisk for build if revision does not have one.

[assembly: AssemblyVersion("1.2.*.*")]
Example of Getting All Assembly Attributes
Assembly a = Assembly.GetExecutingAssembly();

object[] attrs = a.GetCustomAttributes(false);
foreach (Attribute attr in attrs)
{
Console.WriteLine("Attribute: {0}", attr.GetType().Name);
}
Example of Retrieving one assembly attribute.
Assembly a = Assembly.GetExecutingAssembly();
Type attrType = typeof(AssemblyDescriptionAttribute);
object[] version Attrs = a.GetCustomAttributes(attrType, false);
if (versionAttrs.Length > 0)
{
AssemblyDescriptionAttribute desc = (AssemblyDescriptionAttribute)versionAttrs[0];
}
How do you determine whether your assembly has a particular CAS permission?
Don't use demand. Use System.Security.SecurityManager.IsGranted method.

FileIOPermission filePermissions = new FileIOPermission(FileIOPermissionAccess.Read, @"c:\Windows\);
if (SecurityManager.IsGranted(filePermissions) == true)
//
else
//
Do you need to check whether the directory exists prior to using Directory.CreateDirectory("")?
No, it is unnecessary to test whether a directory already exists before creating it.
What is IMembershipCondition?
Defines the test to determine whether a code assembly is a member of a code group.
System.UInt32
Bytes: 4 Range:0 to 4294967295

Positive whole numbers and counters (uint)
uint
Bytes: 4 Range:0 to 4294967295

Positive whole numbers and counters (System.UInt32)
System.Int64
Bytes: 8 Range: -9223372036854775808 to 9223372036854775807

Large whole numbers (long)
long
Bytes: 8 Range: -9223372036854775808 to 9223372036854775807

Large whole numbers (System.Int64)
System.Single
Bytes:4 -3.402823E+38 to 3.402823E+38

Floating point numbers (float)
float
Bytes:4 -3.402823E+38 to 3.402823E+38

Floating point numbers (System.Single)
System.Double
Bytes: 8 -1.79769313486232E+308 to 1.79769313486232E+308

Precise or large floating point numbers.
System.Decimal
Bytes: 16 -79228162514264337593543950335 to 79228162514264337593543950335 Financial and scientific clacuations requiring great precision.
Nullable
Value Type

Nullable<bool> b = null;
bool ? b = null;

HasValue and Value.
What are the simplest stream classes?
StreamWriter and StreamReader
Example of writing to a text file using StreamWriter.
StreamWriter sw = new StreamWriter("text.txt");
sw.WriteLine("Hello, World!");
sw.Close();
Example of reading from a text file using StreamReader.
StreamReader sr = new StreamReader("text.txt");
Console.WriteLine(sr.ReadToEnd());
sr.Close();
Example of creating a generic type.
class Gen<T, U>
{
public T t;
public U u;
public Gen(T _t, U _u)
{
t = _t;
u=_u;
}}
What can you rely that any type will have because it inherits from System.Object?
ToString, GetType, and Equals.
Example of consuming a Generic Type.
Gen<double, int> gb = new Gen<double, int>(10.125, 2005);
Four types of generic constraints
Interface, Base Class, Constructor(parameterless), Reference or Value Type.
Example of applying a constraing to a Generic.
class CompGen<T> where T : IComparable
{

}
How do you raise an event?
Create a delegate:
public delegate void MyEventHandler(object sender, EventArgs e);

Create an event member:
public event MyEventHandler MyEvent;

Invoke the delegate within a method when you need to raise the event:
EventArgs e = new EventArgs();
if (MyEvent != null)
{
MyEvent(this, e);
}
What is type forwarding?
Allows you to move a type from one assembly into another assembly.

[assembly:TypeForwardedTo(typeof(DestLib.TypeA))]
What is widening conversion?
When destination type can accomodate all possible values from the source type.

int i =1;
doubld d = 1.0001;
d=i;
What is narrowing conversion?
If the range or precision of the source type exceeds that of the destination type.
System.Convert
Converts between types that implement the System.IConvertible interface.
type.ToString, type.Parse
Converts between string and base types; throws exception if the conversion is not possible.
type.TryParse, type.TryParseExact
Converts from a string to a base type; returns false if the conversion is not possible.
What is boxing?
Converts a value type to a reference type.

int i=123;
object o = (object) i;
What is unboxing
Converts a reference type to a value type.

object o = 123;
int i = (int) o;
How do you define conversions for your own types?
1. Define conversion operators to simplify narrowing and widening conversions between numeric types.
2. Override ToString to provide conversion to strings, and override Parse to provide conversion from strings.
3. Implement System.IConvertible to enable conversion through System.Convert.
4. Implement a TypeConverter class to enable design-time conversion for use in the Visual Studio Properties.
Example of defining conversion operators.
struct TypeA
{
public int Value;
public static implicit operator TypeA(int arg)
{
TypeA res = new TypeA();
res.Value = arg;
return res;
}
public static explicit operator int(TypeA arg)
{
return arg.Value;
}
If there is no valid conversion between two types what should you do when implementing IConvertible?
Throw an InvalidCastException
ThreadState.Aborted Enum
The thread has stopped.
ThreadState.AbortRequested Enum
The thread has been requested to abort, but the abort is still pending and has not received the ThreadAbortException
ThreadState.Background Enum
The thread is running as a background thread
ThreadState.Running Enum
The thread has started.
ThreadState.Stopped Enum
The thread has stopped.
ThreadState.StopRequested Enum
The thread is being requested to stop. For internal use only.
ThreadState.Suspended Enum
The thread has been suspended. Supported for backward compatibility but deprecated.
ThreadState.SuspendedRequested Enum
The thread has been requested to suspend. Supported for backward compatibility but deprecated.
ThreadState.Unstarted Enum
The Thread has been created, but the Thread.Start method has not been called.
ThreadState.WaitSleepJoin Enum
The thread is blocked as a call to Monitor.Wait, Thread.Sleep, or Thread.Join.
What are the SslProtocols Enumerations?
Default - specifies that either SSL 3.0 or Transport Layer Security (TLS) are acceptable for secure communications,
None - No SSL protocol is specified,
Ssl2 - been superceded by Tls,
Ssl3 - been superceded by Tls,
Tls - Specifies the TLS 1.0 security protocol.
What is the most secure connection protocol supported by .Net Framework version 2.0 and its clients?
TLS
Thread constructors
Thread(ParameterizedThreadStart), Thread(ThreadStart),
Thread(ParameterizedThreadStart, Int32) - this is max stack size of thread, and Thread(ThreadStart, Int32)
FullTrust
Gives code unrestricted access to all protected resources. Skips security checks.
SkipVerification
Grants rights to bypass the verification.
Execution
Permits Execution
Nothing
Denies all resources, including right to execute.
LocalIntranet
Read Username Environment Variable, File Dialog is unrestrictive, Can use Isolated Storage, Reflection Emit, Code Execution, UI Permission unrestricted, DNS granted, default printing, Event Log instrument.
Internet
Open File Dialog, use Isolated Storage, Code Execution, UI - windowing and clipboard, Safe Printing
Everything
All Access
SecurityAction.RequestMinimum
Used for declarative security. Requires a permission for your assembly to run. If your assembly lacks the specified CAS permission, the runtime throws a System.Security.Policy.PolicyException.
SecurityAction.RequestOptional
Refuses all permissions not listed in a SecruityAction.RequestOptional or SecurityAction.RequestMinimum declaration. Defining permissions with this action ensures that your application will have no more permissions than those you have declared. If your assembly lacks the requested CAS permission, the runtime does not throw an excpetion so use combination of RequestOptional and RequestMinimum.
SecurityAction.RequestRefuse
Reduces the permissions assigned to your app. Use this type of declaration to ensure that your app does not have access to critical resources. This does not cause the runtime to throw an exception.
You need to write text to a file. What it the most efficient way to use the TextWriter class?
FileStream fs = new FileStream("Hi.dat", FileMode.Create);
TextWriter tw = new StreamWriter(fs);
tw.Write("Hello, World");
tw.Close();
fs.Close();

TextWriter class does not have a constructor. Instead you should create it using StreamWriter contructor and pass in a FileStream.
Windows Services - LocalService
Runs in the context of an account that acts as a nonprivileged user on the local computer, and presents anonymous credentials to any remote server. Use to minimize security risks.
Windows Services - NetworkService
Enables the service to authenticate to another computer on the network. This authentication is not required for anonymous connections, such as most connections to a Web server.
Windows Services - LocalSystem
The service runs with almost unlimited privileges and presents the computer's credentials to any remote server.
Windows Services - User
Default. Causes the system to prompt for a valid user name and password when the service is installed.
FileSystemInfo Class
Provides the basic functionality for all informational file system classes.
FileInfo Class
Provides the basic functionality to access and manipulate a single file in the file system.
FileInfo Properties
Directory - Gets DirectoryInfo object that represents the directory that this file is stored within;
DirectoryName, IsReadOnly, and Length.
FileInfo Methods
AppendText - Creates a new StreamWriter that will allow appending text to a file;
CopyTo - Makes a copy of the file in a new location;
Create - Creates a file based on the current file information;
CreateText - Creates a new StreamWriter and a new file for writing text.
MoveTo - Moves a file to a new location;
Open - Opens the file with specified prvileges;
OpenRead - Opens file with read-only access.
OpenText - Opens the file and returns a StreamReader to allow reading of text within the file.
OpenWrite - Opens the file with write-only access.
Replace - Replaces a file with the file that is described in the current FileInfo object.
Example of copying a file using FileInfo.
FileInfo ourFile = new FileInfo(@c"c:\boot.ini");

ourFile.CopyTo(@"c:\boot.bak");
DirectoryInfo Class
Provides the basic functionality to access and manipulate a single directory in the file system.
DirectoryInfo Properties
Parent - Gets the DirectoryInfo object for the parent directory.
Root - Gets the root part of the directory's path as a DirectoryInfo object.
DirectoryInfo Methods
Create - Creates the directory described in the current DirectoryInfo object,
CreateSubdirectory, GetDirectories - Retrieves an array of DirectoryInfo objects, GetFiles - Retrieves an array of FileInfo objects, GetFileSystemInfos - Retrieves an array of FileSystemInfo objects that represent both files and subdirectories in the current directory, MoveTo - Moves the current directory to a new location.
Example of Enumerating Files in a Directory using DirectoryInfo.
DirectoryInfo ourDir = new DirectoryInfo(@"c:\windows");
foreach(FileInfo file in ourDir.GetFiles())
{
Consoloe.WriteLine("File: {0}", file.Name);
}
DriveInfo Class
Models a drive and provides methods and properties to query for drive information.
DriveInfo properties
AvailableFreeSpace, DriveFormat, DriveType - DriveType enumeration, IsReady, Name, RootDirectory - Gets DirectoryInfo object that represents the root directory of the drive, TotalFreeSpace, TotalSize and VolumeLabel (only can be set on drives that are not readonly).
DriveInfo methods
GetDrives - static method that returns all the drives on the current system.
Example of enumerating drives
DriveInfo[] drives = DriveInfo.GetDrives();

foreach(DriveInfo drive in drives)
{
}
Path Class
Provides methods for manipulating a file system path.
Path methods (important)
All static methods. ChangeExtension, Combine - combines two compatible path strings, GetTempFileName - Generates a temporary file in the file system and returns the full path to the tile.
FileSystemWatcher Properties
EnableRaisingEvents, Filter - file filter to determine which files to watch, IncludeSubdirectories, NotifyFilter, Path.
FileSystemWatcher Method
WaitForChanged - Synchronous method for watching a directory for changes and returning a structure that contains all the changes.
FileSystemWatcher Events
Changed, Created, Deleted, Error and Renamed.
Stream Methods
Close, Flush, Read - performs sequential read of a specified number of bytes from the current position, ReadByte, Seek, SetLength, Write, WriteByte.
Example of dumping contents of a stream to the console.
static void DumpStream(Stream theStream)
{
theStream.Position = 0;
while(theStream.Position != theStream.Length)
{Console.WriteLine("{0:x2}", theStream.ReadByte());
}
Example of appending information to a stream.
static void AppendToStream(Stream the Stream, byte[] data)
{
theStream.Position = theStream.Length;
theStream.Write(data, 0, data.Length);
}
File.AppendAllText
Appends a specified string into an existing file, alternatively creating the file if it does not exist.
File.AppendText
Opens a file (or creates a new file if one does not exist) and returns a StreamWriter that is prepared to allow text to be appended to the file
File.Copy
Copies a file to a new file. The new file must not exist for the Copy to be successful.
File.Create
Creats a new file and returns a FileStream object.
File.CreateText
Creates or opens a file and returns a StreamWriter object that is ready to have text written to it.
File.Move
Moves a file from one place to another.
File.Open
Opens an existing file and returns a FileStream object.
File.OpenRead
Opens an existing file and returns a read-only FileStream object.
File.OpenText
Opens an existing file and returns a StreamReader object.
File.OpenWrite
Opens an existing file for writing and returns a StreamWriter object.
FileAccess Enumeration Members
Read - ReadOnly, Write - WriteOnly no read, ReadWrite - full access to file.
FileMode Enumeration Members
Append, Create - creates a new file (if the file already exists it is overwritten), CreateNew - Creates a new file (if file already exists an exception is thrown), Open - opens existing file (if file does not exist an exception is thrown), OpenOrCreate - Opens an existing file (If file does not exist, it creates a new file), Truncate.
FileStream Methods other than inherited methods from stream.
Lock - Prevents other processes from changing all or part of the file; Unlock.
StreamReader class
Provides the basic functionality to read data from a Stream derived class.
StreamReader properties
BaseStream - Gets the underlying stream that the reader is writing into, CurrentEncoding, EndOfStream - Determines whether the reader has encounterd the end of the stream.
StreamReader methods
Close, Peek, Read, ReadBlock, ReadLine, ReadToEnd.
Example of Opening a file.
FileStream theFile = File.Open(@"c:\boot.ini", FileMode.Open, FileAccess.Read);
Example of reading a file using FileStream and StreamReader.
FileStream theFile = File.Open(@"c:\boot.ini", FileMode.Open, FileAccess.Read);

StreamReader rdr = new StreamReader(theFile);
Console.Write(rdr.ReadToEnd());
rdr.Close();
theFile.Close();
Example of reading a file using StreamReader and a static method from File.
StreamReader rdr = File.OpenText(@"c:\boot.ini");
Console.Write(rdr.ReadToEnd());
rdr.Close();
StreamWriter properties
AutoFlush - Gets or sets an indicator that shows whether every call to the Write method should flush changes to the underlying stream., BaseStream, Encoding, NewLine - Line terminator string.
StreamWriter methods
Close, Write, WriteLine
Example of opening a file for writing.
FileStream theFile = File.Create(@"c:\somefile.txt");
Writing to a file using FileStream and StreamWriter.
FileStream theFile = File.Create(@"c:\somefile.txt");
StreamWriter writer = new StreamWrither(theFile);
writer.WriteLine("Hello");
writer.Close();
theFile.Close();
Writing to a file using StreamWriter and static method of File.
StreamWriter writer - File.CreateText(@"c:\somefile.txt");
writer.WriteLine("Hello");
writer.Close();
StringReader and StringWriter
Write to and read from in-memory strings.
BinaryReader and BinaryWriter
Write and read binary data from streams
Example of using BinaryWriter.
FileStream newFile = File.Create(@"c:\somefile.bin");
BinaryWriter writer = new BinaryWriter(newFile);
writer.write("hello");
writer.Close();
MemoryStream properties not inherited from Stream
Capacity - Gets/Sets the number of bytes allocated for the stream.
MemoryStream methods
GetBuffer - Retrieves the array of unsigned bytes that were used to create the stream. ToArray - Writes the entire stream to an array of bytes. WriteTo - Writes the memoryStream to another stream
Example of using MemoryStream
MemoryStream memStrm = new MemoryStream();

StreamWriter writer = new StreamWriter(memStrm);
writer.WriteLine("Hello");
When might you use a memory stream?
To limit the time a file is open for writing (because it locks the file).
Example of using MemoryStream to limit the time a file is open for writing.
MemoryStream memStrm = new MemoryStream();

StreamWriter writer = new StreamWriter(memStrm);
writer.WriteLine("Hello");
writer.Flush();
FileStream theFile = File.Create(@"c:\inmemory.txt");
memStrm.WriteTo(theFile);
writer.Close();
theFile.Close();
memStrm.Close();
BufferedStream class
Provides the basic functionality to wrap streams to improve performance by buffering reads and writes through the stream.
Example of using BufferedStream
FileStream newFile = File.Create(@"c:\test.txt");
BufferedStream buffered = new BufferedStream(newFile);
StreamWriter writer = new StreamWriter(buffered);
writer.WriteLine("Some data");
writer.Close();
Example of compressing data with a compression stream
FileStream sourceFile = File.OpenRead(inFilename);
FileStream destFile = File.Create(outFilename);
GZipStream compStream = new GZipStream(destFile, CompressionMode.Compress);

int theByte = sourceFile.ReadByte();
while (theByte != -1)
{
compStream.WriteByte((byte)theByte);
theByte = sourceFile.ReadByte();
}
IsolatedStorageFile Class
Provides basic functionality to create files and folders in isolated storage.
IsolatedStorageFile methods (static)
All are static. GetMachineStoreForApplication, GetMachineStoreForAssembly, GetMachineStoreForDomain, GetStore - Retrieves stores whose scope is based on the IsolatedStorageScope numberator, GetUserStoreForApplication, GetUserStoreForAssembly, GetUserStoreForDomain.
IsolatedStorageFile methods (not static)
Close, CreateDirectory, DeleteDirectory, DeleteFile, GetDirectoryNames, GetFileNames, Remove.
Example of creating a Store for Isolated Storage.
IsolatedStorageFile machineStorage = IsolatedStorageFile.GetMachineStoreForAssembly();
IsolatedStorageFileStream class
Encapsulates a stream that is used to read, write and create files in isolated storage. This class derives from the FileStream class.
Example of writing to IsolatedStorage.
IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForAssembly();
IsolatedStorageFileStream userStream = new IsolatedStorageFileStream("UserSettings.set", FileMode.Create, userStore);

StreamWriter userWriter = new StreamWriter(userStream);
userWriter.WriteLine("User Prefs");
userWriter.Close();
How to determine if a file exists in Isolated Storage.
IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForAssembly();

string[] files = userStore.GetFileNames("UserSettings.set");
if (files.Length == 0)
{
}
else...
You need complete control over how serialized data is formatted. What interface should you use?
IFormatter
You are writing an application that requires the user to open a second app named "Application.exe", make a configuration change, and then close the app. You want to automatically launch the application for the user,and then wait undefinitely until the user closes the application. How would you code this?
Process p = new Process();
p.StartInfo.FileName = "Application.exe";
p.Start();
p.WaitForExit();
You are writing a multithreaded application, and multiple threads need to read and write the same file. At times, a thread will need to read from the file, and then immediately write to the file. What it the most efficient way to handle this is the thread?
Create a ReaderWriterLock object and call ReaderWriterLock.AcquireReadLock.
Perform the reads.
Call ReaderWriterLock.UpgradeToWriterLock and perform the writes.
IComparer interface
Implement Compare method that returns an integer. < 0 left-hand object is less than the right-hand object. o = equal and > 0 left-hand object is more than right hand object.
What should you use to iterate through a dictionary?
DictionaryEntry
What do you need to do to generate your own HashCode for a HashTable?
Override GetHashCode, Overrid Equals.
IEqualityComparer Interface
Hashtable class supports a constructor that can accept an instance of the IEqualityComparer interface as an argument. Supports two methods GetHashCode and Equals.
CollectionUtils.CreateCaseInsensitiveHashtable() and CollectionUtils.CreateCaseInsensitiveSortedList()
Creates case insensitive hashtable or sortedlist respecitively.
How do you modify MS Widnows access control security for a named mutex?
Create an instance of the Mutex class. Create and instance of the MutexSecurity class using Mutex.GetAccessControl(). Add access rules to the MutexSecurityClass. Call Mutex.SetAccessControl()
What identifies both the user's current domain and login name?
WindowsIdentity.GetCurrent()
Example of Serializing an object using BinaryFormatter.
FileStream fs = new FileStrieam("SerializedData.Data", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, System.DateTime.Now);
fs.Close();
Example of Deserializing an object using BinaryFormatter.
FileStream fs = new FileStream("SerializedDate.Data", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
DateTime previousTime = new DateTime();
previousTime = (DateTime) bf.Deserialize(fs);
fs.Close();
Explain the inner workings of deserialization.
While deserializing if an object references another object, the Formatter queries the ObjectManager to determine whether the referenced object has already been deserialized, or whether it has not been deserialized. If it has not been deserialized the Formatter registers a fixup with the ObjectManager. It finalizes the object referece after the referenced object has been deserialized.
How can you serialize and deserialize custom classes?
By adding the Serializable attribute to the class.
IDeserializationCallback interface
OnDeserialization method, runtime calls method after deserialization is complete
Example of using XML to Serialize an object.
FileStream fs = new FileStream("SerializedDate.XML", FileMode.Create);
XmlSerializer xs = new XmlSerializer(typeof(DateTime));
xs.Serialize(fs, System.dateTime.Now);
fs.Close();
Example of using XML to Deserialize an object.
FileStream fs = new FileStream("SerializedDate.XML", FileMode.Open);
XmlSerializer xs = new XmlSerializer(typeof(DateTime));
DateTime previousTime = (DateTime)xs.Deserialize(fs);
fs.Close();
How do you create classes that can be serialized by using XML Serialization?
1. Specify the class as public.
2. Specify all members that must be serialized as public.
3. Create a parameterless constructor.

Note: classes do not have to have the Serializable attribute.
How do you take complete control over XML serialization?
Implement IXmlSerializable interface and override the ReadXml and WriteXml methods to control the XmlReader and XmlWriter classes.
How do you override the serialization built into the .Net Framework?
By implementing ISerializable interface and applying the Serializable attribute to the class.
What does implementing ISerializable involve?
Implementing the GetObjectData method and a special constructor that is used when the object is deserialized.
For a method to respond to an ISerializable event what requirements must it meet?
1. Accept a StreamingContext object as a parameter.
2. Return void
3. Have the attribute that matches the event you want to intercept.
Give an example of how to create an object that responds to serialization events.
[Serializable]
class ShoppingCartItem
{
public Int32 productId;
public decimal price;
public Int32 quantity;
public decimal total;
[OnSerializing]
void CalculateTotal(StreaminContext sc)
{total = price * quantity;
}
[OnDeserialized]
void CheckTotal(StreamingContext sc)
{
if(total==0){CaluclateTotal(sc);}}}
Events are supported by which Formatters?
BinaryFormatter. Soap and custom formatters you are limited to the IDeserializationCallback interface.
What is StreamingContext?
Provides information about the destination of a serialized object.
How do you create a custom formatter?
Implement the IFormatter or IGenericFormatter interface.
Thread Methods
Abort - Raises a ThreadAbortException on the thread to indicate that the thread should be aborted.
Interrupt - Raises a ThreadInterruptedException when a tread is in a blocked state (ThreadState.WaitSleepJoin). If the thread never blocks, the interruption never happens; Join - blocks the calling thread until the thread terminates. Start - Sets a thread to be scheduled for executions
Static Thread Properties
CurrentContext - Gets the current ThreadContext object related to the current thread; CurrentPrincipal - Gets/Sets the user associated with the current thread. CurrentThread - Gets the current running thread.
Example of creating a Thread
ThreadStart operation = new ThreadStart(SimpleWork);
Thread theThread = new Thread(operation);
theThread.Start();
How do you make your application wait for a thread to complete?
myThread.Join();
What should the method look like when you use ParameterizedThreadStart?
method must have a single parameter of type object and return nothing
Interlocked Methods
All are static. Add - Adds two integers as an atomic operation. Can be used for subtraction by adding a negative integer.
Decrement - Subtracts one from a value as an atomic operation. Exchange - Swaps two values as an atomic operatio. Increment - Adds one to a value as an atomic operation. Read - Reads a 64-bit number as an atomic operation. Required for 32-bit systems because 64-bit numbers are represented as two pieces of information.
What is the main problem with the Interlocked class?
Only works with a small set of .NET Types. Can only be used for single operations (?).
Why would you use a synchronization lock?
To lock more than one piece of code.
How do you increment a performance counter?
PerformanceCounter hitCounter = new PerformanceCounter("ApplicationPerformance", "HitCounter");
hitCounter.ReadOnly = false;
hitCounter.Increment();
What method should you use to generate a hash value for the dataArray object?
hash.ComputeHash(dataArray);
Which compression method should you use for compressing without cyclic redundancy?
DeflateStream
What is the third parameter o the DeflateStream or GZipStream constructor?
Boolean representing whether or not to keep the stream open.
You need to display the file names of all libraries referenced by the current process. How do you do this?
foreach (ProcessModule library in Process.GetCurrentProcess().Modules)
Console.WriteLine(library.FileName);
Example of adding two threads to the tread pool and waiting for one to complete before processing the other.
WaitCallback cbRetrieve = new WaitCallback( RetrieveDat);
WaitCallback cbProcess = new WaitCallback( ProcessData);
ThreadPool.QueueUserWorkItem(cbRetrieve);
ThreadPool.QueueUserWorkItem(cbProcess);
Example of encoding a UTF-32 encoded string into an ASCII-encode byte array.
public byte[] ASCIIEncode(string regionalData){
ASCIIEncoding aEncode = new ASCIIEncoding();
return aEncode.GetBytes(regionalData);
}
You wnat to create a custom event log on the server ApplicationServer. What code would you use to create a custom event log on ApplicationServer?
EventSourceCreationData sourceData = new EventSourceCreationData("Application1", "Profile");
sourceData.MachineName = "ApplicationServer";
EventLog.CreateEventSource( sourceData);
How do you launch an application with command line arguments?
Process myProcess = new Process();
myProcess.StartInfo = new ProcessStartInfo ("App.exe");
myProcess.StartInfo.Arguments = "sample.txt";
myProcess.Start();
Your application needs to load a very large file and performance is a must when deserializing what method should you use?
UnsafeDeserialize
What 3 classes should you use to create a secure data stream?
TcpClient, SslStream and X509Certificate

TcpClient clientCon = new TcpClient(serverName, 443);
SslStream clientStream = new SslStream (clientCon.GetStream());
X509CertificateCollection certificate = new S509CertificateCollection();
certificate.Add(new X509Certificate(certFilePath));
clientStream.AuthenticateAsCleint("server", certificate, SslProtocols.Default,true);
Example of synchronization lock.
public void UpdateCount()
{
lock (this)
{
_count = _count + 1;
if ((count % 2 ==0)
{
_eventCount = _eventCount +1;
}}}
What does the synchronization lock require?
That you use an object.
What should you use instead of synchronization locks if you need more control?
Montior Class
What is the synchronization locks underneath the covers?
Use the Monitor Classes.
Monitor Class Methods
Static Methods. Enter - Creates an exclusive lock on a specified object. Exit - Releases an exclusive lock on a specified object. TryEnter - Attempts to create an exclusive lock on a specified object; optionally supports a timeout value on acquiring the lock. Wait - Releases an exclusive locak, and blocks the current thread until it can re-acquire the lock.
Example of using Monitor class.
public void UpdateCount()
{
Monitor.Enter(this);
try
{
_count = _count +1;
if (Counrt % 2 == 0)
{
_evenCount = _evenCount +1;
}
}
finally
{Monitor.Exit(this);
}}
What can you do to avoid deadlocking?
Use Monitor.TryEnter with timeouts, reduce the amount of code you have loced to reduce the time that a resource is locked.
What is a ReaderWriterLock?
Allows multiple readers to access the data at the same time, but only a single writer can get a lock on the data. All readers must release their locks before a writer can get a lock on the data.
ReaderWriterLock Properties
IsReaderLockHeld, IsWriterLockHeld
ReaderWriterLock Methods
AcquireReaderLock - Gets a reader lock within a specified time. If a lock cannot be granted within the timeout period, and application exception is thrown. AcquireWriterLock - Gets a writer lock within a specified time. If a lock cannot be granted within the timeout period, an application exception is thrown. DowngradeFromWriterLock, ReleaseReaderLock, ReleaseWriterLock, UpgradeToWriterLock.
Example of using a reader lock.
ReaderWriterLock rwLock = new ReaderWriterLock();
int counter = 0;
try
{
rwLock.AcquireReaderLock(100);
try
{
Console.WriteLine(counter);
}
finally
{
rwLock.ReleaseReaderLock();
}
}
catch(ApplicationException)
{
}
Example of using a writer lock.
ReaderWriterLock rwLock = new ReaderWriterLock();
int counter = 0;
try
{
rwLock.AcquireWriterLock(1000);
try
{
Interlocked.Increment(ref counter);
}
finally
{
rwLock.ReleaseWriterLock();
}
}
catch(ApplicationException)
{}
Example of Upgrading a reader lock to a writer lock.
try
{
LockCookie cookie = rwLock.UpgradeToWriterLock(1000);
counter++;
rwLock.DowngradeFromWriterLock(ref cookie);
}
catch(ApplicationException)
{}
What are the three kernel objects that allow you to perform thread synchronization?
Mutex, Semaphore and Event.
What is a Mutex?
Allows synchronization (like a lock) across AppDomain and process boundaries.
What is a Semaphore?
Used to throttle access to a resource to a set number of threads. Supports a certain number of valid slots at once. When the slots are filled, the reamining code will block until a slot is made available by another thread releasing the slot.
What is an Event?
Provides a way to notify multiple threads (across AppDomain and process boundaries) that some event has occured.
What class do Mutex, Semaphore, AutoResetEvent and ManualResetEvent derive from?
WaitHandle class
WaitHandle Properties
Handle - Gets orsets the kernel object's native system handle.
WaitHandle Methods
Close - Releases all resources used by the current kernel object.
WaitOne - Blocks the current thread until the kernel object is signaled.
Example of using a Mutex.
Mutex m = new Mutex();
if (m.WaitOne(1000, false))
{
try
{
//some work
}
finally
{
m.ReleaseMutex()
}
}
else
{
// react to not getting the resource
}
Example of using a mutex across AppDomains.
Mutext theMutex = null;
try
{
theMutex = Mutex.OpenExisting("MYMUTEX");
}
catch (WaitHandleCannotBeOpenedException)
{
}
if (theMutex == null)
{
theMutex = new Mutex(false, "MYMUTEX");
}
Example of creating a new instance of the Semaphore class.
Allows you the specify the current number of used slots and the number of maximum slots.

Semaphore theSemaphore = new Semaphore(0,10);
Example of releasing a Semaphore.
When you release a Semaphore you can specify how many slots you want to release.

theSemaphore.Release(5);
What are the two states of events?
On and Off
What are the two types of events?
auto reset and manual reset.
What is an auto reset event?
The first object waiting for the event turns it back to a non-signaled state.
What is a manual reset event?
Allows all threads that are waiting for it to become unblocked until something manually resets the vent to a nonsignaled state.
What class do AutoResetEvent and ManualResetEvent inherit from?
EventWaitHandle which itself inherits from the WaitHandle class.
Example of creating new instance of both event classes.
Allow you to specify the signal state of the event.

AutoResetEvent autoEvent = new AutoResetEvent(true);
ManualResetEvent manualEvent = new ManualResetEvent(false);
What are the two methods EventWaitHandle supports for working with events?
Set = turns event on
Reset = turns event off
What must you use instead of AutoResetEvent and ManualResetEvent when opening or creating a named event?
EventWaitHandle
Example of opening a named event.
EventWaitHandle theEvent = null;
try
{
theEvent = EventWaitHandle.OpenExisting("THEEVENT");
}
catch(WaitHandleCannotBeOpenedeException) {}

if (theEvent = null)
{
theEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "THEEVENT");
}
Example of Wait-Until-Done model of APM.
strm.Read(butter, 0, buffer.Length);
IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length, null, null);

//do some work here

int numBytes = strm.EndRead(result);

strm.Close();
Example of Polling model of APM.
IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length, null, null);

while (!result.IsCompleted)
{
//do some work here
Thread.Sleep(100);
}

int numBytes = strm.EndRead(result);

strm.Close();
Example of Callback model of APM.
IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(CompleteRead), strm);

static void CompleteRead(IAsyncResult result)
{
FileStream strm = (FileStream) result.AsyncState;

int numBytes = strm.EndRead(result);

strm.Close();
When are exceptions thrown during APM
During the EndXXX call.
How do you handle Windows Forms Application Exception Handling for APM?
Register for the ThreadException event on the Application class.

Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
Application.Run(new Form1());
Example of using Thread Pool to do work.
WaitCallback workItem = new WaitCallback(WorkWithParameter);
if (!ThreadPool.QueueUserWorkItem(workItem, "ThreadPooled"))
{
//Could not queue item.
}

WorkWithParameter = function name; "ThreadPooled" = parameter.
When would you want to set the maximum threads in the treadpool and give example of doing so?
When you have too many work items and you are reaching the maximum number of threads in the pool.
int threads;
int completionPorts;
ThreadPool.GetMaxThreads(out threads, out completionPorts);
ThreadPool.SetMaxThreads(threads + 10, compltionPorts+100);
When would you want to set the minimum threads in the treadpool and give an example.
When the startup costs of using the thread pool are expensive, increasing the minimum can improve performance.

int threads;
int completionPorts;

ThreadPool.GetMinThreads(out threads, out completionPorts);

ThreadPool.SetMinThreads(threads +10, completionPorts + 100);
Typically, the ThreadPool limits the number of new threads to be created uring the running of a process to...
two per second.
What is the mechanism the thread pool uses to wait on WaitHandle handls and fire off callbacks to methods when the WaitHandles are signaled?
ThreadPool.RegisterWaitForSingleObject
Example of using ThreadPool.RegisterWaitForSingleObject
Mutex mutex = new Mutex(true);

ThreadPool.RegisterWaitForSingleObject(mutex, new WaitOrTimerCallback(MutexHasFired), null, Timeout.Infinite, true);
mutex.ReleaseMutex();


static void MutexHasFired(object state, bool timedOut)
{
if (timedOut)
{
}
else{}
}
What is the SynchronizationContext class?
Allows you to write code without knowing the threading model of the particular app.
How do you use the SynchronizationContext class?
Get an instance of the SynchronizationContext class by calling the static Current property of the SynchronizationContext class. Call either Send to block until executing thread is complete or Post which is more asynchronous. Depending on threading model and if async is supported or not different results can occur. If async is not supported then both methods will run the code and return after execution.
Example of using SynchronizationContext and Send.
SynchronizationContext ctx = SynchronizationContext.Current;
ctx.Send(RunMe, "Hi");
Example of using SynchronizationContext and Post.
SynchronizationContext ctx = SynchronizationContext.Current;
ctx.Post(RunMe, "Hi");
How do you temporarily stop a Timer from firing?
Call Timer.Change and set the time values to zero.
AppDomainSetup Class
Configuration Information for a new application domain.
AppDomainSetup Property ApplicationBase
Gest/Sets the name of the root directory conating the application. When the runtime needs to satisfy a type request, it probes for the assembly containing the type in the directory specified by the ApplicationBase property.
Example of using AppDomainSetup when creating an AppDomain.
AppDomainSetup ads = new AppDomainSetup();
ads.ApplicationBase = "file://" + System.Environment.CurrentDirectory;

AppDomain d = AppDomain.CreateDomain("New Domain", null, ads);
Example of examining the properties for the current application domain.
AppDomainSetup ads = AppDomain.CurrentDomain.SetupInformation;
How do you implement a Windows Service?
1. Modify the ServiceBase.ServiceName property. It is used by the OS to identify the service and can be used to programmatically identify the service.
2. Add code to the OnStart method to setup polling or monitoring. (Enable a timer)
3. Add code to the OnStop method.
4. Optionally override the OnPause, OnContinue and OnShutdown methods If you override these methods set the ServiceBase.CanPauseAndContinue or ServiceBase.CanShutdown to true.
What classes does .Net provide for installing a Windows Service?
ServiceInstaller and ServiceProcessInstaller.
What is ServiceInstaller?
Defines service description, display name, service name and start type.
What is ServiceProcessInstaller
Defines the service account settings (LocalService, NetworkService, LocalSystem, and User).
How do you install a service manually?
Run InstallUtil yourservice.exe.
How do you uninstall your service manually?
Run InstallUtil /u yourservice.exe.
How do you control Window's Services from an assembly?
Use the System.ServiceProcess.ServiceController class.
Example of controling Window's Services from an assembly.
ServiceController sc = new ServiceController("Server");
sc.Stop();
Thread.Sleep(2000);
sc.Start();
ConfigurationUserLevel Enum
None - Gets the System.Configuration.Configuration object that applies to all users.
PerUserRoaming - Gets the roaming System.Configuration.Configuration object that applies to the current user.
PerUserRoamingAndLocal - Gets the local System.Configuration.Configuration object that applies to the current user.
What do you need to provide when you using one of the openmapped config methods?
ExeConfigFileName
Example of configuring supportedRuntime.
<?xml version ="1.0"?>
<configuration>
<startup>
<supportedRuntime version="v1.1.4322" />
</startup>
</configuration>
Rules of supportedRuntime
1. If the version of the Framework that the app was built with is present, that version will be used by the app.
2. If the version of the Framework that the app was built with isn't present and nothing is specified in the supportedRuntime version tag, the app will run under the lastest version of the Framework avail on the machine.
3. IIf the version of the Framework that the app was built with isn't present but the config file specifies a supportedRuntime tage will use it.
What should you do when you are using a shared assembly and verifying that it works with multiple applications.
Add environment path DEVPATH that points to assembly.
<configuration>
<runtime>
<developmentMode developerInstallation="true"/>
</runtime>
</configuration>
How do you specify where a certain verson of an assembly is located by using the machine configuration file?
<configuration>
<runtime>
<assemblyBinding xmlns="schemaname">
<dependentAssembly>
<assemblyIdentity name="myprogram"
publicKeyToken="xxxxxxxxx" culture="en-us" />
<codeBase version="x.0.0.0"
href="http://www.adatum.com/myprogram.dll"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Whate are the three categories of cultures?
Invariant Culture, Neutral Culture, and Specific Culture.
What is an Invariant Culture?
Culture-insensitive. Default culture when consistency is desired.
What is a Neutral Culture
A neutral culture is associated with a language but has no relationship to contries or regions (en) (fr) and (sp)
What is a Specific Culture?
Most precise, represented by a neutral culture a hyphen and then ta specific culture abbreviation.
What are zh-CHS and zh-CHT?
Neutral cultures and exception to the rule.
How do you detect a user's curent culture information?
CultureInfo usersCulture = Thread.CurrentThread.CurrentCulture;
CultureType Enumeration
AllCultures, FrameworkCultures, InstalledWin32Cultures, NeutralCultures, ReplacementCultures (custom cultures created by the user that replace cultures shipped with the .Net Framework), SpecificCultures, UserCustomCulture, WindowsOnlyCultures.
Example of getting cultures.
foreach (CultureInfo usersCulture in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{}
What two properties of the CultureInfo will work with RegionInfo?
LCID and Name
Example of RegionInfo
CultureInfo usersCulture = Thread.CurrentThread.CurrentCulture;
RegionInfo demoRegion = new RegionInfo(usersCulture.Name);
Example of using CompareInfo with a CultureInfo
String firstString = "Cote";
String secondString = "cote";
CompareInfo demoInfo = new CultureInfo("fr-FR").CompareInfo;

demoInfo.Compare(firstString, secondString, CompareOptions.IgnoreCase)
Who can register a custom culture on a PC?
An administrator.
What reference must be included in order to use CultureAndRegionInfoBuilder?
sysglobl.dll
CultureAndRegionModifiers Enumeration
Neutral, None = a specific supplemental custom culture, Replacement = replaces an existing .Net Framework culture or Windows Locale.
What is an assembly?
a logical container for Assembly metadata, type metadata, code and resources.
What is assembly metadata?
Data that is defines the assembly, such as the name, version, strong name, and culture information. Also called the manifest.
What is type metadata?
All the info that describes what a type looks like, including the namespace and type names, the individual members of a type and their parameters.
How do you get the modules returned from an assembly?
Assembly a = Assembly.GetExecutingAssembly();

Module[] mods = a.GetModules();
foreach (Module m in mods)
{}
How can you get Type objects?
From the Assembly Class, from the Module Class, From instances of Object, using the typeof keyword in C#.
Example of Getting Types from Assembly object.
Assembly a = Assembly.GetExecutingAssembly();
Type[] assemblytypes = a.GetTypes();
What are all the derived classes of MemberInfo?
ConstructorInfo, EventInfo, FieldInfo, LocalVariableInfo, MethodBase - Represents any member that can contain code is the base class for CustructorInfo and MethodInfo, MethodInfo, PropertyInfo, and Type.
Example of checking a member type.
if (member.MemberType ==MemberTypes.Property)
{
PropertyInfo prop = (PropertyInfo)member;
What is the MethodBody class?
Container that contains local variable and actual IL. Get a MethodBody by using the GetMethodBody call on a MethodBase instance.

MethodBody body = meth.GetMethodBody();
BindingFlags Enumeration
DeclaredOnly - Members directly declared on the specific type are included. Inherited members are ignored.
Default - No binding flags are used.
FlattenHierarchy - Declared and inherited members should be returned, but also returns protected members.
IgnoreCase - A case-insensitive matching of the member name should be used.
Instance - Members that are part of an instance of type will be included
NonPublic, Public, Static.
Example of using BindingFlags.
Type t = typeof(String);
BindingFlage flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;

MemberInfo[] members = t.GetMembers(flags);

foreach(MemberInfo member in members){}
Example of creating a Hashtable and adding a row writing the code dynamically.
string path = @"c:\Windows\Microsoft.Net\Framework\v2.0.50727\" + "mscorlib.dll";

Assembly theAssembly = Assembly.LoadFile(path);

Type hashType = theAssembly.GetType("System.Collections.Hashtable");

Type[] argumentTypes = Type.EmptyTypes;
ConstructorInfo ctor = hashType.GetConstructor(argumentTypes);

object newHash = ctor.Invoke(new object[] {});

MethodInfo meth = hashTypye.GetMethod("Add");
meth.Invoke(newHash, new object[] {"Hi", "Hello"});

PropertyInfo prop = hashType.GetProperty("Count");
int count = (int) prop.GetValue(newHash, null);
How do you invoke a static member?
writeLineMethod.Invoke(null, new object[](count.ToString()});

Pass in null.
What are the shortcomings of COM Interop?
Lack of support for static/shared members, COM types do not allow parameterized constructores, inheritance and portability.