70-564 - Passed

Filed under: , , , , , by:

It was last week when I took the 70-564 exam and I passed with the score 985/1000. It looks like I got 1 question wrong. Nevertheless, I have earned Microsoft Certified Professional ASP.NET 3.5 Developer title.





Here is my experience with the exam:
  • there is 50 (!) questions (70-503 (WCF) exam also has 50 questions but on the other hand 70-505 (Windows Forms 3.5) exam has only 40 questions) and 120 minutes
  • questions are not harder than those for 70-562 exam, so if you can pass that exam, you can pass this one
  • there is very few questions on Ajax - MCTS ASP.NET 3.5 exam (70-562) had about 10 questions on Ajax but this one maybe 3 or 4. Also I think 1 question was exactly the same as I had at 70-562 exam
  • there is a lot of questions on state management, which is in line with the exam objectives (Manage state of controls and Design a state management strategy).
  • main focus of questions is to test the ability to identify appropriate usage, so in oder words 70-562 exam requires a tester to know how to use something  whereas 70-564 exam requires to know when to use something or which one to use in this scenario. 
  • the most crucial aspect at the exam is to read questions very carefully - most questions will contain a list of requirements that almost all answers will meet but there will, of course, only 1 answer (unless it is multiple choice question) that will meet every single requirement and every single word in all the requirements. 
  • very often requirement(s) will contain a comma separated list ie.types of files or activities so make sure that answers will satisfy all elements from the list(s). 
I hope those guidelines will be helpful for everyone who considers taking the 70-564 exam, even though everyone could come to the same conclusions after studying the exam objectives. Given the fact that the exam doesn't cover anything more than 70-562 exam does, I would encourage everyone to take 70-564 exam if he or she has passed 70-562 exam with a good score. I waited a month to read a little more about designing enterprise applications using ASP.NET with the focus on requirements and proposed solutions that would meet those requirements. There is really no point to wait unless you were not comfortable with the 70-562 exam.
Next exam on path to MCPD Enterprise Application Developer 3.5 is MCTS 70-561 ADO.NET 3.5, which will be the last one before the final 70-565 exam.

70-564 - Extending controls with control extenders

Filed under: , , , , by:

Before .NET 3.5 to extend a control meant usually to inherit from a base control and add extra functionality or create a custom control that would contain a control to extend with additional items ie. javascript. But .NET 3.5 introduced another way to extend a control, which is through Ajax Control Extender, but I have experienced that still many developers are not aware of that fact and still use either inheritance (in java keyword extends is equivalent of keyword inherits in VB.NET or ":" in C#) or create a custom control where they could take advantage of ExtenderControl class. That class enables you to programmatically add AJAX functionality (or simple javascript) to an ASP.NET server control. Since it's not based on inheritance, there is no limitation of extending only unsealed controls.Also one extender may extend different types of controls (TextBox, Button, MyTextBox, etc.) - before it would require creating custom class for each type of controls being extended. I believe that's why AjaxControlToolkit contains so many control extenders ie. SliderExtender, RoundedCornersExtender or ModalPopupExtender. But even though there always will be a business need (or rather functional requirement) to create a custom control extender ie. FocusExtender that will apply different css style whenever a target control gets focus and reverts it back to the default css style when a target control has lost focus. Plus target control can be any type of control - TextBox, Button, DropDownList, etc.
Control extender is created by creating a new project of type: ASP.NET Ajax Server Control Extender.


Once created, a project contains a class that inherits from ExtenderControl and a javascript file in which client-side behavior is specified that will be added to a target control being extended.
FocusExtender.cs

using System;
using System.Collections.Generic;
using System.Web.UI;
namespace Extenders
{
[TargetControlType(typeof(Control))]
public class FocusExtender : ExtenderControl
{
protected override IEnumerable<ScriptDescriptor>
GetScriptDescriptors(Control targetControl)
{
ScriptBehaviorDescriptor desc = new ScriptBehaviorDescriptor(
"Extenders.FocusBehavior", targetControl.ClientID);
desc.AddProperty("onFocusCssClass", OnFocusCssClass);
desc.AddProperty("defaultCssClass", DefaultCssClass);
yield return desc;
}
 
protected override IEnumerable<ScriptReference>
GetScriptReferences()
{
ScriptReference sRef = new ScriptReference();
sRef.Name = "Extenders.FocusBehavior.js";
sRef.Assembly = this.GetType().Assembly.FullName;
yield return sRef;
}
 
public string OnFocusCssClass
{
get
{
String s = (ViewState["OnFocusCssClass"] as String);
return s ?? "";
}
 
set
{
ViewState["OnFocusCssClass"] = value;
}
}
 
public string DefaultCssClass
{
get
{
String s = (ViewState["DefaultCssClass"] as String);
return s ?? "";
}
 
set
{
ViewState["DefaultCssClass"] = value;
}
}
}
}
FocusBehavior.js
Type.registerNamespace('Extenders');
Extenders.FocusBehavior = function(element)
{
Extenders.FocusBehavior.initializeBase(this, [element]);
this._onFocusCssClass = null;
this._defaultCssClass = null;
this._focusHandler = null;
this._blurHandler = null;
}
Extenders.FocusBehavior.prototype =
{
initialize : function()
{
Extenders.FocusBehavior.callBaseMethod(this, 
'initialize');
var e = this.get_element();
this._focusHandler = Function.createDelegate(
this, this._onFocus);
this._blurHandler = Function.createDelegate(
this, this._onBlur);
$addHandler(e, 'focus', this._focusHandler);
$addHandler(e, 'blur', this._blurHandler);
},
dispose : function()
{
var e = this.get_element();
if (this._focusHandler)
{
$removeHandler(e, 'focus', this._focusHandler);
this._focusHandler = null;
}
if (this._blurHandler)
{
$removeHandler(e, 'blur', this._blurHandler);
this._blurHandler = null;
}
Extenders.FocusBehavior.callBaseMethod(this, 'dispose');
},
_onFocus : function(evt)
{
var e = this.get_element();
if (e != null)
{
e.className = this._onFocusCssClass;
}    
},
_onBlur : function(evt)
{
var e = this.get_element();
if (e != null)
{
e.className = this._defaultCssClass;
}
},
get_defaultCssClass : function()
{
return this._defaultCssClass;
},
set_defaultCssClass : function(value)
{
this._defaultCssClass = value;
this.raisePropertyChanged('defaultCssClass');
},
get_onFocusCssClass : function()
{
return this._onFocusCssClass;
},
set_onFocusCssClass : function(value)
{
this._onFocusCssClass = value;
this.raisePropertyChanged('onFocusCssClass');
}
}
Extenders.FocusBehavior.registerClass('Extenders.FocusBehavior', Sys.UI.Behavior);

Next, Extenders.dll  can be added to any Web Site project and any control can gain new behavior, which will allow to change its color when it got focus.
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="Extenders" Namespace="Extenders" TagPrefix="MI" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<style type="text/css">
.Normal
{
background-color: White;
color:Black;
font-weight:normal;
}
.Highlight
{
background-color: Blue;
color:White;
font-weight:bold;
}
.HighlightButton
{
background-color: Yellow;
color:Red;
font-weight:bold;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
Username:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
Password:
<asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Value1</asp:ListItem>
<asp:ListItem>Value2</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Button1" />
<MI:FocusExtender ID="focusExtender1" runat="server" TargetControlID="TextBox1" OnFocusCssClass="Highlight"
DefaultCssClass="Normal" />
<MI:FocusExtender ID="focusExtender2" runat="server" TargetControlID="TextBox2" OnFocusCssClass="Highlight"
DefaultCssClass="Normal" />
<MI:FocusExtender ID="focusExtender3" runat="server" TargetControlID="DropDownList1"
OnFocusCssClass="Highlight" DefaultCssClass="Normal" />
<MI:FocusExtender ID="focusExtender4" runat="server" TargetControlID="Button1" OnFocusCssClass="HighlightButton"
DefaultCssClass="Normal" />
</div>
</form>
</body>
</html>

And here are the screenshots:


This very simple example shows how one control extender can change behavior of many different types of controls or add some custom javascript to the page. Some developers who are not experienced in Ajax client-side library and creating Ajax behaviors might find writing control extenders a little complex but nowadays it's almost impossible to be a thriving professional .NET ASP.NET Web Developer without having a good understanding of Ajax client-side programming as he cannot take a full advantage of .NET 3.5 and Visual Studio 2008. And the problem is that Ajax will be getting more and more popular so the sooner you get familiar with all features of Ajax, the easier it will be to learn new features of its next versions and next versions of .NET and Visual Studio. I hope this will encourage everyone to get familiar with control extenders and use them to add extra functionality to the existing controls when next time you will have to extend a control.

70-564 - Visual Studio 2008 Templates

Filed under: , , , , by:

Choosing appropriate project templates is very crucial, yet many times developers will choose a template they are most accustomed to or sometimes they don't simply know that there's already a template that will meet their need. Very rarely do books describe available templates and developers usually too busy to explore that end up using either the wrong kind of template or create one from scratch, where they could save a lot of time by using something that has already been developed and tested and is ready to use out of the box. Personally I know a few .NET Web Developers that still don't really understand the difference between ASP.NET Web Site and ASP.NET Web Application. That's why I thought it would be good to go through at least Web templates as those are the subject of the 70-564 exam.
There are two kinds of Web templates - Web Site and Web Project, which they can be accessed for example from the context menu of the solution.



1. Web Site templates - below is the screenshot containing all Web Site templates



  • ASP.NET Web Site - introduced in Visual Studio 2005; doesn't have a project file; all classes must be placed in App_Code folder; all classes by default don't contain namespaces; classes can be written in different languages as long as they are in separate subfolders within App_Code folder; to deploy everything must be copied to IIS folder; separate assembly can be created per page hence changes in 1 page will result in recompiling only 1 assembly; web references are added to special folder App_WebReferences; structure of the project is based on file system (folders represent physical system folders)
  • ASP.NET Web Service – this template opens ASP.NET Web Site template and adds web service file (*.asmx) and puts code-behind file to App_Code folder
  • Empty Web Site – this template creates blank ASP.NET Web Site project but without Default.aspx page, web.config file and without App_Data folder
  • WCF Service –  this template opens ASP.NET Web Site template and adds WCF service file (*.svc) and puts code-behind file to App_Code folder
  • ASP.NET Reports Web Site –  this template opens ASP.NET Web Site template and adds Default.aspx page with ReportViewer element and opens a wizard to create a new Report Data Source, which allows you to choose views or tables from which to retrieve data to strongly typed DataSet that is put in App_Code folder.Finally a local report (*.rpdl) is created
  • ASP.NET Crystal Reports Web Site –  this template opens ASP.NET Web Site template and adds Default.aspx page with CrystalReportViewer element and opens a wizard to create a new Crystal Report (*.rpt), which is being placed in the root folder
  • Dynamic Data Entities Web Site – new template (requires .NET 3.5 SP1) provides a scaffolding framework that enables you to create a data-driven application within minutes using ASP.NET Web Site template,  EntityDataSource and ADO.NET Entity Framework
  • Dynamic Data Web Site – new template (requires .NET 3.5 SP1) provides a scaffolding framework that enables you to create a data-driven application within minutes using ASP.NET Web Site template, LinqDataSource and LINQ to SQL.
2. Web Project templates - below is the screenshot containing all Web Project templates.


  • ASP.NET Web Application - introduced in Visual Studio 2003;  require project file, which defines project structure in application; contains bin folder with compiled assembly of the project; no special App_Code folder is required; all classes automatically get a namespace when added to the project;  all classes must be in one language; only visual elements and compiled assemblies must be copied to IIS folder; you can add pre-build and post-build steps during compilation; web reference is added to folder Web References
  • ASP.NET Web Service Application – this template opens ASP.NET Web Application template and adds web service file (*.asmx) with code-behind file to the root folder
  • ASP.NET Ajax Server Control – this template creates a new ASP.NET custom server control that inherits from ScriptControl, which inherits from WebControl class (base class for all ASP.NET Web server controls) and implements IScriptControl (interface with methods to define JavaScript resources of the custom control)
  • ASP.NET Ajax Server Control Extender – this template creates a new ASP.NET control extender that inherits from ExtenderControl, which inherits from Control class (class defines the properties, methods, and events that are shared by all ASP.NET server controls) and implements IExtenderControl (interface with methods to define JavaScript resources with the behavior for an extender control). This templates allows to add custom client behavior to the existing controls and extend their functionality. It can extend different types of controls (buttons, textboxes, etc.) at the same time, where normally you would have to create several custom controls that would inherit from the controls you want to extend.
  • ASP.NET Server Control – this template, known in VS2005 as Web Control Library, creates ASP.NET Server control(s) – classes that inherit from WebControl class and can be added to Visual Studio Toolbox
  • WCF Service Application  – this template opens ASP.NET Web Application template and adds WCF service file (*.svc) and with its code-behind file in the root folder.
  • Dynamic Data Entities Web Application – this is new template (requires .NET 3.5 SP1) provides a scaffolding framework that enables you to create a data-driven application within minutes using ASP.NET Web Application template,  EntityDataSource and ADO.NET Entity Framework
  • Dynamic Data Web Application – this is new template (requires .NET 3.5 SP1) provides a scaffolding framework that enables you to create a data-driven application within minutes using ASP.NET Web Application template, LinqDataSource and LINQ to SQL
All templates described above are Visual Studio 2008 default templates but you can also download custom templates or create your own ones. Creating a template is done by simply exporting your current project to the template file followed by the export wizard. In the same way you can create an item template.




I hope you've found this overview of Visual Studio 2008 templates useful and helpful in deciding what type of template to use when you're going to create a new project next time. Maybe you will need to create a data-driven web site and you will consider using Dynamic Data Entities Web Site template rather than creating your project from scratch - or maybe you will decide to create additional templates so next time you can take advantage of something you've already developed so you can write less code and play more golf.

70-562 - ASP.NET + REST WCF + Ajax + JSON

Filed under: , , , , , by:

Nowadays almost every enterprise application takes advantage of SOA platform, which in most cases means that there is some sort of web service that an application is consuming in order to enable unprecedented dynamic interaction and reduce costs and speed time to market by maximizing interface (components and various domain functionality) reuse. And also in most cases it is Web applications that takes advantage of Web services. Therefore, in .NET anyone who develops ASP.NET applications will have to integrate WCF service into his application. Most of the time it will by adding web or service reference but when developing RIA using Ajax technology there is a way to consume WCF services with Ajax client library to avoid page postback. And when adding JSON message formatting an application can respond even quicker as JSON format is a lot less overhead comparing to SOAP. That's why it is so important that every .NET developer who builds RIA should always consider using REST WCF (with JSON message response fomat) from Ajax. 
Example:
An ASP.NET page that will allow user to enter mortgage fixed loan amount with note rate and number of years, and after clicking Calculate button a javascript function will call WCF service and receive values of monthly payment and total amount to pay (loan amount + interests). There will be no UpdatePanel and no service or web reference and proxy class generated by svcutil.exe tool.
1. WCF Service
- LoanService.svc
<%@ ServiceHost Language="C#" Debug="true" Service="WcfAjaxService.LoanService" CodeBehind="LoanService.svc.cs" Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" %>
- LoanService.svc.cs

using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
namespace WcfAjaxService
{
[ServiceContract(Namespace = "WcfAjaxService")]
public class LoanService
{
[WebGet(ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
public LoanPayments GetPaymentInfo(double LoanAmount, double AnnualRate, int Terms)
{
return LoanPayments.Create(LoanAmount, AnnualRate, Terms);
}
}
 
[DataContract]
public class LoanPayments
{
[DataMember]
public double MonthlyPayment { get; set; }
[DataMember]
public double TotalPayments { get; set; }
 
public static LoanPayments Create(double LoanAmount, double AnnualRate, int Terms)
{
LoanPayments payment = new LoanPayments();
double MonthlyRate = AnnualRate / 1200d;
double t = Math.Pow(1d + MonthlyRate, Terms*12);
payment.MonthlyPayment = LoanAmount * MonthlyRate * t / (t - 1d); 
payment.TotalPayments = Math.Round(payment.MonthlyPayment * Terms*12,2);
payment.MonthlyPayment = Math.Round(payment.MonthlyPayment,2); 
return payment;
}
}
}

- Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AjaxWcfJson._Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Consuming REST WCF service from Ajax</title>
<link href="Stylesheet.css" rel="stylesheet" type="text/css" />
 
<script language="javascript" type="text/javascript">
// <!CDATA[
var amount;
var rate;
var term;
function Submit1_onclick() {
amount=parseFloat($get("txtLoanAmount").value);
rate=parseFloat($get("txtNoteRate").value);
term=parseInt($get("txtTerms").value);
var service =new WcfAjaxService.LoanService();
service.GetPaymentInfo(amount,rate,term, onSuccess, null, null);
}
function onSuccess(result) {
$get("txtPayment").value=result.MonthlyPayment;
$get("txtTotalPayments").value=result.TotalPayments;
}
// ]]>
</script>
 
</head>
<body>
<form id="LoanForm" runat="server">
<div>
<asp:ToolkitScriptManager ID="ToolkitScriptMgr" runat="server">
<Services>
<asp:ServiceReference Path="http://localhost:4465/LoanService.svc" />
</Services>
</asp:ToolkitScriptManager>
<asp:RoundedCornersExtender ID="PaymentCalcPanel_RoundedCornersExtender" runat="server"
Enabled="True" TargetControlID="PaymentCalcPanel" BorderColor="#003300" Corners="All"
Radius="10">
</asp:RoundedCornersExtender>
<asp:Panel ID="PaymentCalcPanel" runat="server" Height="180px" Width="190px" BackColor="#FF6600">
<table align="center">
<tr>
<td>
Loan Amount
</td>
<td>
<asp:TextBox ID="txtLoanAmount" runat="server" CssClass="textbox"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Note Rate
</td>
<td>
<asp:TextBox ID="txtNoteRate" runat="server" CssClass="textbox"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Terms
</td>
<td>
<asp:TextBox ID="txtTerms" runat="server" CssClass="textbox"></asp:TextBox>
</td>
</tr>
<tr>
<td align="center" colspan="2" height="37px">
<input type="button" id="btnCalculate" class="button" value="Calculate" onclick="Submit1_onclick()" />
</td>
</tr>
<tr>
<td>
Payment
</td>
<td>
<asp:TextBox ID="txtPayment" runat="server" ReadOnly="True" CssClass="textbox"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Total to pay
</td>
<td>
<asp:TextBox ID="txtTotalPayments" runat="server" ReadOnly="True" CssClass="textbox"></asp:TextBox>
</td>
</tr>
</table>
</asp:Panel>
</div>
</form>
</body>
</html>

- Stylesheet.css
body
{
font: font-family: 'Times New Roman', Times, serif; font-size: small; color: #FFFFFF; font-weight:bold;
}
.button
{
background-color:Green;
font: font-family: 'Times New Roman', Times, serif; font-size: small; color: #FFFFFF; font-weight:bold;
}
.textbox
{
font: font-family: 'Times New Roman', Times, serif; font-size: small; color:Teal ; font-weight:bold;
width:80px;
text-align:right;
}
Here is the screenshot of the application is action:


Here is a list of requirements that need to be met to support consuming REST WCF with JSON by Ajax:
  • WCF Service (LoanService.svc) uses factory WebScriptServiceHostFactory that automatically adds ASP.NET Ajax endpoint to a service. However, it could've been done without the factory class by simply adding serviceModel configuration to web.config file that defines <enableWebScript/> element in service endpoint, using webHttpBinding and also allowing compatibility with ASP.NET applications (either by adding to service class [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] attribute or by adding under serviceModel element <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />  a
  • Operation contract method uses WebGet attribute which is required to define REST WCF Service but also it allows to define response message format as JSON
  • Adding reference to the WCF service has been done by adding <asp:ServiceReference path=uri/> to Services collection to ScriptManager or here ToolkitScriptManager. However, a proxy class in javaascript could've been generated by adding /js or /jsdebug to the address of WCF service
  • Instantiate service class object is by using keyword new and service name with service namespace, which is why ServiceContract defines namespace (although namespace should always be changed), hence the service object is WcfAjaxService.LoanService
  • Operation contract method (exposed web method) is called with the following parameters: method arguments, succeeded callback function, failed callback function and associated user context. In the example only succeeded callback was used, which is called when web service has finished executing and has returned a value
  • Succeeded callback function has 1 parameter, which is an object returned by operation contract method. Since WCF service returns object in JSON format, javascript requires nothing else to be able to parse it as it contains full support for JSON objects. Therefore, object contains properties as defines by data contract of the WCF service
  • To see service response as text (not an JSON object) the following line of code must be added to GetPaymentInfo (operation contract) method: WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";

    And this is how the JSON response message looks like:

    However, if you try to run it without commenting out lines in onSuccess javascript method that access properties of result argument, you will get an error. This is because response message is not longer an JSON object but a string. But because the string is in JSON format it can be parsed to JSON object using javascript eval function. Here is an example how to parse a JSON-formatted message if outgoing response from web service was returned as plain text.

  • Button is an HTML input element of type button, therefore calling WCF service doesn't require page postback and also doesn't require using UpdatePanel, unless there is other control that causes page postback, which loads content of textboxes - holding results of calculations - from ViewState
I hope this very simple example will spur everyone on towards using REST WCF services with Ajax and JSON when creating rich Internet applications. Also I hope that this will also be beneficiary for all of those who are considering taking 70-562 exam which covers Ajax and WCF services. But first of all, I hope this will help you thrive as .NET web developers as you'll be better equip to provide better QoS.

70-562 - Ajax Client Library

Filed under: , , , , by:

70-562 exam covers Ajax and I can tell that more and more developers take advantage of Ajax. However, still I notice that a lot of times Ajax for a developer means UpdatePanel, UpdateProgress, Timers + AjaxToolkit. Ajax is a lot more than that - it is also Ajax client library, without which more complex solutions wouldn't be possible. Even book Professional ASP.NET 3.5: In C# and VB (Programmer to Programmer) in chapter about Ajax doesn't mention Ajax client library. There's a lot of books about Ajax that does pretty good job describing ajax client library but a lot of developers usually get books like forementioned one rather than 5 seperate ones (ASP.NET, Ajax, WCF, Security, etc.). So this post will describe most common classes, events and properties that each developer, who uses Ajax, must know.
All ajax client classes come from System.Web.Extensions.dll. Most common are Sys.Application, Sys.WebForms.PageRequestManager, Sys.Debug, Sys.Component, Sys.UI.DomElement.
1. Sys.Application - is used mostly for its events, from which more often used are Init, Load and Unload. To utilize those events you put in javascript ie. Sys.Application.add_load(_pageLoadHandler) or Sys.Application.add_init(_pageInitHandler).
2. Sys.WebForms.PageRequestManager - this class managed every partial postback on client side, therefore it's the most often used object by developers. It offers a lot of properties, methods and events. Most common events are:
a) initializeRequest - the first event raised during the partial postback life-cycle. Mostly used to determine the HTML element that triggered the postback, cancel the current postback or abort already executed asynchronous postback.
b) beginRequest - this event is raised just before the request is sent to the server. The UpdateProgress control uses this event to displayed its output.
c) pageLoaded - raised when page being refreshed. It has access to updatepanels being deleted or updated. In this event you put animations that an update has arrived.
d) endRequest - completion of partial postback. The UpdateProgress control uses this event to displayed its output. Also any errors during postback are avaiable here.
And methods are:
a) get_isInAsyncPostBack() - this method gets a boolean value if there are any asynchronous postbacks that are still being processed (besides the current). In this way a current postback can be cancelled to wait for previous postback to finish.
b) abortPostBack() - this aborts current and other postbacks that are still being processed. Mostly used to cancel long-running operation.
But besides those methods there are arguments that are passed to events (initializeRequest, endRequest, etc.) that gives access to other methods:
a) args.get_postBackElement() - gets an element that caused the current postback
b) args.set_cancel(true) - cancels the current postback and let previous ones to finish
c) args.get_error() - to get an error if occurred during request (available in endRequest)
d) args.set_errorHandled(true) - informs that our code handled the error
e) args.get_dataItems() - gets data that was registered ScriptManager.RegisterDataItem, which is used when registered item is not part of asynchronous postback (ie. it's not inside UpdatePanel) but it should be updated as well during asynchronous postback.
3. Sys.Debug - it offers methods to help debugging a client-side code. Most common methods are:
a) trace(message) - it shows a message in debugger's output
b) traceDump(object,message) - it shows message in debugger's output plus information on an object (usually control)
c) fail (message) - it breaks into debugger so it should be used to catch developer errors.
4. Sys.Component - base class for all components and non-visual controls on the page. It is used mostly to create a component with static method Sys.Component.create or $create.
5. Sys.UI.DomElement - provides helper methods for manipulating DOM elements. Most common methods are:
a) getElementById or $get(id) - it retrieves an element with given id. It can also return a component, however to return a component $find(id) should be used.
b) setVisible(element,true/false) - makes an element visible or invisible
Examples:
1. Page with 2 buttons - btnCancel and btnRun and Label lblStatus. When user clicks btnRun a long-running operation takes place. We want to able to cancel that operation by clicking btnCancel (but only when there is a running operation) and to be able to ignore another call when user clicks again btnRun when a previous one is still running. Here is a java script that would perform those operations:

<script type="text/javascript">
var mgr=Sys.WebForms.PageRequestManager.getInstance();
var el;
var isPostBack;
mgr.add_initializeRequest(initHandler);
mgr.add_endRequest(endHandler);
function initHandler(sender,args)
{
el=args.get_postBackElement();
isPostBack=mgr.get_isInAsyncPostBack();
if (mgr.get_isInAsyncPostBack())
{
if (el.name=="btnCancel")
{
mgr.abortPostBack();
return;
}
if (el.name=="btnRun")
{
$get("lblStatus").innerText='Your request is still being processed';
args.set_cancel(true);
return;
}
}
else
{
if (el.name=="btnRun")
$get("lblStatus").innerText='Processing your request';
}
}
function endHandler(sender,args)
{
if (args.get_error()!=null)
{ 
args.set_errorHandled=true;
$get("lblStatus").innerText=args.get_error().message;
}
else
{
if (el.name=="btnRun") 
$get("lblStatus").innerText='Finished';
else
if (el.name=="btnCancel" && isPostBack )
$get("lblStatus").innerText='Your request has been cancelled';
}
}
</script>
2. This example shows how to create modal popup window with UpdateProgress panel. Also in this example you can see how to change a message in popup window (precisely in UpdateProgress template) based on the button that triggered the postback. I have seen so many times applications with generic message: Please Wait....Wouldn't it be better to show a user a little more informative message like: Retrieving list of customers or Saving user settings in the database? This simple example shows a way to do it:
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="MainPage" %>
<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Namespace="System.Web.UI" TagPrefix="asp" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Modal Popup Window</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<script type="text/javascript" language="javascript">
var ModalProgress = '<%= ModalProgress.ClientID %>';    
var mgr = Sys.WebForms.PageRequestManager.getInstance();
mgr.add_initializeRequest(InitRequest);
mgr.add_beginRequest(beginReqest);
mgr.add_endRequest(endReqest);
function InitRequest(sender, args) 
{
var el = args.get_postBackElement();
if (el.name == "btnOrder")
$get("lblProcessing").innerText = ' Retrieving orders...';
else
if (el.name == "btnCustomer")
$get("lblProcessing").innerText = ' Retrieving customers...';
else
$get("lblProcessing").innerText = ' Processing request...';
}
function beginReqest(sender, args) 
{
$find(ModalProgress).show();
}
function endReqest(sender, args) 
{
$find(ModalProgress).hide();
}     
</script>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Panel ID="panelUpdateProgress" runat="server" 
CssClass="ProgressPanel">
<asp:UpdateProgress ID="UpdateProg1" DisplayAfter="0" runat="server">
<ProgressTemplate>
<div style="position: relative; top: 35%; text-align: center;">
<img src="loading.gif" style="vertical-align: middle" 
alt="Processing" />
<asp:Label ID="lblProcessing" runat="server" 
Text="Processing"></asp:Label>
</div>
</ProgressTemplate>
</asp:UpdateProgress>
</asp:Panel>
<ajaxToolkit:ModalPopupExtender ID="ModalProgress" runat="server" 
TargetControlID="panelUpdateProgress"
BackgroundCssClass="Background" PopupControlID="panelUpdateProgress" />
<asp:UpdatePanel ID="updatePanel" runat="server">
<ContentTemplate>
<asp:Button runat="server" Text="Get Orders" ID="btnOrder"
OnClick="btnOrder_Click" Width="100px" />
<asp:Button runat="server" Text="Get Customers" ID="btnCustomer" 
OnClick="btnCustomer_Click" Width="100px" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class MainPage : System.Web.UI.Page
{
protected void btnOrder_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(4000);
}
protected void btnCustomer_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(4000);
}
}
style.css:
.Background
{
background-color:Silver;
filter: alpha(opacity=50);
opacity: 0.50;
}
.ProgressPanel
{
border-width: 1px;
border-style: solid;
background-color: #FFFFFF;
position: absolute;
width: 180px;
height: 60px;
}
Modal popup window in action:

This post will never replace a book on Ajax but I hope it has made you aware that Ajax is also a very powerful client library that allows you to create even richer Web applications and hopefully this post has encouraged you to start using it and also to thrive to be a better developer, and if you're taking an exam, to get a better score.

70-562 - Asynchronous Pages

Filed under: , , , , by:

Asynchronous pages in ASP.NET have been in ASP.NET since version 2.0, but I have noticed that very few developers take advantage of it. Now we have version 3.5 and soon 4.0 but still a lot of production ASP.NET applications don't use "async" pages. So due to that fact and the fact that 70-562 exam covers using asynchronous pages I decided to show how easy it is and encourage developers to learn it and use it.
To use async pages, one must add <%@ Page Async="true" %>. Then we add in Page.Load event either:

Page.AddOnPreRenderCompleteAsync(new BeginEventHandler(BeginMethod), 
new EndEventHandler(EndMethod));
or
Page.RegisterAsyncTask(new PageAsyncTask(new BeginEventHandler(BeginMethod),
new EndEventHandler(EndMethod),
new EndEventHandler(TimoutMethod),SomeArgumentToPass, true));
The first method can only register only 1 async task whereas the second one can register many async tasks and allows adding a timeout method. As one can see, it is not a rocket science, however a developer must know how to create asynchronous methods (BeginMethod and EndMethod) rather than synchronous methods (Method). As an example I created a simple page with a custom web control that reads rss weather feed from yahoo. In this control there are 4 methods: BeginFeed, EndFeed, TimeoutFeed and GetFeed (to test synchronous vs asynchronous). To read and parse rss feed I used System.Xml.Linq.XDocument object, even though since version 3.0 there is System.ServiceModel.Syndication.SyndicationFeed class that allows to read rss feeds - however that class doesn't expose asynchronous methods to load rss feed and in order to consume yahoo weather rss feed with that class, the Rss20FeedFormatter formatter would be necessary because of date / time format problems. Therefore, I used XDocument that fully meets our needs.
[ToolboxData("<{0}:WeatherWatcher runat=server></{0}:WeatherWatcher>")]
public class WeatherWatcher:WebControl 
{
private WebRequest _request;
private String _desc;
private String _name;
 
public IAsyncResult BeginFeed(object sender, EventArgs e, 
AsyncCallback cb,object state)
{
_request = WebRequest.Create(@"http://weather.yahooapis.com/forecastrss?p="+state.ToString());
return _request.BeginGetResponse(cb, state);
}
 
public void EndFeed(IAsyncResult ar)
{
using (WebResponse response = _request.EndGetResponse(ar))
{
using (StreamReader reader =
new StreamReader(response.GetResponseStream()))
{
XDocument doc = XDocument.Load(reader);
_name = doc.Element("rss").Element("channel").Element("item").Element("title").Value; 
_name=_name.Remove(_name.IndexOf("at"));
_desc = doc.Element("rss").Element("channel").Element("item").Element("description").Value;
_desc = _desc.Remove(_desc.IndexOf("<a"));
}
}
}
 
public void TimoutFeed(IAsyncResult ar)
{
_request.Abort();
_request = null;
_name = "";
_desc = "Couldn't retrieve weather information";
}
 
public void GetFeed(string zipcode)
{
XDocument doc = XDocument.Load(@"http://weather.yahooapis.com/forecastrss?p="+zipcode);
_name = doc.Element("rss").Element("channel").Element("item").Element("title").Value;
_name = _name.Remove(_name.IndexOf("at"));
_desc = doc.Element("rss").Element("channel").Element("item").Element("description").Value;
_desc = _desc.Remove(_desc.IndexOf("<a"));
}
 
protected override void RenderContents(HtmlTextWriter writer)
{
writer.RenderBeginTag(HtmlTextWriterTag.Center);
writer.RenderBeginTag(HtmlTextWriterTag.B);
writer.Write(_name ?? "Place name unavailable");
writer.RenderEndTag();
writer.RenderEndTag();
writer.Write(_desc ?? "Weather info  unavailable");
base.RenderContents(writer);
}
}
Now the page that will use our control. I have put it twice and each of them will show weather for different zip codes (Minneapolis and St. Paul) - Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AsynPageTest.MainPage" Async="true" Theme="Theme" %>
<%@ Register assembly="WebControls" namespace="AsynPageTest" tagprefix="ww" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Weather Watcher</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<ww:WeatherWatcher ID="WeatherWatcher1" runat="server" />
<ww:WeatherWatcher ID="WeatherWatcher2" runat="server" />
</div>
</form>
</body>
</html>
Now the code-behind - Default.aspx.cs. It will contain 3 Page_Load only to demonstrate how to use all 3 ways to get feeds.
1. AddPreRenderCompleteAsync method
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace AsynPageTest
{
public partial class MainPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Page.AddOnPreRenderCompleteAsync(
new BeginEventHandler(WeatherWatcher1.BeginFeed), 
new EndEventHandler(WeatherWatcher1.EndFeed),"55401");
Page.AddOnPreRenderCompleteAsync(
new BeginEventHandler(WeatherWatcher2.BeginFeed), 
new EndEventHandler(WeatherWatcher2.EndFeed), "55101");
}
}
}
}
2. GetFeed - synchronous method
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
WeatherWatcher1.GetFeed("55401");
WeatherWatcher2.GetFeed("55101");
}
}
3. RegisterAsyncTask
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Page.RegisterAsyncTask(new PageAsyncTask(
new BeginEventHandler(WeatherWatcher1.BeginFeed),
new EndEventHandler(WeatherWatcher1.EndFeed),
new EndEventHandler(WeatherWatcher1.TimoutFeed),
"55401", true));
Page.RegisterAsyncTask(new PageAsyncTask(
new BeginEventHandler(WeatherWatcher2.BeginFeed),
new EndEventHandler(WeatherWatcher2.EndFeed),
new EndEventHandler(WeatherWatcher2.TimoutFeed),
"55101", true));
}
}
Here is the screenshot of the page displaying our weather info.

I have also created a simple multithread test application (although I could've used WCAT - Web Capacity Analysis Tool) that was calling my pages using System.Net.WebClient class. However, before I started testing the performance I had to add a few more ASP.NET pages to our Web Application. The reason for that is that an asynchronous page does not load faster so testing 1 page would generate the same results whether we are using async or not. However, when using synchronous calls a thread from application pool is not released until it finishes processing a page (even if it has to wait for web service or database call or in our example a response with weather info), whereas asynchronous pages release processing thread to application pool for the time of waiting so that thread could be used to process other request in the meantime, which for multi pages applications it can mean a lot. My test showed that for 800 calls with ratio 1:9 (1 calling our async page and 9 calling other pages) there was 1 second difference within 5 second test between a synchronous page and an asynchronous page, and that's like 20% better performance. One more note: AddOnPreRenderCompleteAsync method can be used more than once but registered tasks using that method will be executed one after one, so only RegisterAsyncTask method can register more than 1 task to be executed in parallel.
I hope this will encourage developers to use asynchronous pages more often and help all studying to 70-562 exam to review information on asynchronous pages. Of course with advent of Ajax now developers can build pages that all long-running tasks can be executed during asynchronous postbacks without posting back the whole page. Nevertheless, I think that a professional developer should know more than 1 way of getting to a solution so he can propose the best one under the given circumstances, and in my opinion that's what makes a developer professional - not only being able to solve a problem but being able to solve it using the best solution.

70-562 exam

Filed under: , , , , , by:

The next couple posts will be about Microsoft exam for MCTS ASP.NET 3.5 Developer as that's the exam I'm currently studying to. In this post I will write about other people's experience with the exam, and what and how I'm studying to this exam, but in my next posts I will try to present some of the topics covered by the exam and I will try to compare that with my working experience with .NET Web Development.
This exam will be my 8th Microsoft exam and I have already passed MCTS and MCPD ASP.NET 2.0 so there isn't much new stuff for me that I would have to study or practice. Nevertheless before every exam I always try to find what people who already have taken the exam say about it and what are their opinions. I usually look for information what books are good to study, a list of objectives with links to MSDN, etc. I have gathered links to few blogs and forums where people express their experience with the exam:
Want to pass
Passed
Passed my first exam
70-562 my experience
Good tips
But I always like websites, like below, that have exam study guide with all exam objectives as links to MSDN library so if you need to learn about specific topic, check some examples or validate if what you know about the given topic is enough, there is no better way than going to MSDN library and reading information on that topic(although sometimes some books can convey the knowledge about a topic in the form that will be easier to understand or will include more examples):
Part 1
Part 2
Part 3
Part 4
Part 5
Part 6
Part 7
If you look at those topics, you'll see how much information is covered by the exam. Fortunately, if you have a working experience and if you have taken previous ASP.NET exams, you will see that it's not really that much to learn.
My strategy to this exam is to read those books:
Professional ASP.NET 3.5
Introducing Ajax
Professional Linq
ASP.NET 2.0 -Advanced Topics
ASP.NET 2.0 - Core Reference
ADO.NET 2.0 - Core Reference
Programming WCF
Learning WCF - Hands-on Guide
It's a lot of books but some of them I got when studying for 70-528, 70-547 and 70-503 exams. I also usually get Microsoft Self-Paced Training Kit books but this time because I have so many other books, it would not yield high benefits. I might have done it if I didn't have 20% off voucher (each book comes with 15% off voucher). Personally, I prefer reading books rather than searching through MSDN but if I had to study to this exam without the books I bought for previous exams, I would probably buy Programming ASP.NET 3.5 and study all objectives from Part 1 to Part 7. I haven't done it yet as I'm still reading my books (I usually read them 10 times to make sure I remember and understand all the topcis from the book) but before the exam I will definitely look up a few topics to make sure I haven't missed anything.
As I mentioned, in my next few posts I will share some things from my working experience with ASP.NET, Ajax and WCF that should be helpful to other developers and those who want to take the exam. Precisely, some of those things will come from the tips that people who have taken the exam shared, some of those things will include information that I have learned at work and I have not found in any of the books I have mentioned, and some of the things will include material that are in those books but not many developers know about or use. I hope everyone will find it interesting and useful whether you are studying to the exam or you were just born to thrive to be a better .NET Web developer.