aspnet

Page 1

Reviewed: Nintex Workflow 2007 www.aspnetPRO.com

April 2009 Volume 8 Number 4

Solutions for Building Enterprise Web Applications


Fast, Lightweight, High-Performing One of the many ASP.NET AJAX User Interface Components in the leading Toolset for developing Web 2.0 applications

learn more at: infragistics.com Four Platforms. One Package.

Copyright 1996-2009 Infragistics, Inc. All rights reserved. Infragistics, the Infragistics logo and NetAdvantage are registered trademarks of Infragistics, Inc. Aikido and WebDataGrid are trademarks of Infragistics. All other trademarks or registered trademarks are the respective property of their owners. Patents pending.


In April

2009

This |

Volume 8 Number 4

,iĂ›ÂˆiĂœi`\ĂŠ ÂˆÂ˜ĂŒiĂ?ĂŠ7ÂœĂ€ÂŽyÂœĂœĂŠĂ“ääÇÊ WWW ASPNET02/ COM

!PRIL 6OLUME .UMBER

Columns

18

3OLUTIONS FOR "UILDING %NTERPRISE 7EB !PPLICATIONS

22

48

28

LINQ (language-integrated query) enables developers to work at a higher abstraction layer by making querying a first-class citizen in C#. In this two-part series, Zeeshan Hirani shares experiences he’s encountered working with LINQ, as well as some common gotchas to avoid and hidden features that can help you write concise and expedient LINQ queries.

Departments 4

Executive Editor’s//Comment by Sheila Molnar

6

Crossword Puzzle by Ravi Nangunoori

BackDraft: Trailblazer The first rendition of a particular technology or concept often isn’t the one that eventually earns the largest market adoption. Jonathan Goodyear explains why.

Features

The Best of Both Worlds Silverlight 2 has been released. But is that “ho-hum� or “hurrah� for ASP.NET developers? As Austin Avrashow explains, it turns out that many scenarios benefit from both technologies used together. And as we’ll see in this article, using them together couldn’t be easier.

32

More Smart SEO Search Engine Optimization (SEO) has become the major driver for Uniform Resource Locator (URL) rewriting in Web sites. SEO-driven URL rewrites are essential for preserving page rank and link equity for Web pages. The URL Rewrite module is a useful tool that will save you time in creating rewrite and redirection rules for Web sites that run under IIS 7.0. Jeffrey Hasan shows us how.

Review

41

Exploring WCF Services: What’s New in WCF 4.0? The .NET Framework 4.0 will be released with Visual Studio 2010 — bringing with it many new WCF features. To provide you with a well-rounded view of the forthcoming release, Michele Leroux Bustamante provides a high-level summary of features planned for WCF 4.0.

Cover Stor y

8 LINQ Deep Dive: Part I

CoreCoder: Input Validation in ASP.NET MVC Dino Esposito continues his exploration of data entry in ASP.NET MVC. This month he delves in to model state and data validation.

Š Microgen – Shutterstock.com Cover Design by Diana Nishimura

44 Toolbox 47 Advertising Index

Issue

CloserLook: Nintex Workflow 2007 Nintex Workflow 2007 is designed to ease MOSS development pains and reduce development cycle times. Cole Shiflett tells us if it fulfills those objectives.

asp.netPRO Online Here’s just some of the content that’s available only online at www.aspnetpro.com. • “AJAX 4.0 Client Templates.â€? Many of the new technologies that come out of Microsoft are related to data and databases. The newest example of this trend is the latest preview release of AJAX 4.0. Of several new data access features, probably none is more interesting than AJAX client templates, as Don Kiely explains. • “Express Yourself.â€? Joydip Kanilal takes a brief look at Microsoft Expression Studio. He provides an overview of its components, how it integrates with ASP.NET, and the features of each of the components of Microsoft Expression Studio. • You’ll also find additional book and product reviews, product announcements, and more — and only available at www.aspnetpro.com.

2

April 2009

| www.aspnetPRO.com


Ease into XBRL compliance with the complete set of tools from Altova® Experience how the Altova MissionKit® 2009, the integrated suite of XML, database, and data integration software, delivers all the tools you need to work with XBRL – without breaking your budget.

The Altova MissionKit 2009 includes intelligent tools for editing, mapping, and publishing XBRL: XMLSpy® – the leading XML editor with XBRL support • XBRL and Dimensions validation • Graphical XBRL taxonomy editing MapForce® – graphical data mapping & conversion tool • Any-to-any mapping of XBRL, database, XML, & Excel 2007 data • Drag & drop generation of XBRL filing reports StyleVision® – stylesheet design and report publishing tool • Publication of XBRL financial reports in HTML, PDF, Word – simultaneously • Intelligent table wizard for easily presenting renderings of XBRL data

Download a 30 day free trial! Try before you buy with a free, fully functional, 30-day trial from www.altova.com.


Executive Editor’s//Comment Kim Paulsen, Senior Vice President, Penton New Media Group Jim L’Heureux, Senior Vice President, eMedia Kim Hansen, Publisher Sheila Molnar, Executive Editor, asp.netPRO and WinDevPro.com David Riggs, Editor in Chief, asp.netPRO Michele Crockett, Editorial and Custom Strategy Director Amy Eisenberg, Executive Editor, IT Group Jeff James, Editor in Chief, Web Content Strategist Cindy Bushong, IT Group Managing Editor Dave Bernard, Group Editorial Director, Custom Media

Editors Barb Alexy, Karen Bemowski, Jason Bovberg, Erin Bradford, Anne Grubb, Vicki Hamende, Linda Harty, Derek Maness, Caroline Marwitz, Chris Maxcer, Lavon Peters, Gayle Rodclay, Rita-Lyn Sanders, Zac Wiggy, Brian Keith Winstead Brian Reinholtz, Production Editor Mary Waterloo, Administrative Assistant

Contributing editors Jonathan Goodyear and Mike Riley

technical editor Anand Narayanaswamy

Contributing Writers Austin Avrashow, Michele Leroux Bustamante, Dino Esposito, Jeffrey Hasan, Zeeshan Hirani, Ravi Nangunoori, and Cole Shiflett

Art & Production Mike Friehauf, Art Director Linda Kirchgesler, Production Director Diana Nishimura, Production Coordinator, asp.netPRO

Ad Sales Cathy Sanassarian, National Sales Manager, asp.netPRO

Reprint Sales Diane Madzelonka (216) 931-9268

List Rentals, Walter Karl, Inc. 2 Blue Hill Plaza, 3rd Floor, Pearl River, NY 10965 Marie Briganti (845) 732-7054 Rosalie Garcia (845) 732-7027

Circulation & Marketing Evelyn Bridge, Marketing Director Marie Evans, IT Group Director of Audience Development mevans@penton.com .......................... (970) 203-2761 Customer Service . .... (800) 793-5697 (US and Canada) ...........................................44-161-929-2800 (Europe)

Sharon Rowland, Chief Executive Officer Sharon.Rowland@penton.com Jean Clifton, Chief Financial Officer Jean.Clifton@penton.com

Printed by Schumann Printers, Inc.

701 South Main Street Fall River, WI 53932 Phone: (920) 484-3348

 By Sheila Molnar Penton Media Welcomes asp.netPRO Readers!

W

arm greetings to the loyal developer readers of asp.netPRO magazine and the aspnetpro.com website. I’m very pleased that asp.netPRO has joined the

Penton Media family of online and print publications. We’ll continue the great tradition of providing high-quality how-to content for ASP.NET enterprise web developers; additionally, I want to introduce you to our other developer website, WinDevPro.com. WinDevPro’s mission is to bridge the gap between development and IT, help technical folks who find they have a “blended” job description in the new economy, and work with developers to position their IT group as strategic to the business.

Participate in Community on WinDevPro.com. I recommend adding WinDevPro.com to your favorites: You’ll find your familiar asp.netPRO content there as a channel. Plus, you can explore WinDevPro’s other developer channels, as well as its ASP.NET-enabled community features — blogs and forums and places for reader feedback. We’re building out the WinDevPro.com site and we welcome your feedback and, even better, your contributions. Improvements to aspnetpro.com. aspnetpro.com was a cutting-edge website back in the days of ASP programming. I’m pleased to tell you that we’re planning a substantial upgrade of the site to ASP.NET. As the Penton development team plans and executes on that path I encourage you to participate in building the community on WinDevPro.com. These websites will work better together. Deep Technical Articles. Many of the writers you look for in asp.netPRO have also written for Penton Media’s other publications. It’s great to be working with such excellent authors. It feels like home. In addition, I want to invite you to share your development solutions by submitting a Reader to Reader (R2R) article for publication. R2R articles are always popular because they’re written by your fellow experts in the field. The best R2R articles guide you step by step through the solution to a problem that could be similar to something you’ve encountered. Free Email Newsletters. We’re now publishing the free asp.netNOW email newsletter twice a month, on the second and fourth Thursdays. We’re still publishing Don Kiely’s articles, and we’re looking for more content! We’ve added tips and tricks, plus more reviews and news about Microsoft and other vendors. Send us your letters, tips, and feedback on products — this is another great way to build developer community. In addition to the asp.netNOW email newsletter, we also publish a free WinDevPro UPDATE email newsletter the first and third Thursday of every month. This newsletter goes to developers interested in ASP.NET, SQL development, .NET Framework, Visual Studio, etc. If you’d like to try this UPDATE, here’s the URL to sign up: www.windevpro.com/ eNewsletters/tabid/186/Default.aspx. Other Penton Properties. You may be familiar with Penton Media’s publication and website for IT Pros — Windows IT Pro magazine and windowsitpro.com — and with our publication for database experts, SQL Server Magazine and the sqlmag.com website. I encourage you to explore these websites or pass them along to your colleagues who have a focus in those areas. See You at TechEd US. As always, you’ll see asp.netPRO magazine at TechEd US. This year’s TechEd is in Los Angeles, May 11-15. Please stop by our booth and chat with your editors. We’ll be sharing the booth with fellow Penton publications Windows IT Pro magazine and SQL Server Magazine. I’m looking forward to meeting you and getting your thoughts on asp.netPRO magazine. Cheers! </>

Distribution by CUrtis Circulation Company

730 River Road New Milford, NJ 07646 Phone: (201) 634-7400 Fax: (201) 634-7497

4

April 2009

| www.aspnetPRO.com

Sheila Molnar is Executive Editor of asp.netPRO and WinDevPro.com. Reach her at Sheila.Molnar@penton.com.


Be The Master On Any Platform

Choose A Higher Power For DataVisualization To master the art of data visualization, you must seek out the leader. For almost two decades, Software FX has risen above all others by bringing top-of-the-line data visualization tools to enterprise developers working with diverse markets, platforms and environments. This wisdom has evolved into a vast body of products, including Chart FX and Grid FX which provide best-of-breed solutions for Windows developers seeking enterprise quality and performance. Power Gadgets is a professional IT solution offering incredible features for reporting and monitoring data. For a world of data visualization products that can raise your work to a higher level, depend on the source that’s clearly on top.

Visit softwarefx.com for interactive demos and more information about our latest products.

Data visualization for every need, every platform


Basic C# and OOP Crossword Puzzle

Sponsored by

 By Ravi Nangunoori ACROSS

By Ravi Nangunoori www.devexpress.com/crossword

DOWN 14. This class _______________ defines the characteristics and members of a new class.

4. To access a public instance member from outside a class, one must use a variable name and a member name using this notation.

15. -if; -if..else, switch in C# are known as _____________ statements.

6. For these parameter types, the system copies the actual parameter to the formal parameter.

18. -break: and -return: in C# are examples of these types of statements.

7. This keyword allocates memory for a class object.

19. These are data members of a class.

8. This modifier allows passing a variable number of actual parameters to a method.

21. For a method that does not return a value, the return type is specified as ____________.

11. One employs these members to model actions of a real-world object a class represents.

22. -for:, -while:, -do:, and -foreach in C# are known as _______________ statements. 23. In a class, the curly braces contain member declarations that make up the class ______________.

13. These members model the properties or attributes of a real-world object a class represents.

1. A class is always of this type. 2. Denotes a data structure that can store data and execute code. 3. These members are accessible within the class in which they are inherited. 5. A parameter used to pass data from inside a method to a calling code. 9. These represent function members of a class. 10. Members accessible to all other objects in a program. 11. These local variables are declared in a method’s parameter list rather than in the method’s body. 12. In the declaration below, “Getaspnetpro” is the _________ of the method: class dotnetMagazine {void Getaspnetpro( ) { console.writeline ("Buy Subscription"); } };

2

1 4

3

5 6

7

16. In this class: 8

9

class aspnetPro1 { int A3=30; string A4="ASP.NET";},

10 11

13

12

14

the variables A3 and A4 are initialized __________________.

17. In the declaration of the class below: 15

16

17

class aspnetPro { int A1; String A2;},

18 19

22

21

Please visit www.aspnetPRO.com/puzzle for answers to this puzzle.

20

23

Copyright © www.dotnetvideos.net, www.visualsoftinc.com

April’s Crossword Puzzle is sponsored by DevExpress. To be entered in the drawing for a DXperience™ Enterprise – by DevExpress, complete the crossword puzzle and fax to 913-514-3972 by March 13. One random winner will be drawn.

6

April 2009

| www.aspnetPRO.com

the variables A1 and A2 are initialized __________________.

20. These members are always associated with a class rather than the instance of a class.

Ravi Nangunoori is a Principal at www.visualsoftinc.com and specializes in developing Web applications using .NET technologies. He also runs a multimedia content site (www.dotnetvideos.net) serving the Microsoft developer community around the world. He can be reached at ravi443@gmail.com.



C o v erS to r y LANGUAGES: C#

 By Zeeshan Hirani

ASP.NET VERSIONS: 3.5 

LINQ Deep Dive Part I: Tips for Delving in to LINQ

L

INQ (language-integrated query) enables developers to work at a higher abstraction layer by making querying a first-class citizen in C#. LINQ provides

the same query model for different domains, such as LINQ to Objects, LINQ to XML, and LINQ to SQL.

Although the querying concept is the same at the syntax level, we are dealing with different domains that have totally different behaviors, which LINQ cannot abstract. For instance, when you write a LINQ query that is applied on SQL Server, you rarely consider optimizing the query. SQL Server has a built-in optimizer to execute the query to yield maximum performance in the most efficient manner. However, LINQ to Objects does not have that richness; therefore, it is left to the developer to write queries that can be executed by the compiler in the most efficient manner. I’ll share in this two-part series some of my experiences and pain that I’ve encountered working with LINQ on a daily basis. I’ll also demonstrate some common gotchas to avoid, as well as hidden features in LINQ that can help you write concise and expedient LINQ queries.

Tip One: Apply Filters Before a Join to Improve Query Performance A LINQ to SQL query is translated into SQL by the LINQ provider and sent to SQL Server for execution. As a developer, you don’t have to worry about the order in which the join and filter clause needs to be applied to return data faster. SQL Server has a built-in query optimizer that looks at query execution plans and indexes to determine the fastest possible way to read data, such as doing a table scan or using an index or hash join to retrieve data. LINQ to Objects queries are not endowed with any such optimizers. Therefore, it is essential to understand query behaviors to try to limit the result by applying filters before join clauses, causing the projected output to be joined against a smaller subset. Joining against fewer rows offers better performance. Figure 1 shows an example that illustrates performance benefits gained by putting a where clause before joins. 8

April 2009

| www.aspnetPRO.com

Figure 1: Applying a where clause before a join makes queries run faster.

Figure 1 contains two integer collections, nums1 and nums2, which are generated using the Range extension method on the Enumerable class. The Range method creates a sequence of numbers specified within a range. The LINQ query in Figure 1 uses a join clause to find common integers in nums1 and nums2. Because I’m only looking for numbers that fall below the 500,000 range, I also applied a where filter to limit my search. To calculate query execution time, I recorded the start and end time of each LINQ query. Both queries in Figure


ASP.NET / ASP / WINDOWS FORMS / .NET / ACTIVEX

WORD PROCESSING

COMPONENTS ( WHAT YOU SEE IS WHAT YOU GET )

Word Processing Components for Windows Forms & ASP.NET

WWW.TEXTCONTROL.COM

TX Text Control Sales: US +1 877 - 462 - 4772 (toll-free) EU +49 421 - 33591 - 0


CoverStory

|

LINQ Deep Dive

1 accomplish the same task, the difference being the first query applies the where clause Figure 2: Results from executing the after joining the query in Figure 1 show an increase of two collections, performance when you apply a where and the second clause before the join statement. query limits the rows to be joined with the nums2 collection by applying the where clause before the join statement. Figure 2 shows the time taken by both queries.

Figure 3: Applying a where filter to return products in the Beverages category.

Results from Figure 2 confirm there is a magnitude of speed difference when you apply a where clause before the join statement. Applying the where clause before took only 6.8 seconds, compared to the original query, which took 16.5 seconds. Remember, when executing queries on in-memory objects, understanding your data is essential so you can limit the search results before joining it to another table. Most of these capabilities are provided for you by SQL Server when you write LINQ to SQL queries, but in LINQ to Objects, developers are responsible for writing queries that can perform optimally.

Tip Two: Filter LINQ Queries Using Object Reference Comparison You are not required to explicitly specify the primary key column in the where clause of the query if the LINQ query is filtered based on a primary key. Comparing object references will ensure that the query you send to the database gets filtered based on the primary key column. This sometimes removes noise from the code and makes it easier to read. Figure 3 demonstrates using object comparison to apply a where clause to retrieve only products in the Beverages category. As Figure 3 shows, I returned products that belong to the Beverages category. Instead of filtering products based on CategoryID, I filtered the results by comparing the category on the product object with the category I retrieved from the database. The object reference comparison gets converted to a primary key comparison on SQL Server. This can be confirmed by the SQL capture displayed below the LINQ query in Figure 3. Notice that the Products table is filtered based on the CategoryID column.

Tip Three: Apply Aggregates to Empty Collections in LINQ to SQL Queries LINQ to SQL has support for aggregate operators, like Sum, Count, and Average. For collections implementing IQueryable, aggregate operations are performed on the database. Certain aggregate operators like Sum and Max would cause LINQ to SQL queries to throw an exception. For instance, to determine the total sales an employee has made, you would group the Orders table by employee and sum the order total for each order to get their TotalSales. But what happens when there are employees in the database who have not cre10

April 2009

| www.aspnetPRO.com

Figure 4: An aggregate operation applied on an empty collection on the database requires casting to nullable types.

ated an order? Those employees will not have any records present in the Orders table, and SQL Server will return null for their sum (instead of 0). The implementation on SQL Server for calculating the sum on empty rows differs from how LINQ to Objects applies Sum on empty collections. For instance, if an employee has not created an Order, getting its Orders would return an empty collection of Orders. When you apply Sum on an empty collection, you would end up with 0 totals. However, for the same scenario, SQL Server would return a null value for TotalSales. So be aware that if the aggregation is performed on SQL Server, the type that is going to hold the sum must be a nullabe type. If the query is performed in memory, you can be assured that results will not be null. Let’s look at an example of comparing both LINQ to SQL and LINQ to Objects implementations for getting total revenue for each employee (see Figure 4).



CoverStory

|

LINQ Deep Dive

As Figure 4 shows, I calculated the total revenue generated by each employee. In the first section of the code, I preloaded all the Orders and OrderDetails for all employees by making use of DataLoadOptions. By using DataLoadOptions, I’m telling the LINQ to SQL query engine that while you are retrieving employees, also fetch all the orders for that employee, and, for each Order, also retrieve its OrderDetails. By preloading all the orders from the database, I can force all the aggregate operations to be performed in memory. The query in Figure 4 displays the employee name, and for each employee I am flattening the list of OrderDetails. Because each Order has many OrderDetails, I make use of the SelectMany operator to flatten the hierarchy of OrderDetails into one collection that contains all the OrderDetails for all the orders created by a particular Employee. Once I’ve obtained all the OrderDetails, I sum the OrderDetails total for each order by multiplying the quantity and price available on the OrderDetails entity. Figure 5 shows the output of printing the anonymous type on the screen. Notice that we have an employee named zeeshan that has no orders created; hence, the sales total shows a value of 0. For the same query to work in LINQ to SQL, I must cast results returned from the Sum operation to a nullable decimal type. SQL Server returns null for TotalSales when there is no order created by an employee. If you do not make your TotalSales nullable, LINQ to SQL will throw an exception complaining null values cannot be assigned to types that are not defined as nullable.

Tip Four: Delay Loading a Property in LINQ to SQL LINQ to SQL by default supports lazy loading of entity refs and EntitySets. This lazy-loading behavior allows the developer to load only the data needed for processing. If you don’t require additional collections, there is no need to incur the performance degradation and memory consumption for loading additional collections from the database. But what happens if there are certain columns in your table entity that are expensive to load and you rarely need them in your user interface. It would be beneficial in these scenarios to take advantage of lazy loading on certain columns of the table. One way to achieve this is to write a LINQ query that returns an anonymous type that contains only the data you need to display on the Presentation layer. However, an anonymous type cannot be passed across tiers in a strongly typed manner. Another option is to partly populate your LINQ entity with only columns you need to display. In this option, you must at least populate your LINQ entity with a column marked as the primary key, because object tracking uses primary key columns to track entities. Both options have weaknesses, because if you don’t load the column at the time you run the query, those columns never get loaded — and you don’t get a second chance to load the property unless you call Refresh to refresh the entity from the database. 12

April 2009

| www.aspnetPRO.com

Figure 5: Results from a Sum operation applied on SQL Server using LINQ to SQL and in memory using LINQ to Objects.

Figure 6: Code generated by the LINQ to SQL designer when you set Delay Loaded to True.

The LINQ to SQL designer provides a Delay Loaded property on every column in the table. When you set the Delay Loaded property to True on a column, the LINQ to SQL engine will exclude that column from the query when it makes a request to the database. Only when you access that column will LINQ make a request to SQL Server to get only that column value. It is useful in scenarios when you have defined columns as XML data type, varchar(max), or varbinary. Figure 6 shows setting the Delay Loaded property on the LINQ to SQL designer. Figure 6 shows a preview where I marked the Picture column with Delay Loaded set to True. On changing the setting in the Properties window, the LINQ to SQL designer will create a private variable of type System.Data.Linq<T>, where T is the type of property (Binary in this case). System.Data.Linq.Link has the smartness to enable lazy loading on the property. After setting the Picture column to be lazy loaded, querying the Categories table will exclude the Picture column. Figure 7 confirms the behavior by printing the SQL sent to the database. Notice that our query does not include any reference to the Picture column. Setting lazy loading in the designer is a good option, but it applies lazy-loading behavior for the property for all the queries in your application. What happens when you have a genuine need to have the properties not be lazy loaded


Figure 7: The SQL query sent by LINQ to SQL excluded the Picture column.

Figure 8: The Picture column is loaded when we fetch the Category entity from the database.

on certain queries. In those cases you can use the familiar LoadWith option to load properties. LoadWith not only works with foreign key tables, but you also can use that to load lazy-loaded properties. Figure 8 demonstrates loading the Picture property when the Category entity is retrieved. Therefore, this time, my SQL-generated code includes the Picture column, despite the fact that the Picture property on the Category entity has deferred-loading enabled.

Figure 9: This query returns the Beverages category both times, even though our function dictates returning Beverages and Produce.

Tip Five: Use Table-valued Functions with Eager Loading Turned On User-defined functions provide composability for LINQ to SQL queries compared to stored procedures. When you call a stored procedure from your datacontext, the collection returned is IEnumerable<T>. If further transformations are applied on the query, such as a where or order by clause, they get executed in memory. These kinds of queries are deceiving, because they compile fine and do not throw exceptions at run time. Because part of the query gets executed on SQL Server and any transformations applied are done in memory, you could end up bringing lots of rows on the Web server, which could increase your network traffic and increase memory consumption. However, tablevalued functions return IQueryable, and are marked with the IsComposable attribute set to True. This allows us to further compose our queries by joining it to another table and adding where, order by, or any other LINQ operators. Then the entire query gets sent to SQL Server for execution. Table-valued functions work well, but they tend to give incorrect results if you turn on eager loading for child collections. For instance, if I have a table-valued function that returns categories and I’m eager-loading products for the category as well, then when I print the categories it will return the correct number of categories, but they all would be the same. Figure 9 shows a table-valued function named BvgAndSeaFood that returns two categories (Beverages and Produce). To use the

Figure 10: Joining categories returned from the function to the Category table removes duplicates of the Beverages category.

function, I dragged the function on the categories table to the LINQ to SQL designer to indicate that my function returns a collection of Category objects. In the query, I made use of DataLoadOptions to eagerly-load products for the categories returned from my function named BvgAndSeaFood. Once I’ve configured my DataLoadOptions, I assigned the object to the datacontext. On printing the categories to the output screen, both times the Beverages category is printed. If you don’t use DataLoadOptions to preload products, the results printed on the console will be Beverages and Produce, as dictated by my table-valued functions. This leads me to believe there is something wrong with the implementation of table-valued functions when you turn on eager loading. As mentioned earlier, one way to get around the problem is to join the Category table and select a category from the asp.netPRO | April 2009

13


CoverStory

|

LINQ Deep Dive

Figure 11: A join is optimized because the smaller array is on the right side and the larger array is on the left side.

Category table. Figure 10 shows the working version where I get correct categories with no duplicates printed on the console window.

Tip Six: Put Joins in the Correct Order in a LINQ to Objects Query If you are doing lots of joins in memory using LINQ to Objects, you must to be aware of the order in which joins are applied. For instance, if you have two sequences in memory and you have to join those sequences, always use the smaller sequence on the right side of your query and the larger sequence on the left side. It makes a considerable difference in performance. Figure 11 shows the time taken to join a large collection to a small collection. To create my first array, num1, I used the Range operator. The Range operator takes in the start position from where to start generating numbers; the second parameter indicates how many numbers to generate. Looking at Figure 11, you can see that num1 is a large array. I then created my second array using the same Range operator, but gave it a small count, which resulted in a smaller array. I then joined both the sequences with the smaller sequence nums2 on the right side and the larger sequence nums1 on the left side. The time taken to execute the query was 0.18 seconds. If I were to rewrite the query slightly differently by putting the smaller array on the left and the larger array on the right, it would dramatically increase the query execution time to 2.6 seconds (see Figure 12). Not only does the query time increase, but the memory consumption goes up because the LINQ query engine must load the entire collection on the right side — and if that happens to be a larger collection, it increases the query time and occupies more memory.

Tip Seven: Compose a LINQ Query Inside a Loop LINQ queries can be composed by dynamically building a lambda statement and appending it to the existing query. 14

April 2009

| www.aspnetPRO.com

Figure 12: The larger array on the right side of the join causes the query time to increase.

For instance, you can loop through an array and for each iteration build a lambda statement and add it to an existing query. If the lambda statement makes use of a looping variable, results would be inconsistent if the looping variable is not captured correctly. These side effects return misleading results and introduce bugs that are very difficult to find. The problem can be explained by a simple demonstration. In Figure 13, I have an array of cities containing London and Paris. I also have a collection of customers where some customers are from London and some are from Paris. I am looping through my array of cities and building a LINQ query. Inside the loop, I am creating a lambda statement that matches the city in the array and picks the first customer. When I run the query I expect to get two customers, one from London and one from Paris. However, the output on the console window only shows a customer with CustID:3 from Paris. The result is incorrect because the variable city remains in scope and changes with every iteration of the loop. The last iteration of the loop returns the value of Paris, so all predicates using the city parameter in their lambda expression get affected and use the new value of Paris. To solve the problem we must declare another variable inside the loop that captures the value of the looping variable. When the looping variable changes as you iterate the loop, our local variable is not affected. The local variable goes out of scope at the end of each iteration of the loop and, hence, is not affected by the changing value of the looping variable. Consequently, with each iteration of the loop we create a lambda statement that captures a different local variable. To avoid the side effect of the city variable being changed, I can declare another variable, _city, inside the loop, which captures the value of the city at that moment and passes that to the lambda statements (see Figure 14). Once that iteration ends, the local variable _city goes out of scope and does not cause any side effects. The output printed on the


Providing the vision and

intelligence to keep you and your company competitive in today’s market!

One Place, One Time ...

DevConnections Fall ‘09 NOVEMBER 9-12, 2009

LAS VEGAS, NV • Mandalay Bay Resort & Casino

DEVCONNECTIONS

ROCKS the technology industry as the LARGEST and most EXCITING event focused on MICROSOFT TECHNOLOGY and YOUR needs.

Exciting Announcements: Be among the first to get the insiders scoop on the products and technology you rely on!

As a DevConnections attendee, you and your colleagues can attend all of the Connections shows, and cross between all of the sessions, at the same time for the same price.

Scott Guthrie Microsoft

Thomas Rizzo Steve Riley Microsoft Microsoft

Corporate Vice President, .NET Developer Division

Director, SharePoint Group

Senior Security Strategist in Microsoft’s Trustworthy Computing Group

CHECK WEBSITE FOR DESCRIPTIONS OF SESSIONS AND WORKSHOPS

www.DevConnections.com • 800.438.6720 • 203.268.3204 • Register Today!


CoverStory

|

LINQ Deep Dive

Figure 13: The side effects if the looping variable is not captured correctly when building LINQ queries dynamically.

console confirms we are getting two customers, one from London and one from Paris.

Conclusion LINQ queries make the code more readable because the code specifies what needs to be done and leaves to the compiler the underlying details of how it needs to be done. Although LINQ abstracts different programming domains, such as LINQ to Objects, LINQ to XML, and LINQ to SQL, it cannot hide the complexity and different behavior of each domain. It is essential that we understand how each domain interprets the LINQ query and ensure that a particular query works optimally for the domain we are targeting. In this installment we explored different query behaviors specific to each domain, such as how where clauses are executed in memory as compared to being applied on the database, and what performance tradeoffs we must consider. We also learned how aggregate behavior varies in each domain where LINQ to Objects would return 0 for empty collections and LINQ to SQL would return null. It is important that we understand these differences and ensure that our query returns correct results for the specific domain we are targeting. To improve query performance we learned how to delayload a particular column in the database that is not used often. We also discussed some of the constraints of using table-valued functions when eager-loading is turned on, and how to overcome those inconsistencies. We also talked about how to put joins in the proper order to ensure a query runs faster and does not occupy lots of memory. Finally, we 16

April 2009

| www.aspnetPRO.com

Figure 14: Declare a local variable to avoid the side effects of looping variables and, thus, return correct customers from London and Paris.

learned that when you are composing queries inside a loop, you must take precaution to capture the looping variable correctly; otherwise, your LINQ expressions will be filtering data based on the last value of the looping variable, resulting in incorrect results. We’ll continue our exploration in Part II by introducing users to caching features offered by the object tracking service, and in which scenarios caching is used and how it ensures object reference consistency. We’ll also discuss how LINQ to SQL automatically maps dynamic SQL to entities, and how a non-default constructor can prevent composing queries from other queries. We’ll also learn how to understand and identify if the query is being sent to a database for execution, or if it is being applied in memory. </> Source code accompanying this article is available for download to asp.netPRO subscribers at www.aspnetPRO.com.

Zeeshan Hirani is a senior developer at CheaperThanDirt.com. He specializes mainly in ASP.NET, AJAX, and leveraging OR-mapping solutions like LINQ and Entity Framework in business applications. He has written several articles for CodeProject.com and is an active member in the user-group community in Dallas/Fort Worth. He is a frequent blogger. One of his greatest achievements was writing a 500page learning guide that walks you through different concepts and modeling scenarios supported by Entity Framework. The learning guide can be downloaded at weblogs.asp.net/zeeshanhirani/archive/2008/12/ 18/my-christmas-present-to-the-entity-framework-community.aspx. You can find his blog at weblogs.asp.net/zeeshanhirani. Contact him with any questions at zeeshanjhirani@gmail.com.


CA

LL

W NO

OR

VIS

O IT

UR

WE

BS

ITE

BE

W! LO

.BLF .POFZ XJUI :PVS 0XO 8FC )PTUJOH 3FTFMMFS #VTJOFTT

D ITE FFER /09 LIM E O 3/31 TIMDS 0 EN

Managing Multiple Websites? Host unlimited websites, email and domain names in our world-class US data center and resell everything under your own brand. Try the Fasthosts Reseller Account FREE and without obligation for a year.

3FTFMMFS 8&# )045*/( "$$06/5

/03."--:

1&3 .0/5)

OR IDEALEFB W ERS DESIGN

6OMJNJUFE 8FCTJUFT

Total flexibility - create your own web hosting solutions or resell our white-label plans from $0.99/mo.

6OMJNJUFE #BOEXJEUI

Unlike other providers, we don’t limit your website traffic or charge you extra.

6OMJNJUFE 8FC 4QBDF

Host large websites knowing you’ll never have to pay for more space again.

6OMJNJUFE &NBJM

Resell unlimited POP3/IMAP mailboxes and offer complete Hosted Microsoft Exchange solutions.

RIS TRIK FRE AL E

U O V P D D " S BMVF

F M M F T F FREE :3FBS W GPS B tion fee subscrip o /m 0 5 the $ plies to Offer ap

(SFBU 'FBUVSFT BOE #FOFGJUT t $SFBUF ZPVS PXO QMBOT BOE DVTUPN TPMVUJPOT t -PBE CBMBODFE 8JOEPXT BOE -JOVY PQUJPOT t 'BTU 64 XFC TFSWFST JO PVS XPSME DMBTT EBUB DFOUFS t 1SJWBUF MBCFM UPPMT VTF ZPVS PXO CSBOE OBNF See website for details

24/7 Technical Support

t &YQFSUT PO IBOE XIFOFWFS ZPV OFFE UIFN t IFMQMJOF BOE FNBJM TVQQPSU t *O IPVTF QSPGFTTJPOBMT CBTFE JO UIF 64 t $PNQSFIFOTJWF SFTFMMFS TVQQPSU XFCTJUF

6OMJNJUFE 8FC )PTUJOH

6OMJNJUFE &NBJM

-PX $PTU %PNBJO /BNFT

1SJWBUF MBCFM #SBOEJOH

0OMJOF $POUSPM

64 #BTFE %BUB $FOUFS

5FDIOJDBM 4VQQPSU

The Flexible One-Stop Reseller Hosting Package Start Making Money Today Visit:

www.fasthosts.com

Call Toll Free 1- 877- 440 - 5515 Š 2009 Fasthosts Internet Inc. All rights reserved. Fasthosts and the Fasthosts logo are trademarks of Fasthosts Internet Inc For full promotional offer details, visit www.fasthosts.com. Product and program specifications, availability and pricing subject to change without notice. Not responsible for typographical errors.


C o r eCo der languages: C#

 By Dino Esposito

 ASP.NET VERSIONS: 3.5 | MVC

Input Validation in ASP.NET MVC Explore Model State and Data Validation

L

ast month I discussed how to arrange a data

A Common Pattern for a Data Entry Page

entry page using the ASP.NET MVC Framework.

Since the advent of ASP.NET 1.0, I’ve been working on quite a few Web pages to do data entry. When it comes to this, you have essentially two points to address: isolating the editing UI and update logic from the page, and letting the page know about what happens during the editing phase.

There’s a common sentiment around the commu-

nity that the ASP.NET MVC Framework is not particularly suited to data entry. I was one of those sustaining this point of view. Well, it lasted until I tried it out seriously. Now I’ll probably remain a fan of Web Forms for most of the foreseeable future, but this is not a good reason to yield to prejudice when it comes to ASP.NET MVC and data entry. Data entry (and input validation as we’ll see in this article) can be equally as effective in ASP.NET MVC as it is in Web Forms. This said, feel free to pick up the framework with which you feel most comfortable.

By employing a user control for editing the record, you are able to isolate the editing UI from the page. Furthermore, in an ASP.NET MVC scenario, the logic to handle the update is already out of the page, isolated in the controller. You must figure out how to pass data to the user control; possibly in a way that abstracts the actual view away. In addition, you must figure out how the user control communicates with the host page. This regards how the input data is being passed to the user control, but also how messages for errors and notifications are shown.

But let’s make it clear — it is a matter of preference. Figure 1 shows where I stopped last month. The figure shows a Web page through which a user can select a customer from a list and click to edit its record. When this happens, a new view is displayed that includes a user control. The user control incorporates the user interface to edit the content of the bound record. The user control also contains a Save button and posts a new request to the site to update the record. Keeping the editing stuff isolated in a user control makes it easy for you to replace it and decouples to an acceptable level the host page from the edit-record engine. In this article, I’ll further enhance the user control to add the ability to display user messages that regard validation and other errors. In doing so, I’ll also be using the jQuery library to add some animation. 18

April 2009

| www.aspnetPRO.com

Figure 1: A sample data entry page.


Everything else takes place within the user control. The user control renders its own view, drawing data from passed objects, and waits for the user to enter data. Let’s skip for just a moment over validation and focus on the Save button. When the user clicks the Save button, a POST request is generated to a URL input/update/id. The controller’s Update action does the following: public ActionResult Update(string id) { // Update the data model (if current data is OK) UpdateRecord(id); // Save a message to UI SetMessageBar(); // Redirect to Edit mode on the current record RedirectToAction("Edit", new RouteValueDictionary(new { id = id }));

Figure 2: Internal architecture of an ASP.NET MVC data entry page.

Figure 2 shows structure and overall behavior of a sample page using this pattern. When the user clicks to edit, a POST is made to the Web server to turn the selected record into edit mode. The controller’s Edit action is invoked for a POST verb: [ActionName("Edit"), AcceptVerbs(HttpVerbs.Post)] public ActionResult EditViaPost(string listCustomers) { string customerID = listCustomers; return RedirectToAction("Edit", new RouteValueDictionary(new { id = customerID })); }

The parameter indicates the currently selected element in the list. The action method simply redirects to the Edit action for a GET verb — the same action you expect to take place when an input/edit/id URL is requested. This ensures a dual programming interface to the page — the user gets to the same point via both the user interface and the address bar. The Edit action for GET verbs performs two steps. First, it refills the list and selects the element identified by the URL argument. Second, it stores in the view’s data container any data needed to update the user interface. It is recommended that you opt for a custom data structure that abstracts away the data required by the next view. However, a similar fragment of code still works: object data = GetContentForTheUserControl(...); ViewData["CustomerData"] = data;

The view will check the presence of data for the user control and display it on demand, as shown here: <% object data = ViewData["CustomerData"]; if (data == null) return; Html.RenderPartial(userControlViewName, data); %>

}

The first step accomplished by the controller is updating the record — provided that valid data has been provided through the user interface. The controller’s method receives this data from the ASP.NET MVC machinery. In turn, the ASP.NET MVC machinery gets raw data from the Request.Form collection packed with the POST request (see last month’s article for details). Finally, the controller sets any information for the user interface and redirects to Edit mode. This is the pattern I found very comfortable to use in a data entry page, and especially easy and effective in ASP.NET MVC. Is there any reason to use a redirect in Update (and other actions) instead of simply rendering the view? Using a redirect separates the action of updating the model from the action of updating the view. They are two distinct actions performed by the browser. The pattern PRG explains this approach. PRG stands for Post/Redirect/Get. In this way, any page refresh is done via GET, which makes for a cleaner MVC solution. However, it also saves you from a nasty problem — if the user refreshes (F5) the page displayed after, say, an update, no POST is repeated and no message about resending data is displayed. If you use the PRG pattern and redirect to a GET, any F5 refresh repeats a GET, not a POST. Let’s see more about updating the user interface to reflect the state of the record during the update phase.

A Bit of jQuery in the User Control It’s fine to have the helper user control trigger the update on the controller and redirect to a selected view. This is what one would call a clean MVC solution. What about synchronizing the rest of the user interface (mostly the page) with the effect of updates? Let me explain with an example. Suppose you have a master/detail view. You edit asp.netPRO | April 2009

19


CoreCoder

|

Input Validation in ASP.NET MVC

the detail record through the user control, but still you may need to update the master record to possibly reflect changes. The user control can hardly take care of that. In this case, the best you can do is instruct the user control to fire an event to the host page. This the most general approach. However, in simpler — but not necessarily infrequent — situations, you don’t need to sync up the rest of the page with the actions performed through the user control. Any feedback regarding the update in this case can be displayed within the user control itself. In Figure 2, in fact, you see a message bar area in the user control that displays the content set by the controller. Here’s how the controller stores data to display in the view:

<% string msg = TempData["OutputMessage"] as string; %> <script type="text/javascript" src="../../Scripts/ jquery-1.2.6.min.js"></script> <script type="text/javascript"> var timer; $(document).ready(function() { timer = window.setInterval("clearMsg()", 2000); }); function clearMsg() { $("#UpdateMsg").text(""); window.clearInterval(timer); } </script>

Figure 3: A flashy message using jQuery.

// TempData is a dictionary on the controller base class TempData["OutputMessage"] = "Successfully updated!";

Why use TempData instead of ViewData? Any data you stuff in ViewData is stored for the duration of the request. But if you redirect to render the view, any such content is lost. TempData ensures that any data you place in it also survives a second request, if this is a redirect. How would you display a message (be it an error or a notification) after an update? If the update didn’t work because of errors, you want to keep the message on during editing for the user to keep in mind what went wrong. If the message, instead, is a plain notification that the update worked successfully, you might want to show it, but hide it at some point because during an editing phase it doesn’t make much sense to recall that the last update worked just fine. In other words, what you want are flashy messages that appear for just a few seconds if a text is found in TempData and disappear shortly afterwards. You need clientside capabilities for this. Figure 3 shows how to do it with jQuery. Figure 4 shows the real effect on the user interface. The message “Successfully updated!” disappears in a couple of seconds, leaving the editing interface clean for a new set of changes. You put the code in Figure 3 in the ASCX file of the user control. The message is displayed when the page renders out. At the same time, when the document is ready, a timer is set up that clears the message at the end of the interval.

Features for Validation You can use the TempData container to pass up to the user interface any error message you want that relates to the update. The user control receives an entity object from the model (in the sample code it’s a Customer object) and attempts to fit into that object any data the user entered through input fields. But what if the input data is invalid? 20

April 2009

| www.aspnetPRO.com

Figure 4: The effect on the user interface when using jQuery.

Clearly, any invalid data should originate an error message that must be reported to the user. The best way to validate the state of an object in an MVC context is a non-trivial problem with many aspects, and deserves an article of its own. For the purpose of this article, I’ll simply assume you know how to validate an object and capture the list of invalid input values and related error messages. How would you display these messages? In Web Forms you have server-side validation controls that make it easy. A validation control simply applies a built-in validation rule to a value, and has no vision on the object that may be behind that scalar value. ASP.NET MVC provides some facilities to display error messages associated with input data. You have a ValidationMessage helper to generate a label and a ModelState collection to capture all error messages to display. Let’s start with the markup in the user control: <td><b>Country</b></td> <td><%= Html.TextBox("Country", ViewData.Model.Country, new Dictionary<string, object>() { { "class", "textBox" } })%> <%= Html.ValidationMessage("Country") %> </td>

ValidationMessage produces no output if the ModelState collection on the ViewData object is empty. You add an entry to the collection for each detected error. The controller’s


message is displayed. At least in Beta 1, you need to pass the content of ModelState to TempData so the user control can retrieve it: if (!cust.Country.Equals("Germany")) { ViewData.ModelState.AddModelError("Country", "Invalid country."); TempData["OutputMessage"] = "Check your input data."; TempData["ModelState"] = ViewData.ModelState; } else { ... }

The user control then copies the content of the passed model state into its own model state: Figure 5: An example MVC application.

<% if (TempData["ModelStateForUserControl"] != null) { foreach (var x in (ModelStateDictionary)TempData[ "ModelStateForUserControl"]) { if (x.Value.Errors.Count <= 0) continue; string errorMsg = x.Value.Errors[0].ErrorMessage; ViewData.ModelState.AddModelError(x.Key, errorMsg); } }

UpdateModel method uses the content in the Form collection to update an entity object: UpdateModel<Customer>(customer);

Next, you validate the object applying some rules. For each error detected, you add an entry to the ModelState: if (!cust.Country.Equals("Germany")) { ViewData.ModelState.AddModelError("Country", "Invalid country."); TempData["OutputMessage"] = "Check your input data."; } else { context.SubmitChanges(); TempData["OutputMessage"] = "Successfully updated!"; }

%>

With this fix, it works also when the user interface is isolated in a user control. </> Source files accompanying this article are available for download to asp.netPRO subscribers at www.aspnetPRO.com.

The preceding code is excerpted from a controller method. However, this is a debatable point that deserves more attention. In ASP.NET MVC, the whole point is to fill the ModelState collection. Once this is done, matching ValidationMessage elements will display messages. The match is found on the key passed to ModelState and the argument passed to ValidationMessage. If the page contains a CSS style named .input_validation_ error, that is automatically applied to the control with wrong data, provided that the control is not styled already (see Figure 5).

Fix for User Controls The approach described works great for HTML elements incorporated in the Web page. If the input elements live within a user control — and the user control has a strongly typed view data model — no information about model state ever reaches the user control. As a result, no error

Dino Esposito is an architect at IDesign and specializes mainly in ASP.NET, AJAX, and RIA solutions. Dino is the author of Microsoft .NET: Architecting Applications for the Enterprise (Microsoft Press, 2008). He also wrote Programming ASP.NET 3.5 Core Reference, also for Microsoft Press. Late-breaking news is available at weblogs.asp.net/despos. asp.netPRO | April 2009

21


Exp loring WC F S er vices languages: C#

 By Michele Leroux Bustamante

TECHNOLOGIES: .NET 4.0 | WCF

What’s New in WCF 4.0? An Early Look at Forthcoming WCF Features

T

his month’s column explores the next generation of features to be released with WCF 4.0 when the .NET Framework 4.0 ships.

The .NET Framework 4.0 will be released with Visual Studio 2010 — bringing with it a plethora of new WCF features. WCF 4.0 will solve many pain points related to configuration, tracing and diagnostics, serialization, and messaging. In addition, this release will include exciting new enterpriseready features, such as service discovery and routing, and, when combined with the power of WF 4.0, Workflow Services will greatly simplify how developers incorporate asynchronous programming models to offset expensive IOintensive operations and improve overall application performance and throughput. To provide you with a well-rounded view of the forthcoming release, I’ll provide in this article a high-level summary of features we know will be released with WCF 4.0. In subsequent articles I’ll explore these features in greater detail.

Simplified Configuration One of the major pain points experienced by WCF developers is configuration. In WCF 4.0 we can look forward to a significant improvement in this area through configuration defaults, behavior inheritance, and implicit endpoints. Collectively, these features can yield a truly configuration-free experience when you host your WCF services. 22

April 2009

| www.aspnetPRO.com

The idea is that you provide better binding configuration and behavior defaults for your specific application’s requirements, and the runtime picks up those defaults when it initializes the ServiceHost. Figure 1 illustrates providing default settings for WS2007HttpBinding and several behavior defaults. They are noted as defaults by using an empty string (“”) for the binding and behavior name. When the ServiceHost is initialized, an endpoint will be created automatically for each contract implemented by the service type — for each base address provided. When you combine this behavior with default binding configurations and behavior settings, configuration-free hosting actually seems plausible.

<bindings> <ws2007HttpBinding> <binding name="" maxReceivedMessageSize="1000000" > <readerQuotas maxArrayLength="1000000" maxStringContentLength="50000"/> <security mode="Message"> <message clientCredentialType="UserName" negotiateServiceCredential= "false" establishSecurityContext="false" /> </security> </binding> </ws2007HttpBinding> </bindings> <behaviors> <serviceBehaviors> <behavior name=""> <serviceMetadata httpGetEnabled="true"/> <serviceCredentials> <userNameAuthentication userNamePasswordValidationMode="MembershipProvider"/> </serviceCredentials> <serviceAuthorization principalPermissionMode="UseAspNetRoles" /> <serviceThrottling maxConcurrentCalls="30" maxConcurrentSessions="1000"/> </behavior> </serviceBehaviors> </behaviors>

Figure 1: Binding and behavior defaults in WCF 4.0.


Serialization Enhancements The new DataContractResolver will provide new extensibility that are hooks useful for customizing CLR type mapping for the DataContractSerializer. This can be useful for simple overrides such as altering the name and namespace for CLR types written to the wire, for overriding which CLR types are involved in serialization, and for dynamically managing known types.

Queued Messaging ReceiveContext To guarantee exactly one instance of delivery of messages from a queue in Microsoft Message Queuing (MSMQ), you must work with transactional queues and the WCF service operation must participate in the playback transaction. If an exception is thrown while processing the message, the service can guarantee the message doesn’t get lost by returning it to the queue — either the originating queue, the dead letter queue, or a poison message queue, depending on configuration and MSMQ versions. This is quite useful, but has limitations in that there is no way to ensure the same service processes the failed message the next time it is pulled from the queue, not to mention that transactions are expensive. WCF 4.0 introduces ReceiveContext as an alternative technique for processing queued messages. The thrust of

this new technique is that the message is not pulled from the queue until the message is successfully processed by the service. A ReceiveContext is associated with the message once it is “peeked� by a service and if an exception is thrown and the message cannot be completed, it remains in the queue — but also can remain locked by that particular service to retry processing. This reduces overhead because the message need not be transmitted over the network again to another service. ReceiveContext provides a way to explicitly complete the message so that it can be removed from the queue on success. ReceiveContext guarantees at least one delivery when used without transactions — and when composed with transactions it guarantees exactly one delivery with performance benefits.

Web Programming Since the release of .NET 3.5 it has been much easier to build WCF services that bypass SOAP processing requirements, including Plain-Old-XML (POX), Java Script Object Notation (JSON), and Representational State Transfer (REST) — the latter of which is an architectural approach for designing POX or JSON services. These techniques fall under the Web programming model for WCF services. Microsoft also released the WCF REST Starter Kit, which considerably improves productivity when building services

*O UIFTF VODFSUBJO UJNFT ĂśOBODJBM FYQFSUT BHSFF

5IF FDPOPNZ NBZ MFU ZPV EPXO CVU XF OFWFS XJMM

(P XJUI 7BMVF

03$4 8FC JT .JDSPTPGU (PME $FSUJĂśFE BOE IBT ZFBST PG TFSWJOH CPUI TNBMM BOE MBSHF PSHBOJ[BUJPOT %PO U KVTU UBLF PVS XPSE GPS JU BTL PVS DMJFOUT XXX PSDTXFC DPN DMJFOUT 4FF XIBU UIFZ TBZ BCPVU PVS DPNQMFUF DPNNJUNFOU UP UIFJS TBUJTGBDUJPO BOE TVDDFTT -FU VT ĂśOE B QMBO UIBU NFFUT ZPVS OFFET CPUI OPX BOE BT UIFZ FWPMWF +PJO UIF 03$4 8FC DPNNVOJUZ UPEBZ

asp.netPRO | April 2009

23


Get ready for‌

AJAX Controls Presenting RadControls for ASP.NET AJAX. Faster than ever. New HTTP and ViewState Compression RadControls allow you to compress your entire AJAX traffic completely codelessly resulting in 10x less traffic and 2x faster page load.

Client-Side Rendering and Databinding RadControls provide rich client-side features, declarative binding to WebServices and built-in support for lightweight JSON calls, enabling unprecedented performance.

Performance Optimization Helper Controls RadScriptManager and RadStylesheetManager enable you to easily combine in to a single link all of the JavaScript and CSS links required by the RadControls, reducing the number of resource requests and improving page load performance.

CSS Sprites for Minimal Server Traffic RadControls use CSS sprites to combine numerous images into 1 so you have only 1 request to the server and faster loading pages.

Semantic Rendering for Minimal HTML Output Relevant controls use list items and advanced CSS rather than HTML tables in order to keep the page output clean, minimal and search engine (SEO) friendly.

www.telerik.com/TopPerformance ASP.NET AJAX

WinForms

WPF

Silverlight

Reporting

OpenAccess ORM

Sitefinity CMS

UI Test Studio

64 4BMFT t (FSNBOZ 4BMFT t &VSPQF )2 t F NBJM TBMFT!UFMFSJL DPN


Exploring WCF Services |

What’s New in WCF 4.0?

WS-Addressing semantics or MTOM. Thus, a new profile was born: BP 1.2. This new profile addresses errata for BP 1.1 and includes support for WSAddressing and MTOM. WCF 4.0 will support this profile. Do not confuse BP 1.2 (based on SOAP 1.1) with BP 2.0 (based on SOAP 1.2), which is still a work in progress.

Service Discovery

Figure 2: Discovery probes and announcements from a high level.

for this Web programming model. The WCF REST Starter Kit includes the following:  Many Visual Studio templates for the most common scenarios for POX, REST, and Atom/Pub.  New features to support better error reporting to the browser. Supporting types are WebProtocolException and new behaviors installed with WebServiceHost2 and WebServiceHost2Factory.  A much needed extensibility hook for HTTP requests through RequestInterceptor.  The ability to more easily override HTTP verbs for clients that don’t support PUT and DELETE.  Cached operation responses with WebCacheAttribute.  Tons of code samples illustrating how to work with these features. The idea behind releasing the starter kit was to get these features into the hands of RESTful WCF developers so they could provide feedback on features so .NET 4.0 can include the most relevant features and include any refinements. Thus, many of these features will be included in the WCF 4.0 feature set.

Speaking of protocol support, WCF 4.0 includes a long-awaited implementation of WS-Discovery. This specification documents a multicast protocol that issues SOAP messages over UDP. Services that implement discovery endpoints can receive probe messages from clients that wish to discover services within their subnet. In addition, services can announce themselves to clients listening for announcements. Figure 2 illustrates the flow of communication between clients and services. Discovery messaging works because communication endpoints are well-known UDP addresses. WCF 4.0 makes it very easy to implement service discovery with a few simple steps:  Services that wish to be discoverable implement a discovery endpoint and enable discovery with a service behavior.  Services that wish to send discovery announcements enable announcements as part of the discovery behavior.  Clients that wish to probe services within the subnet use a built-in DiscoveryClient and supply heuristics for searching for the desired services. There are many architectural scenarios that can implement discovery, and this will be the subject of a future article.

Router Service Routers can be very useful when you need to introduce load

Basic Profile 1.2 As you may be aware, there are a number of standards bodies that drive specifications implemented by platforms like WCF, including W3C (www.w3c.org), OASIS (www.oasisopen.org), and WS-I (www.ws-i.org). The goal of the latter is to simplify how the plethora of standards is implemented in vendor platforms. In WCF, BasicHttpBinding supports Basic Profile (BP) 1.1, which is based on SOAP 1.1. This profile is grossly out of date, and does not support 26

April 2009

| www.aspnetPRO.com

Figure 3: Configuring the RouterService in WCF 4.0.


 Increased visibility through correlated WF tracking and WCF tracing events.  Greatly simplified approach to implementing asynchronous programming models; for example, issuing downstream service calls in parallel and correlating responses.  Implementing declarative (XAMLX) services, which provide an alternative to deploying, updating, and versioning — and make it pos- sible to deploy Workflow Services to the cloud.

High-performance Tracing

balancing using custom heuristics, content-based or priority routing, versioning scenarios, or when you need to introduce a security boundary between remote clients and services that live behind the DMZ. Implementing a custom router is a significant undertaking, but WCF 4.0 aims to relieve this effort by supplying us with a built-in router equipped to work with one-way, two-way, and duplex messaging.

WCF 4.0 trace events are based on Event Tracing for Windows (ETW), which significantly enhances tracing and diagnostics performance. From a high level, the architecture of ETW is simple: event providers push events to sessions under a registered provider ID, controllers are used to enable or disable sessions that collect events and associate providers with sessions, sessions can optionally persist events to a log, and consumer applications listen to real-time session events or pick events up from trace logs. ETW is buffered to reduce contention when persisting events to a file-based trace log. Figure 4 illustrates this architecture.

You host the new RouterService as you would any other WCF service, then configure routing rules using a filter table and a set of associated filters. The filters are ultimately evaluated to determine the correct downstream service endpoint to forward messages to. This architecture is illustrated in Figure 3.

Both WCF and WF share the same ETW event provider so that a correlated view can be presented for WF tracking events and WCF tracing events — which is very useful for troubleshooting Workflow Services. Furthermore, Dublin provides a friendly interface to enabling and configuring tracking and tracing through IIS Manager.

Many filtering options are available through a simple configuration, such as XPath queries for content-based routing and queries based on the SOAP action header. There also are extensibility hooks available for deeper control over filters and routing decisions.

Conclusion

Figure 4: WCF tracing and WF tracking with ETW.

Workflow Services New features in WCF 4.0 and WF 4.0 yield a more compelling story for implementing services operations as Workflow Services. In .NET 3.5 one usually restricted the use of Workflow Services to asynchronous, long-running processes that could withstand the overhead of the Workflow Runtime. In .NET 4.0, the Workflow Runtime performance is significantly improved, thus removing that limitation. Instead, the choice to use Workflow Services is purely driven by design choices and singular benefits, such as:

Additional Resources  Learning WCF (O’Reilly, 2007; reprinted for VS 2008, July 2008): www.thatindigogirl.com (get all the book code here!)  Michele’s blog: www.dasblonde.net  IDesign: www.idesign.net

The new features in WCF 4.0 traverse a number of areas, including configuration, tracing, serialization, message queuing, service discovery, routing, and workflow services. All of these new features specifically address pain points that developers experienced with earlier versions of WCF. I’ll explore these enhancements in greater detail in future columns. </>

Michele Leroux Bustamante is Chief Architect of IDesign Inc., Microsoft Regional Director for San Diego, and Microsoft MVP for Connected Systems. At IDesign Michele provides training, mentoring, and high-end architecture consulting services focusing on Web services, scalable and secure architecture design for .NET, federated security scenarios, Web services, interoperability, and globalization architecture. She is a member of the International .NET Speakers Association (INETA), a frequent conference presenter, conference chair for SD West, and is frequently published in several major technology journals. Michele also is on the board of directors for IASA (International Association of Software Architects), and a Program Advisor to UCSD Extension. Her latest book is Learning WCF (O’Reilly, 2007; updated in 2008); visit her book blog at www.thatindigogirl.com. Reach her at mlb@idesign.net, or visit www.idesign.net and her main blog at www.dasblonde.net. asp.netPRO | April 2009

27


a s p: Fea tu re languages: C# | VB.NET

 asp.net versions: 3.5

 By Austin Avrashow

The Best of Both Worlds Introducing the ASP.NET Silverlight Controls

S

ilverlight 2 has been released. For you as an ASP.NET developer, is that ho-hum or hurrah? They both create visible programs that run in a

browser, so are they competing or complementary technologies? Are they like oil and water — interfering with each other and best used separately? Or are they like peanut butter and jelly — both good, but better together? It turns out that although some situations are best with one or the other, many scenarios benefit from both technologies used together. And as we’ll see in this article, using them together couldn’t be easier.

Getting the ASP.NET Silverlight Controls There are two new ASP.NET server controls in the ASP.NET toolbox that open up possibilities previously difficult or impossible to do on an ASP.NET page:  The ASP.NET Silverlight control lets you embed compiled Silverlight content into an ASP.NET Web page.  The ASP.NET MediaPlayer control provides an easy way to add audio or video playback capabilities to an ASP.NET Web page. To get these controls, you need to download and install the Microsoft Silverlight Tools for Visual Studio 2008 Service Pack 1 (go.microsoft.com/fwlink/?LinkId=128134). Be sure to uninstall any earlier CTP or beta versions before installing the Silverlight Tools for Visual Studio 2008 SP1. This also installs the Silverlight 2 runtime you’ll need to test your project, as well as a Silverlight 2 project template for Microsoft Expression Blend 2 Service Pack 1, although Blend is not required to create Silverlight content. After you install the Silverlight tools, two new controls are available in the Toolbox in Visual Studio 2008, as shown in Figure 1. 28

April 2009

| www.aspnetPRO.com

Figure 1: Toolbox with Silverlight controls.

Adding the Silverlight Control to a Web Page With the ASP.NET Silverlight control, you can easily integrate Silverlight content into any ASP.NET Web page. Let’s add a Silverlight application to an existing ASP.NET page. To follow along on your computer, download the accompanying files for this article (see end of article for download details). All you need for this procedure is the MoodIndicator.xap file. Compiling a Silverlight project produces a .xap file as the output. This file combines all the scripts and resources and assemblies into a single file. This file (in zip format) is what the Silverlight control uses to display Silverlight content on an ASP.NET page. First, create a new Web site or Web project with Visual Studio 2008 SP1. You also can use Visual Web Developer 2008 Express Edition with SP1. On the Default.aspx page, add a ScriptManager control between the opening and closing tags for the form element. This control is necessary because the


plug-in is installed (and whether the required minimum version is present) and displays an image that prompts the user to download the Silverlight plug-in or update the plug-in to the required version.

Figure 2: Silverlight content in an ASP.NET Web page.

Silverlight server control creates an AJAX client control in the HTML sent to the browser. The ScriptManager control is located in the AJAX Extensions area of the Toolbox. Next, drag a Silverlight control from the Toolbox below the ScriptManager control and before the closing form tag. The Silverlight control is located in the Silverlight area of the Toolbox, as shown in Figure 1. This adds a Register directive to the page for the Silverlight assembly and also sets references to the Silverlight DLL added to the Bin folder. Then right-click on the Web site in Solution Explorer. Choose Add an Existing Item, then navigate to the MoodIndicator.xap file in the source files that accompany this article and add it to the project. Set the Source property of the Silverlight control to the MoodIndicator.xap file. Change the Width and Height properties of the Silverlight control to 400px (the default is 100 pixels). Press F5 to view the page in the browser. Interact with the buttons to indicate your current mood (see Figure 2). This scenario (where you have a compiled Silverlight application to place on an .aspx page) happens more often than you might think. If a designer or a different group is responsible for creating the Silverlight application, they will provide you with a single .xap file that you will add to an ASP.NET Web site using the steps described in the previous procedure. That’s all you need to do. And even if you are the person developing the Silverlight application, it’s helpful that the only point of contact between Silverlight and ASP.NET is a single .xap file. This allows you to work on the Silverlight application or ASP.NET page independently without affecting the other. The users viewing the page will need to have the Silverlight plug-in installed, but the control detects whether the Silverlight

That functionality is provided automatically, but you can customize the experience for Figure 3: Solution Explorer with two users who do not have projects. the Silverlight plugin installed. You might provide a different graphic than the default image for users who don’t have Silverlight installed, perhaps displaying an image showing what they’ll see on the page if they download and install the plug-in. To customize the experience for users who don’t have the plugin installed, set the PluginNotInstalledTemplate property on the ASP.NET Silverlight control to indicate the HTML to display rather than display the standard Install Silverlight graphic.

Creating Silverlight Content and Testing It on an ASP.NET Page You may need to create the Silverlight application for use with ASP.NET. Visual Studio 2008 SP1 not only lets you create Silverlight content, but also can provide a test project to host the Silverlight application development. Let’s create a Silverlight project and test it on an ASP.NET page: 1) Create a Silverlight Application project with Visual Studio 2008 SP1. Choose either C# or Visual Basic as the language. Name the project MoodIndicator. 2) When prompted whether to create a Web project to host the Silverlight application, click OK. Visual Studio creates a solution with two projects (see Figure 3). 3) Open Page.xaml. Delete its existing content and replace it with the code in Figure 4. Notice that the Path element has a name assigned to it (Name=“mouth”). This is so we can access that element in code in the next step. 4) Open the Page.xaml.cs or Page.xaml.vb code-behind file (depending on your language choice). Add the code for the two button click event handlers for C# (see Figure 5) or Visual Basic (see Figure 6). These event handlers apply a transform to the “mouth” when someone clicks on one of the Silverlight application buttons. 5) Choose Rebuild Solution from the Build menu. This compiles the project and copies the compiled MoodIndicator.xap Silverlight application to the ClientBin folder of the MoodIndicator.Web project (the test project). asp.netPRO | April 2009

29


asp:Feature

|

The Best of Both Worlds

<UserControl x:Class="MoodIndicator.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="300" Height="280"> <Grid x:Name="LayoutRoot" Background="White"> <Ellipse HorizontalAlignment="Stretch" Margin="86,44,64,86" Fill="#FFFFFF00" VerticalAlignment="Stretch"/> <Button Height="32" HorizontalAlignment="Left" Margin="72,0,0,24" VerticalAlignment="Bottom" Content="Happy" Name="btnHappy" Width="72" Click="btnHappy_Click" /> <Button Height="32" HorizontalAlignment="Right" Margin="0,0,48,24" VerticalAlignment="Bottom" Content="Sad" Name="btnSad" Width="72" Click="btnSad_Click"/> <Ellipse Height="30" HorizontalAlignment="Left" Margin="120,78,0,0" VerticalAlignment="Top" Width="24" Fill="#FFFFFFFF" Stroke="#FF000000" StrokeThickness="2" /> <Ellipse Height="30" HorizontalAlignment="Right" Margin="0,78,98,0" VerticalAlignment="Top" Fill="#FFFFFFFF" Stroke="#FF000000" Width="24" StrokeThickness="2" /> <Path Height="25" HorizontalAlignment="Stretch" Margin="120,0,98,108" Name="mouth" VerticalAlignment="Bottom" Stretch="Fill" Stroke="#FF000000" StrokeThickness="4" Data="M120,200 C120,200 130,223 160,223 C190,223 200,200 200,200" /> </Grid> </UserControl>

Figure 4: The Page.xaml file. private void btnHappy_Click(object sender, RoutedEventArgs e) { ScaleTransform txfr = new ScaleTransform(); txfr.ScaleY = 1; this.mouth.RenderTransform = txfr; } private void btnSad_Click(object sender, RoutedEventArgs e) { ScaleTransform txfr = new ScaleTransform(); txfr.ScaleY = -1; this.mouth.RenderTransform = txfr; }

Figure 5: Event handlers in Page.xaml.cs. Protected Sub btnHappy_Click(ByVal sender As Object, _ ByVal e As EventArgs) Handles btnHappy.Click Dim txfr as New ScaleTransform txfr.ScaleY = 1 Me.mouth.RenderTransform = txfr End Sub Protected Sub btnSad_Click(ByVal sender As Object, _ ByVal e As EventArgs) Handles btnSad.Click Dim txfr as New ScaleTransform txfr.ScaleY = -1 Me.mouth.RenderTransform = txfr End Sub

Figure 6: Event handlers in Page.xaml.vb.

6) Press F5 to run the test.aspx page of the MoodIndicator.Web project. 7) The MoodIndicatorTestPage.aspx file is displayed in the browser. Use the buttons to indicate your mood. Notice that Silverlight buttons display a hover effect when the mouse is over them. 30

April 2009

| www.aspnetPRO.com

Notice in Figure 3 there also is a MoodIndicatorTestPage.html page in the test project. You can right-click on that file and choose View in Browser to display the compiled Silverlight .xap file on an HTML page. Each time you compile the Silverlight project, Visual Studio copies the compiled .xap file into the ClientBin folder of the test project.

Microsoft Expression Blend 2 Although we’ve seen that you can author Silverlight content in Visual Studio 2008, you might choose to use Blend 2 SP1 to create Silverlight 2 content because you can work interactively on the design surface in Blend, which often is easier than working in the XAML code as currently required in Visual Studio 2008.

You can work directly in XAML with either tool, but only Visual Studio currently provides IntelliSense. I used Blend 2 SP1 to create the ellipses and paths for the Silverlight control in this article. I stripped out the Blend-only display attributes, which Visual Studio ignores, for readability.

The MediaPlayer Control The ASP.NET MediaPlayer control offers a simple way to add audio or video to an ASP.NET Web page. You might think that only a site that specializes in delivering video would use media on a Web page, but consider how an ASP.NET Web site might use video or audio:  video demonstration of a new product or feature  installation, repair, or maintenance from tech support  a message from the CEO to employees or Web site visitors  testimonials from satisfied clients  video messages to team members or sales personnel  a video tour of homes for sale  in-house training  excerpts from training classes offered to the public  demonstrations on preparing delicious foods from the Northwind products catalog  audio clips for any of the above

Adding Audio or Video to a Web Page To play audio or video on a Web page, you must add the ASP.NET MediaPlayer control to the page and set the MediaSource property to the name and location of the audio or video file. This control is included in the Silverlight Tools you downloaded earlier. The MediaPlayer control inherits from the Silverlight control, but instead of allowing you to have any type of Silverlight content on a page, it is limited in functionality to provide a customizable skin that offers users the ability to stop and start playback, adjust the volume, skip to a specific chapter, etc.


Figure 7: MediaPlayer Tasks window.

Users viewing the page need to have the Silverlight plug-in installed, but this control inherits from the ASP.NET Silverlight server control and so will detect whether the plug-in is already installed and display a prompt if the plug-in is not installed. To add video or audio to a Web page: 1) Create a new Web site named VideoPlayer. 2) In the Default.aspx page add a ScriptManager control below the opening tag for the form tag and before its closing tag. 3) Right-click on the Web site in Solution Explorer and choose Add an Existing Item. Select any .wmv video file on your system. You can use the Dulcimer.wmv video file that you can download with the source files for this article. 4) Drag a MediaPlayer control from the Toolbox to be inside the form tag and below the ScriptManager control. The MediaPlayer control is in the Silverlight section of the Toolbox (again, Figure 1). 5) In Design View, the MediaPlayer control displays a smart tag window, as shown in Figure 7, where you can set some properties. 6) Set the MediaSource property to the video file you added to the project. 7) You can click Import Skin if you want to use a different MediaPlayer skin (Professional is the default). You can select the Auto-play checkbox if you want playback to begin when the page loads. If the Auto-play checkbox is not selected, users will need to click the start button on the MediaPlayer to begin playback. Using the Property window you can set the Height and Width of the control to any value appropriate for your video file. 8) Press F5 to display the default Web page in a browser. You can play or pause the video, as shown in Figure 8. Most MediaPlayer skins have built-in full-screen playback capability, so someone watching the video can switch to or from full-screen mode by double-clicking on the video or clicking the full-screen button, if the skin provides one.

Figure 8: Video on an ASP.NET page.

you can interact with the control programmatically to change any of its properties. A postback is required to change properties currently in the browser. For example, you could allow users to select which video to play from a DropDown control that, when the selection changes, sets the MediaSource property on a MediaPlayer control and causes a postback to occur. When an .aspx page with a MediaPlayer server control is rendered as HTML sent to the browser, a MediaPlayer client control is generated in the HTML. You can interact with the MediaPlayer client control’s properties, methods, and events at run time using scripting. See the documentation for the clientside MediaPlayer control (in the Sys.UI.Silverlight.MediaPlayer namespace). Wei-Meng Lee’s article “Media Guide” in the April 2008 issue of asp.netPRO has many examples of how to customize the appearance and add client-side scripting functionality to the MediaPlayer control.

Conclusion To add Silverlight content or media content to your ASP.NET Web sites, all you need is the free Silverlight Tools download from Microsoft. As you can imagine, there’s much more you can do with these controls. Think about situations where you might want to add rich Silverlight functionality or a splash of video or audio and you’ll find you are limited only by your imagination. </>

How It Works

Source code accompanying this article is available for download to asp.netPRO subscribers at www.aspnetPRO.com/ download.

The MediaPlayer control wraps the functionality of a Silverlight MediaElement object and allows you to simply place the control on a Web page and determine which media file to play. Because the MediaPlayer is an ASP.NET server control,

Austin Avrashow is a contract technical writer at Microsoft, most recently with ASP.NET User Education. asp.netPRO | April 2009

31


a s p: Fea tu re languages: C#

 By Jeffrey Hasan

asp.net versions: ALL 

More Smart SEO URL Rewriting and Redirection Using the IIS 7.0 URL Rewrite ModuleBy Jeffrey Hasan

S

earch Engine Optimization (SEO) has become the major driver for Uniform Resource Locator (URL) rewriting in Web sites. URL rewriting involves

intercepting an incoming HTTP request and remapping the original URL request to an alternate URL. URL redirection publicly notifies the site visitor of a temporary or permanent change in the URL they requested. URL rewriting and redirection are not the same thing. URL rewriting recognizes URL pattern matches, then rewrites the incoming URL to a different internal URL. The action of rewriting a URL can be done “silently” without notifying the visitor of an official redirect, using HTTP status codes 301 and 302 (for permanent and temporary redirection, respectively). URL redirection employs the same pattern matching process as URL rewriting, but then takes the process one step further by redirecting the site visitor and sending them an official HTTP status code.

combine the URL rewriting pattern matching process with public notification to the site visitor of a change in the URL. URL rewriting in IIS 5 and 6 is a manual coding and configuration effort, although third-party tools make the task easier. The task is much easier in IIS 7.0, courtesy of the newly released Microsoft URL Rewrite module, which is available as a free download from www.iis.net/. The focus of this article is on URL rewriting and redirection using the IIS 7.0 URL Rewrite module. Note: This article focuses on URL rewriting and redirection using IIS 7.0. For a complete discussion of SEO and URL rewriting in previous versions of IIS, please consult my previous article, “Smart SEO: URL Rewriting Using ASP.NET and IIS 6.0”, in the March 2009 issue of asp.netPRO.

Feature

Description

Rules-based URL rewriting engine

The core function of the module is to process URL rewrites using configured rules. The module also supports rule actions that follow rewrites, including redirects. Rewrite rules can be established globally, or for a specific Web application, where the rules are encoded within the web.config file. Rewrite rules establish the mappings between requested URLs and their rewritten replacement URLs.

GUI support

The module provides graphical user interface screens to configure and test URL rewrite rules, and their follow-up actions. It also provides screens to manage rewrite rules and maps.

Rewrite maps

Rewrite maps group sets of rewrite rules.

Failed request tracing support

A feature of IIS 7.0 that helps you troubleshoot failed URL rewrites.

For instance, here’s an example of an SEO-friendly URL for an HP printer on an e-commerce site: http://www.jeffshop.com/printers/hp/P1006/ Here’s an alternate URL for the same product, constructed in a development-friendly format: http://www.jeffshop.com/printers.aspx?mfr= hp&model=p1006 URL rewriting is useful when you want to expose SEO-friendly URLs, but map them internally to a different URL format or site structure. URL redirection is useful when you want to 32

April 2009

| www.aspnetPRO.com

Figure 1: Features of the IIS 7.0 URL Rewrite module.



Instantly Search Terabytes of Text ◆ dozens of indexed, unindexed, fielded

data and full-text search options (including Unicode support for hundreds of international languages) ◆ file parsers / converters for

hit-highlighted display of all popular file types ◆ Spider supports static and dynamic web

data; highlights hits while displaying links, formatting and images intact

|

More Smart SEO

Colors: Cyan, Magenta, Yellow, Black

1-2008 dtSearch 7 AD: CMP ASP.netPRO1/3 page Vertical 2.1806 x 9.75 tall

asp:Feature

◆ API supports .NET, C++, Java, databases,

etc. New .NET Spider API

Figure 2: The URL Rewrite module under IIS 7.0 management console.

Introduction to the IIS 7.0 URL Rewrite Module The IIS 7.0 URL Rewrite module provides rules-based URL rewriting and redirection capabilities. The module coordinates with IIS 7.0 to intercept URL requests before they are processed by the Web server. Rewrite rules can be configured using a forms-based utility that is accessible from the IIS management console. Or, you can directly edit rules in the Web application’s web.config file. The URL Rewrite module provides several features, as outlined in Figure 1. h Spider Desktop wit h Spider Network wit CD/DVDs Publish for ider Web with Sp Win & .NET Engine for Linux Engine for

New 64-bit

The Smart Choice for Text Retrieval ® since 1991 ◆ “Bottom line: dtSearch manages a

terabyte of text in a single index and returns results in less than a second” – InfoWorld ◆ “For combing through large amounts

of data,” dtSearch “leads the market” – Network Computing ◆ dtSearch “covers all data sources ...

powerful Web-based engines”– eWEEK ◆ dtSearch “searches at blazing speeds”

– Computer Reseller News Test Center See www.dtsearch.com for hundreds more reviews, and hundreds of developer case studies

Contact dtSearch for fully-functional evaluations

1-800-IT-FINDS www.dtsearch.com 34

April 2009

| www.aspnetPRO.com

This article will not cover every available feature in the URL Rewrite module, but rather will cover two important features that will help you get comfortable with using this tool. The features we’ll cover are:  Create a URL rewriting rule using regular expressions.  Rewrite and redirect a URL using pattern matching by example. The URL Rewrite module is versatile, and we’ll demonstrate how you can use the tool with both regular expressions and auto-generated pattern matches, which the tool generates for you based on examples you provide.

Installing the URL Rewrite Module You can download the URL Rewrite module from www.iis.net/downloads/ default.aspx?tabid=34&g=6&i=1691. The module will install on both 32bit and 64-bit versions of the Microsoft Vista operating system (as well as Windows Server 2008). You must have administrator privileges to install the module. When the installation is complete, restart your machine, then browse the IIS management console; you’ll see a new icon entitled “URL Rewrite”, as shown in Figure 2.

Using Visual Studio 2005 with Windows Vista and IIS 7.0 The code and configuration examples in this article are built on Windows Vista and IIS 7.0 using Visual Studio 2008. However, many developers have yet to upgrade from Visual Studio 2005. You can continue to use Visual Studio 2005 on Windows Vista, but you will need to make some minor configuration updates in order to run Web applications under IIS 7.0 using your machine’s http://localhost Web server root. First, make sure you have IIS 7.0 installed on your Windows Vista machine, because it is not installed by default. To do this, go to Control Panel | Programs



asp:Feature

|

More Smart SEO

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="printers.aspx.cs" Inherits="printers" %> <!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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>URL Rewrite Module Test</title> </head> <body> <h1>Printer Product Page</h1> <table> <tr> <td>You Requested:</td> <td><%= Request.ServerVariables["HTTP_X_ORIGINAL_URL"] %></td> </tr> <tr> <td>You Were Served:</td> <td><%= Request.ServerVariables["SCRIPT_NAME"] + "?" + Request.ServerVariables["QUERY_STRING"] %></td> </tr> </table> </body> </html>

Figure 3: Set IIS 6.0 management compatibility.

Figure 5: URL Rewrite Module test page.

and Features and select “Turn Windows features on and off” from the sidebar. You need to expand the IIS 6 Management Compatibility icon and select most of the features, as shown in Figure 3. If you are an advanced user, you also can select the IIS Management Scripts and Tools and IIS ManFigure 4: Run Visual Studio as an agement Service administrator. features, but these are not required for minimum Visual Studio 2005 compatibility. Second, if you want to create IIS 7.0 managed Web applications, you’ll need to run Visual Studio as an administrator when you launch the application from the Programs menu. Figure 4 shows which menu option you need to select. If you don’t run Visual Studio as an administrator, you’ll still be able to create Web sites that run under the local ASP.NET Web server at http://localhost:PortNumber. 36

April 2009

| www.aspnetPRO.com

Figure 6: URL Rewrite rule templates.

URL Rewriting Using Rules with Regular Expressions This first example will show you how to use the URL Rewriting module and regular expressions to map an SEOfriendly URL to the actual URL. The SEO-friendly URL is: http://localhost/URLRewrite/printers/hp/P1006/ The actual URL is: http://localhost/URLRewrite/printers.aspx?mfr= hp&model=p1006 First, create a simple ASP.NET Web application in Visual Studio, named URLRewrite, and configure it to run under IIS 7.0. Add a single ASPX page named printers.aspx and copy in to the page the code shown in Figure 5.



asp:Feature

|

More Smart SEO

<system.webServer> <rewrite> <rules> <rule name="PrintersRedirect"> <match url="^printers/([a-z]+)/([0-9a-z]+)" /> <action type="Rewrite" url="printers.aspx?mfr={R:1} &model={R:2}"" /> </rule> </rules> </rewrite> </system.webServer>

Figure 9: URL Rewrite rule in the web.config file.

Figure 7: URL Rewrite rules property page.

Next, we’ll create a rule that pattern matches the incoming SEO-friendly URL and rewrites the URL to instruct the Web server to serve the intended Web page. First, browse the new Web site named URLRewrite under the IIS manageFigure 8: Test a URL Rewrite pattern match ment console and expression. double-click the URL Rewrite icon. Next, click the Add Rules link to open the available rule templates. Select Blank rule, as shown in Figure 6. Next, fill in the rules property page, as shown in Figure 7.

Figure 10: URL Redirection using the User friendly URL rule template.

http://localhost/URLRewrite/printers/hp/P1006/ The Web page will display the following:

The name of the rule is “PrinterRewrite” and the regular expression pattern match for the incoming rules is: ^printers/([a-z]+)/([0-9a-z]+)

You can click the Test pattern button to test an example, as shown in Figure 8. The example being tested here is the meaningful substring of the full Web site URL: printers/hp/p1006

Finally, apply the changes and you’ll see the new rule listed in the rules summary screen. In Visual Studio, switch over to the Web application’s web.config file and you’ll see that a new section has been added to the web.config file (see Figure 9). To test the URL Rewrite rule, simply browse to the URLRewrite test application using this SEO-friendly URL: 38

April 2009

| www.aspnetPRO.com

Printer Product Page You Requested: /URLRewrite/printers/hp/p1006 You Were Served: /URLRewrite/printers.aspx?mfr= hp&model=p1006 Notice that the original SEO-friendly URL remains in the browser URL field, which is consistent because the rewriting has been done internally. The Web server has been instructed to serve the correct page, but no official redirect is issued back to the client.

URL Redirection Using Rules Redirection is easy to accomplish using the same rule manager. From an SEO perspective, you want the incoming URL requests to be formatted as simply as possible, while preserving your flexibility to serve pages using alternate URLs. So, typically, you would not want to redi-



asp:Feature

|

More Smart SEO

rect the user, you would simply want to rewrite the incoming URL so the Web server knows where to look to service the request.

<rule name="RedirectUserFriendlyURL1" stopProcessing="true"> <match url="^printers\.aspx$" /> <conditions> <add input="{QUERY_STRING}" pattern="^mfr=([^=&]+)&model=([^=&]+)$" /> </conditions> <action type="Redirect" url="{C:1}/{C:2}" appendQueryString="false" redirectType="Permanent" /> </rule> <rule name="RewriteUserFriendlyURL1" stopProcessing="true"> <match url="^([^/]+)/([^/]+)/?$" /> <action type="Rewrite" url="printers.aspx?mfr={R:1}&model={R:2}" /> </rule>

Redirection implies there is a structural change to your Web site that you want the outside world to know about. More importantly, a change that you want search engines to pick up on. Redirection is correctly Figure 11: URL Rewrite rule in the web.config file. accomplished when the Web server returns an HTTP status code 301, which indicates to search engine spiders that a permanent Notice that the redirect type is permanent, which will issue redirection has taken place, and that the link equity and an HTTP status code 301. Finally, open a browser window page ranking of the former page should be transferred to and type in the SEO-unfriendly URL: the newer page. My previous article on SEO (in the March 2009 issue of asp.netPRO) explains in detail why you should http://localhost/URLRewrite/printers.aspx?mfr= never issue HTTP status code 302 temporary redirects. hp&model=p1006 URL redirection is simple using the URL Rewrite module. You create a similar type of pattern matching rule that we created in the previous section, but you add an additional instruction on the rule property page to issue a redirect to the site visitor. The URL Rewrite module provides a rule template named User friendly URL, which you can select from the rule templates page shown in Figure 6. This rule template allows you to specify incoming URLs by example, rather than by regular expression, so you avoid having to create complicated regular expressions. Figure 10 illustrates this. In this example we want incoming SEO-unfriendly URLs to be mapped to their SEO-friendly alternatives. In this case, we want: /URLRewrite/printers.aspx?mfr=hp&model=p1006

You’ll find the URL has been redirected to: http://localhost/URLRewrite/printers/hp/P1006/

Conclusion SEO-driven URL rewrites are essential for preserving hardearned page rank and link equity for Web pages. The URL Rewrite module is a useful tool that will save you time in creating rewrite and redirection rules for Web sites that run under IIS 7.0. The tool has several useful features that we did not touch on, including the ability to return a custom response, and the ability to create rule maps that group multiple pattern matching rules together. For more information on the tool, review the online documentation and examples at www.iis.net/. </> Source code accompanying this article is available for download to asp.netPRO subscribers at www.aspnetPRO.com/ download.

to be mapped to: /URLRewrite/printers/hp/p1006 As Figure 10 shows, simply enter an example of the SEOunfriendly URL, then select from the drop-down list the corresponding URL to which you want it to be mapped. The Substitution URL textbox automatically updates. Finally, check the Create corresponding redirect rule checkbox and click OK. The rule manager screen will now list these two additional rules:  RewriteUserFriendlyURL1  RedirectUserFriendlyURL1 Next, switch to the test application’s web.config file and you’ll see that additional rules have been added to the web.config file (see Figure 11). 40

April 2009

| www.aspnetPRO.com

Jeffrey Hasan, MCSD, is Senior VP of Strategic Consulting Services at Axis Technical Group, Inc. (www.axistechnical.com). He has been a professional systems architect and developer for 12 years. His work focuses on enterprise integration, business intelligence, data warehouses, and workflow-driven portals using SharePoint. Jeff has authored several .NET books, including Expert Service Oriented Architecture in C# (Apress, 2006).


C lo serL oo k

 By Cole Shiflett Rating: ���� Web Site: www.nintex.com Price: Available in workgroup, standard, and enterprise editions. Contact sales for licensing costs at sales@nintex.com.

Nintex Workflow 2007 Ease MOSS Development Pains and Reduce Development Cycle Times

O

ne of the most painful areas of Microsoft Office SharePoint Server (MOSS) development is related to workflow, particularly using Visual

Studio and Workflow Foundations (WF). This development environment provides developers with unparalleled power to code against the ubiquitous .NET Framework, while leveraging the MOSS workflow and task management APIs. However, coding and deploying workflows in this manner does come with downsides: It has a considerably steep learning curve; it’s an environment plagued by incomplete or nonexistent documentation; it has few relevant examples on the Web; and, it has a very complex deployment and debugging environment. This complexity has led many to resort to using the workflow functionality in SharePoint Designer; however, that environment, while reasonably useful and simple to deploy with its no-code approach, has limited ability for custom or advanced functionality. So what is a developer to do — spend weeks (or more) toiling through the trial and error world of WF, or simply limit workflows to the most basic functionality? Fortunately, as MOSS 2007 continues to become more pervasive in the market, products are starting to surface that attempt to ease MOSS development pains and reduce

development cycle times. Workflow 2007 by Nintex is one such product that allows you to create powerful workflows using an intuitive Web-based user interface. The intent of this product seems clear: provide the ease of use and intuitive interface of SharePoint Designer while leveraging the enterprise workflow features of the WF framework. It’s important to note that Workflow 2007 is not a server, nor is it a separate workflow engine. It is a workflow designer tool based on the Workflow Foundations API, built to run inside the MOSS environment and use the MOSS workflow engine. Having experienced the pains of MOSS workflow development firsthand, I was eager to see what Nintex could offer. Installation was very simple, as Nintex has used the standard feature framework to deploy their product. Once installed, the features are available throughout the farm and must be activated at both the site collection and site level (see Figure 1). Administration is handled by extending the Application Management page in Central Administration (see Figure 2). Fortunately, there is little administrative overhead. Most of the items in the administration menu will be addressed only once during the initial installation. All the heavy lifting is done within the workflow designer interface. Once the product is installed, configured, and activated at the col-

Figure 1: Features must be activated at both site collection and site level after installation.

Figure 2: The Nintex administration menu is provided as an extension in Central Administration. asp.netPRO | April 2009

41


CloserLook

|

Nintex Workflow 2007

Figure 3: Workflows are activated by custom options under the Settings menu.

lection and site level, you are ready to start designing a workflow. As noted earlier, this product is designed exclusively for the MOSS environment, which is a significant implementation difference from standard WF. Additionally, workflows are created and deployed at the list level, so activating the workflow designer is achieved through two custom menu options within the Settings menu of a list within the activated site (see Figure 3). When creating a new workflow, you may start with a blank canvas or load one of the many available templates, which then can be modified to suit your needs (see Figure 4). Creating a typical sequential workflow is straightforward, as the product provides a toolbox of drag and drop objects that provides most all of the expected functions of a business workflow, including approval branches, conditions, loops, and various objects to query and manipulate MOSS sites, lists, and items (see Figure 5). There also are integration objects that allow you to call an external Web service, query a SQL data source, query XML, and even integrate with Active Directory. Manipulating the objects when they are on the palette also is simple, with a consistent menu for editing the object display and configuring the functionality. In my first workflow I was able, in about an hour, to call an external ASP.NET Web service, query XML, apply a regular expression, set some workflow variables, and create a simple two-level approval flow. Deployment was equally as simple: Simply select Publish from the Actions menu. As noted earlier, a workflow is created against a single list and activated 42

April 2009

| www.aspnetPRO.com

Figure 4: Workflows can be based on templates or created from scratch.

from the Settings menu of that same list. When published, the workflow is deployed to the list and, at that point, functions in the same manner as any other MOSS workflow. Workflow task forms, for approvals or reviews for example, are automatically created by the tool as custom ASP.NET pages, and links to such are conveniently included in task e-mails. E-mail notifications are customizable and can include custom links and related workflow values. An existing workflow can be easily reopened, modified, and republished. Workflow 2007 is available in three editions: workgroup, standard, or enterprise — the latter of which includes greater integration functionality and some reporting/ monitoring features. However, the look and feel remains the same throughout the different editions. My experience, using the standard edition, was quite positive. I was able to produce a typical workflow of moderate complexity in about an hour. Subsequent updates were applied and deployed with only a few mouse clicks; there was no

Figure 5: The workflow designer provides an intuitive drag-and-drop interface.


Pros

Cons

• Simple installation and deployment • Intuitive drag-and-drop Web interface • Fully integrated into MOSS environment • Based on Workflow Foundations API • Supports sequential and state machine workflows

• Cannot be used outside of MOSS • Does not allow for solution packaging and deployment • Ease of use necessitates a strong governance policy if open to nondevelopers

uninstalling or redeployment of solutions or features. To some, however, this level of abstraction would classify as a negative, as the product provides no way to package a workflow as a solution file and deploy it for re-use across the farm. While this is true, there is the ability to import and export saved workflows and save common workflows as templates. A compelling aspect of this tool is that it is not strictly for developers; a tech-savvy business analyst or project manager easily could create powerful workflows without

the slightest exposure to writing code. Ease of use is a double-edged sword, however, so it’s important to have a good governance model in place to control who has the ability to create workflows. Overall this is a good, affordable product that dramatically improves the workflow development experience in MOSS 2007. Both IT and line of business managers will appreciate the reduced cycle times, and developers will appreciate the speed and power of a tool that allows them to do something easily in MOSS 2007. </>

Cole Shiflett is a Solutions Architect for a large financial services organization in Atlanta, GA. Currently pursuing a graduate degree in Computer Science, Cole holds several certifications, including Microsoft Certified Technology Specialist in MOSS 2007, Sun Certified Java 2 Programmer, and IBM Certified Application Developer in Websphere, and he is a Six Sigma Green Belt. He can be reached at cole.shiflett@gmail.com.

iÌÊ ÀiÊ -*° /Ê v À >Ì Ê i ÛiÀi`ÊÌ Ê9 ÕÀÊ L Ý >ë° iÌ "7Ê ÃÊÌ iÊ , Êi > Ê iÜà iÌÌiÀÊVÀi>Ìi`ÊLÞÊÌ iÊ iÝ«iÀÌÃÊ>ÌÊ>ë° iÌ*,"Ê >}>â iÊÌ >ÌÊ V Õ`iÃÊ } } ÌÃÊvÀ Ê Ì iÊ >}>â iÊÌi> i`ÊÜ Ì Ê À } > ÊV Ìi ÌÊ ÌÊ>Û> >L iÊ> Þ Ü iÀiÊi Ãi°Ê / « VÃÊ V Õ`i\ UÊ-iVÕÀ ÌÞ UÊ*iÀv À > ViÊ> `Ê wÊ}ÕÀ>Ì UÊ7iLÊ À ÃÊ> `Ê ÌÀ à UÊ7iLÊ-iÀÛ Vià UÊ Ü >`Ê/ ÃÉ/ÀÞÊÌ Ã 9"1Ê 9Ê Ê Ê7

,\

ÛiÀÞÊ Ì iÀÊÜii Ê>ë° iÌ "7ÊÜ ÊLiÊ} Û }Ê>Ü>ÞÊ iÊ -ÕLÃVÀ «Ì Ê Vi ÃiÊv ÀÊÌ iÊÌi iÀ Ê,>` ÌÀ ÃÊÃÕ ÌiÊ Ê>ÊV iVÌ Ê vÊ>Ü>À` Ü }ÊV « i ÌÃÊv ÀÊ -*° /Ê `iÛi « i Ì°Ê

Ê­>ÊÌ Ì> ÊÛ> ÕiÊ vÊf ®

Ê - } Õ«Êv ÀÊÌ iÊ>ë° iÌ "7Ê iÜà iÌÌiÀÊÌ `>ÞÊ>ÌÊ

ÜÜÜ°>ë iÌ*,"°V

asp.netPRO | April 2009

43


To o l B o x

ComponentOne Announces Studio for iPhone ComponentOne announced a new product in its line-up: ComponentOne Studio for iPhone. This suite of components enables you to generate Web applications that mimic the iPhone interface and navigation. ComponentOne Studio for iPhone combines with the power of Microsoft ASP.NET to create cutting-edge versions of corporate Web sites that target the iPhone and iTouch devices. ComponentOne is offering a Studio for iPhone subscription at the standard retail price of US$800. ComponentOne Studio Enterprise now includes Stu-

dio for iPhone, along with Studio for WinForms, Studio for WPF, Studio for ASP.NET, Studio for Silverlight, Studio for Mobile, and Studio for ActiveX, and may be purchased for US$1,100. ComponentOne offers online purchase options at www.componentone.com or by telephone at 412.681.4343 or 1.800.858.2739. Visit www.componentone.com/ Store.aspx for more information. ComponentOne Price: US$800 Web Site: www.componentone.com

The Imaging Source Releases TX Text Control Roadmap Software component vendor The Imaging Source recently published its roadmap for the upcoming version of the word processing component family TX Text Control. Apart from the PDF/A support, the company announced a new concept for Web-based document viewing and forms processing. One of the new features of the components for Visual Studio 2005 and 2008 is an extension of the existing Adobe PDF export. In version 15.0, TX Text Control is able to create and save ISO conforming PDF/A documents. In recent years, PDF/A has been getting stronger in the electronic archiving market. Using TX Text Control, PDF/A documents can be created automatically or converted from other supported formats. With the new roadmap, The Imaging Source announced a new concept for Web-based document viewing and forms processing in ASP.NET. Using TX Text Control 15.0, Microsoft Word-compatible forms can be displayed and completed in any browser. The completed form can be processed server-side, printed, or saved as an Adobe PDF document. The final version is planned for the second quarter of 2009. Interested users can start development 44

April 2009

| www.aspnetPRO.com

with the current version of TX Text Control, because TX Text Control 15.0 will be backward compatible. For owners of a one-year subscription, TX Text Control 15.0 will be available free of charge when it is released. For more information visit www.textcontrol.com/blog/ permalink/2008120101/. All versions ship with unlimited free developer support. Users can download an evaluation version from www.textcontrol.com/downloads/trials/. The Imaging Source manufactures the TX Text Control line of software components to edit, convert, create, and modify standardized document formats, such as Office Open XML, DOC, and RTF. Documents can be edited directly in the browser, using the component’s page view, or on the server, using document templates and data from a database. The resulting document can be exported to a number of formats, including Adobe PDF. The Imaging Source, LLC Price: TX Text Control .NET Standard, US$549 (update US$299); TX Text Control .NET Professional, US$1,149 (update US$599); TX Text Control .NET Enterprise, US$2,398 (update US$1,198), TX Text Control .NET Server, US$2,998 (update US$1,498). Web Site: www.textcontrol.com

AppDev OnDemand Released AppDev announced the release of AppDev OnDemand, their online subscription of training for Microsoft technologies. AppDev launches their complete online learning library with more than 60 courses, covering such Microsoft technologies as SharePoint 2007, SQL Server 2005/2008, Visual Studio 2005/2008, and more. AppDev OnDemand subscriptions are available for single courses, learning suites, or the complete library. AppDev OnDemand provides an economical learning solution for individuals and small teams of up to six users. Individuals have full access to the learning and reference resources at their desktop to help them complete projects or learn new technologies, which helps developers and companies stay on budget and within project deadlines. AppDev OnDemand provides step-bystep instruction delivered by Microsoft MVP expert instructors, and is reinforced with hands-on labs, code, printable courseware, and pre/post exams. Users can get on-the-spot answers by jumping to the topics they need, or they can take complete courses with their subscription. With an AppDev OnDemand library subscription, users can take any of the courses from the extensive online learning library for as little as US$45 per course when purchasing the library at the single-user price. In addition to the 60+ courses now, subscribers will receive new courses free for technologies within this library during the year-long subscription period. AppDev OnDemand is available now, with additional courses to be added throughout the upcoming year. Visit www.appdev.com to subscribe to AppDev OnDemand or for more information. AppDev Web Site: www.appdev.com


JetBrains Releases TeamCity 4.0 JetBrains announced the availability of TeamCity 4.0 (www.jetbrains.com/ teamcity), a continuous integration server and distributed build management tool. TeamCity automates routine procedures, streamlines the software development process, improves team communication, and helps development teams implement agile methodology and other industry-best practices. Its key benefits include on-the-fly build feedback, faster builds and better scalability, clean code base, better control over large-scale environments, easy set up and adoption, and extensibility. Starting with v3.0, TeamCity has been free for small and medium-sized teams. New features include:  Build Chains support, which allows breaking down a single build procedure into several parts/ builds that can be run on different build agents using the same sets of sources in all of them.  Tests Re-ordering — tests that are likely to fail are determined and performed first the next time the project builds.

 Possibility to redo any build from a particular version control revision (history builds).  Improved agents authentication mechanics, per-agent CPU-benchmarks, and agents overview statistics matrix.  Statistics for an entire project, and comparative statistics on a single chart.  New integrations, including FxCop and dedicated Rake runner, as well as improvements for old ones, such as MSTest.  Improved Eclipse integration, which brings to the Eclipse world many features previously available only for IntelliJ IDEA users.  User interface improvements: new Project page with project-centric information and statistics, dedicated page for viewing individual test statistics and details, and many improvements in dependencies management.  Some of the plug-ins bundled with TeamCity, such as integrations with Eclipse, ClearCase, and FxCop, are now open source.

DXperience v2008 vol 3 Available from DevExpress Developer Express announced the availability of DXperience v2008 vol 3, providing feature-complete presentation components, reporting controls, IDE productivity tools, and business application frameworks for Visual Studio. Enhancements in v2008 vol 3 include:  a set of new ASP.NET controls: Gauge Control, Filter Editor Control, Data-bound Image Control, and Loading Panel Control  ASP.NET Grid View and HTML Editor for SharePoint  a new WinForms Alert Window Control  Beta 2 of WPF products with a Go-Live license  Beta of the WinFoms RichEdit control  Beta of the Silverlight AgLayoutControl

For a complete list of the new controls, features, and options available in DXperience v2008 vol 3, visit www.devexpress.com/Products/ NET/DXperience/WhatsNew2008v3/ or www.devexpress.com/Support/ WhatsNew/NET/index.xml. If you are currently using older versions of Developer Express products, or are considering switching from competing products, contact clientservices@devexpress.com for upgrade/competitive pricing options. If you have technical questions or require additional pre-sales information, contact info@devexpress.com. Developer Express Price: https://www.devexpress.com/ClientCenter/ Order/default.aspx?group=.NET Web Site: www.devexpress.com

 Numerous other improvements, including notifications, VCS integration, an improved search engine, and more. To learn more about JetBrains TeamCity and to download the latest build, see the official TeamCity site at www.jetbrains.com/teamcity. A free Professional Edition is available for download at www.jetbrains.com/ teamcity/download/index.html. JetBrains, Inc. Price: TeamCity 4.0 is available free of charge for individual developers and small-to-medium teams (free Professional Edition is restricted to 20 build configurations and three build agents). Web Site: www.jetbrains.com

AccuSoft Announces Silverlight Imaging Toolkit AccuSoft, a provider of imaging development toolkits, announced the availability of ImageGear for Silverlight, a comprehensive Silverlight imaging software development toolkit (SDK) for building the next generation of Web imaging applications. Designed for Silverlight 2.0, ImageGear for Silverlight provides developers with high-level controls for rapid application development and features a fast display engine with sophisticated layout options, powerful image processing capabilities, support for 80 image formats, nearly 200 digital camera RAW formats, and more. ImageGear for Silverlight is part of AccuSoft’s ImageGear family of imaging SDKs, which provide developers with everything they need to build and deploy powerful ActiveX, DLL, Java, .NET, and .NET Compact Framework imaging solutions. AccuSoft Corp. Pricing & Availability: ImageGear for Silverlight is available immediately through AccuSoft and its worldwide network of resellers with pricing starting at US$2,995. Web Site: www.accusoft.com asp.netPRO | April 2009

45


To o l B o x

Xceed Adds Data Virtualization to DataGrid for WPF Xceed launched version 3.1 of Xceed DataGrid for WPF Professional Edition. New features, including asynchronous data virtualization and Excel export, have been added to this grid control, designed specifically for Windows Presentation Foundation. A fully functional trial version is available for download from Xceed’s Web site. Xceed DataGrid for WPF Professional Edition marks the debut of five features that users of Xceed’s WPF grid control have most requested. Asynchronous data virtualization has been implemented, which can improve performance and reduce memory usage, particularly when working with large data sources. Because the data virtualization is asynchronous, the UI is decoupled from the data source, which ensures that the application remains responsive as data is being retrieved from the data source. Furthermore, the data virtualization supports caching, pre-emptive loading, and delayed triggering of events to avoid needless querying during scrolling. Programmers have complete control over the number of records in memory and the size of data blocks through the API. Excel export lets the datagrid export its content using either the XMLSS or

the CSV format. Groups, detail content, and statistical functions (formulas and values) can all be exported using this new feature. Developers also can now add the ability to persist datagrid user settings to their applications. As a result, the datagrid can save, then restore, settings, such as the positions, sizes, and states of columns (whether a column is visible and/or fixed, grouping, sorting), in both master grids and details. The API is extensible, so other aspects can be persisted by developers. A column chooser available through a context menu can be used in the datagrid, which lets end-users add or remove columns quickly with a simple right-click in certain regions of the datagrid. Finally, support for UI automation has been added, which enables scriptbased testing and assistive technology, as well as other features, such as clipboard copy support (HTML or CSV), alternating row styles, a delete selected rows command (available in the master grid, in details, or in both), as well as various other minor fixes.

To continuously evolve its components, Dundas offers an extensive line of fully commented add-ons to provide users with the company’s latest features and functionality. Available in ASP.NET and Windows Forms editions, Dundas Chart for .NET is available from the Dundas Web site; a full-featured evaluation copy can be downloaded from the site.

Altova announced the availability of MissionKit v2009, an integrated suite of XML, database, and UML tools. Version 2009 adds new features and functionality across multiple tools in the MissionKit, including support for the Extensible Business Reporting Language (XBRL) standard and native database support for SQL Server 2008, Oracle 11g, and PostgreSQL 8. This release also includes functionality for working with the Health Level Seven (HL7) standard in MapForce, along with new database differencing capabilities in DatabaseSpy and DiffDog, and more. Additionally, Altova is decreasing its prices across the entire Version 2009 product line. Version 2009 adds native support for additional databases to all database-enabled Altova MissionKit tools, including XMLSpy, MapForce, DatabaseSpy, StyleVision, and DiffDog. Current support for SQL Server and Oracle databases is now extended to include the most recent versions (SQL Server 2008 and Oracle 11g). New support for the PostgreSQL database is now available, as well. DatabaseSpy 2009 and DiffDog 2009 both add major new functionality for comparing and merging database content. The new Sequence Diagram Generation feature in UModel 2009 assists developers who need to reverse engineer existing applications written in Java, C#, or Visual Basic. Altova tools are available separately or as part of the Altova MissionKit 2009 tool suite. A complete list of new features is available at www.altova.com/ whatsnew.html. Visit www.altova.com/ download.html to download a 30-day free trial of any Altova product.

Dundas Data Visualization Web Site: www.dundas.com

Altova Web Site: www.altova.com

Xceed Software Inc. Web Site: xceed.com

Dundas Announces Chart for .NET Silverlight Add-on Dundas Data Visualization announced the beta release of Dundas Chart for .NET Silverlight Add-on, which lets users integrate Dundas Chart for .NET into Silverlight applications. All of Dundas’ interactive ASP.NET features are retained or enhanced, including annotations, scale breaks, real-time charting, drill down, full-hit testing, and more. In addition, more than 20 samples with full source code are included. 46

April 2009

| www.aspnetPRO.com

MissionKit v2009 Available


Advertising Index Altova......................................................................................... 3 asp.netNOW............................................................................. 43 Aspose...................................................................................... 7 ceTe Software................................................. Inside Back Cover ComponentOne, LLC ................................. Outside Back Cover DevConnections Conference.................................................. 15 Developer Express.................................................33, 35, 37, 39 dtSearch.................................................................................. 34 FastHosts................................................................................ 17 Infragistics.................................................. Inside Front Cover, 1 ORCS Web.............................................................................. 23 SoftwareFX................................................................................ 5 Syncfusion............................................................................... 11 Telerik................................................................................. 24-25 TextControl................................................................................ 9 asp.netPRO is published monthly by Penton Media, Inc. asp.netPRO, 221 E. 29th St., Loveland, CO 80538. (800) 621-1544 or (970) 663-4700. Advertising rates furnished upon request. Periodicals postage paid at Loveland, Colorado, and at additional mailing offices. Basic one-year subscription rates: U.S. $34.99, Canada $44.99, all other countries $79.99, must be prepaid in U.S. dollars drawn on a U.S. bank. Printed in the USA. For subscription and address changes, call (800) 793-5697 or (970) 663-4700. POSTMASTER: Send address changes to asp.netPRO, 221 E. 29th St., Loveland, CO 80538. Post International Publications Mail Product (Canadian Distribution) Sales Agreement No. 40028783. Code listings may be downloaded from the asp.netPRO Web site at www.aspnetPRO.com. Penton Media, Inc. assumes no responsibility whatsoever for the uses made of any software code in this issue, whether modified or not. Penton Media, Inc. will not be liable for special, incidental, consequential, indirect, or other similar damages, even if we have been advised of the possibility of such damages. In no event will our liability for any damages to you or any other person ever exceed the price paid for your subscription to asp.netPRO, regardless of any form of the claim. Editorial contained within does not necessarily reflect the opinions of Penton Media, Inc. Penton Media, Inc. assumes no responsibility for the products or services advertised within this publication. Copyright©2009 Penton Media, Inc. All rights reserved. No part of this publication may be reproduced in any way without the written consent of Penton Media, Inc. asp.netPRO is a publication of Penton Media, Inc. and is not sponsored by or affiliated with Microsoft Corporation. Microsoft is not responsible in any way for the editorial policy or other contents of this publication. asp.netPRO is a trademark of Penton Media, Inc., Loveland, Colorado. Microsoft and Visual Basic are trademarks of Microsoft Corporation and asp.netPRO is used by Penton Media, Inc. under license from owner. Windows is a trademark of Microsoft Corporation. All other products mentioned within are trademarks of their respective owners. Microsoft, Visual Basic, Visual Studio, MSDN, ASP.NET, and the Visual Studio, .NET, Microsoft Office, and Visual Basic Logos are registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries and are used by LICENSEE under license from owner. We welcome your comments and suggestions about the content of asp.netPRO, as well as your commentary on the subject of ASP.NET development. We reserve the right to edit all submissions. Letters should include your name and address. Please direct all letters to letters.aspnetpro@windevpro.com. Writers interested in having works published in asp.netPRO may obtain a style guide by e-mailing David Riggs at David.Riggs@penton.com. For direct mailings/e-mailings to our subscriber list please contact Walter Karl, Inc. 2 Blue Hill Plaza, 3rd Floor, Pearl River, NY 10965, Marie Briganti (845) 732-7054, Rosalie Garcia (845) 732-7027. To obtain multiple reprints of articles in asp.netPRO or at www.aspnetpro.com, contact Diane Madzelonka at (216) 931-9268 or via e-mail at Diane.Madzelonka@penton.com.

Trailblazer (continued from page 48)

is still comprised of only a small subset of the functionality of WPF, yet the development community has flocked to Silverlight as the platform for their next applications. The guidance is supposed to be that applications built for behind the firewall should be done in WPF, while applications built for outside the firewall should be done in Silverlight (to leverage its multi-platform support). Deployment shouldn’t be a factor anymore, because even WPF applications can be hosted in a Web browser (it requires the .NET Framework 3.5 be installed on the host machine, which shouldn’t be a problem in controlled corporate environments). However, that doesn’t appear to be what is happening. Silverlight development is dominating the landscape for both inside and outside the firewall (where ASP.NET with AJAX doesn’t suffice). Why? Probably because Silverlight is “just good enough” to accomplish what developers need in their applications while allowing them to maintain platform independence. As you can see, the first rendition of a particular technology or concept often isn’t the one that eventually earns the largest market adoption. Often there’s a single factor (price, deployment, platform independence) that is so important that it trumps the other factors and forces a decision to go with a technology that is not preferred. It is important, however, to evaluate each situation separately and choose the technology that fits your current set of requirements, rather than simply using the technology you used last time or that your friends and colleagues are using. I’ve got to run — I just remembered I need to TiVo the premiere of Survivor. </>

Jonathan Goodyear is president of ASPSOFT (www.aspsoft.com), an Internet consulting firm based in Orlando, FL. Jonathan is Microsoft Regional Director for Florida, an ASP.NET MVP, a Microsoft Certified Solution Developer (MCSD), and co-author of ASP.NET 2.0 MVP Hacks (Wrox). Jonathan also is a contributing editor for asp.netPRO. E-mail him at jon@aspsoft.com or through his angryCoder eZine at www.angryCoder.com. asp.netPRO | April 2009

47


BackDraft

 By Jonathan Goodyear Trailblazer

F

orging new ground in any field is a tough thing to do. Doing it with technology can prove even tougher. Aside from building whatever “world-

changing” technology you’ve dreamed up, you need to convince the world that it wants or needs to be changed. Once you’ve done that, you need to hold off the “alsorans” who seek to take your market share away at much less expense than it took you to create the market in the first place.

Here’s an example that is near and dear to me. As you can probably imagine, my schedule is pretty jam-packed. Between running a consulting company and a product/ service company and juggling a family of six, I keep very irregular hours. That is why I love my TiVo (www.tivo.com/). It lets me record my favorite shows and watch them when I eventually get some down time (Sunday afternoon?). Of course, I don’t really own a TiVo. Instead, I have one of the generic Digital Video Recorder (DVR) devices that my cable provider offers. I used to own a TiVo, and, because of its vast superiority in feature set, I often wish I still did. I need seven of them, though (I mentioned my big family, right?), and paying $3 extra per month per device is much more palatable than shelling out $200 per device, plus the higher monthly service fees. No, my generic DVRs have just enough functionality to keep me mostly satisfied. I still call it a TiVo, though, and when I set it to record something, I “TiVo the show”. When you invent something great, your company name often works well as both a noun and a verb. I “Google” things on www.live.com all the time (sorry, Microsoft). The actual TiVo company may not exist 10 years from now as it is slowly gobbled up by commodity alternatives, but its name will be etched into technology parlance for all time. The same sort of trailblazer phenomenon happens in software, as well. An example from the Microsoft files from a few years ago is Windows Forms versus ASP.NET. By almost all accounts, Windows Forms is a better plat48

April 2009

| www.aspnetPRO.com

form for building corporate intranet applications. Features that you must jump through hoops to implement in ASP.NET are trivial to accomplish in Windows Forms. So why are most corporate intranet applications built with ASP.NET? Ease of deployment. ASP.NET applications can be deployed with ease, because it is all server-based. I respectfully waive my dismissive hand at those of you who are now jumping up and down and yelling “ClickOnce”. In my opinion, ClickOnce was dead on arrival, tangled with complications and incompatibilities with certain infrastructure configurations. Most of that has been worked out by now, but does anybody care anymore? Incidentally, ASP.NET applications also share the advantage that they can be repurposed for extranet and external Web site usage, where tight control over the deployment platform is not possible. At the end of the day, ASP.NET is “just good enough” to make it the clear choice for corporate software development. Windows Forms and all of its great features has had to take a back seat. Fast-forward a few years and it’s déjà vu all over again. Microsoft released Windows Presentation Foundation (WPF) as part of Windows Vista back in 2006. I won’t go into the specifics of WPF, but suffice it to say that it represents a quantum leap forward in both visual and functional capabilities for software applications — and pretty much nobody used it. The technical skill barriers to entry are fairly high, and even two and a half years later, there really isn’t a seamless visual designer that gives developers the same easy experience that the Windows Forms designer offers (sorry Expression Blend). Enter Silverlight. A stripped-down derivative of WPF, Version 1 was released more than a year after its predecessor, yet even while in beta it grabbed oodles (I love that word) of attention. All this even though Version 1 didn’t do much more than show video content and didn’t support .NET native languages (you had to use JavaScript). When Silverlight Version 2 was released in 2008, it included .NET native language support, as well as a suite of controls and more enhanced features. Silverlight “Trailblazer” continued on page 47


DynamicPDF Viewer O u r n e w, c u s t o m i z a b l e DynamicPDF Viewer allows you to display PDF documents within any WinForm application. No longer rely on an external viewer for displaying your PDF documents. DynamicPDF Viewer utilizes the proven reliable and efficient Foxit PDF viewing engine and maximizes performance and compatibility with our other DynamicPDF products.

DynamicPDF Converter

Try our three new products FREE today! Fully functional and never expiring evaluation editions available at www.cete.com/download

Our DynamicPDF Converter library can efficiently convert over 40 document types (including HTML and all common Office file formats) to PDF. The conversion can be managed with events fired for success and conversion problems. This is highly intuitive and flexible and integrates well with our other DynamicPDF products.

DynamicPDF Rasterizer Our DynamicPDF Rasterizer library can quickly convert PDF documents to over 10 common image formats including multi-page TIFF. Rasterizing form field values as well as annotations is fully supported. PDFs can also be rasterized to a System.Drawing.Bitmap class for further manipulation. To learn more about these or any of our other popular tools: DynamicPDF Generator, DynamicPDF Merger, DynamicPDF ReportWriter, DynamicPDF Suite, DynamicPDF WebCache or Firemail, visit us online.

ceTe Software has been delivering quality software applications and components to our customers for over 10 years. Our DynamicPDF product line has proven our commitment to delivering innovative software components and our ability to respond to the changing needs of software developers. We back our products with a first class support team trained to provide timely, accurate and thorough responses to any support needs.


STUDIO FOR SILVERLIGHT STOCK PORTFOLIO DEMO

STUDIO FOR IPHONE CTP NOW AVAILABLE

labs.componentone.com/iphone

Studio for Silverlight Produce limitless RIAs: state-of-the-art Silverlight controls • Most complete suite: with 30+ controls you'll find the Silverlight 2

control you need • Developers get ahead of the pack with access to the

best resources: 15+ samples with source code for quick learning

• Runs everywhere and does everything: no need to worry

about HTML or JavaScript compatibility on the Web

Studio Enterprise 2008 v3 delivers exactly what you need to produce next-generation UIs for the Web.

Studio for ASP.NET AJAX-enabled controls for desktop-like experiences on the Web • Lightweight, high-performance Web apps: 3x smaller

footprint, 10x faster performance • Guaranteed compatibility: Web apps perform across all

popular browsers • Code-free styling & animation: dozens of built-in visual

styles & animation effects

Studio for iPhone Build Web apps that look and feel like the native UI of the iPhone and iPod touch • Familiar ASP.NET-based controls: develop without the hassle of

learning a new technology

GET STARTED TODAY DOWNLOAD YOUR FREE TRIAL @

componentone.com/amazingweb

Grids • Charting • Reporting • Scheduling • Menus and Toolbars • Ribbon • Data Input • Editors • PDF

WinForms • WPF • ASP.NET • Silverlight • iPhone • Mobile • ActiveX ComponentOne Sales

1.800.858.2739 or 1.412.681.4343

© 1987-2009 ComponentOne. All rights reserved. iPhone and iPod are trademarks of Apple Inc. All other product and brand names are trademarks and/or registered trademarks of their respective holders.


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.