BUY THIS BOOK
Add to Cart

Print Book $44.99


Add to Cart

PDF $35.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £27.99

What is this?

Looking to Reprint or License this content?


Building a Web 2.0 Portal with ASP.NET 3.5
Building a Web 2.0 Portal with ASP.NET 3.5

By Omar Al Zabir
Book Price: $44.99 USD
£27.99 GBP
PDF Price: $35.99

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introducing Web Portals and Dropthings.com
In this book, I will show you how to develop an Ajax-enabled Web 2.0-style portal.
The portal is built using ASP.NET 3.5, ASP.NET AJAX, and .NET 3.5, as well as Language-Integrated Query (LINQ) and SQL Server 2005. While building this application, you'll learn about the:
  • Design decisions that must be made for and usability issues involved in a Web 2.0 user interface
  • Architectural complexities and development challenges of JavaScript-rich, widgetenabled web sites
  • Production and maintenance challenges of running a high-volume web application
Ajax web portals are among the most extreme implementations of client-side technologies you'll find on the Web. They not only use large amounts of JavaScript, CSS, and HTML, but also push the Ajax and server-side technologies to their limits for interactivity, performance, and scalability. By the time you finish reading this book, you will be equipped with enough technical know-how to launch a Web 2.0 Internet startup on your own.
The application example, which I have named Dropthings, for reasons that will become clear shortly, is a reduced feature set prototype of a real web portal, like Google's iGoogle or Pageflakes. You will be able to deploy the Dropthings on a production server and run it as your own personal web site, a group site, or even as a corporate intranet. Including drag-and-drop enabled widgets, complete support for personalization, the ability to place widgets on multiple pages, centralized authentication and authorization, and much more.
As you work through this book, you will see how Dropthings is architected and implemented. It's a real, living, breathing, open source web portal that you'll find at http://www.dropthings.com. Although the application does not compare to a real web portal in terms of its code quality, feature set, scalability, performance, and other aspects of the product, it works as a good proof of concept for several nascent technologies.
However, you can use it for your current day-to-day personal use, and you are welcome to support continued development of the project by adding more features to it or by making cool new widgets for it.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Defining a Web Portal
A web portal is a page that allows a user to customize his homepage by dragging and dropping widgets onto it. This approach gives the user complete control over what content he sees on his home page, where on the page he wants to see it, and how he wants to interact with it.
A widget is a discrete piece on a web page that performs a particular function and comes with its own UI and set of features. Examples of widgets include to-do lists, address books, contact lists, RSS feeds, clocks, calendars, playlists, stock tickers, weather reports, traffic reports, dictionaries, games, or almost anything you can imagine that can be packaged up and dropped onto a web page. In a corporate environment, widgets can connect to internal systems; for example, an expense tracker widget can interact directly with the internal accounting system. If you are familiar with the SharePoint Portal, then you already know about widgets, which are called Web Parts in SharePoint and ASP.NET 2.0.
Specifically, an Ajax-powered web portal is a web portal that uses Ajax technologies to create richer experiences for its users. It is one step ahead of the previous generation of web portals, including pioneer sites such as MSN or AOL, because it gives you a state-of-the-art UI that behaves more like a Windows client application with widgets, animations, pop ups, client-side data grids, and other effects not usually found on a non-Ajax web portal. Not surprisingly, MSN and AOL have already adopted many of the practices discussed in this book.
Some of the most popular Ajax web portals include iGoogle (www.google.com/ig), My Yahoo (http://my.yahoo.com), and Pageflakes (www.pageflakes.com; see ).
Figure : Pageflakes uses widgets to deliver functionality, including local weather, local news, videos, local photos, podcasts, stock portfolio, local events with Google Maps, and more
A web portal, especially one that is Ajax-powered, gives users a fun way to browse the Internet. Users can add photos, videos, music, podcasts, and video blogs to their Start page. The web portal can also help users become more productive by allowing them to check email, read news, and get weather reports from a single page. They can organize their digital life by putting appointment calendars, to-do-lists, and address books in a central place on the Web. No matter where they happen to be—in the office, home or airport—as long as they can get to the Web, users can access this information directly from their web portal. It's like bringing the whole Internet onto a single page, displayed exactly the way you want it to be. Gone are the days of running after content—now information and entertainment comes to you.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Defining a Web 2.0 Portal
The term "Web 2.0" defines a set of principles and practices for web applications, which, when followed, entitle a web application to wear the Web 2.0 crown. A web site can claim to be a Web 2.0 site if it:
  • Allows users to control data presented on the web site
  • Presents a platform that enables the mixing (or mash-up) of technologies and data
  • Enables services to be consumed that are beyond the boundary of the application
  • Harnesses collective intelligence by enabling the following:
    — Aggregation of relevant content from heterogeneous sources
    — User contributed content
    — User moderation of content via tagging and rating
  • Uses state-of-the-art technologies that take interactivity on the Web to the next level by use of popular technologies like Ajax, Flash, and Silverlight.
Dropthings, being a web portal, allows a user to control what the user wants to put on the page. The widget architecture allows mashup of technologies in the form of widgets. It exposes web services that external entities can consume. The portal aggregates content from many different sources, such as photos from Flickr, news from CNN, weather reports from Weather.com, and many more. It supports usersubmitted content aggregation in the form of RSS feeds. Finally, it pushes interactivity on the Web to the next level by using Ajax technologies.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using a Web Portal
With a web portal, every visitor to your web site will be able to customize and set it up exactly the way they would like to see it the next time they visit. Best of all, the layout is saved per user, so your master layout remains unchanged. Moreover, visitors can add more widgets from a widget catalog and decorate the page as they like.
The advantages of Ajax and a rich client-side experience give users a fun and exciting environment to do their regular work. All the functionality is developed as small widgets that perform only a specific job, like showing messages from an Exchange Mail server, assigning tasks from a SharePoint List, or even displaying your expenses from an internal accounting system. Just as with a regular web portal, enterprise users can drag the widgets around and put them anywhere they like. For example, an email inbox can be put on the left, expenses in the middle, and a list of "Phone calls to make" on the right. A key advantage is that these widgets can provide content from different web servers on different platforms, including Linux, Unix, or IBM OS/2 servers. As long as the platform speaks XML and HTTP, any functionality can be provided in the form of a widget. The main framework takes care of authentication, authorization, user profile, communication, and all those cool Ajax effects. As a result, the widgets are a lightweight component with a small amount of code to do exactly what they are supposed to.
An Ajax web portal is also quite useful for group portals or social web sites. For example, say you want to make a .NET developer group portal. You would start with a blank page, add lots of .NET feeds, put a link widget and fill it with useful .NET web site links, add an address book widget and fill in useful contacts, put in a calendar widget to publish events for the group, and so on. With just these basic widgets and some rearranging, you have a dynamic, personalizable developer group portal that is state of the art in both technology and usability.
Enterprise portals especially can benefit from using Ajax web portals. Enterprise portals bring in content from many sources and different platforms. By using an Ajax widget platform, you can make the whole portal in terms of small widgets that connect to different systems and serve content to the page. The benefit of such a platform is that the complexity of the entire portal is dramatically reduced because it's just a generic widget platform.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Navigating Dropthings
When you first visit Dropthings, which I encourage you to do now, you get a predefined default setup of widgets that you can customize anyway you like. For example, there's a Flickr photo widget, some RSS feeds, and several community contributed widgets for weather, news, and so on (see ).
Figure : Your initial visit to Dropthings gives you a predefined template that can be customized
On the Dropthings Start page, you can add widgets, remove widgets that you don't like, and customize individual widgets by clicking on the "edit" link on each title bar. Clicking on the "edit" link brings up the "Settings" area for the widget where you can change its look, feel, and behavior (see ).
Figure : The photo widget allows you to change the photo stream by clicking on "edit" link on the title bar of widget
You can also drag-and-drop widgets from one column to another and reorganize the page as you like. When you come back to the page, your customization is preserved even if you did not sign up. However, when you sign up, your pages are saved permanently and you can access them from anywhere (see ).
It is possible to have more than one tab (page) of widgets. There's already a precreated empty second tab where you can add new widgets. So from there, you can add as many tabs as you like. This helps you keep your tabs clean and light and groups relevant widgets in the same location.
Clicking on the "Add stuff" link on the top right of the web page brings up a pop-up widget gallery that shows the list of available widgets (see ). From the list, you can click anywhere on the widget and have it added to your page. After adding it, you can further customize it by clicking on the "edit" link on the widget's title bar.
Figure : You can drag and drop widgets on the page and reorganize the page as you like
Figure : Create a "Photo" tab and add a Flickr photo widget to it with Add Stuff; each photo widget shows a specific photo stream from Flickr as defined by the widget's settings
At the top part of the page, there's a bar where you can search the Internet. Search is the most used function on the Web. Therefore, web portals need to have convenient search functionality; otherwise users won't set a web portal as browser homepage. The
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using ASP.NET AJAX
The web portal you'll learn how to build is an N-tier application with a user interface (UI) layer, a business layer, and a data access layer. You'll use ASP.NET AJAX to implement the UI layer of the web portal application, which includes the homepage and the widget's UI. ASP.NET AJAX provides the framework (via UpdatePanel) for updating widgets without doing any postbacks, and it changes page layout by dragging and dropping widgets on the page. It also offers a rich collection of Control Extenders that add cool effects like fade in/fade out, smooth transitions, and client-side animations. You can add to the rich client-side experience by providing autocompletion behavior on text boxes, asynchronous data loading via web service calls, client-side paging, sorting, and much more.
The ASP.NET AJAX runtime provides a framework you can use to make XML HTTP calls from within the widgets. It also provides the framework for building client-side effects using Custom Extenders. The drag-and-drop behavior of widgets on the page is built as an Extender. You'll also reuse some extenders from the Ajax Control Toolkit (ACT) to enrich the client user experience within the widgets.
ASP.NET AJAX exposes a handy API that you can use to authenticate against the ASP.NET Membership application service. A good thing about the ASP.NET Membership API is that it's fully compatible with ASP.NET AJAX and providers for Membership, Profile properties, and so on; they all work exactly the same way as a regular ASP.NET web site. This means you can make client-side login and signup forms, and change user preferences without requiring any postback.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using C# 3.0 and .NET 3.5
Dropthing's business layer is built with the Windows Workflow Foundation (WF), which was introduced in .NET 3.0. Major operations like a first-time user visit, a subsequent user visit, adding a new widget, and creating a new page are all orchestrated using workflow. The workflows contain all the business rules and activities needed to complete each operation. For example, the New User Visit workflow creates the user account, populates the user profile with default values, creates some default pages, populates them with specific widgets, etc. Such compound operations are very easy to build with workflows, which enable you to break the complete operation into smaller chunks called Activities. Each Activity does a very small amount of work. It talks to the data access layer and performs the task. The data access layer is built with .NET 3.5, using LINQ to SQL, which vastly simplifies the querying of databases from within your application code.
The web project and the widgets make good use of .NET 3.5 by using new functionality for lambda expressions, LINQ to SQL, and LINQ to XML. You will use LINQ queries to work with collections and database rows. Widgets make good use of LINQ to XML to consume XML from external data sources.
The application is built following a typical N-tier architecture where there's a clear separation between the UI, business logic, and data (see ). For example:
Web layer
Consists of web pages, web services, resources (e.g., graphics, CSS, JavaScript, and .resx files), and configuration settings.
Business layer
Provides the entity classes, business rules, and middle-tier caching of data to reduce database roundtrips.
Data access layer
Encapsulates database access and provides an interface that is database and data source independent. It also provides object factories that create Entity classes out of database rows and vice versa.
In , the technologies are mapped to each layer.
Figure : Mapping technologies to the different layers
The web portal application in this book makes use of some of the newest .NET 3.0 and .NET 3.5 technologies. The web layer uses ASP.NET AJAX for a rich user experience, and the business layer uses the new WF to orchestrate complex operations. All three layers use LINQ to work with data structures.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
Ajax web portals push Ajax technologies to their limits. Microsoft's ASP.NET AJAX offers a rich set of Ajax components and a robust cross-browser compatible framework to harness the full power of Ajax in web portals. The new features in .NET 3.0 and 3.5 Frameworks empower architects and developers with features like Workflow Foundation, LINQ to SQL, and LINQ to XML. This chapter, provided a brief overview of what an Ajax web portal can do and what technologies are involved in making such a project. The next chapter will discuss the architectural challenges, performance issues, and security threats that make architecting a web portal more challenging than typical web applications.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Architecting the Web Portal and Widgets
Because it strives to deliver its functionality on a single page, an Ajax web portal that lives up to its promise is invariably a masterpiece of Ajax technology. It is a great architectural challenge to provide so much on one page without compromising the performance of either the server or client. Some of the unique challenges seen only in web portals include incorporating many features into one web application and aggregating content from every kind of web site.
This chapter explains the architecture of the Dropthings portal, which you can also use to design one of your own. We'll examine a number of architectural challenges, including how to run many widgets on one page, load a web portal quickly, and deal with security threats such as denial-of-service (DoS) attacks, attempts to compromise user data, and more.
The heart of any web portal is its support for widgets, which is the mechanism by which users can customize their start pages and the means by which providers can make their services available, whether a department inside a company or a third-party, like Reuters.
In an ASP.NET implementation like the one we use in this book, Default.aspx is the homepage that displays the widgets and allows them to be added, removed, moved, customized, and run within the page without ever causing a page refresh or postback.
The application remembers a user's actions and customizations so that on her next visit she sees the exact same widgets she saw when she left, with her customizations preserved. Web portals typically allow anonymous users to use many of their features, including adding widgets, editing, deleting, and creating multiple pages, and changing preferences, without registering.
ADropthings widget is basically an ASP.NET web control. It can be a user control or a server control, but works just like a regular web control participating in the ASP. NET page life cycle. Widgets support postbacks, the ViewState, sessions, and caches. The only difference is that a Dropthings widget must implement IWidget—a custom interface—to integrate with the widget framework and use the services provided by the core framework we use for the application. A custom-built Ajax control extender provides the drag-and-drop feature for the widgets. The widget frame-work and its core are explained later in this chapter (see the "Using a Widget Framework" section).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Object Model
The ASP.NET membership provider contributes the user and roles. If the user has one or more pages, each page can contain one or more widget instances. The difference between a widget and widget instance is that a widget is like a class, whereas a widget instance is an instance of that class. For example, the Flickr photo widget is a widget that loads photos from Flickr. When a user adds the Flickr photo widget to the page, it becomes an instance of the Flickr widget. Although the term widgetis used throughout this book, it will actually means an instance of a widget.
shows the entire object model.
Figure : The web portal object model consists of a User, its settings (UserSetting), and associated pages (Pages). A Page can contain Widget instances, each of which is an instance of Widget.
The object model starts with the user, which can have some settings and one or more pages. Each page contains zero or more widget instances.
Dropthings uses the Facade pattern to provide a single entry point to the business layer. It provides access to internal subsystems, which deal with users, pages, widgets, etc. The façade is named DashboardFacade (see ).
Figure : Default.aspx calls DashboardFacade in the business layer for all operations, which, in turn, uses workflows that work with databases via DatabaseHelper and DatabaseContext
On the web layer, Default.aspx is the entry point. It uses DashboardFacade to perform operations such as adding a new tab or widget, or storing a widget state. DashboardFacade invokes different workflows for different operations. The workflows do the real work and are developed using Windows Workflow Foundation (WF), as explained in . Each workflow consists of one or more activities. Each activity is like a class that performs some unit task. Activities use the DatabaseHelper and DashboardDataContext classes to work with the database. DatabaseHelper is a class used for performing common database operations. DashboardDataContext is generated by LINQ to SQL and maps entities to database tables.
To implement the data model used by the application, we use the ASP.NET membership provider's default database tables—the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using a Widget Framework
Dropthings makes use of a widget framework that allows you to focus on providing features that are relevant to the widget itself without worrying about authentication, authorization, profile, personalization, or storage. Widgets get these functions from the widget framework, or the core, shown in .
Figure : Widgets are automatically authenticated, authorized, profiled, and personalized, and they receive storage and utility libraries from the host, which allows you to easily add more functionality to the web portal in the form of widgets. The core coordinates these services.
Moreover, you can build widgets independently of the host project. You don't need the whole web portal's web application source code in your local development computer to build widgets. All you have to do is create a regular ASP.NET 2.0 web site, create a user control, make it do what it's supposed to do in a regular postback model (don't worry about JavaScript), implement a little interface, and you are done!
You don't have to worry about Ajax and JavaScript with the widget framework I have created for Dropthings. The architecture allows you to use regular ASP.NET 2.0 controls, Ajax Control Toolkit controls (http://www.asp.net/ajax/ajaxcontroltoolkit/samples), and any extender in ASP.NET AJAX. Full server-side programming support is also included, and you can use .NET 2.0, 3.0, or 3.5, as well as regular ViewState and store temporary states. ASP.NET Cache can be used to cache widget data. This approach is far better than what you would find in any current web portal where you have to build the whole widget using only JavaScript, abide by specific API guidelines, and follow a strict "no postback" model (see ).
In the Dropthings widget framework, the core does authentication and authorization using the ASP.NET membership provider. This allows the widgets to get the current user's profile when loading. The core also provides widgets with a data storage service to persist their states, as well as the user's actions, such as expanding or collapsing a widget, moving, or deleting. The communication between the widget and the core is done via a
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Adding Widgets
A widget is made up of settings and body parts. The body part is always shown as long as the widget is not minimized. The settings part is only shown when user clicks the "edit" link on the widget header. The settings part stores customization options for the widget. For example, with a Flickr photo widget, settings could include allow the user to choose what type of photos to show, to enter tags, or to enter a user ID. The settings area hides customization options from the UI until the user wants them, but there can be as many choices as you like. The settings part can be made using a regular ASP.NET Panel that contains all the elements for the customization area. By default, the Panel is invisible, but the widget makes it visible when it is notified that a user has clicked the "edit" link.
As noted earlier, widgets are created as ordinary web server controls. To integrate widget functionality, implement the IWidget interface, which defines how the widget container communicates with the widget (see ).
Example 2-2. IWidget interface
public interface IWidget
{
    void Init(IWidgetHost host);
    void ShowSettings();
    void HideSettings();
    void Minimized();
    void Maximized();
    void Closed();
}
The IWidget interface defines a way to inform the widget when to initialize the widget area and restore its state. When a user clicks the "edit" link, ShowSettings informs the widget to show the settings area. When a user clicks the maximize or minimize links (the plus or minus icons), Maximized and Minimized functions are called. The same happens when a user closes the widget—Closed is called and the widget cleanups any information stored in database. These are all post-event callback methods—actions the user has already performed and the widget reacts to.
Widgets are regular ASP.NET web controls with IWidget—a simple interface implementation.
Widgets get references to an interface implementation named IWidgetHost via the IWidget.Init method. This interface exposes methods to communicate with the container as well as the services provided by the container. IWidgetHost
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Maximizing the First-Visit Experience
The most challenging part of a web portal is the first-visit experience. On first visit, a new user gets a page that is set up with predefined widgets that are ready for further customization (see ).
Figure : The first visit to a web portal requires setting up the user account, creating pages, and populating with predefined widgets that user can further customize
During a first-time visit, the page does the following before the user sees it:
  • Creates a new user account using a ASP.NET 2.0 membership provider
  • Creates a new profile using a ASP.NET 2.0 profile provider
  • Creates new pages for the user
  • Creates default widgets on the first page
  • Sets up widgets with default data, e.g., shows the weather in the user's city by inferring the user's location based on the IP address
  • Renders the widgets and any associated client script
  • Delivers the entire client framework to support the web portal functionality
The challenge here is to execute server-side tasks instantly so the server does not have a noticeable delay before it starts to deliver the page content to the browser. Once the response is delivered, the browser needs to download the Ajax framework, widget scripts, graphics, CSS, etc., which takes a long time. To give the user perceived fast speed, the server needs to deliver the content almost instantly and progressively download the rest while the user is looking at the content of the page.
Basically, during the first visit, the application needs to deliver almost every aspect of the web portal, because you don't know what user might do once the page becomes functional. With Dropthings, users can use all the features of the application on the first visit. For example, a user can drag widgets, add new pages, and organize the content in pages, and then sign up to continue using the customized page. The user does all of this from a single web page with absolutely zero postback and no navigation to other pages. If postback was allowed on the page or the page was broken into multiple pages, then we could deliver only basic content and client-side features, like drag and drop. The rest of the functionality would be delivered when the user does something that makes a postback to the server or navigates to a different page. Because postback or navigation to other pages is not allowed, if the entire client framework is not ready by the time the user starts interacting with the page, there will be JavaScript errors and actions will fail.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Rendering a Second-Visit Experience
The second visit is piece of cake. The user account is already available from a browser cookie, which you get via the ASP.NET membership provider. All the Ajax scripts are already in the browser's cache. So, you just load existing pages and widgets on the page and render the page to the browser (see ).
Figure : On the second visit, the user account, pages, and widgets are already created so the user page loads very fast
Here's what the web portal does on the second visit:
  • Gets user from encrypted browser cookie via theASP.NET membership provider
  • Loads user pages and creates tabs for each page
  • Finds the current page
  • Loads all widgets on the current page
  • Allows widgets to load their previous state
  • Renders the widgets and scripts
  • Delivers the client-side framework (should be cached on browser already)
Because the client-side framework, widget scripts, and extender scripts are already cached on the browser, the duration of a second-time visit is basically the time spent on the server and the time the browser spends initializing scripts. However, in the meantime, the browser cache might expire and the cached JavaScript can get lost. If this happens, the browser will download the scripts again and the user will notice some delay during the next visit.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Improving ASP.NET AJAX Performance
There are several ways to improve your ASP.NET AJAX performance.
The Ajax web portal can be rendered in two ways: from the server or from the client. Server rendering means that the HTML on a page, along with all the widgets, is created in server code, rendered by the server code, and delivered statically to browser. So, the browser just renders the HTML, loads the JavaScript (or Ajax framework, extenders, widget scripts, etc.), and initializes it. iGoogle is a good example of server-side rendering.
In contrast, client rendering means the content of the widget is not sent along with the page content. Once the scripts download and initialize, the page calls a web service to get the content of the widgets and dynamically creates the widgets on the page, one after another.
The advantages of server rendering include:
  • Uses server-side technologies to their full potential. For example, it makes full use of ASP.NET features.
  • Renders and delivers entire page to the client in one shot. If the page does not have too many widgets, the perceived speed is better than client-side rendering approach.
  • Shows the content and then downloads the Ajax runtime, core scripts, widget scripts, etc., and initializes them later. Because the user sees the widgets before the whole page is downloaded, she feels it is a fast-loading page.
The disadvantages of server-side rendering include:
  • The page's cache output is delivered every time the user visits the site because it doesn't know if the user has already changed the page on another computer or if the page's content has changed by other means.
  • All widgets need to be developed mostly using server-side technology like ASP. NET. You cannot have JavaScript-only widgets.
  • If a widget does not follow the ASP.NET-style postback model, it will need a lot of support from a client-side framework. For example, you will have to provide support for features, such as expanding, collapsing, closing, and resizing, in the client framework and make sure the server is kept in sync with such client-side activities via web service calls.
The advantages of client-side rendering are:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Adding Authentication and Authorization
Because it makes use of web services and asynchronous postbacks, a web portal is faced with four challenges:
  • Authenticating the caller and ensuring the caller is a legitimate user on all asynchronous postback and web service calls.
  • Authorizing calls to web services and asynchronous postbacks. Making sure the caller has the right to make that call.
  • Preventing flooding. Making sure the caller cannot continuously call the service and flood the system.
  • Preventing bots from hitting Default.aspx.
Web portals treat anonymous users the same way as a registered user. Although you might want to disable some features for anonymous users and make them available only to registered users, the main reason for registering is to save the pages permanently because anonymous cookies can get lost. Almost all web services can be called by any user except a user profile-related service, such as changing a user email address.
Although it sounds like security would be easier with web portal architectures, it is actually more complicated. For security purposes, you need to make sure each and every web service call is made on the caller's pages or widgets. For example, when deleting a widget from a page, you need to verify that the widget belongs to one of the user's pages that just made the call. If it isn't, then it's definitely a hacking attempt. Similarly, when you remove a page, you need to make sure that it belongs to that user and not someone else. This is a big performance concern because such checks always require database calls. If you had a registration-only site or an intranet-only site, you could skip these checks because you trust registered users more than anonymous users. But, since you have to support anonymous users, you cannot leave any web service method call unchecked. For example, when checking for a widget, you need to get the containing page of the widget and make sure it belongs to the user making the call. Once you are satisfied that the call is legitimate, you can update the widget's position. If you don't do this, anyone can run a program and call the service by passing an arbitrary widget ID and change other users' page setups.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Preventing Denial-of-Service Attacks
Web services are the most attractive target for hackers because even an unsophisticated hacker can bring down a server by repeatedly calling a web service. Ajax web portals are a good target for such DoS attacks because if you just visit the home page repeatedly without preserving a cookie, every hit is producing a new user, a new page setup, and new widgets.
You can try this yourself with a simple code like this:
	for( int i = 0; i < 100000; i ++ )
	{
	  WebClient client = new WebClient();
	  client.DownloadString("http://www.dropthings.com/default.aspx");
	}
To your great surprise, you will notice that after a couple of calls, you will simply get no response. It's not that you brought down the server, but that your requests are being rejected. You no longer get any service, thus you achieve denial of service (for yourself), and the site is happy to deny you of service (DYoS).
A simple trick to remember how many requests are coming from a particular IP is to record a caller's IP in the ASP.NET cache and count the requests per IP. When the count exceeds a predefined limit, reject further requests for a specific duration, say 10 minutes. After 10 minutes, allow requests from that IP again.
The ActionValidator class maintains a count of specific actions such as first visit, revisit, asynchronous postbacks, adding a new widget, adding a new page, etc. It checks whether the count for a specific IP exceeds the threshold value or not. The following code shows the enumeration that contains the type of actions to check for and their threshold value for a specific duration, which is 10 minutes:
	public static class ActionValidator
	{
	    private const int DURATION = 10; // 10 min period

	    public enum ActionTypeEnum
	    {
	        FirstVisit = 100, // The most expensive one, choose the value wisely
	        ReVisit = 1000, // Welcome to revisit as many times as the user likes
	        Postback = 5000, // Not much of a problem
	        AddNewWidget = 100,
	         AddNewPage = 100,
	    }
A static method named IsValid does the check. It returns true if the request limit is not passed and false if the request needs to be denied. Once you return false, you can call
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
In this chapter you learned the basics of the web portal architecture used to build Dropthings, which encapsulates most of the client functionality that makes it easy for developers to create widgets that plug into a web portal. In particular, you've seen how use of a widget framework greatly facilitates their development and deployment.
It can be quite challenging to provide a rich client-side experience in a web portal; the biggest challenge is the first visit, where huge scripts must be downloaded. A web portal is also vulnerable to certain security risks, so you must implement mitigations that prevent them. Now that you know about the architectural challenges, let's use ASP.NET AJAX to build the web layer in the next chapter.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Building the Web Layer Using ASP.NET AJAX
The biggest challenge you'll face developing an Ajax web portal is providing almost all of your web application's functionality on a single page. A web portal is all about aggregating many services in one place. It's a never-ending challenge to have as many features on one page as possible yet keep them small, simple, and fast. So, the Default.aspx is the most complicated of all the pages in your application because it does everything from loading Ajax frameworks to serving the widgets on the page. Sometimes it is the only page users will see during their entire stay on the web site.
In this chapter, you will learn to code the Start page Default.aspx, the widget container, and the IWidget and IWidgetHost interfaces. Then you will put it all together and build a Flickr photo widget and a RSS widget. Finally, you will use ASP.NET 2.0 Membership and Profile providers to implement authentication, authorization, and profiles.
The Default.aspx page in this web project is the Start page of the Ajax web portal. (see ).
It contains the following:
  • The header which shows a search box
  • The Add Stuff area where users can add more widgets
  • The tab bar
  • The columns
  • The footer
The Default.aspx page starts with regular ASP.NET page syntax (see ).
Figure : The Default.aspx page contains almost everything in the Start page
Example 3-1. Default.aspx, part 1: Declarations of external components
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_
Default" Theme="Default" EnableSessionState="False" %>
<%@ OutputCache Location="None" NoStore="true" %>
<%@ Register Src="Header.ascx" TagName="Header" TagPrefix="uc1" %>
<%@ Register Src="Footer.ascx" TagName="Footer" TagPrefix="uc2" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"
TagPrefix="ajaxToolkit" %>
<%@ Register Assembly="CustomDragDrop" Namespace="CustomDragDrop" TagPrefix="cdd" %>
<%@ Register Src="WidgetContainer.ascx" TagName="WidgetContainer" TagPrefix="widget" %>
<!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 id="Head1" runat="server">
    <title>Ajax Web Portal</title>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Implementing the Start Page of a Web Portal
The Default.aspx page in this web project is the Start page of the Ajax web portal. (see ).
It contains the following:
  • The header which shows a search box
  • The Add Stuff area where users can add more widgets
  • The tab bar
  • The columns
  • The footer
The Default.aspx page starts with regular ASP.NET page syntax (see ).
Figure : The Default.aspx page contains almost everything in the Start page
Example 3-1. Default.aspx, part 1: Declarations of external components
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_
Default" Theme="Default" EnableSessionState="False" %>
<%@ OutputCache Location="None" NoStore="true" %>
<%@ Register Src="Header.ascx" TagName="Header" TagPrefix="uc1" %>
<%@ Register Src="Footer.ascx" TagName="Footer" TagPrefix="uc2" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"
TagPrefix="ajaxToolkit" %>
<%@ Register Assembly="CustomDragDrop" Namespace="CustomDragDrop" TagPrefix="cdd" %>
<%@ Register Src="WidgetContainer.ascx" TagName="WidgetContainer" TagPrefix="widget" %>
<!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 id="Head1" runat="server">
    <title>Ajax Web Portal</title>
The code block in does the following:
  • Registers the WidgetContainer control, which is the web control for the widget container.
  • Adds a reference to the CustomDragDrop assembly, which contains the CustomDragDropExtender and the CustomFloatingBehavior.
  • Turns off all caching because the page must be downloaded from the server every time a user visits. If the page is cached, then users will not see the latest content in widgets after making changes on the page.
  • Registers the header and footer web controls.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Building a Custom Drag-and-Drop Extender for a Multicolumn Drop Zone
I first considered a plain vanilla JavaScript-based solution for my drag-and-drop functionality. It required less code, less architectural complexity, and was faster. Another reason was the high learning curve for properly making extenders in ASP.NET AJAX, given that there's hardly any documentation available on the Web (or at least that was the case when I was writing this book). However, writing a proper extender that pushes ASP.NET AJAX to the limit is a very good way to learn the ASP.NET AJAX framework's under-the-hood secrets. So, the two extenders introduced here will tell you almost everything you need to know about ASP.NET AJAX extenders.
Before I wrote my own implementation of drag and drop, I carefully looked at existing solutions. The Ajax Control Toolkit comes with a DragPanel extender that could be used to provide drag-and-drop support to panels. It also has a ReorderList control, which could reorder the items into a single list. Widgets are basically panels that flow vertically in each column. So, it could be possible to create a reorder list in each column and use the DragPanel to drag the widgets. But ReorderList couldn't be used because:
  • It strictly uses the HTML table to render its items in a column. But I have no table inside the columns, only one UpdatePanel per column.
  • It takes a drag handle template and creates a drag handle for each item at runtime. But there already is a drag handle created inside a widget, which is the widget header, so ReorderList can't create another drag handle.
  • It must have client-side callbackto JavaScript functions during drag and drop to make Ajax calls and persist the widget positions. The callback must provide the Panel where the widget is dropped, depending on which widget is dropped, and at what position.
The next challenge is with the DragPanel extender. The default implementation of drag and drop in the Ajax Control Toolkit doesn't work for these reasons:
  • When you start dragging, the item becomes absolutely positioned, but when you drop it, it does not become statically positioned. A small hackis needed for restoring the original positioning to static.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Implementing WidgetContainer
WidgetContainer dynamically creates a widget inside its body area. The container consists only of header and body areas. The rest is provided by the actual widget loaded dynamically inside the container's body area. The settings area that you see when you click"edit" on the header also comes from the actual widget. WidgetContainer informs the widget only when to show it. The "Building Widgets" section later in this chapter shows how the widget handles this notification. WidgetContainer acts as a bridge between widgets and the core. The core communicates to the widgets via the container, and the widgets use the core's features via the container.
WidgetContainer's header contains the title text, the expand and collapse button, the "edit" link, and the close button within an UpdatePanel, as shown in .
Example 3-40. WidgetContainer's header panel
<asp:Panel ID="Widget" CssClass="widget" runat="server">
    <asp:Panel id="WidgetHeader" CssClass="widget_header" runat="server">
        <asp:UpdatePanel ID="WidgetHeaderUpdatePanel" runat="server"
        UpdateMode="Conditional">
        <ContentTemplate>
          ...
          ...
          ...
        </ContentTemplate>
        </asp:UpdatePanel>
    </asp:Panel>
By doing this, we are preventing the body area from refreshing when something changes in the header. If the body area refreshes, the widget hosted inside it will unnecessarily refresh. To avoid downloading and refreshing a large amount of data in the whole widget, the header and body contain separate UpdatePanel controls.
There is an UpdateProgress extender attached to the header UpdatePanel, which shows a "Working…" indicator when the header is going through asynchronous postback. This happens when a user clicks on the title to change it or clicks some button on the header area.
	<asp:UpdateProgress ID="UpdateProgress2" runat="server"
	        DisplayAfter="10"
	        AssociatedUpdatePanelID="WidgetHeaderUpdatePanel" >
	             <ProgressTemplate>
	                     <center>Working...</center>
	             </ProgressTemplate>
	</asp:UpdateProgress>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Building Widgets
Now that you've seen how to implement WidgetContainer, let's lookat how you build the widgets it hosts. First, we'll create a simple widget to display Flickr photos, followed by another widget to display RSS and Atom feeds.
Let's look first at a simple Flickr photo widget that downloads photos from Flickr and displays them in a 3×3 grid, as shown in .
Figure : The Flickr widget downloads the Flickr photo stream as XML and parses using LINQ to XML and the photo grid is dynamically rendered
The widget downloads Flickr photos as an XML feed from the Flickr web site and then renders a 3×3 grid with the pictures. The Flickr photo stream is available as an XML feed (not a RSS feed) at http://www.flickr.com/services/rest/?method=flickr.photos.getRecent&api_key.
You need to first obtain an application key from the Flickr developer zone and pass it at the end of the URL. The key I have embedded inside the project may not work if the request quota has already been exceeded.
The URL returns recent Flickr photos uploaded by the user as XML:
	<?xml version="1.0" encoding="utf-8" ?>
	<rsp stat="ok">
	<photos page="1" pages="10" perpage="100" total="1000">
	  <photo id="431247461" owner="25524911@N00" secret="cb9370fd16" server="162"
	  farm="1" title="P1020899" ispublic="1" isfriend="0" isfamily="0" />
	  <photo id="431247462" owner="46871506@N00" secret="036edda0e9" server="188"
	  farm="1" title="black" ispublic="1" isfriend="0" isfamily="0" />
	  <photo id="431247458" owner="91583992@N00" secret="6cd9a27d6d" server="153"
	  farm="1" title="DSC00647" ispublic="1" isfriend="0" isfamily="0" />
However, the XML does not contain the URL of the photo file. It needs to be built dynamically.
The first step is to download and parse the XML using LINQ to XML, which is avail-able in .NET 3.5. Here's an easy way to prepare a XElement from an URL:
	var xroot = XElement.Load(url);
Next we convert each photo node inside the XML to an object of the PhotoInfo class for convenient processing:
	var photos = (from photo in xroot.Element("photos").Elements("photo")
	select new PhotoInfo
	{
	         Id = (string)photo.Attribute("id"),
	         Owner = (string)photo.Attribute("owner"),
	         Title = (string)photo.Attribute("title"),
	         Secret = (string)photo.Attribute("secret"),
	         Server = (string)photo.Attribute("server"),
	         Farm = (string)photo.Attribute("Farm")
	})
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Page Switching: Simulating a Nonpostback Experience
Content preview·Buy PDF of this chapter|