Monday, August 10, 2009

Chapter 16-Lesson 1-2

  • System.Globalization namespace is required for creating culture-sensitive applications.
  • As a rule, a culture will be grouped into one of three categories: an invariant culture, a neutral culture, or a specific culture.
  • Thread.CurrentThread.CurrentCulture gives a CultureInfo object representing the culture of the system in which the thread is executing.
  • We should use formatting options when setting/displaying strings in our applications so that any changes made to the CurrentCulture would propagate to it.
  • CurrentUICulture represents the culture for displaying the application and may or may not be the same as CurrentCulture.
  • Also, CurrentUICulture must be set at application startup (suitably in Main( ) or Form constructor) which is a behavious opposed to CurrentCulture property. (which may be set at any time.
  • The DateTimeFormatInfo class provides a comprehensive set of methods and properties to handle and respond to the dates of different cultures.
  • Thread.CurrentThread.CurrentCulture.DateTimeFormat property is used for this purpose. It is of type DateFormatInfo.
  • NumberFormat property represents the same case for numbers and currencies.
  • CompareInfo property of CultureInfo allows for culture sensitive comparisons (usually for strings)
  • CultureRegionAndInfoBuilder class is new in .NET 2.0
  • A reference to C:\Windows\.NET Framework\[VERSION]\sysglobl.dll is required to use this class.
  • This class takes CultureAndRegionModifiers enumeration value in its second argument for constructor which specifies how much of an existing culture should be loaded in the new custom culture.

Chapter 15-Lesson 2

  • Any problem with the SMTP Server throws an SmtpException in .NET 2.0
  • The runtime encrypts the message while transmission using SSL if SMTPClient.EnableSsl property is set to true.
  • This property is new in .NET 2.0
  • Send( ) and SendAsync( ) may be used to send MailMessages through SmtpClient objects.
  • For synchronous transmissions, if the SMTP Server is not responsive, the application will wait for 100 seconds to send message by default.

Chapter 15-Lesson 1

  • System.Net.Mail is new in .NET 2.0
  • MailMessage object's To property is of type MailAddressCollection.
  • Attachments property is of type AttachmentCollection.
  • We may use AlternativeViews instead of MailMessage.Body. These allow to define different scenarios for displaying email to the recipient, depending on what capabilities the recipient may have.
  • CreateAlternateViewFromString( ) static method of AlternateView class creates a new object for it.
  • LinkedResource class is used to embed specific objects (such as images) within an HTML MailMessage using ContentID.

Sunday, August 9, 2009

Chapter 14-Lesson 5

  • All ...Builder classes derive from their ...Info counterparts and are used to create Assemblies, Modules, Types and Members at runtime.
  • System.Reflection.Emit namespace is required.
  • AppDomain.CurrentDomain.DefineDynamicAssembly( ) method creates new Assembly in the current AppDomain with the specified AssemblyName and AssemblyAccess.
  • AssemblyAccess enumeration defines why the dynamic Assembly is being created (i.e. For Running, Reflection only, etc.). If wish to save the Assembly at a later point, we may use AssemblyAccess.RunAndSave.
  • Similarly DefineDynamicModule( ) method over the AssemblyBuilder object would create a new Module inside the dynamic Assembly.
  • Again, similarly, DefineType( ) method over a ModuleBuilder object would create a new Type with the specified Name, TypeAttributes, Parent Type (if any) and any base interfaces.
  • TypeAttributes define what the type would be (class, struct, etc.), what would be its visibility (public, private, etc.) and other attributes related to a Type.
  • GetILGenerator( ) method over a MethodBuilder (or ConstructorBuilder) object would return an ILGenerator which can be used to write code into the method.
  • MSIL opcodes are defined as static members inside the ILGenerator.
  • See page 881 for PropertyBuilder usage.
  • We may call the Save( ) method over AssemblyBuilder object to save the Assembly to the disk.

Chapter 14-Lesson 4

  • The mscorlib.dll is required by every .NET Application.
  • We may use Invoke( ) method over an instance of type MethodBase to run it, passing the required parameter values as array of objects.
  • PropertyInfo class supports GetValue( ) and SetValue( ) methods to get/set values of a specific property within a Type. We simple call the method on an object and supply it with the property name and any required parameters (such as an index number, in case of a Collection property).
  • ConstructorInfo instances always return an object when invoked.
  • When invoking static methods using Dynamic Code, pass null in the object parameter.

Chapter 14-Lesson 3

  • GetTypes( ) method on an Assembly objects returns all types (classes) in all the Modules of the Assembly.
  • However, the same method may be called on a Module class to get all the types present in that particualr Module.
  • The GetType( ) method or typeof keyword (in C#) may be used over an object to ask it about its type.
  • The Fullname property of the Type class gets a fully qualified name for the Type, without the assembly information.
  • GetCustomAttributes( ) method may also be used over Type class.
  • See "What type is that Object?" on page 858.
  • MemberInfo is an abstract class and all other ...Info classes derive from it.
  • The Type class also derives from MemberInfo class.
  • MemberInfo -> MethodBase -> MethodInfo is the inheritance hierarchy for MethodInfo and ConstructorInfo classes.
  • MemberType enumeration defines possible types of members.
  • By default, the Get...( ) methods return only public members within a Type.
  • To have more control while getting members of a type, we use BindingFlags enumeration. e.g. to get protected, internal and private members, use BindingFlags.NonPublic.
  • We may use more than one BindingFlag values (using operator) during a Get...( ) method call.
  • MethodBody class represents IL Code and local variables for a particular MethodBase object.

Chapter 14-Lesson 2

  • Attributes for an Assembly are usually specified in the AssemblyInfo (.cs or .vb) file.
  • We may specify attributes such as AssemblyCompany, AssemblyCopyright, AssesmblyAlgorithm, AssemblyCulture, AssemblyDescription, AssemblyFileVersion, etc.
  • The AssemblyVersion attribute (different from AssemblyFileVersion) is composed of four parts representing: major, minor, build number and revision number.
  • We may use asterisk for both build number and revision number to tell the compiler to generate them automatically. (Note: if revision number is specified, Build number cannot be asterisk)
  • There is no inheritance tree for assemblies in .NET 2.0
  • GetCustomAttributes( ) method of the Assembly class provides an array of objects representing sttributes specified on a given Assembly.

Chapter 14-Lesson 1

  • An Assembly consists of the following parts: Assembly metadata, Type metadata, IL Code, Resources.
  • Assembly metadata is also called the manifest and contains information such as Strong Name, Version, Culture, etc.
  • Type metadata contains information about all the classes, structs, interfaces and their members.
  • Resources contain objects like images, strings, etc.
  • An Assembly may consist of multiple files.
  • The Assembly class is used to represent a .NET assembly in the code.
  • The Load( ) static method if this class loads the specified Assembly in the current AppDomain.
  • Each assembly contains one or more modules that represent containers for type information.

Friday, August 7, 2009

Chapter 13-Lesson 3

  • Platform Invoke (or P/Invoke) is sometimes required when we need to call Windows API or other unmanaged code which does not support .NET directly.
  • System.Runtime.InteropServices namespaces is required. System.Runtime.CompilerServices may also be required.
  • StringBuilder is preferrable over string during a P/Invoke.
  • All that needs to be done is to create a static external method with same name as the name of the function that needs to be called and decorate it with DllImport attribute, specifying the unmanaged dll. (This would only be a function declaration, similar to like we'd be writing prototype for that function)
  • After that whenever we call the function from within our managed code methods, the platform is invoked.
  • If we wish to convert data type from unmanaged to managed code we may us MarshalAs Attribute over a field or a parameter and specify any of the UnmanagedType enum values.
  • If an unmanaged function requires a callback, we may create a delegate specifying the signature that the callback method should possess, and while creating prototype for unmanaged code (one that requires a callback), give it an instance of that delegate. (See code on page 818)
  • This means that we cannot send a method name directly in the callback parameter of an unmanaged function due to Type-Safety.

Thursday, August 6, 2009

Chapter 12-Lesson 2

  • COM Callable Wrapper (CCW) works the exact opposite of RCW. i.e. it makes .NET assemblies usable for COM.
  • We may se it simpy by putting a check on Register for COMInterOp option in Project Properties -> Build tab.
  • To turn on/off COM visibility of individual elements within an assembly use COMVisible attribute and set it to either true or false.
  • Any class or members of a class that need to be available for COM need to be public.
  • Also, the class thats required for COM visibility should use default constructor with no parameters, and should not be abstract as well.
  • After the assembly is built, we may use Type Library Exporter utility (TlbExp.exe) to export it.
  • Interface Definition Language (IDL) may be used to generate resource scripts for COM available .NET libraries.

Chapter 13-Lesson 1

  • Runtime Callable Wrapper (RCW) is the .NET Component that handles all complex issues related to referencing and communicating COM components.
  • Type Library Importer Tool (TlbImp.exe) may be used besides Visual Studio to add reference to a COM component.
  • Regsvr32 maybe used to register any DLLs for use as COM components.
  • null value cannot be passed during a Call By Reference.
  • TlbImp generates a .NET assembly from a COM assembly.
  • Intermediate Language Disassembler (Ildasm.exe) allows to view a visual representation of the Intermediate Language (IL).
  • Use Assembly Registration Tool (Regasm.exe) to Add/Remove .NET assemblies from system registration database.
  • In .NET versions prior to 2.0, System.Exception would handles only Common Language Specification (CLS)-compliant exception. Because COM errors won’t be CLS compliant, they won’t be caught.
  • However, in .NET 2.0 there exists RuntimeWrappedException class in System.Runtime.CompilerServices namespace which inherits from System.Exception class. Therefore, now we may catch all Exceptions (CLS-based and Non-CLS-based) through System.Exception class.
  • See Limitations of COM InterOp on page 794.

Wednesday, August 5, 2009

Chapter 12-Lesson 3

  • Rijndael Symmetric Algorithm is the government standard for encryption in US, also called AES (Advanced Encryption Standard). This is also the safest of all symmetric encryption systems available in .NET 2.0
  • AES is the only class written in managed code in .NET 2.0. Other symmetric key algorithms call unmanaged code.
  • System.Security.Cryptography namespace is required.
  • Data Encryption Standard (DES) uses 56 bit keys while AES uses 128 - 256 bit keys.
  • TripleDES applies DES three times and uses 156 bits, of which only 112 bits are effectively used for encryption.
  • All these classes derive from SymmetricAlgorithm class.
  • IV (Initialization Vector) property of any of these classes must be set same for both Encryptor and Decryptor.
  • To change cipher mode (such as CBC, Cipher Block Chaining) use Mode property.
  • See Best Practice on page 749.
  • If we wish to convert a user-defined password into a Key, we may use Rfc2898DeriveBytes class. This class (which is new to .NET 2.0) works the same as the older PasswordDeriveBytes class (which is not based on standards)
  • Both KeySize and BlockSize properties are defined as a number of bits.
  • CryptoStream class defines the Stream the would encrypt source bytes to a destination Stream.
  • After the source bytes are encrypted, the Key and IV must be stored in order to decrypt the data.
  • HTTPS and SSL use Asymmetric Algorithms to exchange Symmetric Keys and then use Symmetric Encryption Algorithms for rest of the communications. The reason is that although Asymmetric Algorithms are more secure, they carry a performance overhead and are not suitable for large data.
  • Although a typical symmetric key is 182 bits, the .NET Framework implementation of the RSA algorithm supports key lengths from 384 through 16384 bits.
  • RSAParameters is a structure.
  • RSACryptoServiceProvider class is used for encrypting and decrypting data with RSA Algorithm.
  • ExportParameter( ) method of the above class would publish public and/or private key as RSAParameters structure.
  • System.Text.Encoding.Unicode.GetBytes( ) method is used to convert a string into a byte array and System.Text.Encoding.Unicode.GetString( ) method reverts it back.
  • Hashing classes derive from HashingAlgorithm base class.
  • RIPEMD160 is new in .NET 2.0 and is intended as a replacement for MD5.
  • HBMACSHA1 (Hash Based Message Authentication Code using Secure Hash Algorithm 1) produces a hash of size 20 bytes, whereas MACTripleDES produces hash of size 8 bytes.
  • ComputeHash( ) method is used to find a hash for data that exists as a byte array. We may use BinaryReader class to read a file as a byte array.
  • We may use DSACryptoServiceProvider or RSACruptoServiceProvider for Signing Data.

Chapter 12-Lesson 2

  • A Discretionary Access Control List (DACL) is an authorization restriction mechanism that identifies the users and groups that are allowed or denied access to an object.
  • By default, a DACL is controlled by the owner of an object or the person who created the object.
  • DACL contains ACEs (Access Control Entries) which are entries in an object’s DACL that grants permissions to a user or group.
  • FileSystemRights enumeration is used to specify permissions regarding Files and Folders.
  • A Security Access Control List (SACL) is a usage event logging mechanism that determines how file or folder access is audited.
  • DACLs restrict access, whereas SACLs audit access.
  • We can use the classes in the System.Security.AccessControl namespace to programmatically access DACLs, SACLs, and ACEs for files, folders, registry keys, cryptographic keys, Event Wait handles, mutexes, and semaphores.
  • This entire namespace is new in .NET 2.0
  • We may create objects of types inheriting from NativeObjectSecurity or AuthorizationRule classes and call GetAccessRules( ) or GetAuditRules( ) upon them to get an AuthorizationRuleCollection.
  • In order to check/create access rules for registry, we may require Microsoft.Win32 namespace.
  • AccessControlType enumeration determines Allow or Deny access when setting ACEs thorugh SetAccessRule( ) method.

Sunday, August 2, 2009

Chapter 12-Lesson 1

  • WindowsIdentity class in System.Security.Principal namespace represents a Windows User as an object. This class uses static methods (such as GetCurrent( ) ) to create objects.
  • WindowsPrincipal class represent the User Group in which a given user exists. After finding the WindowsIdentity of a user, we may pass it to a new WindowsPrincipal object in constructor to determine its Roles/User Group.
  • IsInRole( ) method of the WindowsPrincipal class can check for a user membership in either WindowsBuiltInRole enumerated values or a custom User Group defined as string.
  • Incase of using a string to check if user is in that particular role, we may use System.Environment.MachineName or System.Environment.UserDomainName to form strings such as "TestPC\Administrator".
  • PrincipalPermission class (and attributes) allow for imperative as well as declarative security requirements of a given user. Authenticated, Name and Role are three properties that exist for this attribute.
  • We may use PrincipalPermission attribute over a method to declaratively apply Role Based Security (RBS) to it, i.e. restricting that only certain users or user groups may be able to call it.
  • For that we first need to set the System.AppDomain.CurrentDomain.PrincipalPolicy, then decorate the method with the attribute using any of the options (name, role or authenticated)
  • Also, we must make sure we call the method within a try block with a catch for SecurityException so that if an unauthorized user tries to call the method, an exception is thrown by runtime.
  • We may also use imperative RBS with PrincipalPermission class within our method to restrict access on a more granular level.
  • WindowsIdentity, FormsIdentity, PassportIdentity and GenericIdentity inherit from IIdentity interface.
  • WindowsPrincipal and GenericPrincipal classes inherit from IPrincipal interface.
  • To implement IIdentity, one must implement the following: AuthenticationType as string, IsAuthenticated as bool and Name as string.
  • Similarly to implement IPrincipal, three things are required at minimum: A constructor (which takes IIdentity and an array of string for roles), Identity property as IIdentity and IsInRole method which takes a string for role and returns bool.

Chapter 11-Lesson 2

  • We may use declarative CAS for methods using almost the same approach as used for namespaces.
  • The difference is only in the location where they are declared (ofcourse before a method) and the names of attribute enumerations.
  • Declarative CAS for methods check those mthods for security Permissions which would be calling our method. (refer to Diagram 11-9 and 11-10)
  • SecurityAction.Demand would require every caller in the stack to have enough Permissions, while SecurityAction.LinkDemand only checks the immediate caller for enough Permissions.
  • We may use Imperative CAS demands (i.e. using C# method calls rather than attributes) if we wish to catch the exceptions raised by Demand/DemandLink inour own method. (refer to page 678 code example)
  • If we just wish to pass exception to the caller method (for not having enough Permissions) we may use Declarative CAS.
  • Demand is designed to check an assembly’s caller for permission, not the assembly itself. Instead, use the System.Security.SecurityManager.IsGranted method.
  • Most .NET built-in classes use Demand to ensure that callers have Permissions required to use them, e.g. StreamWriter itself checks for FileIOPermission.
  • SecurityAction.Deny reduces Permission such that it removes Permissions only for the specified set, while SecurityAction.PermitOnly reduces Permission such that it allows only the specified set and nothing else.
  • Deny performs a similar function to RequestRefuse, whereas PermitOnly is similar to RequestOptional.
  • CodeAccessPermission is a class which provides (also all the classes that derive from it) static methods Deny( ), PermitOnly( ), RevertDeny( ) and RevertPermitOnly( ) for imperative method CAS.
  • Best Practice is to use imperative security in error-handling routine, such as in a catch block. Acquire the bare minimum permissions for say, log an event, log it, and finally revert the permission limitation.
  • An assembly decorated with AllowPartiallyTrustedCallers attribute allows partially trusted code to access the assembly.
  • We may call Assert( ) static method only once in a given method, so if we wish to assert multiple Permissions, we'll use Assert on PermissionSet object.