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
When I was studying for my 70-503 exam (MCTS WCF 3.5), I only used 2 books plus MSDN of course. Those books were: Programming WCF Services and Learning WCF: A Hands-on Guide. They are great books and a great resource when preparing to either 70-503 exam or 70-562. However, when I was watching some webcasts and reading MSDN, I found out that there were a few important WCF concepts that they did't mention, and one of them was Syndication Feed. Therefore, this post will demonstrate that creating syndication feed in .NET doesn't have to cumbersome if one knows how to use WCF.
Visual Studio 2008 has a template "Syndication Service Library" in WCF project type.
Even though there is no ServiceHost, the project can be run as it will be hosted by WcfSvcHost. Of course for production purpose a hosting application will have to be created, which most of the time will be a WCF Service Application. Below is an example of WCF service that uses Syndication Library to create a web site with RSS feeds that show tiles of movies along with director name and release date, which information is retrieved from XML file "movie.xml" (which has been added to Resources.rex file).
Project: WcfSyndication
File: IMovieFeed.cs
namespace MovieLibrary
{[ServiceContract(Namespace="MoviesFeed.org")]
[ServiceKnownType(typeof(Atom10FeedFormatter))]
[ServiceKnownType(typeof(Rss20FeedFormatter))]
public interface IMovieFeed
{[OperationContract]
[WebGet(UriTemplate = "*", BodyStyle = WebMessageBodyStyle.Bare)]
SyndicationFeedFormatter CreateFeed();
}
}
namespace MovieLibrary
{public class MovieFeed : IMovieFeed
{public SyndicationFeedFormatter CreateFeed()
{SyndicationFeed feed = new SyndicationFeed("Movie Feed", "A WCF Syndication Feed with Movies", null);var items = from element in XDocument.Parse(Resource.movies).Root.Descendants("Movie")select new SyndicationItem(
element.Element("Title").Value,"Director: " + element.Element("Director").Value + " Realse date: " + element.Element("ReleaseDate").Value,null);
feed.Items = items;
string query = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["format"];
SyndicationFeedFormatter formatter = null;
if (query == "atom")
{formatter = new Atom10FeedFormatter(feed);
}
else
{formatter = new Rss20FeedFormatter(feed);
}
return formatter;
}
}
}
<?xml version="1.0" encoding="utf-8" ?>
<Movies>
<Movie>
<Title>Shrek</Title>
<Director>Andrew Adamson</Director>
<Genre>0</Genre>
<ReleaseDate>5/16/2001</ReleaseDate>
<RunTime>89</RunTime>
</Movie>
<Movie>
<Title>Fletch</Title>
<Director>Michael Ritchie</Director>
<Genre>0</Genre>
<ReleaseDate>5/31/1985</ReleaseDate>
<RunTime>96</RunTime>
</Movie>
</Movies>
File: Service.svc
<%@ ServiceHost Language="C#" Service="MovieLibrary.MovieFeed" %>
<system.serviceModel>
<bindings />
<services>
<service name="MovieLibrary.MovieFeed" behaviorConfiguration="ServiceBehavior">
<endpoint address="" behaviorConfiguration="SyndicationLibrary.MovieFeedBehavior"
binding="webHttpBinding" contract="MovieLibrary.IMovieFeed" />
<endpoint address="mex" contract="IMetadataExchange" binding="mexHttpBinding"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:2500/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="SyndicationLibrary.MovieFeedBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Here are a few important and hopefully interesting aspects of this project, which I couldn't find in the aforementioned books.
- returned feed is of type SyndicationFeedFormatter (base class for Rss20FeedFormatter and AtomFeedFormatter) rather than XML
- operation contract method of the service has WebGet attribute which means that a method can be called by Web programming model - Http Get verb and response will be XML and JSON rather than SOAP - this model is also called REST or RESTful and service is called a REST service
- in order to work a WebGet attribute requires WebHttpBehavior ( in this example by adding <webHttp/> to EndpointBehaviors in a config file) and WebHtppBinding
- Operation method is using WebGet attribute that specifies UriTemplate, which defines how a REST service can be called from a Web Browser - in our example any path, where regular WCF service would return information of missing endpoint for address other than specified by endpoints
- If we specify the given query "?format=atom" in path, a response will be in Atom format, where without the specified format it is RSS
- Self-hosting this service would require WebServiceHost and/or WebServiceHostFactory classes
- Accessing REST service on clients would require WebChannelFactory<IMovieFeed>
When it comes to WCF, from my experience I know that for the great majority of .NET developers WCF is just an acronym and definitely not a framework of their choice when building distributed application. But ASP.NET 3.5 specialist must know how to use WCF services. On my road to MCPD Enterprise Developer I had to take 70-503 exam, which covers WCF 3.5, therefore for me WCF part on ASP.NET 3.5 exam shouldn't be a problem, but I know that for some of developers that consider taking 70-562 exam that might be another obstacle. That's why I thought of creating this post that will give a short overview of WCF. I hope this will help anyone studying to the exam and anyone who wants to thrive as a .NET developer.
WCF stands for Windows Communication Framework and was created to unify all Microsoft Distributed Computing Technologies (Web Services, .NET Remoting, Enterprise Services, WSE, Microsoft Queueing). Before one had to learn 5 different technologies, whereas with WCF one learns one concept that is the same for all those technologies. This basic concept of WCF is a three-step process:
- You define a contract and implement it on a service
- You choose or define a service binding that selects a transport along with quality of service, security and other options
- You deploy an endpoint for the contract by binding it (using the binding definition, hence the name) to a network address
That's ABC (Address, Binding, Contract) of WCF. Address is a physical address where the service can be reached along with specifying transport protocol, Binding describes transport and message protocol, Contract describes class being exposed as a service. These are common for all remoting technologies. Based on specified binding and address a technology to use is determined.
Examples:
- Addresses: net.tcp://localhost:9000, http://localhost:8000, net.msmq://localhost
- Bindings: NetTcpBinding (connections across process and machine over TCP), BasicHttpBinding (support for ASMX web services), NetMsmqBinding (reliable messaging over MSMQ)
So if you use NetMsmqBinding with address net.msmq://localhost, you utilize Message Queue as before using System.Messaging.MessageQueue.
Contracts are the classes or interfaces that expose distributed methods. They require ServiceContract attribute. Methods require OperationContract attribute. Transfer objects (like custom classes returned by methods) require Serializable or in WCF DataConctract attribute, and within those objects all properties and fields require DataMemeber attribute.
Hosting a service:
- If you create ie. a WCF service library and run it, a WCF Service Host (WcfSvcHost.exe) will be launched and it will host the service
- Self-hosting the service in console application, Windows Forms or Windows Service by using System.ServiceModel.ServiceHost class
- In IIS or WAS Windows Activation Service) when you create WCF Service Application, which creates Service.svc. When you click on it and click "View Markup", you will see that it has something like that: <%@ ServiceHost Language="C#" Service="WCFService.Service" %>, which instructs to luanch ServiceHost and host specified service
Consuming a service:
- By WCF Test Client (WcfTestClient.exe) - a GUI tool that enables to test a service, invoke exposed methods and view responses sent by the service
- By proxy class generated after adding a service through Add Service Reference.
- By proxy class generated after running SvcUtil.exe utility. This tool has many options that allow to customize the way a proxy is generated ie. without generating config file or to generate also asynchronous methods
- By creating a class that inherits from System.ServiceModel.ClientBase
- By using ChannelFactory<TChannel> class, which has a method CreateChannel that returns TChannel. Usually, TChannel is an interface or a class that is defined by ServiceContract attribute.
- By adding a service reference with path to the service to ScriptManager object in order to utilize it from Ajax
So there's a lot of ways in which a service can be hosted and also consumed but in order to do that, it has to be properly configured. Most of the times it will be a proper configuration in web.config or app.config file. If you self-host a service or consume a service via ChannelFactory, you can instantiate and configure an EndpointAddress object along with approperiate binding ie. BasicHttpBinding. You can also create your own ServiceHostFactory and hard-code configuration in order not to read from a configuration file, but the good practise is to have a configuration of your service in a configuration file within <system.serviceModel> configuration section. This process can be done by:
- altering an existing configuartion ie. created when creating WCF service from template
- writing from scratch
- using Configuration Editor Tool (SvcConfigEditor.exe) that is available when you select config file and choose from context menu "Edit WCF Configuration".
Here are a few screenshots that demonstrate different ways of hosting a service, consuming it and configuring it. The screenshots will come from examples that I will use to explain syndication feed available in WCF and how to consume WCF services in Ajax/javascript using JSON. I hope you've found this post useful and helpful when it comes to understanding different ways of hosting, consuming (calling) and configuring WCF services. I can't emphasize how much it is important sometimes to know more than 1 way of getting to the solution so you can choose the best one, and sometimes only other way will be the only one you'll be able to use. I hope this post has taught you what are different ways of hosting, consuming and configuring a WCF service. We will need those skills to create and call 2 WCF services that I'll create in the next two posts.

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';
elseif (el.name=="btnCancel" && isPostBack )
$get("lblStatus").innerText='Your request has been cancelled';
}
}
</script>
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...';
elseif (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>
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);
}
}
.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;
}
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.
Page.AddOnPreRenderCompleteAsync(new BeginEventHandler(BeginMethod), new EndEventHandler(EndMethod));
Page.RegisterAsyncTask(new PageAsyncTask(new BeginEventHandler(BeginMethod),
new EndEventHandler(EndMethod),new EndEventHandler(TimoutMethod),SomeArgumentToPass, true));
[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);}
}
<%@ 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>
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");
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{if (!Page.IsPostBack){WeatherWatcher1.GetFeed("55401");WeatherWatcher2.GetFeed("55101");}
}
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));
}
}
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.
















