Monday, October 26, 2009

Chapter 6-Lesson 1

  • In Client-Server model, a thin client is one where most processing is done on server, while a thick client is one where most processing is done on the client.
  • Every ASP.NET AJAX page should contain one ScriptManager control.
  • This control is reponsible for generating Microsoft AJAX Library code for the client.
  • If a page that uses AJAX controls, contains a ScriptManager, it would conflict if the page uses a masterpage that also uses a ScriptManager. To overcome this, use ScriptManagerProxy control inside the child page.
  • Similarly use ScriptManagerProxy for User Controls that use AJAX, so that they may not conflict with any ScriptManager that is present in the page that employs the User Control.
  • UpdatePanel control defines areas of the page that are able to send Asynchronous Postbacks to the server.
  • Setting UpdatePanel.UpdateMode property to Always denotes that its contents will be updated on every Postback (partial or complete) that occurs from within the page.
  • We may set the UpdatePanel.UpdateMode property to Conditional so that it updates its contents upon certain conditions, e.g. in case of nested UpdatePanels as described in Page 334.
  • Another way is to call the Update( ) method on the UpdatePanel from server-side code. (This might be done during another Async Postback)
  • By default Nested UpdatePanel (whose UpdateMode is set to Conditional) will not cause update to the parent UpdatePanel. To enable this, set ChildrenAsTriggers property of the outer UpdatePanel to true.
  • We may assign different trigger controls to an UpdatePanel using either markup () or using properties pane.
  • If an error occurs during an Async Postback, it may be handled using the AsyncPostbackError event of the ScriptManager control.
  • All the content is place inside ContentTemplate control within an UpdatePanel.
  • UpdateProgress control present inside an UpdatePanel ContentTemplate would render as a hidden div in the resulting HTML.
  • By default the UpdateProgress control shows up on every Async Postback. To associate it with a particular UpdatePanel, set its AssociatedUpdatePanelId property.
  • We may also change the DisplayAfter property to number of milliseconds for the UpdateProgress after which it would show up following the Async Postback. (This defaults to half second)
  • PageRequestManager class contains abortPostBack( ) method which may be used to cancel a partial postback if called from a control within UpdateProgress control.
  • Timer control is used to execute certain code (at Tick event) on the client on periodic basis. If it is placed inside an UpdatePanel, the TimeInterval property will be reset after the UpdatePanel postback is complete. If placed outside, it will be reset as soon as the event is fired.
  • In case a postback is in progress if the Tick event fires, the first postback is cancelled.
  • The Timer control can also be used from outside an UpdatePanel to trigger it for Async Postback.

Monday, October 19, 2009

Chapter 5-Lesson 3

  • Webparts are components within a webpage that can have their own personalization, positioning and event systems.
  • Any control can be a webpart.
  • Using webparts on ASP.NET pages requires ASPNETDB (a SQL Express) database to be used which keeps track of user personalizations for specific webparts.
  • Webparts are placed inside WebpartZone controls that define an area within a page that contains or may contain webpart(s).
  • Within WebpartZone control we need a ZoneTemplate to allow us to place standard controls within a zone.
  • Webparts may be created by simply placing standard ASP.NET controls or even a user control inside the ZoneTemplate. The WebpartManager will take care of the rest.
  • A WebpartManager control (non-visual) is required on every page that uses webparts (or any controls present in System.Web.UI.WebControls.Webparts). It handles events and other stuff related to the Webparts.
  • Webparts may be displayed in various modes allowing users to view, design and even edit the webpart.
  • We may switch between different webpart display modes by setting DisplayMode property to one of SupportedDisplayModes collection values of the WebPartManager class.
  • Webparts within a same page may connected statically or dynamically.
  • Static connections are the ones that are defined by the developer and cannt be modified or removed by the user. On the other hand, Dynamic Connections are modifiable by users.
  • To create a static connection, we create a Provider class, a Consumer class and then tell the WebPartManager control about these two using StaticConnections markup within WebPartManager markup.
  • The provider class should have a method decorated with ConnectionProvider attribute. Similarly, the consumer class should have a method decorated with ConnectionConsumer attribute. The value returned by the Provider method would go as argument into the Consumer method.
  • For dynamic connections, all we need is to add a ConnectionsZone object to the page and enable the user to switch to Connect mode using WebPartManager. Once in this mode, the user can create or break connections between any existing Provider and Consumer.
  • Personalization is enabled by default for WebParts, and it uses client-side Cookies to match the user with his/her record in ASPNETDB.
  • If we wish to disable this personalization, we need to set WebPartManager.Personalization.Enabled property to false, either by using code or markup.
  • We may also allow some users of the site to apply changes to WebPart page in such a way that the changes are visible to all users. This is called Shared Personalization.
  • To enable Shared Personalization, we add authorization tag within section of web.config file. Then we define allow tags to specify which users are allowed to do what to our page.

Friday, October 16, 2009

Chapter 15-Lesson 2

  • An ASP.NET Theme may consist of .skin files, CSS files and images.
  • Themes are stored at the root of the Application in App_Themes folder.
  • Themes are applied at page level using Theme/StylesheetTheme attribute in the @Page directive, or at site level using pages Themes/StylesheetTheme attribute in web.config file.
  • Skin files specify settings for ASP.NET controls while CSS files specify settings for HTML elements.
  • A skin may be applied to either all the instances of a particular control (default skins) or applied to specific controls (Named skins)
  • In case of named skins, we set the control properties in the skin file and give it a SkinID. Later on whichever control in the .aspx page matches the SkinID attribute with the named skin would conform to that particualr skin.
  • Theming at various levels follows precedence as mentioned on Page 284.
  • We may disable themes for a particular page by setting EnableTheming to false in @Page directive.
  • Page.Theme property may be used to change the theme programatically during Page_PreInit event.

Tuesday, October 13, 2009

Chapter 5-Lesson 1

  • Masterpages derive from Masterpage and have a @Master directive.
  • ContentPlaceholder can also be placed in the head section.
  • asp:Content tag defines the substitution content for a ContentPlaceholder in Page that derives from a Masterpage.
  • Everything (except the Page directive) inside an ASPX page that derives from a Masterpage should be enclosed within a Content control.
  • Settings on the masterpage usually take priority over settings made on content pages.
  • Masterpages may be applied at individual page level, folder level or entire web application level. This is done respectively using @Page directive or pages section in web.config file.
  • Content pages can reference/access public properties defined in the Masterpage class.
  • @MasterType directive should be defined in the content page where masterpage properties need to be accessed. This enables the use of Master class to access Masterpage's public properties.
  • We may reference Masterpage controls from within content pages using Master.FindControl( ) method.
  • Events first get fired for Masterpage and then for content page.
  • Masterpages can be nested into one another.
  • Page.MasterPageFile property may be used to switch masterpages programatically. We only need to make sure all the different masterpages provide exactly same number and names of content placeholders to ensure compatibility.

Sunday, October 4, 2009

Chapter 4-Lesson 2

  • Application State and Session State are the two Server-side State Management options available in ASP.NET
  • Page.Application is of type HttpApplicationState.
  • Request for an ASP.NET page is processed by ISAPI (Internet Server Application Programming Interface).
  • ApplicationManager is an AppDomain that manages all the execution for a single ASP.NET application (including global variables).
  • HostingEnvironment class allows access to resources (such as files and directories) inside a hosting environment.
  • HttpContext, HttpRequest and HttpResponse are the core objects used to process any ASP.NET page request.
  • Application is started by using (or re-using an existing) an Instance of HttpApplication. When this instance is created objects/modules such as SessionStateModule also get loaded.
  • This Application object serves as the pipeline for all application execution.
  • An Application can have one instance of Global.asax (Global Application Class)
  • Application_LogRequest event is fired when a request is made to the Application.
  • Since Application object can be accessed by more than one page (running on different threads) at the same time, its always a safe practice to use Application.Lock( ) before altering any Application State values.
  • Application object is a collection with members of type object, therefore boxing is required.
  • Session state is scoped only to current browser/user and only available to that session.
  • Session object is of type HttpSessionState.
  • ASP.NET_SessionId is a cookie containing a 24-byte value to keep track of session.
  • Setting SessionState mode property to OFF in Web.config would improve performace.
  • Values stored in Session must be serializable.
  • Page directive also contains an attribute to enable/disable session state for individual pages. This can also be set to ReadOnly.
  • Sessions can be configured to be Cookieless.
  • ASP.NET would raise Session_End event only when state mode is set to InProc.
  • InProc mode keeps session data in server memory and is the default state mode.
  • StateServer hands over state data to ASP.NET State Service which preserves data between Application startups and multiple servers. This Service is present on all IIS Servers but set to manually start by default. To use it we must set its startup to Automatic.
  • SQL Server also preserves session state data but on SQL Server database. It also requires connection string in web.config when configured for use.
  • Profile properties are also scoped to current user.
  • However, Profile properties are always persisted in SQL Server database (and not in server memory)
  • Also, values stored in these profiles can be strongly typed objects.

Sunday, September 27, 2009

Chapter 4:Lesson 1

  • Server-side state is secure but not quite scalable.
  • Client-side state is quite scalable but not secure.
  • Persisted state means saving state information into a database. Can be utilized if database server is heavy.
  • Shared state means storing copies of commonly accessed data on the server (caching) so that the server does not need to process page (or part of page) for every request.
  • ViewState stores object data that is not already represented as HTML in the page response.
  • Page.ViewState property is a Dictionary of type StateBag.
  • Object values on a page are hashed, compressed and encoded into Unicode string and stored using one or more hidden HTML fields (depending on how Page.MaxPageStateFieldLength is set)
  • ViewState includes MAC (Message Authentication Code) used by ASP.NET to check if it has been tampered with during the round trip.
  • ViewState can also be made to encrypt data, both on website level and individual page level.
  • For website level, we may enable viewStateEncryptionMode to Always in web.config, and for page level we set this value to Page directive of the page we want it encrypted for. (Page 189)
  • EnableViewState property on every server control allows for turning on/off ViewState management for that control.
  • ViewState and ControlState are handled as two different values in ASP.NET 2.0 and above. ControlState manages how a control would keep its appearance during Postbacks and therefore a control may still contribute to page size even if EnableViewState is set to false.
  • ViewState does not transfer from one page to another.
  • All Serializable objects can be embeded in ViewState.
  • ControlState cannot be disabled for a control and is used specially in case of custom server controls. (Refer back to Page 192)
  • Hidden Fields may also be used in place of ViewState, except that the Value property of a HiddenField control is not hashed, compressed or chunked nor does it support encryption.
  • Furthermore, HiddenField values would be accessible on server only if page is sent via POST method (and not GET method). So they won't work if user clicks on a Hyperlink on the page.
  • ASP.NET uses Cookies to maintain user sessions.
  • Cookies can be temporary or permanent. To make a Cookie permanent we set its Expire property. To delete a Cookie we may set Expire to a past date.
  • Like Session variables, Cookies need not necessarily be added to the Response.Cookies using Add( ) method. They may also be created using something like
    Response.Cookies["lastvisit"].Value = something;
  • Path property of the HttpCookie class may be used to restrict Cookie access to pages from a specific directory. Similarly, Domain property may be used to restrict Cookie access to a specific domain.
  • Typically, 20 cookies (each of max 4 KB) are allowed per site.
  • A single Cookie may contain multiple Key-Value pairs, e.g.
    Response.Cookies["pref"]["color"] = Color.Blue;
    Response.Cookies["pref"]["lang"] = "en-us";
  • When using QueryStrings, some browsers restrict URL size to 2083 characters which may become a problem. Moreover, QueryStrings require page submission using HTTP GET method.
  • Tip: Always validate values from QueryStrings.
  • QueryStrings provide advantage of maintaining state when users bookmark or email a URL. Typically URL should be limited to 70 characters to enable it to be sent via plain text email.
  • Tip: Always HtmlEncode( ) values from QueryStrings and Cookies, so that client-side scripts may not get processed.
  • Passing HTML code to a QueryString throws HttpRequestValidationException (if not disabled by web server administrator)

Monday, September 21, 2009

Chapter 3-Lesson 2

  • We may use Hyperlink control to enable Client-side Navigation within the page. No data is posted to the newly requested page, so we may need to use QueryStrings.
  • Page.PostBackUrl property is used for Cross-page Posting.
  • When a cross-page post is made, data from first page is posted to the second page. The second page may access that data using Page.PreviousPage property.
  • We may use properties to encapsulate controls on a page so that they could be accessed from another page as strongly typed values during a cross-page posting.
  • To access such porperties in the posted page, add PreviousPageType directive after the Page directive and set its VirtualPath attribute. (Page 169 for exact usage)
  • Response.Redirect( ) method is used to cause a Client-side Browser redirect. This is similar to using Hyperlinks as the browser is sent an HTTP 302 message with the URL to redirect.
  • Server.Transfer( ) method is used to cause a Server-side Page Redirection. PreviousPage property is populated for the new page in this case.
  • Sitemap class is used to access Web.sitemap (or other such) files from code. It has three properties namely Title, Url and Description.
  • Menu, TreeView and SiteMapPath are three navigational controls that use Sitemap files.
  • SitemapPath connects itself to the Sitemap file automatically. It can be put on a masterpage where it could check (automatically) current page on which it is displayed and show its bread-crumb trail.

Chapter 3-Lesson 1

  • ValidationSummary control can be configured to display Pop-up error messages incase of invalid data.
  • Page class contains a Validators collection containing all the validation controls put into it.
  • Similarly, it contains the Validate( ) method which checks to see if data is valid on the page control. This method automatically runs after Page_Load( )
  • We may use Page.IsValid property at any time during event handling to see if Page is still valid on the server.
  • Client validation is by default enabled for all user controls. Use EnableClientScript to turn it off.
  • To set the Focus on a particular control, use Focus( ) method.
  • SetFocusOnError property on validation control ensures that the user does not leave the control until entered data is valid. This is set to false by default.
  • If we wish to have a control bypass validation checks on page (and cause Postback) we may use its CausesValidation property.
  • ValidationGroup property allows to treat set of validation control on a page as a group, so that if a Postback occurs only for that validation group, only controls within that group would be validated.
  • The InitialValue property of the RequiredFieldValidator is used to define a value that we may have set as 'Default Value/Text' on a given control to suggest that this value must be changed by the user.
  • CompareValidator may be used to compare a control values against a given constant. Or it may simply be used to check that the data entered in a given control belongs to a specific data type. Set Operator property to DataTypeCheck in that case.

Monday, September 14, 2009

Chapter 2-Lesson 3

  • Label control is rendered as tag while Literal control is rendered as static text. Therefore we can't apply CSS to Literal control.
  • PassThrough property of Literal control renders the specified text as it is to the browser and it is upon the browser to determine how to render output from it. Encode property would first convert any HTML tags and Javascript to appropriate HTML characters before rendering final HTML. Transform would check the target browser and remove any unsupported tags from the text.
  • Use Table, TableRow and TableCell controls to dynamically create/add tables, rows or columns to a page (maybe during Pre_Init). However, these dynamically added stuff would not persist during Postback.
  • Table contains Rows collection, and each TableRow contains a Cells collection.
  • Image control inherits from WebControl class, and ImageMap and ImageButton inherit from Image class.
  • GenerateEmptyAlternateText property of the Image control, if set to true, could be useful for generating accessible images that typically don't contribute to the meaning of the webpage. These would normally be ignored by non-visual page readers.
  • ImageButton's Click event contains a ImageClickEventArgs parameter which can be used to retrieve x and y coordinates of the user's click.
  • ImageMap differs from ImageButton in that it allows specification of Hotspots which would cause Postback from the image. On the other hand, clicking anywhere on the ImageButton causes a Postback.
  • Hotspots can be Circular, Rectangular or Polygonal.
  • HotspotMode.Postback tells a Hotspot to cause a Postback while Hotspot.Navigate tells a hotspot to navigate to a specified URL (as mentioned in the NavigateURL property).
  • Hotspots may also have a PostBackValue property which would be visible in ImageMapEventArgs of the Click/Command event when the Page is posted back.
  • The SelectionMode property of the Calendar control determines whether the user will be able to select a single date, a whole week, a whole month or none.
  • Calendar control contains a DayRender event that is fired wherever a single day is rendered within the control. We may use DayRenderEventArgs in this event to add various controls to the Cell.Controls collection of this argument.
  • Tilde operator (~) represents application root directory.
  • SaveAs( ) method of FileUpload control requires an absolute path to save a file. For that we use Server.MapPath( ) to specify the directory. Along with it we may use FileName property of the FileUpload control.
  • Panel control renders a DIV element in HTML.
  • A MiltiView control consists of a number of nested View controls. Each View represents a mutually exclusive viewable group of controls. i.e. Only one View is visiable at any time.
  • We may use ActiveViewIndex property or SetActiveView( ) method to change views through code. Setting any of these to -1 would display no Views.
  • Wizard control contains a WizardSteps collection which contains members of type WizardStepBase which in turn inherits from View class.
  • The Xml Control allows to display an XML Document by applying XSL Transforms to it. DocumentSource property is used to specify path to the XML file and TransformSource property is used to specify the XSLT file.

Chapter 2-Lesson 2

  • Use Server.HtmlEncode( ) or HttpUtility.HTMLEncode( ) methods to avoid XSS vulnerabilites while setting Text property of any control.
  • Columns property of a (MultiLine) TextBox determines how many characters would be available per line, and Rows property determines how many lines would be visible to user at any time.
  • A Button can be treated as a Submit button or a Command button.
  • Set the CommandName property of the Button control to treat it as a Command Button. Such buttons raise a Command event on the server (which carries CommandEventArgs parameter).
  • CommandArgument property may be used to provide additional information for the command to perform. This would be available in the CommandEventArgs.
  • CausesValidation property of the Button control, if set to false, allows a Button to bypass page validation.
  • Setting same GroupName property of the RadioButton control causes multiple radio buttons to be treated as a group.
  • CheckBoxList and RadioButtonList are easier to use in case of data binding.

Saturday, September 12, 2009

Chapter 2-Lesson 1

  • All server controls including the Page class derive from System.Web.UI.Control class.
  • ViewState data is not stored on the web server. It is sent as part of the response to the user.
  • PreInit event might be used to create dynamic controls or set masterpage and theme dynamically from code.
  • Init might be used to initialize values for dynamically created controls.
  • ViewState (if any) is retrieved before Load event.
  • Therefore, Load event may be used to check IF the page has been posted back. The Page is in stable state while this event is fired.
  • If the page is posted back, the Control events are processed after Load event.
  • Any changes made to controls during PreRender event are saved to ViewState.
  • Render is a method and NOT an event. It renders the client-side HTML for every control that it runs upon.
  • HTML Server controls are slightly different from ordinary HTML elements in that they have runat="server" and id attribute defined in them. ASP.NET generates an object instance for each HTML Server Control on the server.
  • Use HTML Server Controls when using custom Javascript for a particular control on the form.
  • When converting DIV element to HTML Server Control, we may use InnerText and InnerHTML properties through code.
  • All HTML and Web Server Controls need to be placed inside a Form with runat="server".
  • All postponed control events are raised before the event that actually caused the postback during page life-cycle.
  • The UniqueID property of a control contains its fully qualified name (i.e. NamingContainer(s) Assigned ID + Control ID)

Thursday, September 10, 2009

Chapter 1-Lesson 1-2-3

  • For remotely servers, the server must have Frontpage Server Extensions installed for Visual Studio to connect to it. (This will be required when using HTTP Server during Website creation in Visual Studio)
  • Solution (.sln) files are text files associated only with ASP.NET Web Application Projects (and not ASP.NET Website template) and contains information about information such as target framework, default language, list of project dependencies and so on.
  • Solution User Options (.suo) files is a binary file that contains breakpoints and watch window settings, tasks list and VS window locations for current user.
  • Special folders (usually prefixed with word App_) are protected by ASP.NET from direct user access. This excludes App_Themes folder.
  • A typical ASPX page is made up three parts, namely: Page Directives, Code (or Code-Behind) and Layout.
  • If we place all website files on server, it is referred to as Dynamic Compilation, i.e. the code will get compiled automatically by server the first time a user request is made.
  • On the other hand ASP.NET also allows Pre-compilation which compiles code into assemblies and leaves layout files intact. This removes the first user performance hit but is difficult to manage (as the entire website would need re-compilation for even a small change made to code)
  • Machine.config file contains settings for all .NET application types including Console, Windows and Web.
  • Settings related to the Web Server are stored in Root Default web.config file which resides in the same directory as Machine.config. (Typically %SystemRoot%/Microsoft.Net/Framework//CONFIG/ ) Settings in this file may override some settings from Machine.config
  • Each website may then have an optional web.config at its own root folder. This file may further override Root Default web.config settings.
  • Sub-directories within a website may also their respective web.config files. The runtime effectively flattens this layered configuration model (from Machine.config to Sub-Directory specific web.config) to determine the final settings for pages contained in that folder.
  • The WSAT (Website Administration Tool), accessible in VS 2008 through Website -> ASP.NET Configuration allows to visually change web.config settings.

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.

Tuesday, July 28, 2009

Chapter 11-Lesson 1

  • Code Access Security (CAS) may be used by .NET applications to put restriction on code regarding certain actions.
  • An Application is called partially trusted when some kind of CAS is applied on it, others are called fully trusted.
  • Evidence is something that proves as an identity and describes an individual as deserving a certain level of trust.
  • Permissions determine which applications are trusted to what extent.
  • There are 19 pre-defined Permissions in NET 2.0 (pertaining to different areas such as Web Access, Registry Access, File IO Access, etc.)
  • Permission Sets combine a set of Permissions to represent particular level of security e.g. FullTrust, Internet, LocalIntranet, etc.
  • Applications are brought under CAS using Code Groups which define a set of Permissions (and their respective settings/levels).
  • Each Code Group requires an Evidence object. The assemblies that provide a particular Evidence become eligible to Permissions defined by the code group.
  • Code Groups may be nested within one another and therefore may require more than one Evidence. (e.g My_Computer_Zone is a Code Group that requires a Zone:My Computer type of Evidence and grants FullTrust Permissions to assemblies bearing that Evidence.)
  • Nesting one code group into another would result in a Union Code Group with all the Permissions set by both of them.
  • There are four configurable Security Policies (Unions of Code Groups) built-in for .NET applications; Enterprise, Machine, User and Application Domain.
  • However, if an Assembly falls under more than one Security Policy, the CLR uses the most restrictive one.

Sunday, July 26, 2009

Chapter 10-Lesson 4

  • System.Management provides tools to check system resources using WMI (Windows Management Instrumentation)
  • ManagementObjectSearcher class is used to apply queries onto a system and retrieve useful information.
  • This object uses ManagementScope to determine the system name and Login information, and ObjectQuery to determine the SQL-like query to be used.
  • The Get( ) method invokes the query on the scope object and returns a ManaementObjectCollection.
  • Usually the query is of the form like Select * from Win32_LogicalDisk or Select * from Win32_Service WHERE Started = FALSE
  • ManagementEventWatcher class may be used to track and respond to events in the WMI context. (refer to Lab for specific example)

Chapter 10-Lesson 3

  • An isolated task performed by Operating System is called a Process.
  • An application may be using 1 or more processes.
  • 32-bit processors can allocate a maximum of 4GB memory.
  • Within the memory, a Virtual Memory Manager keeps setting in the form of 4KB memory pages (chunks) that it assigns to processes as and when required.
  • Process class in System.Diagnostics namespace is used to handle processes through .NET
  • GetProcessById( ) static method takes ID of a process as argument and throws an ArgumentException if one is not found.
  • Performace for applications running on Windows can be measured using PerformanceCounter class, since it uses Registry to store values retrieved from code.
  • CounterCreationData may be used to specify Name, Type and other information related to a PerformanceCounter.
  • PerformanceCounterCategory class is used to manage and manipulate PerformanceCounter objects.
  • The Start( ) method of the Process class may be used to invoke an outside process.
  • If we use the overload of Start( ) method that takes Username and Password, then the UseShellExecute property must be set to false.
  • ProcessStartInfo object may also be passed to Start( ) method to specify process name and any Command-line arguments.
  • The StackTrace object represents the CLR Stack trace for a given application.
  • StackTrace is composed of StackFrames which represent individual method calls.

Chapter 10-Lesson 2

  • Debug and Debugger classes are used to programatically control the debugging of code.
  • .NET Runtime considers these classes only when program is built in Debug mode.
  • Debugger.Log( ) static method logs a given message to a target. For that, we need to confirgure the Listeners collection of the Trace object. (overloads define the target which could be a File, Output Window, etc)
  • Debugger class provides only two useful methods, namely Break( ) and Log( )
  • To have more control over debugging, we may use Debug class.
  • Debug.Assert( ) evaluates a given condition and if it is false breaks into the debugger and displays a given message.
  • The following methods send messages to the output window with difference only in either formatting or in use of conditions: Write( ), WriteLine( ), WriteIf( ), WriteLineIf( ).
  • The Print( ) method, however, sends message only to any attached Trace Listeners.
  • DebuggerBrowsable attribute over any member of class would determine its visibility in the Debug window whenever a breakpoint is set. (It is supported only in C#.NET)
  • DebuggerDisplay attribute determines how particular members of a class will be shown when an object is displayed in the Debug window. This method is used to decorate a class.
  • DebuggerHidden attribute tells the debgger to ignore the lines of code that it decorates.
  • DebuggerStepThrough attribute tells the debugger to Step Over the code it decorates. (This will save time for code that we are sure won't cause problems)
  • DebuggerVisualizer attribute is new in .NET 2.0
  • Trace class is implemented both in Debug and Release builds.
  • DefaultTraceListener is attached to the output window.
  • TextWriterTraceListener can redirect trace messages to a text file or Stream. (which is mentioned in the constructor)
  • XmlWriterTraceListener directs Trace or Debug information to a TextWriter or Stream object. However, the file will contain XML as ouput rather than plain text as in the above listener. (XML indeed contains more information than plain text)
  • XmlWriterTraceListener is new in .NET 2.0. If no filename is specified in constructor, CLR uses a GUID to create a filename.
  • EventLogTraceListener directs messages to an EventLog specified in the constructor.
  • DelimitedListTraceListener works the same as the above two but can use a delimiter to seperate entries.
  • All of the above listeners may be configured either by using code or the configuration file.

Chapter 10-Lesson 1

  • Event Log is available in Windows 2000 and above.
  • Event Logs should be avoided in partial trust environments.
  • System.Disgnostics nampespace is required to use objects such as EventLog.
  • WriteEntry( ) method of the EventLog class is used to actually create an entry.
  • The Entries property of the EventLog class is a collection containing objects of type EventLogEntries.
  • We may use any of the existing logs or we may choose to create our own by specifying its name in the EventLog constructor.

Tuesday, July 21, 2009

Chapter 9-Lesson 2

  • Installer class allows for creation of Setup files to help deploy our Assemblies.
  • Adding a class to the project that inherits from Installer class and overriding Install( ), Commit( ), Rollback( ) and Uninstall( ) methods will make an Application installable. Additionally we add a RunInstaller Attribute and set it to true.
  • To initiate an Installer programmatically, we use AssemblyInstaller or ComponentInstaller classes.

Chapter 9-Lesson 1

  • To put Application settings without using Windows Registry or database, we use configuration files in .NET
  • System.Configuration namespace is required to use classes that serve to read/write configuration information for .NET applications.
  • ConfigurationManager class provides properties and methods that return Configuration objects related to a particular Assembly.
  • CodeBase section of the configuration file tells the CLR which .NET Framework version to use.
  • ConfigurationSettings class is obsolete in .NET 2.0. Instead use ConfigurationManager.AppSettings
  • ConfigurationManager.AppSettings is a NameValueCollection containing strings
  • ConnectionString settings can be accessed as ConnectionStringSettingsCollection. It is exposed as ConfigurationManager.ConnetionStrings property.
  • It is better to use WebConfigurationManager in ASP.NET applications rather than ConfigurationManager.
  • We may create settings file by hand or we may add a SettingsFile to our project in order to visually create settings.
  • Configuration Settings are case-sensitive and white-space sensitive.
  • System.Runtime.Remoting section may be used to define settings for remote applications.

Saturday, July 18, 2009

Chapter 8-Lesson 3

  • Windows Services are processes that run in their own user-session without any UI.
  • Windows Services inherit from ServicesBase class.
  • The Main( ) method in a service contains code to call Run( ) method responsible for starting/executing the service.
  • The OnStart( ) method method should NOT stick into an infinte loop not should it get blocked. If we wish to create polling mechanism, use System.Timers.Timer object.
  • To override OnPause( ), OnContinue( ) and OnShutDown( ) methods, first set ServiceBase.CanPauseAndContinue or ServiceBase.CanShutdown to true.
  • Remember to always set the ServiceName property in the property pane.
  • System.ServiceProcess.ServiceController class is required to interact with a service from .NET Assembly.
  • To install the service, we need ServiceInstaller and ServiceProcessInstaller objects (automatically created in Visual Studio when we right click Service Design View and choose Add Installer)
  • LocalService is the least previliged Account and LocalSystem is the most previliged Account property for ServiceProcessInstaller.
  • While creating MSI installer for Service, add Project Output from Service Project as Primary Output and then add a Custom Action. (refer to page 462-463)
  • To record Exceptions for a Service use EventLog.

Chapter 8-Lesson 2

  • In-depth security means we are able to prevent damage caused due to a vulnerability in a (third-party) Assembly that we are not aware of, cannot prevent and cannot fix.
  • We may run Assemblies within an AppDomain with certain previliges by specifying an Evidence object to the Assembly. An Evidence is an object that behaves as an ID card displaying role/status of an entity. The authorities may then use this object to determine what kind of previliges an object (an Assembly in this case) recieves.
  • The Evidence object takes an object array in its constructor. We may store anything in that array or we may use any of the predefined enumerations to define a specific type of previlige-level. The Evidence object will then be passed when ExecuteAssembly( ) method is run on an AppDomain.
  • We may also pass such an Evidence object to CreateDomain( ) method to limit previliges for the entire AppDomain.
  • Certain properties of an AppDomain are configurable via the AppDomainSetup class, which may be passed along with the Evidence object while creating new AppDomains.

Chapter 8-Lesson 1

  • Operating System manages processes, while .NET Runtime manages Application Domains.
  • If we consider an Assembly as class, then its instances could be called Application Domains.
  • If an Application uses more than one assembly, it is possible to create a seperate process for each of them. The problem would be the performance hit ad resource usage caused between context shifts from one process to another. Therefore it is better to use one Assembly that acts as a host for other Assemblies. Then we may share resources (data) among Assemblies within an Application Domain. (e.g. ASP.NET Application object is an Application Domain)
  • Points-to-Ponder: (See page 439)
  • AppDomain class allows for creating Application Domains within .NET
  • AppDomain.CreateDomain( ) static method is used to create a new Application Domain with a friendly name, and RunAssembly( ) instance-level method is used to load an Assembly within a domain.

Wednesday, July 15, 2009

Chapter 7-Lesson 3

  • Asynchronous Programming Model allows us increase performance of our application by running certain piece of code onto a seperate thread while the main thread is blocked for some reason.
  • .NET supports APM by supplying BeginXXX and EndXXX methods built-in to various library classes. (e.g. BeginRead( ) and EndRead( ) methods in Stream class)
  • Rendezvous Models allow for three styles of using APM, Wait-Until-Done, Polling and Callback.
  • Use null while calling an APM supportive method for Callback and state arguments to use Wait-Until-Done. If we use this, EndXXX will block current thread until Asynchronous call is completed.
  • The Completed property of the IAsyncResult object returned by the BeginXXX method may be used to check (poll) whether the Asynchronous work has been completed. If not, we may keep on working on current thread.
  • If BeginXXX is called by one method and EndXXX needs to be called by another method, we would need Callback Model.
  • Callback model allows us to specify a method (using AsyncCallback delegate) in the BeginXXX method. This method would be called in order to complete the Asynchronous call (EndXXX).
  • We may optionally supply an object (as a state object) that might be needed to call EndXXX. (Refer to page 417)
  • If an Exception occurs during Asynchronous method calls, it is thrown when EndXXX is called. Reason: Since it occurred on the other thread, we cannot catch it on the main thread.
  • However, in Windows Forms Applications, the Application object is notified whenever an exception occurs (either on main thread and worker threads). Therefore, we can attach a method to Application.ThreadException to handle an exceptional situation.
  • Creating threads on our own is not recommended. Instead use ThreadPool class to create/reuse threads for our methods. (Don't buy threads, lease 'em)
  • ThreadPool has a number of available slots to be used as threads. These slots are maintained by ThreadPool class and it keeps processor busy by continuously assigning to it slots that have pending work in them. These reusable slots may be called pre-built threads.
  • We make a request to acquire a slot (whenever one becomes available) by calling ThreadPool.QueueUserWorkItem( ) static method and pass it a WaitCallback delegate representing the name of the method we wish to run as thread.
  • If the Application uses a large number of Threads through ThreadPool, Threads may start to starve. In such a situation we may set the SetMaxThreads property of ThreadPool class to incease number of pre-built threads (slots).
  • If faster Startup time is required, we may set the minimum number of threads in ThreadPool using SetMinThreads property.
  • Typically ThreadPool class limits minimum number of threads in the pool to be 2 per second.

Tuesday, July 14, 2009

Chapter 7-Lesson 2

  • There are three operations usually involved with arithmetic operations on variables, i.e. Load Variable value into Register, Change value in Register, Write Back the new value to variable.
  • In threaded code, all the above steps/operations are treated as atomic operations.
  • Therefore, it might happen that two threads read/load the same variable into the register, change its value equally and write it back, all at the same time. (Valid in multi-core or multi-processor scenario)
  • Interlocked class may be used to accertain that a certain variable is accessed by only one thread in a multi-threaded application.
  • Interlocked class has static methods which can be used when performing arithmetic operations on variables.
  • However, interlocked class has some limitations. It cannot be used for a wide variety of types and cannot be used to make pieces of code thread-safe. (Refer to Page 392)
  • To declare a piece of code as thread-safe, use lock keyword to create thread-safe block. Lock keyword requires and object reference passed to it (usually this).
  • This creation of lock block is called Synchronization Locks.
  • Synchronization Locks may also be created using Monitor class static methods.
  • To avoid deadlocks, we may use Monitor.TryEnter( ) method. Otherwise use Timeout.Infinite static property to tell the thread to wait as long as it takes.
  • If we wish to deal (synchronize) reading and writing operations seperately, we may use ReaderWriterLock class to lock certain data only for reading or writing.
  • LockCookie type object would be required to downgrade a WriterLock to a ReaderLock. (This implies that a WriterLock is downgradable only if it was previously upgraded from a ReaderLock)
  • Three OS kernel level objects are represented in .NET by classes named Mutex, Semaphore, AutoResetEvent and ManualResetEvent. All of these derive from WaitHandle class.
  • Mutex is almost same as Monitor class with the fact that it allows synchronization across AppDomain and process boundaries.

Chapter 7-Lesson 1

  • Thread class is used to create and start a thread.
  • ManagedThreadId property may not be the same as operating system thread ID.
  • Abort( ) methods actually raises the ThreadAbortException to kill the thread.
  • Resume( ) and Suspend( ) methods have been deprecated.
  • In order to notify the thread host about the critical region of a thread, use static methods BeginCriticalRegion( ) and EndCriticalRegion( ) of Thread class. Use these methods inside a method that would be used as a thread.
  • The static Sleep( ) method blocks the current thread for a certain amount of time during which other threads may run.
  • SpinWait( ) does the same but does not allow other thread to run during that time.
  • Join( ) method of Thread class asks the host thread to wait until the child/worker thread has finished executing.
  • ParameterizedThreadStart delegate is used to represent threads that require parameters/arguments for calling.
  • Page 383*

Friday, July 10, 2009

Chapter 6-Lesson 3

  • Font class along with Graphics.DrawString( ) method may be used to draw text on forms, Bitmaps and Images.
  • StringAlignment.Near actually aligns text to Left.
  • Font class has 13 constructor overloads.
  • LineAlignment flag determines vertical alignment of text.

Thursday, July 9, 2009

Chapter 6-Lesson 2

  • Image is an abstract class.
  • Image class uses static methods to create objects to/from image files.
  • Bitmap class inherits from Image class and is used for still images.
  • MetaFile class also inherits from Image class and is used for Animated images.
  • Graphics class is still more complex than Bitmap class. We can always use Graphics.FromImage( ) method to represent a Bitmap as a Graphics object and use Graphics methods over it.
  • To save images to a file, use Bitmap.Save( ) method.
  • ImageFormat enum specifies supported image formats (BMP, GIF, JPEG, TIFF, etc) for saving images.
  • SystemIcons class exposes standard windows icons (of size 40 x 40) as properties.

Sunday, July 5, 2009

Chapter 6-Lesson 1

  • Brush is an abstract class. Brushes is a sealed class.
  • ColorConverter and ColorTranslator are used to convert colour value from one format to another.
  • Graphics is a sealed class.
  • Pen (and related) classes are used to draw shapes and Brush (and related classes) are used to fill regions with colours.
  • All classes suffixed with Converter are accessed through TypeDescriptor.
  • Color, Rectangle, Point and Size are structures and not classes.
  • Color names in Color structure are actually properties inside the structure.
  • DrawString( ) method of the Graphics class may be used to draw a string using a specified Brush and Font objects.
  • By default Pen class draws solid lines
  • Usually System.Drawing.Drawing2D namespace is required for Graphics programming.
  • LineCap enumeration defines possible values to set edges of a line.
  • Draw methods usuallu require a Pen type object and Fill methods usually require a Brush type object.
  • Brush is an abstract class. Use one the childrens instead.

Thursday, June 25, 2009

Chapter 5-Lesson 2

  • Use XML serialization when you need to exchange an object with an application that
    might not be based on the .NET Framework
  • Private members of a class are not serialized in XML. This means only public data is serialized.
  • System.Xml.Serialization namespace is required.
  • Xml serialization does not need [Serializable] attribute on a class. However the class must be public and should have a parameter-less constructor.
  • XmlIgnore Attribute is similar to NonSerialized Attribute.
  • Xml Schema Definition tool (Xsd.exe) is used to generate set of classes that are strongly typed according to a schema.
  • DataSet.WriteXml( )/ReadXml( ) methods may be used to serialize datasets into XML.
  • For other types of collections, use TextWriter, initialize it as a StreamWriter and supply this object to XmlSerializer instead of filename in first argument. Collection could be in second argument of Serialize( ) method.

Monday, June 22, 2009

Chapter 5-Lesson 1

  • Converting Object information into another format is called Serialization.
  • System.Runtime.Serialization namespace is required
  • Items copied to clipboard, Remoting and Web Services are good examples of Serialization
  • For Binary Serialization, we use System.Runtime.Serialization.Formatters.Binary namespace BinaryFormatter class.
  • The terms 'Backward Reference' and 'Forward Reference' are used during Deserialization process when an object being Deserialized refers to another object.
  • If the referenced object is already Deserialized, the Formatter treats it a Backward Reference and completes the reference immediatly.
  • However, if the referenced object is not Deserialized yet, it is treated as a Forward Reference and the Formatter registers a fix-up with the ObjectManager which would later on complete the reference.
  • Serializable attribute allows a custom class object to be serialized by a Formatter. All members (including private ones) are serialized.
  • NonSerialized attribute before any class member would omit it from (De)Serialization process.
  • IDeserializationCallback.OnDeserialization( ) method may then be used to initialize objects which were omitted during (De)Serialization.
  • In situations where after serialization, one adds additional members to a class, deserialization may fail because serialized object would not contain info about that additional field. Therefore, if a class has previously been used for Serialization, its always good to use OptionalField attribute to newly added members for sake of Version Compatibility.
  • If members were removed from a class after some objects were serialized, .NET 2.0 would NOT throw an exception while deserializing (since there would be more info available than requested for deserialization). Older versions on .NET did.
  • If object is serialized so that it would later be read by ONLY .NET based applications, use of BinaryFormatter is preferrable. Otherwise use SOAPFormatter.
  • Using SOAPFormatter requires the project to have a reference to System.Runtime.Serialization.Formatters.Soap.dll which is not included by default in .NET 2.0
  • Use BinaryFormatter for best efficiency and SOAPFormatter for portability.
  • SoapIgnore attribute is used for public members of class which we do not wish to serialized to XML.

Monday, June 15, 2009

Chapter 4-Lesson 5

  • Generic classes are type-safe compared to usual collections.
  • There exists a generic equivalent to almost all the collections discussed in earlier chapters. e.g. ArrayList as List<>, etc.
  • Generic List<> collection allows an overload of Sort( ) method to supply a generic delegate for comparison.
  • One difference between generic Dictionary<> class and its non-generic counterparts is that it does not use DictionaryEntry objects to hold items, instead it uses generic KeyValuePair.
  • Generic LinkedList<> is new in .NET 2.0. It consists of LinkedListNode objects and uses ILinkedListEnumerator.
  • Using foreach on a LinkedList will not return LinkedListNode type objects. Instead it will return objects of type that is used to store value in each LinkedList node. Explaination code on Page 255 of MS Press book.
  • Generic collections support generic interfaces, generic enumerators and generic comparisons for type-safety.
  • Three classes are common to almost all collections in System.Collections namespace (and any of its sub-namespaces), namely, CollectionBase, ReadOnlyCollectionBase and DictionaryBase.
  • From .NET 2.0 onwards, its preferrable to use generic collections than non-generic ones.

Chapter 4-Lesson 4

  • BitArray class stores Boolean values in a resizable list. (Manually resizable using Length property)
  • This class also supports standard operations such as AND, OR, XOR, etc.
  • BitVector32 is a structure. It is not resizable, and is used to manipulate bits of, say an Int32.
  • BitArray does not support Add( ) / Remove( ) methods. We use indexers instead.
  • BitVector32 structure actually stores its value in its Data property which is an Int32. Any changes made to the bits would ultimately change the Data property.
  • BitVector32 works on unsigned integers.
  • Practical usage of BitVector32 include Bit Masking, Bit Packing, etc.
  • Bit Packing allows storage of usual small numbers into one relatively large number to save space. (e.g. instead of using three Int16 numbers, we may pack them into one Int32)
  • StringCollection and StringDictionary are strongly typed.
  • StringCollection works identical to ArrayList, and StringDictionary works identical to HashTable except that both Key and Value must be strings.
  • However, Keys in StringDictionary are case-Insensitive, meaning "fourth" and "Fourth" would lead to same Value.
  • The CollectionsUtil class provides static methods for creating case-insensitive HashTable/SortedList.
  • StringComparer object allows for creating Culture-Invariant collections.
  • The NameValueCollection allows to store multiple Values per Key. Values can be retrieved by using Key or Index.
  • This collection would behave like previous collections when items are added using indexer, but behaves differently (allows multiple Values per Key) when Add( ) method is used.
  • It also supports retriving Value using Index number of Key. If a key has more than one Value, using index would return a comma seperated list.

Sunday, June 14, 2009

Chapter 4-Lesson 3

  • Dictionary classes in .NET framework are used to map a Key to a Value.
  • Useful when creating Lookup tables.
  • Dictionaries can also use indexers.
  • Objects in Dictionaries are typically of type DictionaryEntry, which hold a key and a value.
  • All Dictionary classes derive from IDictionary which in turn derives from ICollection interface.
  • The ContainsKey( )/ContainsValue( ) methods in HashTable are used to know the existance of specific Keys/Values in a HashTable collection.
  • HashTable uses unique Hash values to store Values. So using the same Key for different values over time would retain just the latest because all others would overwrite each other.
  • Hash values are internally integers.
  • When using strings as Key, the string class overrides the GetHashCode( ) and Equals( ) method of the object class to make sure two similar strings in the Key specification get to the same Hash value in the collection (keep in mind strings are by default immutable)
  • Therefore, if we use our objects' reference as Key, we might want to override these methods to make sure two instances with some property similar between them would be treated as the same Key point in the collection. (See Page 214-215 [Fish class example] in MS Press Book)
  • The IComparer interface allows for sorting of objects of a class.
  • We may supply object from a class that implements IEqualityComparer in the constructor of a HashTable. IEqualityComparer provides the same two methods discussed above to provide results of comparison in HashTable. Details on Page 216.
  • HashTable returns items in the order of their Hash Values while traversal.
  • SortedList collection returns objects in the sorted order. Sorting takes place with respect to Key.
  • The indices of the DictionaryEntry objects may change as items are added or removed.
  • HashTable is not good (in performance) for small collections (fewer than ten elements). Instead, use ListDictionary.
  • HybirdDictionary starts as a ListDictionary and, as the data grows converts itself into a HashTable. Usage is same as HashTable.
  • HashTable does NOT allow access to items by index.
  • OrderedList class is used to attain performance of HashTable in large data scenario and at the same time allow the use of index for data items. Therefore it has extra methods that allow for insertion and removal as well as accessinf of data at specific index.

Saturday, June 13, 2009

Chapter 4-Lesson 2

  • Queue collection allows to Enqueue duplicate and null values.
  • Queue is a FIFO collection while Stack is a LIFO collection.
  • Queue supports Enqueue( ) and Dequeue( ) methods.
  • Stack supports Push( ) and Pop( ) methods.
  • Both classes support Peek( ) method.

Chapter 4-Lesson 1

  • Collections are classes that support gathering of data in an orderly manner.
  • SortedList is a name/value pair collection.
  • BitArray is compact collection of Boolean values
  • HybirdDictionary collection uses ListDictionary for small group of items and migrates to Hashtable when data size becomes large.
  • The process when ValueTypes are wrapped up in object type is called Boxing.
  • The AddRange( ) method of ArrayList supports every object that has implemented ICollection interface.
  • Add( ) and AddRange( ) methods add objects at the end of ArrayList. For adding items at specific positions, use Insert( )/InsertRange( ) methods.
  • The Remove( ) method will search for a given object in ArrayList, if found, will delete it, and if not found, will return without throwing Exception.
  • ArrayList supports indexers, so we can use them as arr[2] = "something";
  • For details on IEnumerator and how to use it, refer to MS Press book, Table 4-2 onwards.
  • An alternative to using IEnumerable properties is to use the foreach construct.
  • foreach may be used on any collection that supports IEnumerable.
  • If we know the data type of the items in a specific collection, we may specify that in the foreach loop and it will automatically handle Unboxing.
  • ICollection interface derives from IEnumerable interface. For details refer to MS Press book, Table 4-4 onwards.
  • The CopyTo( ) method of the ICollection ensures that the contents of the collection can be converted into an Array.
  • Simple collections such as ArrayList inherit from IList which in turn derives from ICollection. This adds the capability of methods such as Add( ), Clear( ), Contains( ), etc. and properties such as Item.
  • The Sort( ) method in ArrayList uses Comparer class (which implements ICompaarer). So it also allows us to supply a Comparer object incase we dont wish to use the default.

Friday, June 12, 2009

Chapter 3-Lesson 2

  • Encoding converts byte values into characters.
  • .NET 2.0 supports encoding in UTF-8, UTF-16, UTF-32, ASCII and ANSI/ISO using System.Text.Encoding. In .NET 3.5 its all present in System.Text namespace.
  • Code Pages in .NET Framework include IBM-EBCDIC as well as UTF-7 and UTF-8 standards.
  • The default encoding type in framework is UTF-16.

Chapter 3-Lesson 1

  • Regex class is used to match a string against a Regular Expression.
  • When validating input, one must put the leading carat ( ^ ) to represent beginning of input and dollar ($) sign to represent end of input pattern so as to minimize the risk of human error.
  • The carat (^) would match the expression at the beginning of any line in a multi-line string.
  • Regular Expressions characters are case sensitive, even in VB.NET
  • Tip: Use Verbatim strings (that begin with @ sign) to create regular expressions to avoid problems with back-slashes.
  • Try to learn a few simple Regular Expressions for exam.
  • Asterisk (*) means the preceding character must be present zero or more time, while plus (+) sign represents 1 or more times.
  • To define a certain number of occurrence for a character use {n} notation after the character where n is the number of occurrences.
  • We can also define min-max range for a character using {min,max} notation. We can also leave either as blank.
  • Use question mark to make character optional. And Period (.) to represent reserved space for a single character.
  • Use Table 3-3 in the MS Press book for further information.
  • We may use Back-Referencing (using \k with a named group) to search for repeating characters or groups of characters.
  • Use of RegexOptions.ECMAScript with any other options throws an Exception.

Thursday, June 11, 2009

Chapter 2-Lesson 4

  • In .NET 2.0, there are new types of applications that are meant to be deployed and installed from Web pages called “Click-Once applications” or, sometimes, “Smart-client applications.” These new types of applications are meant to solve deployment of applications across a company or enterprise.
  • Isolated Storage means the application will be able to hold data temoporarily in a system provided secure area.
  • We may create both Application-level data store and User-level data store.
  • IsolatedStorageFile class (and its static methods) is used for this purpose.
  • IsolatedStorageFileStream is derived from FileStream class.
  • Get the appropriate data store for Application/User. Create an IsolatedStorageFileStream object specifying the usual filename, FileMode and the store in which to create the file. Once this is done, its all the same as using a FileStream with StreamReader/StreamWriter.

Chapter 3-Lesson 3

  • Both GZip and DEFLATE compression systems allow compression for a maximum of 4GB data.
  • GZipStream is useful for wider distribution scenario while DeflateStream is useful for relatively smaller size (because it does not include header information)
  • Compression Streams would always wrap the FileStream with compressed data, whether during Compression or Decompression.

Sunday, June 7, 2009

Chapter 2-Lesson 2

  • Most operations with Streams involve the File class
  • StreamReader and StreamWriter classes allow for sequential reading and writing of data.
  • Static methods in the File class are almost identical to the FileInfo class.
  • Simple Create( ) method (or Open, etc) would return a FileStream object where as CreateText( ) method (or OpenText, etc) would return a StreamReader/StreamWriter object.
  • The Directory class provides static methods for routine directory operations.
  • The FileAccess enum provides the possible rights assigned when accessing a file.
  • Using FileAccess.Read would allow read-only access, whereas FileAccess.Write would allow append-only access.
  • The FileMode enum determines whether file would be created or opened or deleted, etc.
  • FileMode.Append can only be used with FileAccess.Write
  • FileMode.Create overwrites any existing file while FileMode.CreateNew throws an exception if file exists.
  • Similarly FileMode.Open would throw an exception if file does not exist but FileMode.OpenOrCreate wont.
  • The Length property of the Stream class returns length of a stream in bytes.
  • The SetLength property will Truncate (shrink) the contents of the stream if new length is lesser than the old one and vice versa.
  • The StreamReader is intended to read the Stream as a string rather than as bytes.
  • The StreamReader class is derived from the abstract TextReader class. StreamWriter derives from TextWriter abstract class.
  • Similarly StringReader/StringWriter inherit from TextReader/TextWriter class. StringWriter uses a StringBuilder.
  • For non-textual data there are BinaryReader/BinaryWriter classes.
  • One use of MemoryStream is like we use datasets for database operations. You may continue to write on a MemoryStream and when you decide to make chages permanent you wirte a MemoryStream to a FileStream. This would lock the actual file for a short period of time reducing accessibility downtime.