Categories

mcts 70-528 notes

Chapter 1, Introducing the ASP.NET 2.0 Web Site

  • HTTP protocol, request and respone. See Nikhil’s web development helper tool to analyse HTTP trafic.
  • Web site types: File, FTP, Local HTTP and Remote HTTP (require Front Page Server Extensions).
  • Active/passive mode FTP.
  • Configuration files hierachy: machine.config, web.config (in framework’s config folder), Web.config (web application root), Web.config (sub folder).
  • Trace settings for web.config, trace.axd page.
  • Web Site Administration Tool: Website | ASP.NET Configuration.

Chapter 2, Adding and Configuring Server Controls

  • System.Web.UI namespace.
  • Control is base class for all server controls.
  • Control.Focus() to set focus (cursor) on control.
  • Page.SetFocus() to dynamically set focus on any focusable control.
  • Web page life cycle: Init, LoadControlState, LoadViewState, LoadPostData, Load, RaisePostDataChangedEvent, RaisePostbackEvent, PreRender, SaveControlState, SaveViewState, Render, Dispose, UnLoad.
  • Auto-event wire up: If set to true in aspx (default) and method name pattern Page_EventName.
  • System.Web.UI.HtmlControls namespace.
  • HTML server controls to easier migrate existing ASP sites.
  • Rendering:Visible attribute is never rendered and name attribute gets id value if not set.
  • System.Web.UI.WebControls namespace.
  • Instantiate controls, set properties and add to form1’s controls collection during Init event.
  • EnableViewState: Enables data viewstate, control viewstates is always enabled.
  • Naming container (see INamingContainer) defines unique namespace for control names. Use FindControl() to locate a control within a naming container. Note that FindControl() only searches the top-level naming container.
  • Button control: Can be submit (only one per form) or command (more than one) button.
  • Use HttpUtility.HtmlEncode() to filter user input that is shown in a web page. The encoding converts characters that are not allowed in HTML into character-entity equivalents eg. a blank is converted to ‘&nbsp ;’. This effectively avoids scripting attacks (XSS) because the HTML is shown as text instead of being interpreted.
  • Use HttpUtility.UrlEncode() to convert URL string to valid URLs. All non-letter and non-digit characters are converted to hex values of the ISO Latin 1 set with a preceeding ‘%’. That way an ‘<’ character is encoded as ‘%3C’.

Chapter 3, Exploring Specialized Server Controls

  • System.Web.UI.WebControls namespace.
  • Literal controls render text directly without any additional mark-up and have a Mode property.
  • Table, TableRow and TableCell control to dynamically build tables in custom controls.
  • ‘~’ refers to the web application root. Works only for server-side controls.
  • ImageButton control retrieves coordinates, ImageMap control has defined hot spots. First added HotSpot take precedence.
  • Calender control. Use DayRender event to use as schedule.
  • HttpServerUtility.MapPath() to get absolute path on server.
  • Panel control renders as <div>.
  • Label control renders as <span>.
  • MultiView, View control to group control. Do not render any mark-up code.
  • Wizard control.
  • FileUpload.HasFile: Checks whether the upload control has a file to upload.
  • Xml control to view and transform XML. The last specified source takes precedence.
  • DataBind(): Calls recursively DataBind() on all child controls.
  • Use DataSource or DataSourceID property to assign a data source or DataSourceControl to a data-bound control. DataSourceID takes precedence when both assigned.
  • DataSourceControl class: ObjectDataSource, SqlDataSource, AccessDataSource, XmlDataSource, SiteMapDataSource.
  • Templates can be used with GridView, DetailsView and FormView controls.
  • ListControl class: Has Items collection. Text property is shown to user, Value is posted back to server. Use DataSource, DataMember (identifies result set), DataTextField and DataSourceField to control binding. DataTextFormatString formats the displayed text. DropDownList (single selection), CheckBoxList, RadioButtonList, BulletedList and ListBox (multiple selections) controls.
  • AdRotator displays advertisments retrieved from XML file or database. Place XML files in APP_DATA folder.
  • CompositeDataBound controls: GridView, DetailsView, FormView.
  • GridView control shows a list of items, can edit single items and cannot insert new items. Column types: ButtonField, CommandField, CheckBoxField, …
  • DetailsView control shows a single item, can page through items and insert new items. Can be used with GridView, ListBox or DropDownList to implement Master/Detail view.
  • FormView shows single record. Colums are defined by web server controls.
  • HierarchicalDataBound controls: TreeView, Menu.

Chapter 4, Using ADO.NET and XML with ASP.NET

  • System.Data namespace.
  • DataTable, DataColumn and DataRow class.
  • Caption sets the header text.
  • When Expression is set the column will be calculated.
  • DataTable.Rows.Add()/.Load() to add/update data. Overloads take object array as parameter or use DataTable.NewRow(). LoadOption enumeration: OverwriteChanges, PreserveChanges, Upsert.
  • DataRowState enumeration: Detached, Added, Unchanged, Modified, Deleted. Determines whether the DataRow has been changed.
  • DataRowVersion enumeration: Original, Current, Proposed, Default. The DataRowVersion values are used when retrieving a DataRow.
  • AcceptChanges() resets the DataRowState to unchanged. E.g. use after loading from database and after persisting changes to database.
  • RejectChanges() rolls back to the last time AcceptChanges() was called.
  • ImportRow() to add rows from a DataTable with same schema.
  • DataColumn.MappingType sets the data mapping when writing to XML: Attribute, Element, Hidden, SimpleContent.
  • DataView can sort and filter data: Sort (asc, desc), RowFilter (where clause), RowStateFilter (DataViewRowState enumeration).
  • DataSet, typed DataSet, Designer.
  • Guid. Globally unique identifier.
  • DataRelation. Nested property controls xml output.
  • WriteXml(), WriteXmlSchema(), XmlWriteMode, ReadXml(), ReadXmlSchema(), XmlReadMode.
  • RemotingFormat property for binary serialization.
  • Binary serialization has overhead. Do not use for small files.
  • DataSet.InferXmlSchema() can exclude elements/attributes with specified namespaces.
  • When deserializing XML to a DataSet: Each element with attributes is deserialized as a DataTable with a column per attribute. Elements without attributes are deserialized as a column per element.
  • DataSet.Merge() and MissingSchemaAction enumeration: Add, AddWithPrimaryKey, Error, Ignore.
  • Provider classes: DbConnection, DbCommand, DbDataAdapter, DbProviderFacotry, DbProviderFactories. Db stands for: Sql, Oralce, Odbc and OleDb.
  • ODBC to access text files, Excel or Access databases.
  • OLEDB to use old ADO recordsets.
  • Use connection string encrypt="true" property to activate SSL (requires certificate on server).
  • Connection pool. Connections with exact same connection string, same user when using integrated security and same process ID share one pool.
  • Encrypt connection string: aspnet_regiis.exe -pef "…".
  • Decrypt connection string: aspnet_regis.exe -pdf "…".
  • Encrypt Web.config: DPAPIProtectedConfigurationProvider, RSAProtectedConfigurationProvider.
  • Use base classes and Create methods to reduce provider specific code.
  • DbCommand methods: Execute(), ExecuteNonQuery(), ExecuteScalar() – returns first column of first row, ExecuteReader().
  • MultipleActiveResultSets (MAPS) can be activated in connection string and allows multiple readers on one connection. Degrades performance.
  • SqlBulkCopy class. Use WriteToServer() with a DbDataReader object.
  • DataAdapter has commands for Select, Update, Delete and Insert. Use either designer wizard to create stored procedures or valid select command and SqlCommandBuilder for the others.
  • Improve performance by setting DbDataAdapter.UpdateBatchSize = 0.
  • DbProviderFactory (abstract class) has Create() for command, connection, etc.: SqlClientFactory, OleDbFactory, OdbcFactory and OracleClientFactory.
  • DbProviderFactories used to obtain a DbFactory. Uses Machine.config’s DbProviderFactories section.
  • Use DbException for provider independent exception handling.
  • DbConnection.InfoMessage event to retrieve operational and error information from database.
  • Transaction. Atomicity, consistency, isolation, durability.
  • DbTransaction is returned from DbConnection.BeginTransaction(). Assign to all command objects that are intended part of the transaction.
  • Asynchronous execution. Set async = true in connection string and use DbCommand.Begin*().
  • Handling BLOBs: Use CommandBehaviour.SequentialAccess with Execute() for reading and "select textptr", "updatetext" for writing.
  • It is best practice today to store binary data in database. Because file-access to folders with many files (e.g. more than 5000) can be really slow.
  • SqlDbType.Money is a decimal. In SQL server it can also contain a preceding currency symbol: $100 or CAST(’$100′ AS MONEY).
  • SqlDataSource: SelectCommand – query string or SP name, SelectCommandType – query or SP and SelectCommandParameters.
  • SQLServer connection is for SQL Server 7.0 and newer.
  • System.Xml namespace.
  • Three ways to access XML files:
    • XmlDocuments are an in-memory XML representation. This is useful for changing data and structure of an XML file.
    • XPathNavigator has cursor model to access XML files.
    • XmlReader and XmlWriter have stream access to XML files.
  • XmlDocument and XmlDataDocument class. The XmlDataDocument class has capabilities beyond DOM Level 1 and 2 as it supports data relations. This is useful when being used with ADO.NET datasets.
  • XPathDocument is read-only for fast XPATH querying.
  • XmlConvert class.
  • XPathNavigator has MoveTo*() and Select() for XPATH string or XPathExpression object. Use it with XPathDocument for better performance.
  • XmlDocument has GetElement(s)ByID(), GetElement(s)ByTagName() DOM methods and SelectSingleNode(), SelectNodes() XPATH methods.
  • XmlReader classes: XmlReader is abstract, use it’s create method with XmlReaderSettings to instantiate the appropriate reader. The following concrete implementations exist: XmlTextReader, XmlNodeReader and XmlValidatingReader. XmlReader provides non-cached, forward-only, read-only access. The same story for XmlWriter (it is write-only though :) .

 

Chapter 5, Creating Custom Web Controls

  • System.Web.UI namespace.
  • User control (ascx), custom web control, composite control.
  • Register directive for user control: <%@ Register TagPrefix="" TagName="" src="" />. The Src attribute provides the name of the ascx file.
  • To use absolute positioning for user controls use a panel in user control.
  • Only one form per web page.
  • LoadControl() to dynamically load user controls into page.
  • Templated user controls have a place holder that points to an object. You can style the appearence in aspx page.
  • ToolboxItem attribute to show control in Choose Toolbox Items dialog (default is true).
  • ToolboxBitmap to set bitmap shown in toolbox.
  • ToolboxData, TagPrefix, DefaultProperty and Designer attributes.
  • Declare tag prefix for custom controls in configuration\system.web\pages\controls section using add element with tagPrefix and Namespace attribute.
  • System.Web.UI.Designer namespace.
  • ControlDesigner base class. GetDesignTimeHtml(), use Initialize() to init the base component.
  • CompositeControl base class. Inherits from WebControl and implements INamingContainer.
  • TemplatedControl class. Use it to separate data and appearance.
  • Use ParseChildren attribute to control designer’s behaviour. Set to false renders inner contents as controls, otherwise as properties in property editor.

 

Chapter 6, Input Validation and Site Navigation

  • Validation controls. CustomValidator, RegularExpressionValidator, RequiredFieldValidator, CompareValidator, RangeValidator and ValidationSummary. Provide client and server side validation.
  • Properties: ControlToValidate, ErrorMessage – displayed message on validation error, Text – in-line error typically ‘*’.
  • SetFocusOnError() to set focus on control causing a validation error.
  • Page.Validate(), IsValid, GetValidations() and Validators collection containing all validators on page.
  • CustomValidator. Client-side function – Name(source, arguments) and ServerValidate event handler to perform server-side validation. Requires implementation at least server-side and optionally client-side.
  • Button.CausesValidation property.
  • ValidationGroup property to create validation sections.
  • Site navigation. Client-side code (link, document.location), cross page posting (Button.PostBackUrl), client-side redirect (Response.Redirect), server-side transfer (HttpUtility.Transfer()).
  • To receive posted values from previous page in webfarm (in-proc) use HttpUtility.Transfer(). Then use HttpContext.Handler to access the calling page. It works because Transfer() does not post-back.
  • Page.PreviousPage property to access data from calling page. Use PreviousPageType tag and properties for strongly typed access in crosspage posting and transfer.
  • Site map controls: Menu, TreeView and SiteMapPath. Use SiteMapDataSource that reads from Web.sitemap XML file. access through SiteMap class. Can be used for navigation also.

 

Chapter 7, ASP.NET State Management

  • Client-side state management: View state, Control state, hidden fields, cookies and query string.
  • Client-side pros: Reduce work on server, web-farm compatible.
  • Server-side pros: More secure, reduce bandwith.
  • View state: Sends data to client in hidden field, supports chunking, can be encrypted, can be disabled, can be used with any serializable object.
  • Control state: Cannot be disabled, implemented by SaveControlState(), LoadControlState() and RegisterRequiresControlState().
  • Cookies use Request.Cookies, Response.Cookies or HttpCookie class. Properties: Value, Expires, Path, Domain. Supports also many values per cookie.
  • Query string to sent via email or use in hyperlinks, requires HTTP GET. Note that the max url length is 2083 characters. Remember to validate query strings, use HtmlEncode(), Request.QueryStrings to access.
  • Application state is the same for all users. Application("name").
  • Session state applies to single user. Session("name").
  • Global.asax has Start, End, Error handle methods for session and application.
  • Session state can be disabled in Web.config. <sessionState="off" /> or via page directive. Can be cookieless. <sessionState cookieless="true" />. Modes: InProc (web server memory), StateServer (ASP.NET state service), SqlServer, Custom, Off.
  • Profile properties are user data that is not lost on session expiration. Strongly typed. Stores as xml file to SQL server or web service.

 

Chapter 8, Programming the Web Application

  • Use Page_Error or Application_Error handlers to handle unhandled exceptions using Server.GetLastError() and Server.ClearError().
  • System.Configuration, System.Web.Configuration namespace.
  • Use WebConfigurationManager to access Web.config’s 31 sections strongly typed.
  • Use GetSection("system.web/<section name>") and cast result. Use OpenWebConfiguration() with evt. folder name.
  • Request.ApplicationPath.
  • Save() takes ConfigurationSaveMode enumeration: Full, Minimal, Modified.
  • Asynchronous web pages: Use to improve efficiency of long running web pages. E.g. call to a credit card payment site. Assert Async page directive, add Begin/EndGetAsyncData() and subscribe to those events using AddOnPreRenderCompleteAsync().
  • Http handler implement IHttpHandler or IHttpAsyncHandler. Have IsReusable and ProcessRequest().
  • Configuration:
    1. IIS admin, set extension mapping to aspnet_isap.dll.
    2. Add handler to Web.config section <httpHandlers>.
  • Request.Browser has browser capabilities.
  • Important Page objects: Response (HttpResonse), Request (HttpRequest), Server (HttpServerUtility), Context (HttpContext), Session, Application, Trace.
  • Page.Header has Title and StyleSheet property.
  • HttpContext items are cleared after each request.

 

Chapter 9, Customizing and Personalizing a Web Application

  • Master page has .master extension. Content pages use ASPX pages that refer to a master page via page directive or <pages> element in Web.config. Content controls refer to respective ContentPlaceHolder controls in master page.
  • You can access properties, methods and controls in master pages by setting MasterType page directive in content page and using the Master class.
  • Life-cycle for master and content page: Master control init, content control init, master init, content init, content load, master load, content controls load, content PreRender, master PreRender, master controls PreRender, content controls PreRender.
  • Master pages can be nested. Nested pages have MasterPageFile="parent.master" in page declaration (exactly like content pages).
  • Theme can be set in page directive or <pages> element in Web.config.
  • Application/Global theme. Place in App_Themes folder or iis_default_root/aspnet_client/system_web/<version>.
  • Components: Skin files (mark-up without ID attribute), CSS and images.
  • Use aspnet_regsql.exe -Ap to create a user profile database.
  • Profiles are auto-enabled for authenticated users.
  • For anonymous users set anonymousIdenfication in Web.config.
  • Define <profile> section in Web.config and access through Profile object.
  • Web parts generate client-side menus to customize a web site. Add WebPartManager control to page and WebPartZone controls. Add EditorZone and Appearance/EditorPart for editing.
  • Personalization is persisted for authenticated users by default.
  • Consumer method: Use ConnectionConsumer attribute on void method that takes providers return value type as parameter.

 

Chapter 10, Globalization and Accessibility

  • Local resources: resx file for each language version of a page in App_LocalResources folder. ASP.NET selects the approriate language based on browser info (IE: Tools/Internet Options/Language) or can be overriden programatically. <ASPX page name>.<culture>.resx.
  • Global resources: Stored in App_GlobalResources folder. <name>.<culture>.resx. Use controls Expressions property and ClassKey (resx’s name)/ResourceKey attribute. <%$ Resources: ClassKey, ResourceKey %>. Also use Resources.Resource for strongly typed access.
  • Setting the culture. Culture – language and formatting. UICulture – global/local resources only. Override the InitializeCulture() in Page or set in page directive or in Web.config or in Thread.CurrentThread (does not work for devolpment webserver).
  • Web Content Accessiblity Guidelines (WCAG) and Section 508 guidelines.
    • Use AlternateText for images or assert GenerateEmptyAlternateText to skip.
    • Use solid background colors and contrasting text color.
    • Use flexible page layout.
    • Use Table.Caption property.
    • Use TableHeaderRow and AssociatedHeaderCellID to describe columns in Calender, DetailsView, FormView and GridView controls.
    • Avoid to specify font sizes.
    • Avoid client scripts. Set EnableClientScript to false on validation controls. Avoid LinkButton, ImageButton and Calendar controls.
    • Use TabIndex, AccessKey/AssociatedControlID and DefaultButton on Form and Panel controls.
    • Use DefaultFocus property on form.

 

Chapter 11, Implementing Authentication and Authorization

  • Authentication controls: Login – prompts for user name and password, LoginView – displays message for logged in/not logged in users, LoginStatus – gives a link to log in/log out, PasswordRecovery – e-mails forgotten passwords, CreateUserWizard – creates a new user, ChangePassword – changes password for logged in user. Can be used with ValidationSummary control.
  • System.Web.Security namespace.
  • Membership class to manage users and Roles class to manage user groups.
  • Types of authentication: Windows, Forms, Passport, Anonymous access, None.
  • Web.config’s <configurations><system.web> subsections for <authentication> and <authorization>.
  • ? for unauthenticated users, * for all users. ‘,’ used as separator for listing user initials.
  • Sequence of allow and deny elements matters. Start with users you want to exclude and than allow the others with <allow="*" />
  • Forms authentication. Use protection="Validation"/"Encryption" attribute for more secure cookies, cookieless attribute to control cookies and timeout attribute.
  • FormsAuthentication class. HashPasswordForStoringInConfigFile(), RedirectFromLoginPage() and SignOut().
  • Impersonation. <identity impersonate="true">. Anonymous users run as IUSR_MachineName account, windows users with their account or with specified account by user name and password.
  • Not imporsonated: Anonoymous users run as network Service Account (Win2003 server) and authenticated users as IUSR_MachineName.

 

Chapter 12, Creating ASP.NET Mobile Web Applications

  • Remove default.aspx and add mobile web form.
  • OpenWave phone emulators for testing.
  • System.Web.UI.MobileControls namespace.
  • Mobile web page can have more than one form. By default the first form on page is active.
  • Most mobile devices do not support cookies.
  • Browser capabilities configuration: ../<version>/CONFIG/Browsers/*.browser xml files. Run aspnet_regbrowser -i after change. HttpBrowserCapabilities class to access.
  • AppliedDeviceFilters property to change a control’s appearance depending on the browser.
  • One control per line is standard.
  • Controls: *Validator, AdRotator, Command (Button), Calendar, List (DataList), ObjectList (DataGrid), DeviceSpecific (used for property overrides), Form, Image, Label, Link (Hyperlink), Panel, PhoneCall, SelectionList (CheckBox, DropDown, RadioButton), StyleSheet, TextBox, TextView, ValidationSummary.
  • Device filters in section configuration\system.web\deviceFilters using the <filter> element. Use standard filters or implement custom filter as method in the web page where the filter is being used.
  • For debugging with Microsoft Device Emulator you need to run the web application on IIS.

 

Chapter 13, Monitoring, Deploying and Caching Applications

  • Web setup project. VS project type to generate MSI or setup.exe. Add project output in File System view.
  • View/Editor/Launch Conditions. Search target machine, launch condition (message and evt. help link).
  • Setup wizard and custom pages.
  • View/Editor/Custom Actions.
  • View/Editor/Registry for registry entries.
  • View/Editor/User Interface to add custom pages.
  • Steps: Install, Commit, Rollback and Uninstall.
  • Microsoft installer command line: msiexec /i – install, /a – admin install, /f – repair, /x – uninstall, /L – log, /p – patch.
  • Copy Web Tool. Web application/Copy Web Site.
  • Pre-compile. Web application/Public Web Site. Options: Allow This Precompiled Site To Be Updatable, Use Fixed Naming And Single Page Assemblies, Enable Strong Naming On Precompiled Assemblies.
  • Updatable compiles assemblies for each ASPX page but leaves the mark-up code in the ASPX file.
  • Not updatable compiles assemblies for each ASPX page and leaves only a reference in the ASPX file.
  • Create versioned pre-compiled assemblies: Use AssemblyInfo.cs to assign version number and use compileOptions in all ASPX page declarations and in system.codedom\compilers using compiler element (Web.config).
  • Debug attribute in web.config sets mode for the dynamically compiled assemblies.
  • ASP.NET monitoring. Web events and handling, performance counters.
  • Event provider base class is WebEventProvider. There are about ten implemented providers: SQL server, e-mail, Event log and Trace.
  • Events are implemented for: Audit, Authentication, Error, Lifetime and Heartbeat.
  • Events are configured in <healthMonitoring> section in Web.config.
  • Performance counters. Use existing counters from Server Explorer or Administrative Tools. Create custom counters with PerformanceCounterCategory.Create() and CounterCreationData/CounterCreationDatacollection from System.Diagnostics namespace.
  • Application cache: Cache("…") collection is application wide. Takes objects, requires null check and cast of the result.
  • Cache.Add() takes key and object to put into cache as parameter. There is also a variety of CacheDependency types.
  • System.Web.Caching namespace.
  • Page output caching. @OutputCache page directive, Response.Cache object or <caching><outputCacheSettings><outputCacheProfiles> in Web.config.
  • VaryBy* attributes or SqlDependency control refresh behaviour of the page output caching.
  • Response.WriteSubstitution() and Substitution control to have non-cached parts in the page.
  • Invalidation of cache contents by using Response.Cache.AddValidationCallback and HttpValidationStatus.Valid/Invalid/IgnoreThisRequest.