Categories

mcts 70-536 notes

1 Framework Fundamentals

  • Value types, structs, enums.
  • Anvend structs hvis < 16 bytes.
  • Benyt enum : int {…}.
  • Value types gemmes på stack’en, reference types på HEAP’en.
  • String er en immutable reference type.
  • Constraints for generics: Interface, Base class, Constructor, Reference eller Value type.
  • Delegate: type-sikker funktion pointer.
  • Benyt conversion operator eller IConvertible for at konverterer din custom type.
  • Exceptions

    • Anvend ApplicationException eller nedarve fra den for dine custom exception.
    • Windows applikationer: registrer exception handler for Application objektet før kald til Run() metoden. Håndter SystemException og ApplicationException på en passende måde.
  • FilePermissions kan ikke spørges om før resourcen tilgås. FileIOPermission attribute kan anvendes, som dog ikke giver garanti for at en fil ikke kan låses af en anden proces.

 

2 Input/Output

  • System.IO namespace.
  • DriveInfo for informationer om dreve.
  • FileSystemWatcher for informationer om ændringer i filer/ mapper.
  • File.ReadAllText(), FileInfo.OpenText(), FileStream, StreamReader for at læse en tekstfil.
  • Stream: FileStream, MemoryStream, IsolatedStorageFileStream.
  • TextReader : StreamReader, StringReader, BinaryReader.
  • GZipStream, DeflateStream: byte orienteret, EOF = -1, < 4 GB.
  • IsolatedStorageFile, -Stream, -Permission. Use StreamWriter/StreamReader class to easily use a IsolatedStorageFileStream.

 

3 Searching, Modifying and Encoding Text

  • System.Text.RegularExpressions namespace.
  • Regular expressions.
  • Use ^, $ always when validating user input.
  • ^, $ beginning/end of any line.
  • \A, \Z beginning/end of string.
  • \Z last character of string before \n.
  • \z last character of string.
  • \G contigues matches.
  • Backreference to group: \k<name> or \number.
  • Regex options inline: (?).
  • Named back reference in Replace and Result: ${name} or $number.
  • Encoding classes for conversion.
  • .NET default encoding: utf-16, unicode.
  • StreamReader can auto-detect: ASCII, UTF-8, UTF-16, UTF-32.

4 Collections and Generics

  • System.Collections, System.Collections.Generic, System.Collections.Specialized namespaces.
  • IEnumerable: GetEnumerator(), returns IEnumerator.
  • ICollection inherits from IEnumerable: Count, CopyTo.
  • IList inherits from ICollection: Item, Add, Remove.
  • Queue, FIFO: Enqueue, Dequeue, Count.
  • Stack, LIFO: Pop, Push, Count.
  • IDictionary inherits from ICollection: Item, Add, Remove.
  • Hashtable element equality: Same hash code and Equals returns true.
  • CaseInsensitiveComparer class.
  • SortedList: Dictionary with index access and sorted by key.
  • HybridDictionary: ListDictionary for few elements and migrates to Hashtable for many elements.
  • OrderedDictionary: Dicitionary with index and key access.
  • BitArray, Bitvector32.
  • StringCollection, StringDictionary.
  • CollectionsUtil class can instantiate case insensitive collections.
  • StringComparer.InvariantCulture to make sorting of collections not dependent on the CurrentCulture of the executing thread.
  • NameValueCollection: Stores many values per key and returns values comma separated if you do not use GetValues("key").
  • Generic collections: List<>, Queue<>, Stack<>, Dictionary<>, SortedDictionary<>, SortedList<>, LinkedList<>.
  • IComparable: CompareTo() method.
  • IComparer: Compare() method, only for Array class.
  • IEqualityComparer: GetHashCode, Equals.

5 Serialization

  • System.Runtime.Serialization namespace.
  • Serializable attribute: Public and private members are serialized.
  • ISerializable: GetObjectData and special constructor.
  • IDeserializationCallback to execute after an object is deserialized.
  • Attributes: [NonSerialized], [Serialized], [OptionalField].
  • BinaryFormatter, SoapFormatter: Serialize, Deserialize.
  • Special soap attributes.
  • System.Xml.Serialization namespace.
  • No serializable attribute, public class, public member, parameterless constructor.
  • XML serialization works only on public fields.
  • Xml…Attribute to control serialization.
  • IXmlSerializable to customize serialization.
  • StreamingContext gives destination/source information for streaming. Default values are null for Context and all for State. User has to set those manually.
  • Events: OnSerializing – before serialization occurs, OnSerialized – after serialization occured.
  • Evnets: OnDeserializing – before deserialization occurs, IDeserializationCallback.OnDeserialization – after serialization occured, OnDeserialized – after the IDeserializationCallback.
  • BinaryFormatter is compatible across .NET versions.

 

6 Graphics

  • System.Drawing namespace.
  • System* classes such as SystemFont or SystemColor.
  • How to draw: Call ControlCreateGraphics() or override it’s OnPaint() handler or use an image (as buffer or to save it later).
  • Image.FromFile() or Image.FromStream(). Image has two descendants: Bitmap – still images, Metafile – animated images.
  • Use Graphics.FromImage() to modify a picture.
  • Use DrawString() to write a text. Needs a font. Brush is optional. Use a StringFormat object to align or change direction of the text. The DrawString() takes a so-called formatting rectangle as parameter.

 

7 Threading

  • System.Threading namespace.
  • ThreadStart, ParameterizedThreadStart, Thread.Start.
  • Abort, BeginCriticalRegion, EndCriticalRegion to prevent abortion within region.
  • Context info: Security, culture, transaction context.
  • ExecutionContext to supress flow of context info to helper threads, reduces overhead.
  • Interlocked class to execute atomic operations.
  • lock(object), object is used by framework to identify the lock.
  • Monitor: Enter, TryEnter, Exit, Wait.
  • See Timeout.Infinity.
  • ReaderWriterLock.
  • Heavy kernel objects: Mutex, Semaphore, Event.
  • EventWaitHandle for named events of both types.
  • Asynchronous Programming Model (APM): wait-until-done, polling or callback.
  • Wait-until-done: Begin*(), do work, End*(IAsyncResult).
  • Polling: Begin*(), check IAsyncResult.IsCompleted and do work, End*(IAsyncCallback).
  • Callback: Begin*() and provide callback method which handles End*().
  • ThreadPool: Using, WaitHandle.
  • SynchronizationContext: Send(), Post().

8 Application Domains and Services

  • System namespace.
  • Application domains have separate memory/resources and run in the same thread. They can contain multiple assemblies.
  • AppDomain class: Create, Execute, Load, LoadFrom, Unload.
  • Evidence to give more/less permissions to the AppDomain.
  • AppDomainSetup to specify base directory and other options for creating an AppDomain.
  • Windows service: OnStart must not block or have an endless loop.
  • System.ServiceProcess.ServiceController to start or stop services programatically.

9 Installing and Configuring Applications

  • System.Configuration, System.Web.Configuration namespaces.
  • Use ConfigurationManager to get specific Configuration object.
  • In .NET 1.1 ConfigurationSettings was used. Now obsolete.
  • Use WebConfigurationManager when you need one of the following: GetWebApplicationSection(), OpenMappedWebConfiguration(), OpenWebConfiguration().
  • Add Settings File in VS 2005, use designer to create a strongly typed Settings class.
  • Derive from Installer class, place in assembly and use InstallUtil.exe to install.
  • System.Configuration.Install namespace.
  • Administrative Tools/.NET framework x.x Confguration tool.
  • ConfigurationSectionHandler to have custom sections in app.config. Note that IConfigurationSectionHandler is obsolete.
  • ApplicationSettingsBase to customize configuration manipulation.
  • Example for using ConfigurationSection: Declare section in config file, add your section with contens in config file, implement handler that derives from ConfigurationSection.

10 Instrumentation

  • System.Diagnostics namespace.
  • EventLog class: Set Source and use WriteEntry()/WriteEvent().
  • Only LocalSystem account can write to Security event log.
  • Note: You need registry write access to create an event log source.
  • An event source can only be used once!
  • Alternative for logging: Log 4 .Net or Microsoft’s enterprise library.
  • Debug and Debugger class.
  • TraceListeners and Debugger.Log to write debugging messages.
  • Debug (assert, write methods) and Debugger (sets breakpoints) statements are only compiled in Debug mode.
  • Assert.Fail().
  • Write*() write to VS output window.
  • Print() writes to all attached listeners.
  • Debugger*Attribute to control debugger behaviour.
  • Trace i nearly equivalent to Debug but is compiled in both Debug and Release mode.
  • DefaultTraceListener writes to VS output window.
  • TextWriterTraceListener writes to file or stream.
  • XmlWriterTraceListener writes to xml file or stream.
  • Listeners can also be configured in app.config.
  • EventLogTraceListener, DelimitedListTraceListener.
  • Use CorrelationManager for multi-threaded applications and web applications.
  • Process.GetProcess*().
  • Properties: Computer / Category name / Category instance / Counter.
  • Use Process.Start() with ProcessStartInfo object to start new process.
  • StackTrace, StackFrame class.
  • System.Management to manage system, devices and applications.
  • DirectoryObjectSearcher class uses SQL like queries to access WMI resources.
  • WMI resources: Win32_LogicalDisk, Win32_NetworkAdapterConfiguration, Win32_Service, … .

11 Application Security

  • System.Security.Policy namespace.
  • Code Access Security (CAS) controls authorization for managed code applications.
  • All unmanaged code are fully trusted (same rights as logged on user).
  • Evidence types (membership conditions): Application directory, hash, publisher, site, strong name, URL, zone.
  • Default groups: My_Computer_Zone, Local_Intranet_Zone, Internet_Zone, Restricted_Zone, Trusted_Zone.
  • Default permission sets: FullTrust, SkipVerification, Execution, Nothing, LocalIntranet, Internet, Everything.
  • Default permissions: Directory Services, DNS; Environment Variables, Event Log, File Dialog, File IO, Isolated Storage File, Message Queue, Performance Counter, Printing, Reflection, Registry, Security, Service Controller, Socket Access, SQL Client, User Interface, Web Access, X509 Store.
  • Code group has one type of evidence and one permission set. Can be nested.
  • Intersection of enterprise, machine, user policies defines permission for an assembly.
  • Enterprise and user policy grant full trust by default.
  • CAS is an add-on to Windows Security. It cannot allow something that Windows Security denies.
  • Full trust – does not evaluate CAS, Everything – evaluates CAS.
  • SecurityAction enumeration:

    • Assert. The calling code can access the resource even if callers higher in the stack have not been granted permission.
    • Demand. All callers higher in the call stack are required to have been granted the permission.
    • Deny. Access to resource is denied to callers even if they have been granted permission.
    • InheritanceDemand. The derived class or overriding method is required to have been granted the permission.
    • LinkDemand. The immediate caller is required to have been granted the permission.
    • PermitOnly. Only resources specified can be accessed.
    • RequestMinimum (exception at load time). The request for the minimum permissions required for the assembly to run.
    • RequestOptional (no exception at load time). The request for additional permissions that are optional for the assembly to run.
    • RequestRefuse (exception at load time). The request that permissions that might be missused will not be granted.
  • Guidelines: Use RequestMinimum declarations when your application does not handle missing permissions appropriately, use RequestOptional to list every permission required by your application, and use RequestRefuse to further restrict your RequestOptional permissions.
  • Method permission requests: Assert, Demand, Deny, InheritanceDemand, LinkDemand, PermitOnly.
  • SecurityManager.IsGranted() chekcs if the specified permission is granted by CAS.
  • CodeAccessPermission.RevertAssert() and CodeAccessPermission.RevertDeny().
  • Caspol tool can modify Machine-, User- and Enterprise-level policies via command line: -addfulltrust assembly, -addgroup, -chggroup, -listgroups, -resolvegroup assembly, -resolveperm assembly, …
  • Use the .NET framework configuration tool (from Administrative Tools) to edit CAS settings via UI.

 

12 User and Data Security

  • System.Security.Principal namespace.
  • Authentication: Identifying a user.
  • Authorization: A user’s permissions.
  • Impersonation: Execute with user’s own permissions for local machine/network. Use WindowsIdentity.Impersonate().
  • WindowsIdentity (user), WindowsPrincipal (groups) class. Use Thread.CurrentPrincipal, WindowsIdentity.GetCurrent(), WindowsPrincipal.IsInRole() or Page.User (ASP.NET).
  • Use constants for machine and domain name from Environment class to query for group memberships.
  • PrincipalPermission class to demand authentication or role used with AppDomain, CurrentDomain, SetPrincipalPolicy.
  • IIdentity, IPrincipal, GenericIdentity, GenericPrincipal for custom implementations.
  • System.Security.AccessControl namespace.
  • DACL for access rules.
  • SACL for audit rules.
  • ACL exist for cryptographic keys, directories, files, event wait handles, mutexes, registry keys and semaphores. Each class has GetAccessControl method that returns a *Security object which makes the DACL and SACL accessible. Use the Set AccessControl method to assign a security object.
  • System.Security.Cryptography namespace.
  • Symmetric key: Single key to cypher and decypher. Classes: DESCryptoServiceProvider, RC2CryptoServiceProvider, RijndaelManaged and TripleDESCryptoServiceProvider.
  • Asymmetric key: Private/public key pair. Enrypt with private for signing, encrypt with public for encryption. Classes: DSACryptoServiceProvider and RSACryptoServiceProvider.
  • Hashing algorithms: MD5, RIPEMD160, SHA1, SHA256, SHA381, SHA512.
  • Keyed hashing algorithms (symmetric key) for authentication and consistency: HMACSHA1, MACTripleDES (MAC – message authentication code).
  • Key koncepts:
    • Send symmetric key and IV with asymmetric encryption and use symmetric enryption afterwards. Improves performance.
    • Hash a message an encrypt hash key with private key.

 

13 Interoperation

  • System.Runtime.InteropServices namespace.
  • Interoperation is about using unmanaged code in .NET applications.
  • Register a COM component using Regsvr32.exe and than add a reference to your solution. Or: Use TlbImp.exe to create a wrapper .NET assembly for it.
  • You cannot pass a null value when calling unmanaged code. Use need to pass a valid memory address (object reference). Use Type.Missing for null parameters.
  • COM components throw WrappedException from System.Runtime.CompilerServices namespace. Derives from System.Exception.
  • To make a .NET assembly COM available check the build option "Register for COM interop".
  • Use ComVisibleAttribute to control visibility.
  • Plattform Invoke (P/Invoke) for unmanaged Windows API calls: Create static external method with DllImportAttribute.
  • MarshalAsAttribute specifies unmanaged type to convert from.
  • Use Marshal.GetLastWin32Error() for error handling of unmanaged code.
  • Check-out PInvoke.net for a wiki with P/I calls to existing COM libraries. You will most likely not find a description of the functions but a least it gives you the code to copy/paste.

 

14 Reflection

  • Assembly contains: manifest, type metadata, IL code, resources.
  • Assembly class loads or gets assemblies.
  • Assembly attributes are normally placed in AssemblyInfo.cs and are prefixed with "assembly:".
  • Type info can be accessed via: Assembly, Module, Object instance or using typeof(…).
  • Type class: IsInstanceOfType – checks whether object is of that type.
  • Inherit parameter: Used to specify if you only want type info that is directly declared (as opposed to inherited).
  • Info objects for all kind of members.
  • BindingFlags (flagged enum, parameter for reflection calls) to specify members returned by reflection.
  • LocalVariableInfo, MethodBody class.
  • atype.GetConstructor(Type.EntryTypes) to get a ConstructorInfo object for the type’s parameterless constructor.
  • Use Invoke() to invoke a constructor or method. Invoking the constructor returns an instance of the class.
  • Use GetValue()/SetValue() for properties.
  • System.Reflection.Emit contains builder class for each Info class to generate code at runtime.
  • Use AppDomain.DefineDynamicAssembly to create and then accordingly DefineDynamic*() on the builder objects: Assembly, Module, Type.
  • Use ILGenerator.Emit to insert actual MSIL code. Retrieve generator object by calling GetILGenerator() on the respective builder object.

15 Mail

  • System.Net.Mail namespace.
  • MailMessage class for full-featured email messages and SmtpClient.Send() for quick ones.
  • Use AlternateView and LinkedResource classes to send embedded pictures in email.
  • PickupDirectoryLocation is for Web applications using local IIS to send emails.
  • SmtpClient throws SmtpException and SmtpFailedRecipientException.
  • NetworkCredential class to specify logon credentials.
  • Asynchronous sending: SendCompleted event, SendAsync() and SendAsyncCancel(). Use SendAsync() generic parameter to uniquely identify the sent email.

 

16 Globalization

  • System.Globalization namespace.
  • CultureInfo class: string/number/date comparisions and formats and resources.
  • Invariant (none), neutral (language only) and specific (country/region) culture.
  • CurrentCulture and CurrentUICulture.
  • RegionInfo class. DateTimeFormatInfo and NumberFormatInfo.
  • CompareInfo.Compare() to compare strings.
  • CultureAndRegionInfoBuilder to create a custom culture. Needs sysglobl.dll referenced.