Sei sulla pagina 1di 52

VisualStudioMagazine.

com

IDE
EVOLUTION
As Visual Studio 2010 takes new form,
will your user experience be enhanced?

PLUS

Build Web Parts with


SharePoint Extensions
Create Templates with XML
Literals, WCF and LINQ

APRIL 2009 Volume 19, No. 4

Work with Managed


Extensibility Framework

Project8

3/17/09

12:39 PM

Page 1

Be The Master On Any Platform

VTCVirtual Training
Center for SharePoint

SharePoint is a trademark or a registered trademark of Microsoft Corporation. DataParts is a registered trademark of Software FX, Inc. Other names are trademarks or registered trademarks of their respective owners.

Project8

3/17/09

12:40 PM

Page 2

Choose AHigher Power For DataVisualization


To master the art of data visualization, you must seek out the leader. For nearly 20 years, Software FX
has risen above all others by supplying 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 best-of-breed data presentation solutions, virtual training for SharePoint, and the
most powerful selection of data monitoring and analysis components. For a world of software that can
raise your work to a higher level, depend on the source thats clearly on top.
Our most popular product, Chart FX allows you to build
charts, gauges and maps with additional vertical visualization
functionality for business intelligence (OLAP), geographic data,
financial technical analysis, and statistical studies and formulas.
Recognized for the past 15 years as the innovator and industry
leader in charting components, Chart FX delivers incomparable
gallery options, aesthetics and data analysis features.

Grid FX was built specifically for Visual Studio developers to


provide a powerful design-time experience right out of the box.
Grid FX includes all Chart FX features, and uses AJAX to
provide robust, run-time functionality in ASP.net applications.
Dynamic controls for presentation aesthetics and analysis allow
easy adaptation to existing applications, and specific tailoring
to corporate brand guidelines.

PowerGadgets puts powerful IT monitoring on your desktop


and in your data sidebar. IT professionals can now create gadgets
that consume data from WMI, Exchange, SQL Server and even
the Windows Registry. PowerGadgets does not require any
development environments, servers or browsers to run real-time
gadget components such as charts, gauges and maps.

Introducing our new products for SharePoint 2007


DataParts is a powerful new way to add interactive business
intelligence to SharePoint portals. With DataParts, visualizing
and analyzing data becomes remarkably easy and code-free.
DataParts includes our complete suite of advanced lists, card
views, charts, digital panels and gauges as web parts that are
easily configured for the type of data desired in just minutes.
With the VTC Virtual Training Center your IT and help
desk personnel will no longer be overloaded with SharePoint
questions and training tasks. VTC is a complete program of
expertly produced, self-paced tutorial modules designed to
empower every user and maximize the value of every SharePoint
feature. VTC installs in minutes on your server, allowing instant
on-demand access for everyone in your organization.

Visit SoftwareFX.com for interactive demos, free trial versions and more
information about our latest products.

Data visualization for every need, every platform

Project1

2/24/09

11:24 AM

Page 1

Your best source for


software development tools!

LEADTOOLS Document
Imaging v 16:
by LEAD Technologies
LEADTOOLS Document Imaging has every
component you need to develop powerful
image-enabled business applications including
specialized bi-tonal image display and
processing, document clean up, high-speed
scanning, advanced compression (CCITT
G3/G4, JBIG2, MRC, ABC) and more.
Multi-threaded OCR/ICR/OMR/
MICR/Barcodes (1D/2D)
Forms recognition/processing
PDF and PDF/A
Paradise #
L05 03201A01 Annotation (Image Mark-up)
C/C++, .NET, WPF - Win32/64
$
99
programmers.com/lead

2,007.

Pragma Fortress SSH


SSH Server for Windows

VMware
Lab Automation
Bundle

dtSearch Engine for Win & .NET


Add dtSearchs blazing speeds
(CRN Test Center) searching and
New
file format support
64-bit
Version!
dozens of full-text and fielded
data search options
file parsers/converters for hit-highlighted
display of all popular file types
Spider supports dynamic and static web data;
highlights hits with links, images, etc. intact
API supports .NET, C++, Java, SQL and more;
new .NET Spider API

Single Server
Paradise #
D29 02101A07

91.99

FarPoint Spread
for Windows Forms
The Best Grid is a Spreadsheet. Give your users
the look, feel, and power of Microsoft Excel,
without needing Excel installed on their machines.
Join the professional developers around the
world who consistently turn to FarPoint Spread
to add powerful, extendable spreadsheet solutions to their COM, ASP.NET, .NET, BizTalk Server
and SharePoint Server applications.
Worlds #1 selling development spreadsheet
Read/Write native Microsoft Excel Files
Cross-sheet formula referencing
Paradise #
F02 01101A01 Fully extensible models
Royalty-free, run-time free

936.99

c-treeACE Professional

TX Text Control 14

by FairCom

Best
Word Processing Components
Seller!
TX Text Control is royalty-free,
robust and powerful word processing
software in reusable component form.

by Datacore
DataCore SANmelody overcomes the high
cost barrier and complexity of traditional
SAN storage. SANmelody converts standard
Intel/AMD servers, blades or virtual machines
(VMs) into fully capable storage servers that
virtualize disks and serve them over existing
networks to application servers. They are simple
to operate, take only minutes to install, and
let you cost-effectively optimize, manage and
protect data storage and disk space.
Paradise #
DCA 01101A06

CALL

programmers.com/datacore

800-445-7899
Prices subject to change. Not responsible for typographical errors.

Paradise #
F01 0131

711.

99

Make your applications faster, easier to deploy,


and more affordable with c-treeACE.
programmers.com/faircom

Crystal Reports 2008

CALL I
programmers.com/vmware

.NET WinForms control for VB.NET and C#


ActiveX for VB6, Delphi, VBScript/HTML, ASP
File formats DOCX, DOC, RTF, HTML, XML, TXT
Professional Edition
PDF export without additional 3rd party
Paradise #
tools or printer drivers
T79 02101A01
Nested tables, headers & footers, text
$
99
frames, bullets, numbered lists, multiple
undo/redo, sections, merge fields
Download a demo today.
Ready-to-use toolbars and dialog boxes

919.

programmers.com/theimagingsource

Enterprise Architect 7.1

by SAP BusinessObjects
Crystal Reports 2008 is a powerful,
dynamic, actionable reporting solution that
helps you design, explore, visualize, and
deliver reports via the web or embedded in
enterprise applications. It enables end
users to consume reports with stunning
visualizations, conduct on report business
modeling, and execute decisions instantly
from the report itself-reducing dependency
on IT and developers.

Visualize, Document and


Control Your Software Project
by Sparx Systems
Enterprise Architect is a comprehensive,
integrated UML 2.1 modeling suite
providing key benefits at each stage of
system development. Enterprise Architect
7.1 supports UML, SysML, BPMN and
other open standards to analyze, design,
Corporate Edition
test and construct reliable, well under1-4 Users
stood systems. Additional plug-ins are
Paradise #
Paradise #
also available for Zachman Framework,
C0N 11101A03
SP6 0001
MODAF, DoDAF and TOGAF, and to
$
99
$
99
integrate with Eclipse and Visual Studio
2005/2008.
programmers.com/sap
programmers.com/sparxsystems

462.

programmers.com/farpoint

SANmelody Kit v2.0

Paradise #
V55 72101A01

Special promotional pricing


expires April 30, 2009.

949.

The c-treeACE database engine is a high performance


database alternative proven by developers in mission
Contains Windows SSH & SFTP Servers. Certified
for Windows Server 2008. Works with PowerShell. critical enterprise systems, desktop deployments, and
embedded devices for over 25 years.
Full-featured server with centralized
Complete set of APIs including ADO.NET, LINQ,
& graphical management
C#, C/C++, ODBC, JDBC, VCL, and dbExpress
GSSAPI Kerberos & NTLM authentication
Graphical productivity tools
Fastest SFTP & SCP file transfer
Simple deployment
Supports over 1000 sessions
No DBA or ongoing administration
Runs console applications & allows history
Low deployment licensing costs
scroll back within the same session
Cross-platform support for all major platforms
Runs in Windows 2008/2003/Vista/XP/2000
including Windows, UNIX, Linux, and Mac OS X
programmers.com/pragma

SAVE 15%
off combined
MSRPs

Bottom line: dtSearch manages a terabyte of


text in a single index and returns results in
$
99
InfoWorld
less than a second.
programmers.com/dtsearch

by Pragma Systems

Paradise #
P35 043X

The VMware Lab Automation bundle


helps IT administrators consolidate lab
infrastructure, reduce storage costs and
eliminate time-consuming provisioning
tasks. Lab users benefit from on-demand
access to system configurations while IT
remains in administrative control.
Includes VMware vCenter Lab Manager
and VMware Infrastructure 3 for 8 CPUs,
and vCenter Server.

182.

Orion Network
Performance Monitor

Virtual Iron Extended


Enterprise Edition

by Solarwinds
Orion Network Performance Monitor is a
comprehensive fault and network performance
management platform that scales with the
rapid growth of your network and expands
with your network management needs.
It offers out-of-the-box network-centric views
that are designed to deliver the critical
information network engineers need.
Orion NPM is the easiest product of its
kind to use and maintain, meaning you
will spend more time actually managing
networks, not supporting Orion NPM.

by Virtual Iron
Virtual Iron Extended Enterprise Edition
provides the most advanced server
virtualization and virtual infrastructure
management capabilities available at
a fraction of the cost.

Paradise #
S4A 08201E02

4,606.99

programmers.com/solarwinds

Unlimited virtual servers


Virtual SMP
Local, iSCSI, FC storage
VLAN
LiveMigration
LiveMaintenance
LiveRecovery

Paradise #
V87L01101A01
$

799.99

programmers.com/virtualiron

programmersparadise.com

0409vsm_TOC_003.v3

3/19/09

2:21 PM

Page 3

April 2009// Volume//19 No. 4

Contents

{ FRAMEWORKS }

16
Michael Desmond, Editor in Chief,
Visual Studio Magazine

Going Large

FEATURES

16

IDE Evolution
Microsoft Visual Studio 2010 promises significant changes, from advanced WPF
customization to support for a number of new and updated technologies. What
does the update mean for developers, and how might Visual Studio 2010 set the
stage for Microsofts flagship IDE down the road? BY KATHLEEN RICHARDS

26

Build and Debug Web Parts with SharePoint Extensions


The SharePoint Extension CTP makes developing and testing Web Parts almost
easy, provided you install it correctly. BY PETER VOGEL

DEPARTMENTS

Letters to the Editor

DevDisasters
When Aptitude Leads to Futility BY ALEX PAPADIMOULIS

10

DevInsight DEVELOPER NEWS, REVIEWS, PRODUCT BRIEFS


Microsoft Revamps SQL Data Services Cloud Database PAGE 10
Product Review: Automation Design Canvas Boasts Advanced Web Testing PAGE 12
Product Briefs: ERWin Data Modeler and ComponentOne LiveLinq PAGE 13

32 LANGUAGE LAB

ON VB, C# CORNER, ASK KATHLEEN

On VB PAGE 32
Use XML Literals, WCF and LINQ to create powerful templates that can be called from
both client- and server-side code. BY STEELE PRICE
C# Corner PAGE 40
There are multiple ways to solve every problem. Strive for code that communicates
your intent and makes your meaning clear for every developer using your code.

COVER ILLUSTRATION BY RYAN ETTER

BY BILL WAGNER

Ask Kathleen PAGE 42


Learn how to free your application from dependencies and interchange
implementations using Managed Extensibility Framework. BY KATHLEEN DOLLARD

COLUMNS

3
48
47

Frameworks BY MICHAEL DESMOND


Redmond Review BY ANDREW BRUST
Index of Advertisers

When Microsoft launched .NET Framework


3.0 back in November 2006, it heralded a
rush of frameworks, foundations, programming models and languages that
continuesunabatedto this day.
.NET development has, in short, gone
large. As VSM Executive Editor Kathleen
Richards reports in our cover story on the
evolution of Visual Studio 2010 (see IDE
Evolution, p. 16), developers find themselves confronted with a lot of hard decisions. Decisions that have lasting implications both for your applications and for
your career.
Today, Visual Studio supports development for Windows Presentation
Foundation, Silverlight, ASP.NET, AJAX and
WinForms. And the next version extends
its reach in so many directions, its almost
silly. Theres ASP.NET-friendly cloud
development for Windows Azure, freshly
integrated SharePoint tooling, and support for parallel programming and functional languages like F#. And I didnt even
mention the Dynamic Language Runtime.
Consequently, developers need to
grasp the big picture even as they master
the minutiae, which explains the changes
in this issue of Visual Studio Magazine.
Weve adopted a new design, a fresh
approach and a broader mission. Well continue to provide detailed tutorials.
Familiar columns including Ask Kathleen,
C# Corner and On VB will appear in every
issue of VSM in our new Language Lab
section (see p. 32). But youll also see a
broader exploration of emerging technologies and challenges facing developerslike the changes posed by Visual
Studio 2010.
So take your time. Check out the new
DevDisasters department from the folks
at The Daily WTF (p.8). Read Andrew
Brusts Redmond Review column (p. 48).
And get back to me with your thoughts
on what we can do betterIm at
mdesmond@1105media.com.

VisualStudioMagazine.com April 2009 VISUAL STUDIO MAGAZINE 3

0409vsm_WTOC_004.v3

3/19/09

3:13 PM

Page 4

Online Contents
Get the complete picture
the latest dev news, analysis
and how-to contentat
VisualStudioMagazine.com
and our partner sites in
the Redmond Developer
Network.

VISUALSTUDIOMAGAZINE.COM

REDDEVNEWS.COM

ADTMAG.COM

Practical ASP.NET
Create a Reporting Dashboard with
WebPartZones (but Without WebParts):
All you need to let your users customize
their Web pages is the ability to create
UserControls. BY PETER VOGEL

RDN Express: The Unbearable


Silverlightness of Being
With version 3 revealed at Mix09, there
was no shortage of opinions from readers,
who took some time to share their
thoughts about Silverlights evolution.

Is SOA Dead?
In an interview following her controversial
blog post, Burton Group analyst Ann
Thomas Manes explains her point was to
get the word out to enterprise architects
that they need to temper expectations
when pitching enterprise application integration projects to corporate sponsors or
else they will be nixed.

LOCATOR+ CODE: VS0904PV1

BY KATHLEEN RICHARDS
LOCATOR+ CODE: VS0904RD1

BY JOHN K. WATERS

Classic VB Corner
Working with Multiple Monitors: Most
of the time it doesnt matter where the
user puts your applications windows, but
every now and then you really need to
knowor even decide this for yourself.
BY KARL E. PETERSON
LOCATOR+ CODE: VS0904KP1

Windows WorkFlow 4.0 Promises


VastImprovement
Developer speaking at VSLive! says
forthcoming WF will be the first truly
usable version since it was released
more than two years ago.
BY JOHN K. WATERS.
LOCATOR+ CODE VS0904ED2

LOCATOR+ CODE: VS0904AD1

Eclipse Launches Effort to Define


Standard Mobile Dev Tools
Pulsar is aimed at standardizing the way
software is developed for different
vendors mobile handsets using tools
based on the open source framework.
BY JOHN K. WATERS

BY JEFF LEVINSON
LOCATOR+ CODE: VS0904JL1

LOCATOR+ CODE: VS0904AD2

Version 1.0 ASP.NET MVC Released


Microsoft released ASP.NET Model-ViewController (MVC) version 1.0 at the MIX09
conference in March. Will the ASP.NET MVC
succeed in advancing a design pattern
for test-driven development of enterprisescale Web applications?
BY MICHAEL DESMOND
LOCATOR+ CODE: VS0904RD3

VisualStudioMagazine.com

RedDevNews.com

VISUAL STUDIO MAGAZINE April 2009 VisualStudioMagazine.com

Open Source Project Gives Java


Devs a Lift
The open source Lift Framework project
aims to develop a Web application framework that solves issues present in existing
approaches. BY JOHN K. WATERS
LOCATOR+ CODE: VS0904AD3

ADTmag.com

ILLUSTRATION FROM ISTOCKPHOTO

Inside VSTS
Inside the TFS Databases: Get to know
the ins and outs of TfsWorkItemTracking
in the first part of this series covering the
most useful aspects of the TFS database.

Project17

1/19/09

5:24 PM

Page 1

Integrate Mapping and GIS into Your Applications


Give your users an effective way to visualize and analyze their data so they can make more informed
decisions and solve business problems.
By subscribing to the ESRI Developer Network (EDNSM), you have access to the complete ESRI
geographic information system (GIS) software suite for developing and testing applications on
every platform. Whether youre a desktop, mobile, server, or Web developer, EDN provides the
tools you need to quickly and cost-effectively integrate mapping and GIS into your applications.

Subscribe to EDN and leverage the power of GIS to get


more from your data. Visit www.esri.com/edn.
Copyright 2009 ESRI. All rights reserved. The ESRI globe logo, ESRI, EDN, and www.esri.com are trademarks, registered trademarks, or service marks of ESRI in the United States, the European Community, or certain
other jurisdictions. Other companies and products mentioned herein may be trademarks or registered trademarks of their respective trademark owners.

0409vsm_Letters_6.v4

3/19/09

7:32 AM

Page 6

Letters

VisualStudioMagazine.com
April 2009 Volume 19 No. 4
Editorial Staff
Vice President, Doug Barney
Editorial Director
Editor in Chief

Michael Desmond

Executive Editor

Kathleen Richards

News Editor

Jeffrey Schwartz

Managing Editor

Wendy Gonchar

Associate Managing Editor

Katrina Carrasco

Contributing Editors

SharePoint
Reflections
VSM readers respond to the March 2009 cover story on the changing face of
SharePoint development.

Andrew J. Brust, Ken Cox, John Cronan, Dan Fergus,


John Gavilan, Roger Jennings, Don Kiely,
Martin Kulov, Jeff Levinson, Bill McCarthy,
John Charles Olamendy Turruellas,
Keith Pleas, Bill Wagner
Art Staff
Creative Director

Scott Shultz

Graphic Designer

Erin Horlacher

Online/Digital Media
Editor, VisualStudio Becky Nagel
Magazine.com
Executive Editor, New Media
Online News Editor

The tools are abysmal. The best examples Ive seen come out of Ted Pattison. His
commentary in the SDK videos pretty much sums it up. He says that someday
Microsoft will produce some great and wonderful tools, but until then you need
to learn the hard way.
Mike, California, posted online

Associate Editor, Web


Web Producer

Good-bye Redmond Developer News


VSM sister publication RDN published its last print issue in February 2009. A
reader shares her thoughts.
Im disappointed that RDN is going away. When it was created I thought it was
different and better than anything else for what it covered. The columns about
technology, the interviews and DevDisasters, too, were all good to have. I work in
a data warehouse development group so we are especially interested in SQL
Server and data access and data presentation. Often I would tear a page out and
put it on my managers desk so he could read it and be aware, too.
Visual Studio Magazine is OK, but its different. RDN will be missed.
Laura Granstedt, Bridgeport, Conn.

Kurt Mackie
Gladys Rama
Shane Lee

Director, Web Development

Rita Zurcher

President

Henry Allain

Vice President, Publishing

The tools, quite frankly, stink. The documentation for those tools is also very,
very poor. The SharePoint developer SDK is full of examples that dont work.
Many examples are trivial, too. The fact that you have to use the tools on the
SharePoint server is just icing on the cake. Virtual PC is a real dog with a full
MOSS installation. On the other hand, so many of our clients are turned off
by the high cost of licensing SharePoint that they decide to go in another
direction instead.
JP, Kansas, posted online

Michael Domingo

Director of Marketing
Online Marketing Director

President &
Chief Executive Officer
Senior Vice President
& Chief Financial Officer
Executive Vice President

Matt N. Morollo
Michele Imgrund
Tracy S. Cook

Neal Vitale
Richard Vitale
Michael J. Valenti

President, 1105 Events

Dick Blouin

Vice President, Finance


& Administration

Christopher M. Coates

Vice President, Digital Media,


Audience Development

Abraham M. Langer

Vice President, Information


Technology & Web Operations

Erik A. Lindgren

Vice President, Digital Media,


Advertising

Doug Mashkuri

Vice President,
Attendee Marketing
Chairman of the Board

Carmel McDonagh

Jeffrey S. Klein

REACHING THE EDITORS


Editors can be reached via e-mail, fax, telephone or mail.
A list of editors and contact information is available at
VisualStudioMagazine.com.
E-mail: E-mail is routed to individuals desktops. Please use the
following form: FirstnameinitialLastname@1105media.com.
Do not include a middle name or middle initials.

Visual Studio Magazine wants to hear from you! Send us your thoughts
about recent stories, technology updates or whatevers on your mind.
E-mail us at editor@visualstudiomagazine.com and be sure to include
your first and last name, city and state. Please note that letters may be
edited for form, fit and style. They express the views of the individual
authors, and do not necessarily reflect the views of the VSM editors or
1105 Media Inc.

VISUAL STUDIO MAGAZINE April 2009 VisualStudioMagazine.com

Telephone: The switchboard is open weekdays 8:30 a.m.


to 5:30 p.m. Pacific Time. After 5:30 p.m. you will be directed
to individual extensions.
San Francisco Office 415-814-0950; Fax 415-814-0961
Irvine Office 949-265-1520; Fax 949-265-1528
Corporate Office 818-734-1520; Fax 818-734-1528
Visual Studio Magazine
The opinions expressed within the articles and other contents
herein do not necessarily express those of the publisher.

Project3

3/18/09

9:10 AM

Page 1

0409vsm_DevDisasters_8-9.v6

3/19/09

8:01 AM

Page 8

S E RVE D U P BY A L E X PA PA D I M O U L I S

</DevDisasters>
{ SOFTWARE DEVELOPMENT GONE WRONG }

Coding Catastrophes
themselves. And who knows, we all
might even enjoy a laugh or two
while were at it.
So, welcome to the first
installment of DevDisasters
in Visual Studio Magazine.
This regular department,
which has appeared in
VSMs sibling publication
Redmond Developer
News since 2007, will
offer readers a chance
to learn the hard lessons
without taking the
hard hits.

A Painful Legacy

Experience may be the best teacher, but


failure too often is its bitter reward. After
all, what software developer worth his salt
hasnt committed some code-bound atrocity or embarrassed himself with an illadvised kludge? The thing is, good developers learn from these failures to become
better developers.
I should know. As the author of
DevDisasters and founder of The Daily
WTF Web site (www.thedailywtf.com), Ive
made it my personal mission to stand witness to the painful shortcomings of software developers. The whole thing started
back in 2004, when I noticed how frequently programmers tend to discuss and
share anecdotes about the poorly written
code they encounter every day. It was clear
to me that developers could learn an awful
lot by reading about some other guys ugly
flameout, rather than experiencing it

The fourth time will be the charm.


Thats what Martin F. told himself on
the first day of a new assignment. He
was the fourth consultant sent from his
IT firm to work with the HR department
at Pan Euro Investments (PEI), a major
European banking and insurance
conglomerate. Apparently, the first consultant walked off the job. The second
ran. And the third sprinted like a bat out
of hell.
Just to warn you, Martins new boss
started, Ive been told that our database is
a bit of a mess. Ever since Robthe guy
who built the systemleft, its changed
quite a few hands and has experienced a
few growing pains over the year.
Growing pains was a gross understatement. Back in the early 90s, PEI
purchased an incredibly inefficient and
unreliable enterprise resource planning
(ERP) system to help HR manage employees. Because the system lacked so many
features, the HR department had no
choice but to supplement it with applications of its own. Thats where Rob came
in. He was an HR specialist who dabbled

VISUAL STUDIO MAGAZINE April 2009 VisualStudioMagazine.com

a bit in programming and took it upon


himself to build the HR departments supplemental systems.
A decade or so later, Robs supplemental applications were central to the
business and the ERP system had faded
out. By the time Rob left, the HR department worked with an amalgamation of
Microsoft Access databases, VB5 applications and macro-powered Excel spreadsheets, strewn across different workstations and servers.
At the heart of this system lay the
central database. It held monthly snapshots of all 50,000-plus employees data
going back about four years. Over that
period of time, the database had grown to
an impressive 2 million records. And for an
Access database on a file share, that
meant a typical Select and Group By
query took a good eight minutes.
Diving into the HR-Access Pool
Roberts first task was to correct a few
bugs in the provider importer. It was an
Excel-based application that PEIs 100-plus
daughter companies would use each month.
After the appropriate data was filled in, the
spreadsheet would generate a few .CSV files
and e-mail them to a manager in PEIs HR
department.
In turn, that HR manager would forward the e-mail to the appropriate subordinates, who would then do the following:
1. Process every .CSV through an
Access-based data-verification program
that output Verified .CSVs
2. Consolidate all the verified files
into another Access database
3. Find and remove any duplicate
employee records
4. Export the data into Duplicate
Verified .CSVs and import it into temporary
tables of the central database

0409vsm_DevDisasters_8-9.v6

3/19/09

8:01 AM

5. Perform the final checks and corrections against temporary tables and then
consolidate to master tables
6. Run the appropriate reports and
send PDF-formatted documents to appropriate managers at daughter companies
This song and dance took
two people a full week to
accomplish. After sending the reports to the
100-plus managers,
they set aside
three days for
feedback and corrections from the
daughter companies, and then
went back to step
one to repeat the
process for the final
version.

Page 9

Apparently, Frank showed good aptitude


and was asked back for a second interview.
When Frank came back for round
two, he was given the grand tour. It was
everything start-up dreams were made of:
posh decor, shiny new Macbooks everywhere, an air-hockey table, free
catered meals and Aeron
chairs as far as the eye
could see. After the
interview,
his future boss
Derrick
made Frank an
offer he couldnt
refuse.
Franks first
day consisted mostly
of introductions.
When he finally made it
back to his desk, he couldnt help but wonder about
some things. Things like, why would a
Web-based software company with
20 employees have only
three developers on staff? And
why would two of those developers be
part-time interns?
The more he thought about it,
the more he worried. Frank counted four different program managers. What tasks at the
small company could possibly keep the New
Product Introduction Manager or Geospatial
Systems Program Manager busy all day?
Did the company really need 10
manager level positions? Frank asked
himself. Shouldnt some of these people
have software backgrounds?
But Frank shrugged his concerns off,
reasoning that this was the type of team
needed to build a successful start-up.

The
developers

didnt seem to know


the difference between
Cache, ViewState and
Session objects, so they
just used all three
simultaneously to
make things
work.

Ol Teller
Martin had little faith that the code powering this ridiculous process would make any
more sense than the process itself. Peering
under the veneer of the ordinary-looking
spreadsheet, Martin uncovered a writhing
heap of undocumented VBA code that
made him shudder.
When Martin completed the requested
bug fixes, his boss thanked him for the
prompt turnaround. Then he quietly added:
Now, ahem, you just need to fix all of the
daughter companies importers.
As Martin begrudgingly edited each
and every one of the 100 or so different
provider importer spreadsheets, he
plotted the ways that he could tastefully
flee like there was no tomorrow. And
who knew, maybe the fifth time would be
the charm.

Death by Aptitude
Nothing screams sexy like an ad for a C#
developer job at a well-funded start-up. In
fact, when Franks recruiter presented the
opportunity to him, Frank knew it would be
a long shot. After all, he had no commercial
software experience and had only limited
Web development experience. But he did
know .NET pretty well, so he figured itd be
worth a try. Maybe his skills could translate
to a Web-based software company.
His first interview went surprisingly
well. They asked a lot of aptitude questions, as they were firm believers that
experience can be gained and skills can be
learned, but attitude never changes.

Wait What?
Once Frank finally settled into his comfy
Aeron chair and fired up his dual-monitor
workstation, he was ready to learn the code.
This, he figured, is where it would all come
together and make sense. He heeded his fellow developers warning that things were a
little beta-ish and dove right in. After all of
two minutes, he wanted to jump back out.

The pages were riddled with race conditions and generally only supported one
request at a time. The developers didnt
seem to know the difference between
Cache, ViewState and Session objects, so
they just used all three simultaneously
to make things work. As for the helper
functionsthey were perhaps the
most unique take on .NET coding
Frank had ever seen. In one baffling
case, the developers created their own
areValuesDifferent method to act as a
wrapper for object.Equals():
public bool areValuesDifferent
(object x, object y) {
... snip ...
if (0 == x.GetType().FullName
.CompareTo("System.String"))
if (0 != ((string)x)
.CompareTo((string)y))
diff = true;
if (0 == x.GetType().FullName
.CompareTo("System.Int64"))
if (0 != ((long)x)
.CompareTo((long)y))
diff = true;
... snip ...
}

As the lead developer later told Frank,


Well, this way, it only checks the value.
Frank took a few minutes to explain
the whole concept of virtual methods, and
how Equals() does exactly the same thing.
His colleague shrugged his shoulders and
replied, Hmm, I guess that would work, too.
The really good news came later that
day, when Frank learned that the company
would be hiring some new intern developers.
Well, not just any interns, only the most
aptitudinal that money could buy. VSM
Alex Papadimoulis is a managing partner at
Inedo LLC and publisher of the Web site The
Daily WTF (www.thedailywtf.com). He writes
DevDisasters in every issue of VSM.

Tell Us Your Tale


Each issue Alex Papadimoulis, publisher of the popular Web site The Daily WTF (thedailywtf.com),
recounts first-person tales of software development gone terribly wrong. Have you
experienced the darker side of development? We want to publish your story. E-mail your tale
to Executive Editor Kathleen Richards at krichards@1105media.com and put DevDisasters
as the subject line.

VisualStudioMagazine.com April 2009 VISUAL STUDIO MAGAZINE 9

0409vsm_DevInsight_10-13.v7

3/19/09

8:06 AM

Page 10

DEVELOPER NEWS /// REVIEWS /// PRODUCTS

Data Services

</DevInsight>

DEVELOPER NEWS

Microsoft Revamps SDS


Cloud Database

always the plan, it said it will no longer


expose those capabilities by requiring
the REST Web services interface.
The move eliminates the Web
services layer and exposes TDS to SQL
Server over the cloud. As a result, says
Microsoft, developers will be able to
move data-driven code developed in
Microsofts T-SQL language for SQL
Server over to SDS.
We were calling it SQL Server
but it really was not similar to a SQL
Server-type experience, explains Niraj
Matrani, senior product manager for
SDS. Customers preferred more with
the traditional T-SQL-based support,
so we decided to go in this direction.
Microsoft is suggesting that
those who want to use REST-based programming for applications that do not require a
relational database management system can use
the Azure table storage. You can still access your relational data (located on premises or in the cloud) via
HTTP/REST using the ADO.NET Data Services framework,
Microsoft Senior Program Manager David Robinson wrote in a
blog posting.

BY JEFFREY SCHWARTZ
After months of criticism that the test build of its cloud-based
SQL Data Services (SDS) lacked the horsepower for enterprisegrade applications, Microsoft is scrapping the effort and moving
to a pure relational model instead.
Microsoft made the surprise move just one week before its
annual MIX09 conference in Las Vegas last month. Ironically, The
company announced its cloud-based database offering at MIX08,
one year before. The test version of SDS that critics panned was
based on REST and SOAP Web services interfaces.
Eliminating Web Services
Under the new plan, Microsoft will offer a pure relational database in the cloud by exposing its Tabular Data Stream (TDS)
over-the-wire protocol for accessing SQL Server via its forthcoming Azure Services Platform.
Microsoft will support traditional relational database capabilities, including SQL queries and support for relational schema
and stored procedures. While the company maintains that was
10

VISUAL STUDIO MAGAZINE April 2009 VisualStudioMagazine.com

SDS DOA
Indeed it was the similarity between Azure Tables for storage
and SQL Server tables using the Entity Attribute Value (EAV)
model that may have helped render Microsofts first test build of
SDS dead on arrival. The two were virtually identical, says consultant and Microsoft MVP Benjamin Day of Brookline, Mass.based Benjamin Day Consulting.
The four-month test of SDS failed to meet the performance
expectations of enterprise developers such as OakLeaf Systems
Principal and VSM contributor Roger Jennings, who found it was
unable to offer the scalability of the existing SQL Server. They
offered some pseudo-relational features but they didnt offer the
ones that people really wanted, Jennings explains.
It also became clear that developers werent going to redevelop their T-SQL application for SDS. It highlights that challenge [that], as people transition to the cloud, theyre absolutely
not going to accept two different programming modelsone for
inside the firewall and one for outside the firewall, says
Forrester Research Inc. analyst Jeffrey Hammond.

Project1

2/24/09

11:22 AM

Page 1

LEADTOOLS v.16 .NET, WPF, WCF,


WF, C API, C++ Class Lib, COM & more!
Document

Form Recognition & Processing

Barcode

Mark-up

DICOM Medical

Multimedia

Develop your application with the same robust imaging technologies used by Microsoft, HP,
Sony, Canon, Kodak, GE, Siemens, the US Air Force and Veterans Affairs Hospitals.
LEADTOOLS provides developers easy access to decades of expertise in color, grayscale, document,
medical, vector and multimedia imaging development. Install LEADTOOLS to eliminate months
of research and programming time while maintaining high levels of quality, performance and
functionality.
Image Formats: All industry standards including TIFF, EXIF,
PDF, JPEG/JPEG2000, DICOM, PCL, DWG and hundreds more.
Image Compression: From standard JBIG, JBIG2, ABIC,
JPEG and CCITT G3/G4 to LEADs specialized ABC, CMP and
CMW compression.
Display Controls: Scroll, zoom, pan, magnify glass,
brightness/contrast/gamma, window level.
Image Processing: 200+ filters, transforms and color
conversion functions with extended grayscale (10 to 16-bit)
support.
OCR/ICR/OMR: Full page or zonal multi-threaded
recognition with formatted output including PDF, DOC and
TXT for Win32 and x64.
Barcode: Read/write all industry standard 1D and 2D barcodes (DataMatrix, PDF417, MicroPDF417, QR Code and more).
Forms Recognition and Processing: Automatically
identify forms and extract user filled data.
Document Cleanup/Preprocessing: Deskew, despeckle,
line and border removal, registration marks and more.
PDF and PDF/A: Read/write raster and text searchable
PDF files.
Annotations: Interactive UI for document mark-up,
redaction and image measurement (including support for
DICOM annotations).
Grayscale Imaging: Display and process signed/
unsigned 10-16 bit, 32 bit data.

Medical Web Viewer Framework: Plug-in enabled


framework to quickly build high-quality, full-featured,
web-based medical image delivery and viewer applications.
Medical Image Viewer: High level display control with builtin tools for image mark-up, window level, measurement, zoom/
pan, cine, and LUT manipulation.
DICOM: Full support for all IOD classes and modalities defined
in the 2008 DICOM standard (including Encapsulated PDF/CDA
and Raw Data).
DICOM Communications: Full support for DICOM
messaging and secure communication enabling quick
implementation of any DICOM SCU and SCP services.
WPF (XAML): Viewer, Image List, Annotations, Transitions
and WIC Codecs.
AJAX Web Form Image controls for developing rich web
applications.
JPIP Client and Server components for interactive streaming
of large images and associated image data using the minimum
possible bandwidth.
Scanning: TWAIN 2.0 and WIA (32 and 64-bit), auto-detect
optimum driver settings for high speed scanning.
DVD: Play, create, convert and burn DVD images.
Multimedia: Capture, play, stream and convert MPEG, AVI,
WMV, MP4, MP3, OGG, ISO, DVD and more.

LEADTOOLS SDKs feature LEADs iCompress Technologies.


Free 60 Day Evaluation! www.leadtools.com/vsm
866-530-3399

0409vsm_DevInsight_10-13.v7

3/19/09

8:06 AM

Page 12

</DevInsight>

Automated Testing

REVIEW

Developer Expectations
The new offering should be welcomed by
developers, says Day: It looks like its
going to make it extremely easy for you to
deploy existing code in the cloud.
But he cautions that until the test
release is available, its too early to say
how well it will perform compared to onpremises versions of SQL Server. Well
have no idea what it will be until we run
it, he notes.
Jennings is skeptical. He pointed out
that TDS was designed to run over highspeed LANs and that its not an Internetfriendly protocol. But Matrani insists
Microsoft has already conducted extensive benchmarking and testing and performance shouldnt be a problem. We
think its appropriate for what we are
doing and the direction we are talking it,
he says. As we get more early-adopter
customers and we look at the type of
workloads theyre building, theyll keep
modifying and tweaking our protocols so
its more workload-friendly.
Matrani adds that SDS will lend itself
well to CRM applications, content management, product lifecycle management, supply chain and collaboration. But he
acknowledges that it wont initially be
suited to data warehousing and OLTP.
Day and Jennings also warn that relational data has its performance limitations. There are theoretical limits on how
scalable you can make a relational database, Day explains.
One of the unanswered questions is
that of cost. While Microsoft still hasnt
disclosed how it is pricing SDS, rival
Amazon Web Services has already lowered the bar. The company slashed the
price of its EC2 service by offering those
who sign one- or three-year commitments
to usage-based pricing that ranges from
3 cents to 24 cents per hour, depending
on configuration. That represents a
30 percent to 50 percent reduction, the
company says.
Microsoft says SDS with TDS support
will be available for testing by mid-year
and commercially available by the end of
the year. DI
Jeffrey Schwartz (jschwartz@1105media.com) is
Visual Studio Magazines news editor and the
editor of ADTmag.com.

12

Automation Design Canvas


Boasts Advanced Web Testing
BY KEN COX
Automation Design Canvas (ADC)

1.1 from ArtOfTest Inc. is a high-end


test tool for developing repeatable,
automated tests of Web applications.
The generated tests execute on
ArtOfTests included WebAiipronounced Web-eyeframework.
The designer portion integrates
seamlessly with Visual Studio 2008
(though not the Express versions) to
record, execute and analyze tests of
browser-based content.
Getting Started

ADC installed flawlessly on a 64-bit


beta of Windows 7 running in a
Hyper-V virtual machine. The setup
adds a template called WebAii to the
VS 2008 Test collection.
The proper configuration of
your test machine is essential. For
the tooling to work properly, you
must disable Internet Explorers
Protection Mode, ease Firefox
browser security settings and shut
off User Access Control in Windows.

The online video and the FAQ document cover these issues adequately.
The Quick Start guide offers a
fine overview of the tools basic features and environment, but it could
use some polishing and expert
review of what looked like syntax
errors in the code examples.
Recording navigation, text
input and mouse clicks are
standard fare for any test tool, but
ADCs strength becomes apparent
both during and after recording
operations.
Using Test Explorer you can
reorder, edit and disable any step to
fine-tune the test sequence. I loved
the Quick Test button for checking
an individual step without slogging
through the whole test sequence.
The powerful Convert to Code function turns a step into a highly readable C# or VB function. This is not a
scripting language. Youre coding
against strongly typed objects with
full IntelliSense and tooltip support.
WebAiis property and method

Automation Design Canvas integrates with Visual Studio 2008 to design and
run flexible tests of Web applications. Each test step remains a separate item
that you can tweak, re-order or turn into a .NET function. You might need to
add a slight pause for AJAX-enabled controls.

VISUAL STUDIO MAGAZINE April 2009 VisualStudioMagazine.com

0409vsm_DevInsight_10-13.v7

3/19/09

8:06 AM

Page 13

AUTOMATION DESIGN CANVAS 1.1

input_Text_Q.Wait.ForExists(1000);

Rather than cluttering Web forms with


junky asdfdadfdf -type input, testers
can store realistic values once in the softwares convenient data table option.
When you point an HTML controls Text
property to the built-in Data[] object,
WebAii loops through its data rows and
inserts whatever is in the table. You can
also use external sources, such as a SQL
Server database, to feed data-driven tests.
Smooth Design

The purpose of most tests is to check for


appropriate responses. To configure
screen reading in ADC, you use an overlay function that suspends record mode
while you highlight a screen object such
as a label or image. The overlays context

menu lets you set the expected result; for


example, a string of text or a visible
image. This point, click and configure
feature is very valuable and welldesigned.
Recording and playback is usually
smooth and automatic, but the
CascadingDropDown sample on the AJAX
Control Toolkit site was an exception. It
required adding delays by hand. I suspected
WebAii was trying to select an option
before its XMLHttpRequest-fed value was
available inside the browser DOM.
ADC logs extensive results and a
summary report for each test run. The
tool can even log a screenshot at any
point in the process to help developers
assess the results at the post-mortem
review stage.
ADC 1.1 and WebAii are chock-full
of impressive and useful features for test
developers. However, prepare for an
enterprise-level price: $2,499 for a

ArtOfTest Inc.
www.artoftest.com
512-535-2428
Price: $2,499 per developer machine;
$199 per execute-only machine license
Quick Facts: A sophisticated Visual
Studio 2008 plug-in for recording,
coding and executing tests of a Web
application using Internet Explorer or
Firefox.
Pros: Easy to learn and use;
powerful recording and playback
features; flexible editing of test steps;
exposes rich, strongly typed C# or VB
objects
Cons: Pricey; AJAX controls may require
special attention

designer workstation license and $199 for


an execute-only machine license. DI
Ken Cox is a Canadian .NET programming
writer and the author of ASP.NET 3.5 for
Dummies (For Dummies, 2008).

Data Modeling

names are intuitive, resulting in recognizable statements such as:

PRODUCTS

ERWin Data Modeler


7.3 and LiveLinq
Erwin Data Modeler 7.3
With more complex data sources throughout the enterprise and
demands to move beyond structured information, modeling tools
are moving beyond their roots. For one thing, database developers
can now find them in application lifecycle management suites.
Case in point is Erwin from CA Inc., one of the most widely used
of the data-modeling tools. The new CA ERwin Data Modeler 7.3 can
now be integrated with Visual Studio Team System 2008 and SQL
Server 2008, among a number of other key data repositories including Teradata and IBM Corp.s DB2 for its mainframe-based z/OS v9.
The tight integration between ERwin and SQL Server allows
for all SQL Server database objects to be captured in ERwin data
models for analysis, says CA partner Antonio Amorin, president of
Northbrook, Ill.-based Data Innovations.
The new release of ERwin also boasts new reporting capabilities via a bundled copy of BusinessObjects Crystal Reports, which
provides graphical rendering in spreadsheets, PDFs and HTML.
Our techie geeks love that because they can completely customize any report they want, when a model is published, says
Donna Burbank, a senior principal product marketing manager at CA.
The new release also has a new option for data profiling,
thanks to a recent partnership with Exeros Inc., whose data profiler
is now integrated into ERwin. The data profiling lets developers
compare data distributed throughout disparate legacy systems,
which CA says will ease the process of identifying information
such as customer data, and making sure its consistent with structural designs. This allows architects and those on implementation
teams to ensure data is modeled so it can be used in data marts,
warehouses and master-data management hubs.
ERwin, which recently celebrated its 20th anniversary, is
among the leading suppliers of data modeling tools, says

Forrester Research Inc. analyst Jeffrey Hammond. ERwin is


probably the most traditional of the data modeling tools, he
notes. Other key providers include Embarcadero Technologies
Inc. and Sybase Inc., according to Forrester. IBM, Microsoft and
Quest Software Inc. also are emerging providers of data
management tools.
ERWIN DATA MODELER 7.3

CA Inc.
Price: $8,000
www.ca.com
800-225-5224

LiveLinq Boosts Queries


One of the key benefits of Microsoft LINQ is that it can cut down
development time for data-driven applications. But for those
looking to optimize the speed of applications developed in LINQ and
for dynamic views of data rendered in LINQ-based queries,
ComponentOne LLC is readying a new tool called LiveLinq. Available
as a community technology preview in February and slated for
release next month, LiveLinq is a new class library that the company
says speeds up LINQ queries by indexing in memory. ComponentOne
claims typical performance boosts of 10 to 50 times.
The live views will render data dynamically to users of apps
using LiveLinq libraries. Any developer familiar with LINQ should
be able to use LiveLinq without training, says ComponentOne
Product Manager Chris Meredith. DI
LIVELINQ

ComponentOne LLC
Price: Not disclosed yet
www.componentone.com
800-858-2739
412-681-4343

VisualStudioMagazine.com April 2009 VISUAL STUDIO MAGAZINE 13

Project3

3/19/09

9:08 AM

Page 1

Project3

3/19/09

9:09 AM

Page 2

0409vsm_F1VS_16-23.v7

FEATURE

3/19/09

12:55 PM

VISUAL STUDIO 2010

Page 16

....................................

Is Microsoft enhancing your user experience in Visual Studio 2010


and beyond? BY KATHLEEN RICHARDS

IDE
EVOLUT

The team in Building 41 on the Redmond campus is

16

WPF, according to many developers, provided limited


guidance and a lack of sufficient tooling.
Its good to see Microsoft using WPF in one of
their core products, as it will surely drive the maturity of
WPF and related tools, says Rockford Lhotka, principal
technology evangelist at Minneapolis-based consultancy
Magenic Technologies Inc.Every time Microsoft buys
into its own technologies like this, we all benefit.
Dated and Confused
These bold moves come as VSs architects attempt to
roadmap a remodel of the IDE with investments in five
areas: extensibility beyond the core throughout the
product, frugality with better dependency management and resource allocations, connectivity with S+S,
scalability to the tune of 10,000 projects in a solution;
50,000 files in a system and overall modernization.
The 2008 product looks a lot like the 1998
product and I dont think thats a good thing, said
Visual Studio architect Rico Mariani in a Channel 9
interview at the Visual Studio Extensibility (VSX)
conference in September.
Were doing a lot of work around scalability and
frugality in the IDE, so that you can afford to be modern, he said. We can pay for our WPF costs with savings elsewhere. We dont expect WPF to be free.
Moving beyond single-threaded app performance in Visual Studio and a Model-View-Controller-type

VISUAL STUDIO MAGAZINE April 2009 VisualStudioMagazine.com

ILLUSTRATION BY RYAN ETTER

working on ways to modernize the developer experience for Microsofts third-largest application and flagship toolset. The Visual Studio platform architects face
the same challenges as their developer customers: How
to revitalize a pivotal legacy codebase as hardware systems, Software plus Services (S+S) and new ways of
building applications demand advancement.
Visual Studio (VS) 2010expected in beta
around the Microsoft TechEd timeframe (May 11-15,
2009)will mark the start of a major remodeling of
the IDE, according to Microsoft, a process that will
continue over several product cycles.
In the upcoming release, the Developer Division
is taking a major leap of faith by dogfooding its
unproven graphics technology. The VS 2010 beta
debuts a new code editor, user interface and shell built
on Windows Presentation Foundation (WPF), the
.NET 3.x graphics subsystem that surfaced to mixed
reviews in Vista.
Weve told developers how to make applications
that are intuitive and exciting and modern looking for
their customers, says Matt Carter, Microsofts Visual
Studio group product manager. What were trying to
do is say, You deserve an environment thats also very
easy to use and intuitive and visually appealing, but
also uses that visual appeal to really provide greater
insight into what youre working on, how the different
parts of your code and your applications are related.
A programming model to take advantage of
Vistas new graphics subsystem, WPF was designed to
modernize the user experience by enabling developers
to code against a powerful framework that housed a
subset of DirectX 3D, animation, vector graphics,
ClearType, declarative programming, data binding,
multimedia, styling and controls. The initial releases of

3/19/09

12:55 PM

Page 17

ION

.........................................

..........

0409vsm_F1VS_16-23.v7

VisualStudioMagazine.com April 2009 VISUAL STUDIO MAGAZINE 17

Project1

1/21/09

11:14 AM

Page 1

Project1

1/21/09

11:15 AM

Page 2

0409vsm_F1VS_16-23.v7

FEATURE

3/19/09

12:55 PM

VISUAL STUDIO 2010

Page 20

..............................

Microsoft, a Kirkland, Wash.-based research firm.


You can look at methods in your code and get a
pop-up with history of the modifications as its
gone through development. You can also leverage debugging information in Team Foundation
Server, create specialized IntelliSense or adorn
XML Documentation Comments.
Microsoft will offer a lot of these extensions, Sanfilippo explains.But it also opens up a
market for that ecosystem. Its an interesting
competitive move: If there are features in competing dev environments, to put [Visual Studio]
on par with whats found on other toolsets.
At TechEd in Barcelona, Zander showed a
DevExpress add-on that lets you create thumbnail code views, so its easy using WPF layers to
pick a word and drill down in the Document
Map Margin.
The WPF shell lets developers undock window palettes and view code on
The new WPF-based Home Screen is also
multiple monitors.
extensible through configuration and XAML
files. I could see extensions to this screen that
can display things like quick-facts, says Sondre Bjells, Microsoft
architecture are among the roadmaps talking points. We have
technology leader for Capgemini in Oslo, Norway. How much
plenty of threads but we dont have a whole lot of concurrency,
code youve checked in lately, how much time you spend testing,
said Mariani. And theres a lot we could do if we separate what
how much time you spend documenting your methods and so
needs to be synchronous, what needs to interface with the user,
forth. It could aggregate data from the Team System warehouse
which is where the SDK models begin. Get the state off of those
and display it personalized for the individual developer.
objects and separated and get separation between the conThe WPF redesign of the IDE is the part of VS 2010 that
trollers, which can initiate asynchronously and have high-quality
impresses Andrew Brust, chief of new technology at twentysix
models in the background.
In VS 2010, developers can experience firsthand the begin- New York, the least.What I saw looks more like a WPF port of the
ning of the IDEs evolution: improved code navigation, annota- 2008 IDE than a true redesign. I hope that Microsoft will consider
tion and extensibility with the WPF-based shell; better perform- making more fundamental UI design changes to VS 2010 before
ance and scalability for native code; and fundamental improve- release, Brust says.
Were not embracing WPF because we want graphical
ments in debugging and test-driven development.
wowthat wouldnt be enough of a reason,blogged VS architect
Mariani in late November. What we want is flexibility and extenSnazzy New UI Bling
Like many teams tasked with modernizing their apps, Microsoft sibility. For instance, its because the new editor is WPF-based that
is revitalizing its legacy code base with a .NET presentation layer. we can, for reasonable engineering cost, offer the ability to add
The UI changes appeared modest to several developers who wit- inline adornments, margins, even heads up display style extennessed the first pubic unveiling at VSLive! in February. The UI sions. ... The best part is you wont have to wait for us to do these
Ribbon found in Vista and Office 2007 is not part of the redesign. thingsyou want profiler information overlaid on your text? No
In the new VS 2010 interface, the menus and commands are problem. Go do it. Test coverage? Hot links to documentation?
connected together in a shelf, so its easy to coordinate and find Online presence indicators based on e-mail names in comments?
things or get the clutter out of the way, explains Carter. Microsoft You could do all these things.
The WPF-based editor is built on Microsofts new
has done design work around how color and negative space is used,
and removed some of the necessary gradients and line work there Managed Extensibility Framework, a .NET 4.0 library for
so that the app is cleaner and crisper than it has been in the past, building extensible applications or discovering extensions.
he explains. It lets you focus on the work that youre doing and MEF is available as a preview on CodePlex (see more about
MEF in this months Ask Kathleen, p. 42).
minimize the distractions from other parts of the environment.
This whole modernizing thing, I think its a little tongueLhotka, who attended the VSLive! keynote delivered by
Microsofts Visual Studio GM Jason Zander where the UI was in-cheek, although its a good direction for Microsoft, says Jeff
first shown, questions the less clutter argument.While its nice Levinson, ALM practice lead at Kirkland, Wash.-based
that Visual Studio is now WPF, it didnt seem to me that the lay- Northwest Cadence Corp. Companies have been writing addins in Visual Studio for 16 years now. They cant just go and
out and dialogs were all that different from today, Lhotka says.
In addition to a new look and feel, WPF allows you to extend dump whats there. I think what theyre going to do is skin it for
the application experience beyond what Microsoft delivers in the WPF, but I dont know how full-featured WPF is going to be in
terms of interoperability, he says.
IDE through third-party or self-written add-ins.
The current VSX architecture remains intact, according to
WPF allows new extensibility to the source code editor that
in the past has been difficult to achieve, says Rob Sanfilippo, VS architect Mariani, but extensibility needs to be more uniresearch vice president of developer platforms at Directions on form. Other questions remain: How can developers find and
20

VISUAL STUDIO MAGAZINE April 2009 VisualStudioMagazine.com

0409vsm_F1VS_16-23.v7

3/19/09

12:55 PM

Page 21

...........................
plug into the appropriate subsystem? How do you de-bug and
update these components? How many extensions are feasible?
A new Extension Manager in VS 2010 lets developers access,
search and download extensions from the VSX gallery, for example, from within Visual Studio without a required VSIP package
on their machines.
Perhaps the biggest question around WPF is how it will affect
the IDEs performance. Mariani, known as a performance guy, has
acknowledged that there will be a penalty. Im expecting to take a
startup hit, he said during a Channel9
interview, noting that around 300-msec
would be acceptable.
The new IDE will be targeted at developer machines.Were going to down-level
to XP in this version, he explained, but to
get the best experience, developers need to
have a graphics accelerator (DirectX 9.0).
From a practical standpoint, WPF
also lets developers zoom in and out of
code, undock palettes and view code
and designer windows on multiple
monitors. Its easier to work in different [but integrated] projects on different screens independently from your
screen resolution, says Daron Yndem,
a Microsoft regional director and
INETA Turkey lead, who described the
WPF support as crazy good in an
e-mail. Im looking forward to the
great days where we will be able to
design our own Visual Studio interface
with full templating.
Crowded with Goodness
Designing custom toolsets appeals to
many developers, especially those who
are accustomed to downloading only the
modules they need, which is the Eclipse
model. The promise of .NET, according
to Microsoft, is that you can target so
many applicationsWindows, Office,
Web, smartphone, cloudwith a single
framework. And theres the rub: How can
a single IDE keep up?
It has been bloated for a number
of years, says Northwest Cadences
Levinson. For example, if you look at
Team Explorer, which is just a Visual
Studio Shell, thats 387MB to download
and install and if you look at something like Eclipse, that thing is around
180MB. Then when you add everything
else on, [Visual Studio] is almost 1GB.
Microsoft has heard the refrain for
yearsVisual Studio needs to be a smaller footprint and take up less resources. It
takes a long time for certain operations to
occur, where it shouldnt take that long,
says Levinson. I would like to see them
shrink it so that you only install the pack-

VISUAL STUDIO 2010

FEATURE

ages that you need and the shell is much smaller. He acknowledged that the ecosystem makes it hard to address a lot of these
issues in a single product cycle.
The platform wave continues in the new IDE, which will
support .NET 4.0, Windows 7, SharePoint 2007 and Microsoft
Office SharePoint Server, the Azure Services Platform and
Silverlight 2.
If youre a Visual Studio developer, you already have the core
knowledge to take advantage of all these great new innovations,

Powerful Imaging for .NET

DotImage 7 Affordable imaging toolkits for .NET.


Runtime royalty-free deployment to the desktop, scalable
licensing for servers, and 3 months of free gold support.
Visit Atalasoft.com for web demos, video tutorials, and a free trial.

Call us toll free at 866-568-0129

www.atalasoft.com

VisualStudioMagazine.com April 2009 VISUAL STUDIO MAGAZINE 21

0409vsm_F1VS_16-23.v7

FEATURE

3/19/09

1:06 PM

VISUAL STUDIO 2010

Page 22

..............................

says Microsofts Carter, pointing to recent developer feedback on


the new SharePoint tooling.
Indeed, the new Server Explorer,VS 2010 Web Parts,Application
Page Designers and user controls for SharePoint are highly anticipated by many developers who have bemoaned the lack of tooling.
This release is primarily focused on Windows 7. (VS 2008
did not fully support Vista/.NET 3.x until Service Pack 1 was
released last summer.) VS 2010 and Visual C++ will offer new
class libraries for building Windows 7 apps (including UI elements like the Ribbon), bring back the MFC Class Wizard and
support multitouch interfaces.
For Web developers, VS 2010 adds much-needed designers
and ASP.NET integration for Silverlight 2, tooling for ASP.NET
MVC, advanced JavaScript IntelliSense, snippets in HTML and
One-Click Deployment.
In addition to support for its bread-and-butter platforms,
Microsoft is baking in tooling to support emerging application
trends, namely cloud computing and parallel programming for
building applications that can take advantage of the performance of
multi-core systems. Visual Studio offers additional support for parallel programming with debugging windows and profiling for
coding against the Parallel Extensions to .NET Framework, PLINQ,
the native Parallel Pattern Library and Concurrency Runtime.
The Windows Azure Tools for Visual Studio, released out of
band at the Professional Developers Conference (PDC) 2008 in
October for building, debugging and deploying cloud apps and
services, is also integrated into the new IDE.
Third-party products and frameworks are also finding their
way into the IDE. Two notable inclusions in the VS 2010 tooling
are Oracle database support with an optional database schema
provider developed by Quest Software Inc., and native JQuery.
We had two paths we could follow there, explains Carter. We
could create a JQuery functional equivalent or we could just use
JQuery ourselves and have it supported by Microsoft. It will
have all the IntelliSense that youd expect from Visual Studio. If
you have a problem and call Microsoft, were here to support it.
Team Collaboration
While developers and analysts describe VS 2010 outside of the
core platform support as somewhere between a point release and
full-fledged upgrade, Team System 2010 is a milestone release
that ratchets up the testing capabilities on par with third-party
testing products, and reinvents the architecture role to ensure
best practices in the build process.
The 2010 release is kind of like an ber release, says
Levinson. The functionality is much better. The introduction of
hierarchical work items will make your life a lot easier. Plus, now
Microsoft is putting out a fully compatible, competitive professional testing tool, which they havent really had before. If I had to categorize VSTS 2010 in a single word, I would say,Awesome!
The new Architecture Edition is more of an app tool than a
systems tool, according to Levinson. It makes elements composable
and discoverable so that you can now reverse engineer with
sequence diagrams or use the Architecture Explorer to drill down to
see relationships. IDE support for UML is also added in 2010. VS
Professional has traditionally shipped with Visio, which offers UML
stencils, but this is the first time Microsoft is supporting it in its own
products. How Oslo, the model-driven development tooling
22

VISUAL STUDIO MAGAZINE April 2009 VisualStudioMagazine.com

New in .NET
Framework 4.0
Visual Studio 2010 will ship with a .NET Framework
that has undergone major changes, most notably a
complete overhaul of Windows Workflow. Other noteworthy additions include:
Managed Extensibility Framework (MEF): A new

.NET 4.0 library for building extensible applications or


discovering extensions. MEF is available as a preview
on CodePlex.
Integration of .NET Parallel Extensions: A new library

for data and task parallelism that includes the Task


Parallelism Library and declarative programming
support via Parallel LINQ (PLINQ).
Support for the functional programming language

developed by Microsoft Research, F# and Microsofts


dynamic languages IronRuby and IronPython via the
new dynamic language runtime built on top of the
common language runtime.
K.R.

announced at PDC, fits into this strategy is unclear. The latest Oslo
community technology preview was released in January.
Improvements like the no repro debugging and the new
Test Lab Manager, a virtual machine environment that developers and testers can spin up and tear down, goes beyond quality,
asserts Carter, to a team dynamic that can be fostered with the
new software.
My read is it will enable teams on tight deadlines and budgets
to put out much higher quality code, because the effort required to
find and fix the bugs will now be greatly reduced, says Brust.
Automation and all the recording features will really help here.
VSTS 2010, which includes role-based client tools that incorporate VS Professional and a license to TFS, is the first major
upgrade to the collaboration environment since its debut in
VS 2005. TFS will drop support for SQL Server 2005 as the backend source control system and thus require an upgrade to
SQL Server 2008. Team System also rolls up the former Developer
edition into the Database edition, resulting in Architect, Tester and
Database roles in addition to Team Suite, which includes all of the
aforementioned functionality in a single SKU.
Were looking at quality across the board, says Carter.
When customers are ready to move up from doing unit testing
in Visual Studio 2010 Professional, to advanced stuff in Visual
Studio Team System, thats an easy transition. Thats really exciting
stuff things like historical debugging, not only drive quality, they
help save time and resources for your team.
Call to Action
With installable beta 1 bits expected next month, developers can
test drive the new editor and try out the code navigation. A
new Call Hierarchy feature provides inline information on code

0409vsm_F1VS_16-23.v7

3/19/09

1:06 PM

Page 23

...........................

interaction. Highlight References bypasses the Find in Files feature


to highlight reference information in context of selected code and
Quick Search provides insight into other code locations.
Like VS 2008, the new IDE will support multitargeting of
.NET Framework, and new with VS 2010, developers will also be
able to multitarget both versions of the Common Language
Runtime (CLR2 and CLR4). Developers can also build client
apps for multiple versions of Office, and
deploy as a single package.
Those with existing solutions based
on C++ project systems will need to convert to MSBuild in VS 2010 to receive full
IDE support. Although Microsoft has
said it will provide migration tools, more
information is needed.
VS 2010/.NET 4.0 beta 2 is expected
before the end of the year with a Go Live
license, according to sources familiar
with Microsofts plans. The tiered VS
pricing structure, which debuted with VS
2005, isnt changing, but professional
developers may be better able to discern
what functionality is available in what
SKU/MSDN subscription based on their
experience with this pricing model.
Microsoft started a step-upgrade
discount program last July that offers 30
percent off to developers who upgrade or
move from competing products to VS
Professional/MSDN Premium subscriptions or VSTS, both of which include the
VS 2010 upgrade. Microsoft has declined
to quantify how many step-upgrades
have been sold.
VS 2010 is the first release in what the
Visual Studio platform architects describe
as a multicycle evolution. The team is
looking at a 64-bit version of the IDE
for VS 11, but hasnt committed to a technology roadmap.
The reason that you do this is to
make sure that the developer experience is
as efficient as possible, says Microsofts
Carter. So thats really what we pivot
aroundto make sure that with Visual
Studio 2008 and 2010 and beyond we
deliver a great productive experience that
is at once familiar to developers, but also
lets them tap into these new capabilities.
The ultimate goal, according to
Mariani, is: How do you make it so that
when a developer sits down, they feel like
theres nothing in his or her way between
their idea and the execution? VSM

VISUAL STUDIO 2010

FEATURE

GO ONLINE

Use this Locator+ code at VisualStudioMagazine.com to go


directly to these related resources.
READ MORE
VS0904KR Read this article online.

Kathleen Richards (krichards@1105media.com)


is executive editor of Visual Studio Magazine,
and editor of RedDevNews.com.
VisualStudioMagazine.com April 2009 VISUAL STUDIO MAGAZINE 23

Las Vegas June 8-11


The Venetian Resort Hotel Casino

Post event workshop on June 11

VSLive! Returns to Las Vegas


Attend the educational conference created by developers with
deep coverage of existing and new technologies that you can
use on the job today. Join your fellow developers for:
Over 45 sessions on WFP, WCF, LINQ, ASP.NET, Oslo, Azure, Team Foundation
Server and more
Cutting edge techniques needed to solve todays development challenges
Independent, real world information provided by industry experts
Face to face time with speakers to ask your toughest questions

Visit www.vslive.com/09lv to view


the complete agenda and register.
Save up to $300 with early bird registration AND get a $50
Venetian gaming credit*. Register by April 29th.
Use priority code NQ9V02

Take
advantage
of our $99
hotel room
rate

* Venetian gaming credit of $50 available to the first 200


VSLive! registrants who book 2 or more nights at the Venetian.

09VSL_LV_VSM_adFinal.indd Sec1:2

3/13/09 7:17:38 PM

Project3

3/20/09

12:07 PM

Page 1

Conference Day 1 Monday, June 8


KEYNOTE: Team Foundation Server 2010
ASP.NET

WPF

WCF

VM1 Build Blazingly Fast ASP.NET Apps with 100%


Clientside UI ExtJS - Peter Kellner

VM2 Build a WPF Application in an Hour - Kenneth


Getz

VM3 Understanding Transactions in WCF Michiel van Otegem

VM4 Introduction to the ASP.Net MVC Framework


- Gus Emery

VM5 Silverlight Design for Developers - Bill Wolff

VM6 WCF Extensibility In-Depth - Jesus Rodriguez

Lunch
VM7 Real World ASP.Net MVC in 75 Minutes!
- Gus Emery

VM8 XAML Crash Course - Billy Hollis

VM9 Advanced Access Control with WCF Michiel van Otegem

VM10 Building High performance ASP.NET web


applications - Peter Kellner

VM11 Silverlight Data Access Methods - Bill Wolff

VM12 WCF-WF Integration In-Depth with an Eye


Towards Dublin - Jesus Rodriguez

VM13 Implementing Caching Technology as One


Rung of the Scalability Ladder - Josef Finsel

VM14 Deep Dive on the WPF/Silverlight Control Set


- Billy Hollis

VM15 Windows Workow and WCF Help Make


Software + Services a Reality - Michael Stiefel

Welcome Reception

Conference Day 2 Tuesday, June 9


KEYNOTE: Silverlight 3
.NET

LINQ

Agile/Design

VT1 Essential C# 4.0 - Mark Michaelis

VT2 Moving from LINQ to SQL to the Entity


Framework - Jim Wooley

VT3 How to Partition and Layer a Software


Application - Michael Stiefel

VT4 Writing Better Code: Using Visual Studio to


Improve Your Code Base - Jason Bock

VT5 Investigating LINQ to XML - Kenneth Getz

VT6 Design Patterns for Mere Mortals


- Philip Japikse

VT7 Practical Parallelism - Rockford Lhotka

VT8 Leveling the LINQ to XML Playing Field with


LINQ to XSD - Leonard Lobel

VT9 Beyond Basic Unit Testing: Mocks, Stubs, User


Interfaces, and Refactoring for Testability
- Benjamin Day

VT10 Exceptional Development: Dealing with


Exceptions in .NET - Jason Bock

VT11 Super-Optimized Microsoft LINQ: Indexed


Objects - Aaron Erickson

VT12 Achieving Balance - Rockford Lhotka

VT13 Self-Writing Programs - Using the Expressions


namespace in C# to Write Code that Writes Code
- Aaron Erickson

VT14 LINQ Kinq for the DBA Guy - Jim Wooley

VT15 Advanced Test Driven Development


- Philip Japikse

Birds-of-a-Feather Lunch

Conference Day 3 Wednesday, June 10


VW1 Introduction to OSLO - Jon Flanders

VW2 Windows Azure: A New Era of Cloud


Computing - Aaron Skonnard

VW3 Get More Out of Team Build 2008


- Brian Randell

VW4 Codename Dublin: Windows Application


Server - Aaron Skonnard

VW5 Windows Azure: Is the Relational Database


Dead? - Benjamin Day

VW6 Dispelling the Myths: Visual Studio


Professional vs. Visual Studio Team System

VSLive! Panel Discussion


Lunch
VW7 Building Textual DSLs with Oslo
- Mark Michaelis

VW8 How to Work with Data in the Cloud: SQL Data


Services Introduction - Josef Finsel

VW9 Customizing Team System Projects


- Brian Randell

VW10 M in Depth: The Underpinnings of Oslo


- Jon Flanders

VW11 Windows Azure, an Enterprise Solution?


- Jerry Sevier

VW12 Better Together: Getting the Most Out of


Visual Studio Team System 2008 Development and
Database Editions

Post-Conference Workshops Thursday, June 11


VPC1 A Day of Windows Azure - Aaron Skonnard

VPC2 SQL Server 2008 for Developers


- Leonard Lobel

VPC3 Build Distributed Apps in .NET 3.5 SP1


- Rockford Lhotka

Should a speaker be unable to attend; all efforts will be made to replace the speaker/session with one of comparable value.

09VSL_LV_VSM_adFinal.indd Sec1:3

3/13/09 7:17:47 PM

0409vsm_How-To_26-32.v5

HOW-TO

3/19/09

10:14 AM

Page 26

SHAREPOINT EXTENSIONS

Build and Debug Web Parts with

SharePoint Extensions
Visual Studio 2008 Extensions for SharePoint makes developing and testing
Web Parts almost easy, provided you install it correctly. BY PETER VOGEL

26

VISUAL STUDIO MAGAZINE April 2009 VisualStudioMagazine.com

0409vsm_How-To_26-32.v5

3/19/09

10:14 AM

Page 27

SHAREPOINT EXTENSIONS

HOW-TO

One of the primary ways to extend SharePoint is to create Web Partsthe same Web
Parts that are used in ASP.NET. But because SharePoint is an application platform
built on top of .NET, creating a Web Part project and then debugging your Web Part
inside SharePoint has always been different and awkward. In addition to making
life difficult for SharePoint developers, the troublesome process has discouraged
ASP.NET developers from bringing their skills to SharePoint.

PHOTO FROM ISTOCK.COM

Microsoft released the Visual Studio 2008 Extensions for


Windows SharePoint Services 1.3 (VSeWSS) as a community
technology preview (CTP) in January 2009. The extensions simplify creating and debugging many kinds of SharePoint components. The CTP version is feature-complete, though presumably
there are still some bugs left to remove (the final version is scheduled for release in the spring). On the Visual Studio side, the CTP
supports VS 2008 but not VS 2005. On the SharePoint side, the
CTP supports both Windows SharePoint Services and Office
SharePoint Server. The Extensions package supports installing
your Web Part, debugging it on the same computer as VS
remote debugging is not supported.
Well walk you through the process of installing the
Extensions and using them to create and debug a Web Part
Project. Along the way, youll see how to create a configurable
search tool for a SharePoint site.
Installing the Extensions
The Extensions download package can be retrieved from
http://tinyurl.com/bjqwmk by following the link in the body of
the page (dont click on the Downloads linkit takes you to a
patch you probably wont need). You can download up to three
components: two .MSI files (one each for 32-bit and 64-bit
Windows) and the release document. You must have IIS,
SharePoint and VS 2008 installed on your computer to run the
installation package.
The installation package installs a Web service (called
VSeWSS) on your computer that VS will use to communicate
with SharePoint. One of the first challenges that youll face after
starting the installation wizard is to configure the Web service
(Figure 1, p. 28). Your first step is to pick an application pool to
use for the Web service. If you dont want to use an existing pool,
youll need to create the new pool in IIS Manager before starting
the installation. There are two conditions that the identity
assigned to the pool must meet:
It must have the same permissions as those granted to the
identity used by the SharePoint Central Administration site
The identity must be part of the Administrators group
I picked the simplest solution to meet the first condition: I
used the SharePoint Central Administration sites pool as the
pool for the Web service. This also saved me from having to set
up a new pool.
To meet the second condition, you must determine the
Identity used by the pool youve picked. You do this in IIS
Manager, under Application Pools, by finding the pool you picked

in the dialog. Once youve found the pool, right-click on it and


select Properties. Youll find the identity name on the Identity tab
(on my machine, the identity was Network Service). The next step
is to add the Identity to the Administrators group: From your
computers Start menu, select Administrative Tools | Computer
Management and drill down through Local Users and Groups |
Group to select Administrators. Right-click on the group, select
Add to Group and enter the name from the Identity tab.
After you make these changes, you can leave the Wizard to
run unattended. After the installation is complete, you can use
VS to determine if your installation was correct.
Creating Your Web Part Project
With the Extensions installed, youre ready to start using their first
feature: A set of SharePoint templates that support creating most
SharePoint components. To create a Web Part, for instance, you
select Web Part project template in the SharePoint category of the
New Project dialog (see Figure 2, p. 28). The resulting project has a
folder called Web Part1delete it (renaming Web Parts is not
100% reliable, at least in the CTP) and use the standard Add New
Item dialog to add your Web Part with the correct name. For this
article, I added a Web Part called VideoSearchPart.
The result is a new folder with the three files required for a
SharePoint Web Part: The code file for the Web Part, an XML file
containing the information needed to install the Web Part and a
.WEBPART file with the XML used to configure the Web Part.
While it doesnt appear in Solution Explorer, the Web Part template also includes a feature.xml and a setup.bat file, which youll
use when installing your Web Part on your production
SharePoint site.
Because you can only debug your WebPart on your development computer, youll need to either copy your target site to
your local computer or create a test site on your computer. In
this particular case, I created a test SharePoint site by starting
SharePoint Central Administration from my Start menu and,
from the Application Management tab, picking Create or
Extend Web Site to bring up the dialog that lets me add a new
site. After clicking the OK button to create my site, I used the
next page in the process to add a Site Collection using
SharePoints Wiki template.
If your development SharePoint site isnt installed on port
80 at http://Localhost then youll have one more configuration
step to make: You must set the start URL for debugging to point
to the URL for your site. To do this, open your project properties,
navigate to the Debug tab and set the Start browser with URL
VisualStudioMagazine.com April 2009 VISUAL STUDIO MAGAZINE 27

0409vsm_How-To_26-32.v5

HOW-TO

3/19/09

10:15 AM

Page 28

SHAREPOINT EXTENSIONS

text box to the URL for the local SharePoint site


where you want to test your Web Part .
With your project created and configured,
you can now check to see if your installation went
correctly: Right-click on the project and select
Quick Deploy | Recycle Application Pool. If there
were any errors in your installation, you will get a
message in your Error List. If you changed the
Start browser with URL option and you get a
message that refers to the original LocalHost URL,
select Recycle the Application Pool option again
(the Extensions seem to use the original setting
once, before using your updated setting).
Configuring the Project and the Site
Youre not quite ready to start creating your Web
Part. While the Extensions make debugging easy,
they dont configure your SharePoint site to support
debugging or report error information. To make
these changes, return to IIS Manager, drill down
through Web sites to your SharePoint site, rightclick and select Properties. On the Home Directory
tab, youll find the path to the folder holding your
sites files in the Local path text box. In Windows
Explorer, navigate to that folder and open the
web.config file in the folder. In this file, change the
debug attribute on the compilation element to
true in order to turn on debugging:

FIGURE 1. Configuring the Web service: You cant move off of this page in
the Extensions setup wizard until youve successfully configured the application pool used by the Extensions Web service.

<compilation batch="false" debug="true">

You should also configure your SharePoint site to


display any error messages that are generated by setting the customErrors tags mode attribute to Off
(the default setting suppresses all error messages):
<customErrors mode="Off" />

To get the full list of called modules listed on the


error screen, youll also need to set the SafeModes
CallStack attribute to true:
<SafeMode CallStack="true" />

FIGURE 2. SharePoint Project Template: The SharePoint Extensions add a


SharePoint category to the Add New Item dialog containing a set of tem-

Before adding code to the .VB or .CS file that repreplates for SharePoint components.
sents your Web Part, you should update the .XML
and .WEBPART files in the project (it doesnt appear
to be possible to change these values after debugging
your Web Part for the first time, at least in the CTP). Inside the By default, your Web Part will appear in the Add Web Parts dialog
properties element in the .WEBPART file, rewrite the default prop- in the Miscellaneous section. To have your Web Part appear in a
erty elements in the file with the title and description you want to different category, open your Web Parts XML file and add two
have displayed in SharePoints Add a Web Part dialog. This example Property tags inside the File element: One with its Name attribshows the settings for my sample search part:
ute set to Group and the other with its Name attribute set to
QuickAddGroups. With the two properties defined, set the Value
attribute on both tags to whatever value you want for your group
<properties>
name. This example will cause the part to appear in a section
<property name="Title type="string">Video Title
called PHV Tools:
Search</property>
<property name="Description" type="string">Fuzzy
search on video titles</property>
</properties>

28

VISUAL STUDIO MAGAZINE April 2009 VisualStudioMagazine.com

<File Path="VideoSearchPart.webpart"
Url="VideoSearchPart.webpart"

Project7

3/5/09

12:14 PM

Page 1

0409vsm_How-To_26-32.v5

HOW-TO

3/19/09

10:15 AM

Page 30

SHAREPOINT EXTENSIONS

Type="GhostableInLibrary" >
<Property Name="Group Value="PHV Tools"/>
<Property Name=vvQuickAddGroups Value=PHV Tools"
/>
</File>

Dim trButton As New TableRow


tbl.Rows.Add(trButton)

Programming the Web Part


Youre finally ready to start creating your Web Part. Within the
Web Parts code file you mustin the CreateChildControls
methodcreate the controls that will appear on your Web Part.
The simplest approach is to create a table, add it to the Web Part
objects Controls collection, add rows and cells to the table, then
add your controls to the Controls collection of the cells in the
table. This code adds a Label control to the first cell in the first
row of the table:

Dim tcButton As New TableCell


trButton.Cells.Add(tcButton)

Dim tbl As New Table


Me.Controls.Add(tbl)

Dim tcTitle As New TableCell


trTitle.Cells.Add(tcTitle)
Dim TitleLabel As New Label()
TitleLabel.Text = "Look for movies with title:"
tcText.Controls.Add(SearchTitle)

For my example, I created a table with four rows: the first row
contains a Label and TextBox for the user to enter the title of a
movie to search for, the second row contains a Label and a
TextBox for the user to enter a category (such as Action or
Drama), the third row contains the button to trigger the search,
and the final row holds a GridView to display the result. In the
CreateControls method, you should also wire up any events

SharePoint
vs. SQL
Is MOSS putting the squeeze on
database development?
BY JEFFREY SCHWARTZ
It has been well-chronicled how pervasive
Microsoft Office SharePoint Server
(MOSS) is becoming in the enterprise.
But for some database developers
and administratorsand in certain cases
even higher-ups in the IT food chain
SharePoints rampant growth is a concern,
particularly in organizations where data
that belongs in SQL Server is finding its
way into MOSS. You dont have to be a
developer to go in there, says Ed Smith,
a systems analyst at Tetra Pak
International, a global supplier of

Dim SearchButton As New Button()


SearchButton.Text = "Search"
AddHandler SearchButton.Click, AddressOf Me.StartSearch
tcButton.Controls.Add(SearchButton)

The event routine pulls data from the two TextBoxes in the table
(in the first and second rows) and fills a DataSet that is bound to
a GridView (in the fourth row):
Private Sub StartSearch(ByVal sender As Object, _
ByVal e As System.EventArgs)
Dim conn As New SqlConnection("")
Dim cm As SqlCommand = conn.CreateCommand
Dim da As New SqlDataAdapter(cm)
Dim ds As New System.Data.DataSet
Dim searchString As String

Dim trTitle As New TableRow


tbl.Rows.Add(trTitle)

30

that your Part needs. This code adds a button to the table and
wires an event routine to it:

Dim tbl As Table


tbl = CType(Me.Controls(0), Table)
searchString = CType( _
tbl.Rows(0).Cells(0).Controls(1), TextBox).Text
cm.CommandText = "Select * From "
da.Fill(ds, "Results")
Dim gv As GridView
gv = CType(tbl.Rows(2).Cells(0).Controls(1), GridView)

packaging machines. You can get two


secretaries together, they can figure out
what they want to do and they can start
putting stuff in there.
This is a common occurrence that
can quickly become problematic, particularly in cases where data that requires
referential integrity is put into a
SharePoint list, says independent consultant and Microsoft MVP Don Demsak,
whos observed this trend and a growing
demand for SharePoint developers.
SharePoint is very successful because
youre removing levels of impedance, and
a lot of DBAs hate SharePoint for those
same reasons, explains Demsak.
Basically youre storing everything in a
BLOB, and you cant relate to object-relational mapping, and you cant do good
entity relationships. You cant do relational models because theres all sorts of

VISUAL STUDIO MAGAZINE April 2009 VisualStudioMagazine.com

problems when people try to extend that


SharePoint model past where its supposed to go.

Strengths and Weaknesses


SharePoint is popular for storing and
sharing documents and other unstructured content, but when an individual has
data based on rows and columns and is
trying to join one list to another, thats
not what those tools were made for,
Demsak says. When you need a relational database, you use a relational databasethe way it was supposed to be.
Paul Andrew, Microsoft technical
product manager for the SharePoint
developer platform says many are already
building custom applications on
SharePoint that use a mix of SQL Server
schema and tables within MOSS. Of
course, each has its own strengths, and

0409vsm_How-To_26-32.v5

3/19/09

10:15 AM

Page 31

SHAREPOINT EXTENSIONS

SharePoint will now allow the user to set a value for the Category
property by selecting the Personalize this Page choice on the
Welcome Usermenu at the top of the page to put the page in personalization mode. Once the user enters a value, SharePoint will
ensure that the property is automatically set to that value whenever
the user returns to the page.

gv.DataSource = ds
gv.DataMember = "Results"
gv.DataBind()
End Sub

It wouldnt be a real SharePoint application if it didnt support


some level of customization. For my example, the category
TextBox is supported by a customizable category property that
manages an internal field called _category:
Private _category As String
<Personalizable(PersonalizationScope.User)> _
<WebBrowsable(True)> _
<WebDisplayName("Movie category")> _
<System.ComponentModel.Category( _
"Movie Search Settings")> _
<WebDescription( _
"A valid movie category to search within")>
Public Property Category() As String
Get
Return _category
End Get
Set(ByVal value As String)
_category = value
End Set
End Property

Simple Debugging
At this point, you get the real payoff for the work youve done in setting up SharePoint Extensions and configuring your project: to test
and debug your project you just set breakpoints in your code and
press F5. When your site displays, youll need to add your Web Part
to a page by selecting, from the Site Actions menu, the Edit Page
choice. When the page redisplays in Edit Mode, click on any of the
Add Web Parts bars to display the Add a Web Part dialog with your
Web Part. After adding the Web Part to your page youll find that
you can debug it as you would any other .NET project type.
The SharePoint Extensions are a real boon for developers
creating SharePoint apps. In addition to simplifying the process
for creating new Web Part projects, the debugging process is
much simpler. Not only does this make life easier for
SharePoint developers, it lowers the barrier to entry for
ASP.NET developers interested in migrating their skills to the
SharePoint arena. VSM
Peter Vogel (peter.vogel@phvis.com) is a principal in PH&V Information
Services, specializing in ASP.NET development with expertise in SOA, XML,
database and UI design. Hes written several books on app development using
Microsoft technologies and presents at conferences around the world.

When the SeachCategory TextBox is added to the Table that


makes up the control, I initialize the TextBox with the _category
field that is set through the personalizable property:

GO ONLINE

Dim SearchCategory As New TextBox()


SearchCategory.Text = _category
tcCategory.Controls.Add(SearchCategory)

READ & DOWNLOAD

each is better suited in different parts of


an application, Andrew says.
Complex data with a deep relational
structure doesnt fit well in SharePoint
lists, according to John Beasley, a director with U.K.-based Microsoft Gold
Certified Partner InfoStrata Solutions Ltd.
To get around this, he uses Quest Web
Parts for SharePoint, which allows simple
relational structures to be simulated in
SharePoint lists, as well as allowing
developers to keep data in SQL Server
while accessing it via SharePoint.
InfoStrata is a Quest partner, but there
are other third-party tools developers
such as Bamboo Solutions and
CorasWorks Corp.that make use of
ASP.NET Web Parts Controls to enable the
building of customizable pages.
SharePoint, Beasley notes, removes
the tedium of re-developing routine facili-

HOW-TO

Use this Locator+ code at VisualStudioMagazine.com to go


directly to these related resources.

VS0904PV Read this article and download the associated code.

ties, such as security, document management and workspaces. This massively


reduces our time to market, he says in an
e-mail. Using these tools means you get
to do all the correct data analysis youre
used to, but can still use SharePoint to
provide all the front-end facilities its so
good at providing.

Adding Controls
Still, others argue that companies need to
understand when to build applications for
SQL Server versus SharePoint. Looking
at SharePoint Lists and relational databases, there isnt a comparison, says
Graham Sutcliffe, director of technology
at RD2 Inc., a Dallas-based design firm.
They both have their uses. You
cant stifle an organizations progression,
but you have to put people in charge of
its data. Not trusting the data is the same

as not trusting the CEOs decisions,


because essentially thats what decisions
are made upon, he says, before adding a
caution: One thing you dont want to do
is swing the pendulum too far and turn
the people responsible for data into a religious organization.
Others are avoiding the problem
altogether by putting controls over whos
permitted to commit data to MOSS
servers. Thats the case for the city of
Prince George, British Columbia, Canada.
Weve locked it down pretty much, so
that all they can do is put in content
directly, says programmer and analyst
Rob Woods. Nobody else really has the
option of doing any of this kind of stuff
except for the IT staff.

Jeffrey Schwartz (jschwartz@1105media.com) is


the news editor for Visual Studio Magazine.

VisualStudioMagazine.com April 2009 VISUAL STUDIO MAGAZINE 31

0409vsm_Langlab_32-46.v11

3/19/09

10:57 AM

Page 32

</Language Lab>
YO U R CO D E S OU RC E

IN THIS SECTION:

On VB 32 // C# Corner 40 // Ask Kathleen 42 ///////////

XML Literals

XML Literals

{ ON VB }

XML Literals,
WCF and LINQ
Learn how to create powerful templates that can be
called from both client- and server-side code.
BY STEELE PRICE
One of the great things about .NET Framework is that there is
so much included to make your life as a developer easier. Over
the past few years weve been flooded with new capabilities.
Staying current with all of these tools is nearly a full-time job.
So whats a developer to do? I choose to pick the tools that apply
directly to a problem I need to solve and use those new capabilities to enhance my productivity. Even more power and flexibility comes when we can take several of these capabilities and
combine them for a unique solution to a problem.
Were going to look specifically at three pieces of the
framework that can be combined to provide a new technique.
This technique helps in writing more responsive ASP.NET pages,
while at the same time making the code more readable. The
three technologies are: XML literals, Windows Communication
Foundation (WCF) Factory Services and LINQ. XML literals
and LINQ are new in Visual Basic 9 (VB9). LINQ gives us a
common syntax for querying just about any data, be it SQL,
XML or objects. Even though WCF has been here for a while,
the out-of-the-box readiness for building factory services is little-known. Here well show you how to create WCF services without changes to config files for endpoints, behaviors and bindings.

XML Literals
VB9 includes XML literals, an incredibly useful new tool. With
XML literals, what used to be an archaic, difficult process of
reading and writing raw XML or XHTML has become straightforward and simple. Type raw XML into the Visual Studio
Editor and it understands that you want an XElement. An XML
literal on its own is a remarkable piece of technology that can
help VB developers in many, many ways.
What used to make code difficult to read becomes transparent when using XML literals. For example, using a
StringBuilder to write long strings makes writing joined strings
easier and more performant:

Dim MyText = String.Empty


Dim sb As New StringBuilder
With sb
.Append("This is a String.")
.Append(vbCrLf)
.Append(vbTab)
.Append("You will notice that the whitespace ")
.Append("is retained when we use the string.")
.Append(vbCrLf)
.Append(vbTab)
.Append(vbCrLf)
.Append(vbTab)
.Append("This is just the beginning and is a bit ")
.Append("easier to read than StringBuilder, right?")
MyText = .ToString
End With

Reading and writing these in the editor is less productive than if


you could just write the whole string and retain the whitespace
as follows:
<MyString>
This is a String.
You will notice that the whitespace is retained when
we use the string.
This is just the beginning and is a bit easier to read
than StringBuilder, right?
</MyString>

Compared to StringBuilder, XML literals are far easier to read


and much less to type. Use MyString.Value to get the text inside
without the <MyString> tags. The goal here is not to maximize
performance in the runtime, but to be more productive. You
can actually read the string and dont worry; performance will
still be very good.
String handling with XML literals is just a side note. For
structured elements that really are XML, such as XHTML, there
is no comparison. The XML literals approach gives us a highly
readable, productivity enhanced solution to writing structured
XML in code behind. Consider the following:

XML literals give you the power to create data

presentation dynamically, in ways that are more productive


than many other alternatives.
32

VISUAL STUDIO MAGAZINE April 2009 VisualStudioMagazine.com

0409vsm_Langlab_32-46.v11

3/19/09

10:57 AM

Page 33

Language Lab
On VB

Reading XHTML in code behind is


now remarkably easier. You also get
true IntelliSense for the elements that
are in a known namespace, which of
course means even less typing. XML
namespaces are recognized by using
Imports statements such as the following for XAML:

XML Literals

Dim MyTable = _
<table>
<tr>
<td>
First Cell Contents
</td>
<td>
Second Cell Contents
</td>
</tr>
</table>

FIGURE 1. When you add a new template to your Web application, it appears in the My
Templates area at the bottom of the Add New Item dialog box.

Imports <xmlns=
"http://schemas.microsoft.com/
winfx/2006/xaml/presentation">
Imports <xmlns:x=
"http://schemas.microsoft.com/
winfx/2006/xaml">
Imports System.Windows.Markup

The result of all this is that you can do things the same way for
code behind as you are used to doing in ASPX source view.
Productivity increases by continuing to write markup this way.
You do not have to learn another language or syntax to achieve
the same in code behind.
Embedded expressions also look very similar to what you
are used to seeing in markup:
<td><%= item.@id %></td>

An embedded expression lets you access something outside the


XML literal and embed it into the result. In this case; item.@id
is an attribute from an item element in another XElement.
Additionally, variables arent limited here; you can use lambdas,
functions or anything else available to VB.
I know what youre thinking, so Ill go ahead and say it. If
youre loading from XML and returning XML, cant you just
use XSLT? Of course we could, but what fun is that? In fact, I
came up with this technique in a project overhaul that was
using XSLT in its previous version. During development, it
became quite clear that working in XSLT was not the way to go
for us. XSLT is a completely different mindset for most of us
and has a fairly steep learning curve. In addition, the old system was forcing SQL to return data as XML, which is not
exactly optimal. This approach eliminated that issue while
dramatically improving performance. Ultimately, using XML
literals means you can be productive faster and have more

tools at your disposal for debugging, without learning a new


language.
WCF Factory Services
I have a Web site that is currently in production. I need to add
some performance features to it and I dont want to retool to
accomplish what I need. I could use AJAX and update panels,
but then I would need to account for the entire page lifecycle,
which in some cases may be quite large.
For example, I have a page that contains aggregate information and I wish to display that in a table format. I could put
all my aggregates into GridView objects and then place those
inside update panels, then no, no, no. Im sure you see the
trouble here already. If I have more than one update panel on
the page, Im really loading the entire page multiple times, just
to get my aggregated information to run asynchronously.
How can you achieve this without creating a new project,
using PageMethods or something else with a large lifecycle?
Enter Windows Communication Foundation (WCF). WCF has
always had a lesser-known feature called a factory service. With
factory services, you dont have to worry about things like security, as it inherits the same security as the site. As for config settings, there are none. This is a perfect solution when you need to
access some information in an AJAX way from client-side code.
The factory services are quite similar to WebMethod(), but
theyre completely WCF compliant. To create a factory service,
you simply create a new WCF service. But wait, you said factory
service; I dont see any factory service in my Add Items templates.
That is correct, to create a configuration-less factory service you need to do it by hand; editing the .SVC file of an AJAXenabled WCF service. To do this, open the .SVC file with the
XML editor and add the following:
Factory="System.ServiceModel.Activation.WebScriptServi
ceHostFactory"

VisualStudioMagazine.com April 2009 VISUAL STUDIO MAGAZINE 33

0409vsm_Langlab_32-46.v11

3/19/09

10:57 AM

Page 34

</Language Lab>

XML Literals

On VB

Then you have to go and delete the config information.


Because this isnt an intuitive way to proceed, I created a template that you can install to do the same thing. Install
the template by copying WCF_Factor ySer vice.zip to
C:\Users\<yourusername>\Documents\Visual Studio 2008\
Templates\ ItemTemplates\Visual Basic
With this template, you can create services that your Web
application can use in a very easy way with no bother to the current configuration. If you need to move to a full service with different bindings, its very easy to change this from a factory service. Simply delete the factory attribute from the .SVC file and
add your binding, behavior, service and endpoint configurations
to web.config.
Something you might be thinking: Why use WCF services
and not a regular page that just returns the small amount of data
we need?
While this approach makes sense in some instances, you
still have a full-page lifecycle to deal with. Furthermore, the
results arent as easy to work with when you want to insert them
into a portion of an already rendered page with JavaScript. If
you used a page you would have to do quite a bit of parsing. In
addition to the speed of execution for WCF, there are supporting features that will make life easier. Throwing FaultExceptions
is one thing you cannot do with page results. You can throw
HttpExceptions, but they arent handled the same way on
the client.
Using LINQ
LINQ provides the magic you need to glue all this together.
Writing markup in code behind is easier to read, while accessing
the same code from both the client side and the server side gives
you a lot of power. Combining LINQ and embedded expressions in XML literals gives you a better way to handle looping
through data.
Instead of a table, lets shift to something more demonstrative, the <ul> element. Say you just need to iterate through a
group of items and return an unordered list. Unordered lists are
great for things like menus and navigation. How is this accomplished with our new toolset? Lets look into that now. In the past
you had to do something like the following:
Dim ul as New HtmlGenericControl("ul")
Dim li As HtmlGenericControl
For Each i In items
li = New HtmlGenericControl("li")
li.InnerHtml = i.Value
ul.Controls.Add(li)
Next

The embedded expressions let you insert external data into


your elements with much less code. Given the same data, the
output is identical.
Lets dissect whats happening here. MyMenu is an
XElement cast by Option Infer, which is a new feature in VB9
that lets you declare variables without explicitly stating a data
type. The compiler infers the data type of a variable from
the type of its initialization expression. The <ul> element is
outside the LINQ query so its not repeated. The LINQ query
iterates through the items and returns a group of <li> elements inside the <ul> element, with the items value inserted
into the list item.
All of this can now be done in one line of easy to read and
simple to type code. Anything used for lists of data can be done
this way: tables, unordered lists, ordered lists, select inputs
(dropdowns), and the like. Have you ever done a view source on
a page only to see a dropdown with all the states listed as options
in the HTML? Using WCF services with AJAX will keep people
from being able to see this with view source. Youll probably get
your page to load faster if that was an AJAX call.
XML literals give you the power to create data presentation dynamically, in ways that are more productive than many
other alternatives. Any LINQ-enabled data, SQL, entities,
objects, files, WMI, XML, RSS feeds and the like can be
accessed this way.
Now that you have all three pieces in place, your Web application is wired up to both client and server sides. Accessing the
service from the server is as simple as calling a method. The service is already there and calling it is as simple as Services.
GetPresidentsList().
On the client you can use ASP.NET AJAX or jQuery to
call the service. Referencing services in ASP.NET AJAX is
incredibly easyjust add a ScriptManager that points to the
service as follows:
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path=
"~/Services/MyFactoryService.svc" />
</Services>
</asp:ScriptManager>

Calling the service in JavaScript is now very easy and completely


wired up for us:
function getPresidents(){
var ws = new Services.MyService();
ws.GetPresidentsList(getPresidentsComplete);
}

Now you can do this:


Dim MyMenu = <ul><%=
From i In items Select <li><%=
i.Value %></li>%></ul>

34

VISUAL STUDIO MAGAZINE April 2009 VisualStudioMagazine.com

function getPresidentsComplete(result, eventArgs){


if (result.d !== null){
$find("<%= PresidentsArea.ClientID %>").InnerHtml =
result.d;}
}

0208vsm_VSMPureAd.final

1/18/08

11:46 AM

Page 32

PURE

VISUAL STUDIO AND .NET

E N T E R P R I S E

S O L U T I O N S

F O R

.N E T

D E V E L O P M E N T

M A G A Z I N E . C O M

POWERING THE WINDOWS SOFTWARE REVOLUTION

OPTIMIZED FOR
PRINT ONLINE EVENTS

For more information visit:


www.VisualStudioMagazine.com
www.RedDevNews.com
www.VSLive.com

0409vsm_Langlab_32-46.v11

3/19/09

10:57 AM

Page 36

</Language Lab>
On VB

XML Literals

This makes an asynchronous call to the service and the result is


returned when the ser vice performs a callback to
getPresidentsComplete (). You have the ability to call the service
both synchronously and asynchronously, depending on what
you need to accomplish. Heres the same idea using jQuery:
$.ajax({
type: 'POST',
url: '/Services/MyFactoryService.svc/'
+ 'GetPresidentsList',
data: '{}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(result, eventArgs) {
if (result.d !== null){
$("#<%= PresidentsArea.ClientID %>")
[0].innerHTML = result.d;}
},
error: onServiceError
});

The json notation is assigned for the dataType because WCF is


returning JSON for the result object. The syntax is a little different, but is still pretty easy to use. jQuerys nice ajax() method
does all the work for you, and what you get returned from the
service ends up in result.d. I used an anonymous function here
to retrieve the result, which we expect to be XHTML into the
InnerHtml of our div element target.
We can inspect for errors, but you can see that if we threw
any FaultExceptions in the WCF service, then another function
called onServiceError runs. The Error Handling function is
passed to the result object for us to inspect for errors and react
accordingly.
My normal process for using this in a production application is to define a single function in my master page for calling
the service. If you provide accessibility through several shortcuts, getting results from the services and assigning those results
become even easier.
Heres a sample that Ive used:
function execMyFactoryService(method, target)
{
var rval = '';
$.ajax({
type: 'POST',
url: '/Services/MyFactoryService.svc/' + method,
data: '{}',
async: true,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(result, eventArgs) {
if (result.d !== null){
target.innerHTML = result.d;
}
},

36

VISUAL STUDIO MAGAZINE April 2009 VisualStudioMagazine.com

error: function(result) {
var msg = '';
if (result.get_message) {
msg = 'Error: ' + result.get_message();
} else {
msg = result.responseText;
if (msg == '') {
msg = 'Error: Unknown... missing Service?'; }
}
alert(msg);
target.innerHTML = '';
}
});
}

Assigning our result to a position on our page is simple. Place


a <div> element anywhere on your page and set the
innerHTML to the result. Anywhere Im using that master
page; I will have a function that I can use to directly assign
the results:
execMyFactoryService('GetPresidentsList',
$("#<%= PresidentsArea.ClientID %>")[0]);

All the error handling and result inspection is handled centrally


and when were assigning results as the response to some action
on the Page, this makes understanding whats happening much
easier. If we were to use the full $.ajax syntax everywhere we
needed to use it, it might make the scripting too verbose to be
readable at first glance.
jQuery provides a great productivity boost through a superb
set of tools for navigating and manipulating DOM objects in
JavaScript. Some of the same features are in ASP.NET AJAX, but
the two models can be used together to provide even more power
for your client-side activities.
The Whole Picture
Now that Ive explained the parts and pieces, how does it all
work together? Lets explore this a little further. A complete
template looks like this inside the service:
<OperationContract()> _
Public Function GetPresidentsTable() As XElement
Dim items = XElement.Load(ApplicationPhysicalPath & _
"App_Data/SampleData.xml")
Try
Dim result = _
<table>
<thead>
<th>Position</th>
<th>Name</th>
<th>Began Term</th>
<th>Finished Term</th>
</thead>
<%= From i In items.Elements Select _

0409vsm_Langlab_32-46.v11

3/19/09

10:57 AM

Page 37

On VB

Lambdas are a new feature in VB9 and can save you a lot of

hassle when you need a quick function. LINQ itself is actually a framework
built on lambda expressions and are an integral part of how it works.

i.@id %></td>
i.@Name %></td>
i.@Start %></td>
i.@End %></td>

Catch ex As Exception
' This is not returning a StackTrace,
' its a shortcut to get the current Method Name
Throw New FaultException(New StackTrace() _
.GetFrame(0).GetMethod() _
.Name & ": " & ex.Message)
Return Nothing
End Try
End Function

The service is a WCF factory service. These are very simple to


create, with the Visual Studio Template included here.
I use a Services Folder in my Application for organization
and security. Add the Services Folder, and then add a web.config for the folder. This lets us assign different security rights to
the services in the folder if we need to limit them by Roles.
Adding a New Item to your Web Application looks like Figure
1, p. 33.
The new Template is in the My Templates area at the bottom
of the dialog. If youre like me, you probably have many installed
Templates you need to scroll through to get to My Templates.
When the template creates the service, we can inspect the
configuration data using Open With.
Choose XML Editor from the list. This will open the .SVC
file for us, rather than the code behind that gets opened when
you double-click on the file itself. You may see some
IntelliSense confusion from the editor, but you can safely
ignore it.
The generated service is:
<%@ ServiceHost
Language="VB"
Debug="true"
Service="Services.MyFactoryService"
Factory="System.ServiceModel.Activation.
WebScriptServiceHostFactory"
CodeBehind="MyService.svc.vb" %>

The code behind is:


Imports System.ServiceModel
Imports System.ServiceModel.Activation

Imports System.Web.Script.Serialization
Imports System.Runtime.Serialization
Namespace Services
''' <summary>
''' This Service provides access to various
''' MyFactoryService procedures through WCF
''' </summary>
''' <remarks></remarks>
<ServiceBehavior( _
IncludeExceptionDetailInFaults:=True)> _
<ServiceContract(Namespace:="Services", Name:= _
"MyFactoryService")> _
<AspNetCompatibilityRequirements( _
RequirementsMode:= _
AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class MyService

XML Literals

<tr>
<td><%=
<td><%=
<td><%=
<td><%=
</tr> _
%>
</table>
Return result

<OperationContract()> _
Public Sub DoWork()
End Sub
End Class
End Namespace

All thats left for us to do is enter the code into DoWork().


Usually youll want to rename this, which is fine, because whats
presented here is just a stub to get us started.
For debugging we simply add a Try/Catch block to handle
anything bad that may cause the template to break. For this
example we are just returning Nothing, but we could add very
rich error handling here by throwing FaultExceptions.
FaultExceptions are handled quite nicely by ASP.NET AJAX and
jQuery on the client. You can decide how to handle problems in
the service and the client can respond using a combination of
results and error handling.
Lets talk briefly about what you can do with this in your
toolbox. I want to display a bunch of images dynamically.
Maybe I want to get the results from a search out on the Web. I
could configure something in the client, or I could stay consistent and use our own services. This lets us control everything
and not expose possibly sensitive information in the clientside code, such as a password. We wont build that one right
now, but think about how useful it could be to control going
out to your external service accounts to grab dynamic status
or images from social networking services.
In our Presidents sample we could go look on an external
service for the images of the Presidents. Configuring this is
really quite easy now that we have a set of tools to work with
that makes this simple. I could use a WebClient to call the
VisualStudioMagazine.com April 2009 VISUAL STUDIO MAGAZINE 37

0409vsm_Langlab_32-46.v11

3/19/09

10:57 AM

Page 38

</Language Lab>
On VB

jQuery provides a great productivity boost through a superb

XML Literals

set of tools for navigating and manipulating DOM objects in JavaScript.


Some of the same features are in ASP.NET AJAX, but the two models can be
used together to provide even more power for your client-side activities.
external API and work with the results in the service prior to
returning them.
What if I already have the images? How do I get them
from the file system easily? I would create a service method
similar to this:
<OperationContract()> _
Public Function GetPortrait( _
ByVal value As String) As XElement
Dim image = (From FileName In _
My.Computer.FileSystem.GetFiles( _
HttpContext.Current.Server.MapPath( _
"~/Images"))
Where FileName.StartsWith(value) Let File = _
My.Computer.FileSystem.GetFileInfo(FileName)
Select <img src=<%=
HttpContext.Current.Server.MapPath( _
File.FullName) %>
title=<%= File.Name %>></img>).First()
Return image
End Function

I have provided a dynamic function to return an image from


our file systemcertainly not a daunting task for us now. We
can expand this to handle getting the image path any way that
suits our needs and we can surround all the proper error handling in the function. I can return either an appropriate fault
exception or an empty element to just ignore missing images, so
the client doesnt see errors.
When designing a template consider whats static and
what requires looping. Looping should be done with either
LINQ or lambdas in this case. A Do Loop or For Each works
just as well, but I find myself replacing them with LINQ since I
had no other alternative before. It also makes the code much
easier to work with in templates if you use LINQ.
Something to consider here is the use of lambda expressions. Lambdas are a new feature in VB9 and can save you a
lot of hassle when you need a quick function. LINQ itself is
actually a framework built on lambda expressions and are an
integral part of how it works. Lambdas in Visual Basic look
like this:
Function(u) If(u.Age < 18, _
u.ParentPermissionGranted, u.PermissionGranted)

38

VISUAL STUDIO MAGAZINE April 2009 VisualStudioMagazine.com

This function will evaluate the condition, and then return a


different field from the user object based on the condition.
The interesting thing here is that we didnt have to tell the
lambda what u is, inference will do that for us most of the
time. Occasionally inference gets confused and you may need
to qualify what u is which you can do with:
Function(u As User)

I dont want to go on too much about lambdas, you will use


them all the time with LINQ. Just about any time you need a
Where clause youll be using lambdas. LINQ hides some of the
verbosity for you when youre using the full query syntax, but
its still a lambda. When you use the extension syntax you
almost always use lambdas:
items.Elements.Where(Function(i) i.@id = 1)

Another reason I bring this up now is to answer the question:


What if we need to return complex conditioning to our data
when we build the return? This is much easier with lambdas
than creating a bunch of functions that may only be used for
this specific template. When building our template, maybe we
want to change the elements returned based on some criteria in
the data. Extended syntax like lambdas make very powerful
tools for building templates.
Easy Formatting Based on Conditions
Because we have a true ternary If() command available to us we
can make templates that do this:
<%= If(items.Count = 0, _
<tr id="norecords" class="GridRow">
<td style="text-align: left" colSpan="4">
<div>No records to display.</div>
</td>
</tr>, _
CType(Nothing, XElement)) _
%>
<%= - continue normal processing - %>

This template lets us return Nothing when we have real data to


work with, or an element describing the lack of data to the
user. I can go on and on about the wealth of possibilities you
have at your disposal when using all these techniques together.

0409vsm_Langlab_32-46.v11

3/19/09

10:57 AM

Page 39

Instantly Search
Terabytes of Text
The Bottom Line
Currently, nothing else is this flexible and this easy with the outof-the-box tools we get with Visual Studio 2008. You have complete access to all the features of .NET Framework for building
your templates. Calling them from both the client and server is
extremely easy, and because youre using WCF, thers no added
page lifecycle overhead. A similar service can be created to return
XAML instead of XHTML. This makes migrating or extending
your templates extremely easy if you need access from Silverlight
or WPF in the future.
T4 templates and other code generator-based utilities are
great when you can generate everything in advance. This technique goes beyond that to generate during runtime, and we can
generate runtime-ready code in any XML derivative such as
XAML and XHTML.
ASP.NET 4.0 is expected to provide a new template system,
but that doesnt change the usefulness of this technique. ASP.NET
4.0 will be using a completely different system, which may or may
not be as easy to use and as flexible in what it returns. From what
Ive seen so far, it looks good, but it still doesnt solve the immediate
issues that are addressed by using this technique.
XML literals, WCF factory services and LINQ, taken by
themselves, are very useful. When these are combined, you get a
completely different picture for solving real-world problems. All
while maintaining a productive, easy-to-implement style.
XML literals provide high productivity and readability
when writing structured XML in code behind. It can also help
format long or complex strings to make them more readable.
Embedded expressions give you the power to insert external
data into the XML in a very easy-to-read and -maintain way.
WCF factory services allow you to extend the power of the
framework to your client-side code without the hassle of all the
configuration knobs and buttons that are available to WCF
services. Starting with a factory service does not limit you in any
way from upgrading to the full configuration format later. A
simple change enables a progressive upgrade path when you
need this ability.
Finally, using LINQ in embedded expressions enables you
to insert external data into XML in a way that is easy to read,
with much less code to accomplish the task. LINQ allows you to
start thinking differently about how you process loops through
any data utilizing the same syntax. Now go see what you can do
with all this new power and productivity. VSM
Steele Price (steeleprice@usa.net) has been professionally designing and
developing data-driven applications for more than 25 years. He has been a
Microsoft MVP for Visual Basic since 2005 and frequently works with the
Microsoft VB team to help improve the language. Price is currently chief
technology officer at Digital Dreamshop, a micro ISV developing enterprise
applications with VB.NET, Silverlight, Windows Presentation Foundation
and LINQ.

N dozens of indexed,

unindexed,
fielded data and
full-text search
options (including
Unicode support
for hundreds
of international
languages)
N file parsers /

converters for
hit-highlighted
display of all
popular file
types
N Spider supports

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

h Spider
Desktop wit
h Spider
Network wit
CD/DVDs
Publish for
pider
Web with S
Win & .NET
Engine for
Linux
Engine for

New
64-bit

N API supports .NET, C++, Java, databases, etc.

New .NET Spider API

The Smart Choice for Text Retrieval


since 1991
N Bottom line: dtSearch manages a terabyte of text

in a single index and returns results in less than a


second InfoWorld
N For combing through large amounts of data,

dtSearch leads the market Network Computing


N dtSearch covers all data sources ... powerful

Web-based engines eWEEK


N dtSearch searches at blazing speeds Computer

Reseller News Test Center


See www.dtsearch.com for hundreds more reviews,
and hundreds of developer case studies

GO ONLINE

Use this Locator+ code at VisualStudioMagazine.com to go


directly to these related resources.

Contact dtSearch for


fully-functional evaluations

READ MORE
VS0904OV Read this article online.

1-800-IT-FINDS www.dtsearch.com
VisualStudioMagazine.com April 2009 VISUAL STUDIO MAGAZINE 39

0409vsm_Langlab_32-46.v11

3/19/09

10:57 AM

Page 40

</Language Lab>
{ C#CORNER }

Clear Code

Make Your Code Clear


There are multiple ways to solve every problem. Strive
for code that communicates your intent and makes your
meaning clear for every developer who uses it.
BY BILL WAGNER
Its often not that hard to create code that works. What often
separates average code from high-quality code is how well that
codeespecially its public interfacedescribes its own capabilities. A small time investment in your code will save time
explaining how it works and avoid enhancing it unnecessarily,
creating more work for yourself and your users.
In this article, Ill walk you through a review of a small
library, discussing a series of changes and the motivation
behind those changes. Youll see how to improve the resiliency
and quality of a codebase.

A Working Numeric Library


Listing 1 (opposite page) shows a small numeric class that performs a few simple calculations on a sequence of numbers. This
library has some simple mathematical functions: mean, median, variance, minimum and maximum. Its not a major library,
but there are enough methods here to demonstrate the concepts involved in shaping the impression your code can give to
customer developers.
This library works, but there are many areas where the code
can be improved. When developers look at your API, theyll create
an impression of the library based on your stated API. If theyre
your team members and they examine your source, theyll continue to build on those assumptions. Your code gives those client
developers an impression of your code. Youre going to spend
your time making its intent clearer, not fixing behavior.
The first problem is that all of the methods on this class are
instance methods. Theres no reason for instance methods on
this class. The first change is to make all the methods static
instead of instance methods:

One less line of code, and that means one less bit of work for
every use of your library. Of course, this first change leads to the
obvious change of making the NumericAlgorithms class a static
class:
public static class NumericAlgorithm

Doing so prevents any customer from accidentally creating a


NumericAlgorithm class. It also prevents library maintainers
from creating instance data or instance methods in the class.
These are small changes, to be sure, but they do prevent
users from accidentally doing the wrong thing.
Next, you should look at the current API and consider its
limitations. All the APIs use List<double> as the input
sequence. Thats unnecessarily limiting. The internals of the
methods dont rely on any capabilities beyond IEnumerable
<double>. You can see the costs of this restriction on the sample
code. Instead of writing this:
List<double> sequence = new
List<double>(Enumerable.Range(1, 50).
Select(n =>(double)n));

Users should be able to write the simpler version:


IEnumerable<double> sequence =
Enumerable.Range(1, 50).Select(n =>(double)n);

This version allows users to call your library using any type of
collection: a list, an array or even a dynamically read sequence
as Im using above.
This changes the signatures of all the methods in the class:

public static double Mean(List<double> sequence)

public static double Mean(IEnumerable<double> sequence)

After this change, your customers no longer need to create a


NumericAlgorithm object in order to use these methods.
Instead of writing this:

In addition, youll need to change the internal implementation


of some of the methods. In particular, the Mean, Median and
Variance methods now must generate both the sum and the
count of elements. Thats because IEnumerable<T> doesnt
contain a Count property where List<T> does.
At this point, youll notice that some of the methods might
need additional work. The Mean() and Variance() methods
must iterate the collection more than once: calculating the sum,
the count of items and even the squares of the collection. You
may be tempted to create more complicated methods to perform all those calculations in one pass. If you look at the fin-

NumericAlgorithm target = new NumericAlgorithm();


List<double> sequence = new
List<double>(Enumerable.Range(1, 50).
Select(n =>(double)n));
double actual = target.Mean(sequence);

After this change, they can write this simpler version:


40

List<double> sequence = new


List<double>(Enumerable.Range(1, 50).
Select(n =>(double)n));
double actual = NumericAlgorithm.Mean(sequence);

VISUAL STUDIO MAGAZINE April 2009 VisualStudioMagazine.com

0409vsm_Langlab_32-46.v11

3/19/09

10:57 AM

Page 41

C# Corner

C#

NUMERIC LIBRARY VERSION 1

public class NumericAlgorithm


{
public double Mean(List<double> sequence)
{
double total = Sum(sequence);
return (sequence.Count == 0)
? total : total / sequence.Count;
}
public double Median(List<double> sequence)
{
if (sequence == null)
throw new ArgumentNullException("sequence",
"Sequence must not be null");
if (sequence.Count == 0)
return 0;

Avoiding Problems
I wrote this sample to be representative of common production
code I see in libraries. Too often, many of the developers I work
with create libraries from the inside out. They have strong
knowledge about how theyll implement a particular set of features, and that knowledge deeply colors how they create the
functionality. Those assumptions show up quickly in the test
code. Its especially evident in the test code that demonstrates
the successful scenarios for your library. For example, lets look
again at one of the first test samples for the original library:

List<double> local = new List<double>(sequence);


local.Sort();
return local[local.Count / 2];
}

Clear Code

ished version of the numeric library, youll notice that I didnt do


that extra work. I ran some performance tests and found that
making those changes just didnt change the performance
metrics by any appreciable amount. Therefore, I went with the
simpler implementation. Your mileage may vary, but test
performance before making changes with the intent of
improving performance.
Also, your algorithms should make the smallest set of
assumptions about the parameters you need. By making fewer
assumptions, you automatically get more reach from possible
users. Look at your methods and determine if you need all the
capabilities of a parameter type. Whenever you can, provide a
less-constraining interface.

public double Variance(List<double> sequence)


{
double sum = Sum(sequence);
if (sequence.Count == 0)
return 0;
List<double> squares =
sequence.Select(n => n * n).ToList();
double sumSquares = Sum(squares);
double variance = (sumSquares + sum * sum /
sequence.Count) / (sequence.Count - 1);
return variance;
}

[TestMethod()]
public void MedianSimpleTest()
{
NumericAlgorithm target = new NumericAlgorithm();
List<double> sequence = new
List<double>(Enumerable.Range(0, 50).
Select(n => (double)n));
double expected = 25;
double actual = target.Median(sequence);
Assert.AreEqual(expected, actual);
}

public double Sum(List<double> sequence)


{
if (sequence == null)
throw new ArgumentNullException("sequence",
"Sequence must not be null");
double total = 0;
sequence.ForEach(num => total += num);

Contrast that with the final version:

return total;
}

[TestMethod()]
public void MedianSimpleTest()
{
IEnumerable<double> sequence = Enumerable.Range(
0, 50).Select(n => (double)n);
double expected = 25;
double actual = NumericAlgorithm.Median(sequence);
Assert.AreEqual(expected, actual);
}

LISTING 1 This version of the numeric library works correctly.


However, there are many poor practices in this library that make it
harder to use. In addition, those practices will confuse users of the
code. Theyll make assumptions about what the code does because
of how its structured. In its current form, those assumptions will
be wrong.

Theres not a huge difference in size. You may not easily see benefits when you examine a single test method. Instead, seriously
examine the clarity of the test code. Is it clear what the test code
is trying to do? Is it clear how to use the API?
The second test, which executes the exact same actions, has
less code thats unrelated to the problem at hand. Its easier to
understand exactly what test is executing. (I realize that the
Enumerable.Range() method may be unfamiliar if you dont
use LINQ much, but thats not related to the API.) In fact, using
the new version, you could replace the range call with an array,
or any other storage.
I look at test code as a way to evaluate the code that client

developers will need to write. When possible, Ill write the success scenario tests before I create any of the library code. That
forces me to think about the problem and the solution through
a client developers eyes: What code would I want to call in
order to solve a given problem? If I start by writing the library
code, Ill create a library that looks like how I solved the problem, not a library that looks like how I want to use a solution.
Of course, not every project can be written that way. Too
often, were extending existing systems that dont have a test
framework already in use. In that case, youll end up working
through the tasks I outlined earlier in this article: create the

VisualStudioMagazine.com April 2009 VISUAL STUDIO MAGAZINE 41

0409vsm_Langlab_32-46.v11

3/19/09

10:57 AM

Page 42

</Language Lab>
C# Corner

Clear Code

tests; look at the code in the tests; and modify the library
until you have the API youd like. At each step, look at
your testsespecially the success testsand decide if the API
is as convenient as it could be. If not, you should continue to
make modifications until you have an API that matches your
expectations.
Structuring Your Code
Compare the initial version of the library with the final version
(see Go Online for how to access a sample of the final version).
Even with only a few methods, you can see more clarity in how
the library will use its parameters and how it can be used. The
API more clearly describes how it will be used.
Think about your own classes and examine if they communicate their intent and their use for other developers. Does
their structure communicate your design intent? If not, modify
the public API until it matches your assumptions about the
usage of your classes.

Your code communicates your design intent to its users.


Its important that you take advantage of this opportunity to
communicate to the users of your code. Do it well. VSM
Bill Wagner (wwagner@srtsolutions.com), author of Effective C#: 50
Specific Ways to Improve Your C# (Addison-Wesley Professional, 2004)
and More Effective C#: 50 Specific Ways to Improve Your C# (AddisonWesley Professional, 2008), has been a commercial software developer for
the past 20 years. Hes a Microsoft regional director and a Visual C#
MVP. Wagners interests include the C# language, .NET Framework and
software design.
GO ONLINE

Use this Locator+ code at VisualStudioMagazine.com to go


directly to these related resources.
READ & DOWNLOAD
VS0904CC Read this article and download the associated code.

{ A S K K AT H L E E N }

Working with MEF


Learn how to free your application from dependencies
and interchange implementations using Managed
Extensibility Framework.
BY KATHLEEN DOLLARD
Q: Ive been hearing the term MEF lately and I know it means

Managed Extensibility Framework, but I dont understand what it


does. Would it be a good fit for allowing customers to add their own
forms to our Windows Presentation Foundation (WPF) app? We
need those new forms to appear in our menus and we dont want to
give customers our Visual Basic source code to recompile.
A:This sounds like a good application for MEF. You could use
the same approach for WinForms or ASP.NET and the C# code
would be similar to what Ill show here.
MEF is an extensibility model that allows components to
interact using a simple model. Components are called parts in
MEF. MEF is designed to be extensible to different types of models, but ships with an attributed model. This lets you define the
interaction between your parts via normal .NET attributes. If a
part needs something, it uses an Import attribute and if a part
supplies something it uses an Export attribute. Any part can be a
host or client, provider or consumer. MEF bases these interactions on contracts and offers a flexible discovery model. Your
application makes a request and leaves it to MEF to provide the
implementation. This frees your application from dependencies
and lets you interchange implementations.
MEF is currently available as a preview on CodePlex. Its in
the System.ComponentModel namespace, indicating that it
will appear as a full member of .NET Framework 4.0. Several
42

VISUAL STUDIO MAGAZINE April 2009 VisualStudioMagazine.com

projects within Microsoft are committed to it, including the


Visual Studio (VS) 2010 code editor. Until it appears in .NET
Framework, youll need to download MEF and place
System.ComponentModel.Composition.dll in an accessible
location.You should also realize that changes to the API may occur.
Your application will be the MEF host while your customers will write MEF clients or extensions. Extensions are
simpler to write because the host must also manage the
CompositionContainer. Ill step through the process of creating
an interface, building extensions and building a WPF host. The
WPF host will pass a catalog to a CompositionContainer that
will specify a directory to search for menu extensions.
Extensions support contracts. The most common contracts are interfaces, and these interfaces might be quite simple:
Public Interface IExtension
Sub ShowWindow()
End Interface

Your customers can add extensions by implementing this


interface and specifying the Export attribute from the
System.ComponentModel.Composition namespace:
<Export(GetType(IExtension))> _
<ExportMetadata("MenuCaption", "First")> _
Partial Public Class First
Implements IExtension
Public Sub ShowWindow() _
Implements Common.IExtension.ShowWindow
End Sub

0409vsm_Langlab_32-46.v11

3/19/09

10:57 AM

Page 43

Ask Kathleen

Overriding the OnStartup method lets you prepare the container when your application starts:

You can also use an arbitrary string to identify the export, but
the common case for extensions is to retrieve via an interface
contract. The ExportMetadata attribute lets you include extra
information about the extension that the host can retrieve without actually instantiating the underlying object, which lets you
control instantiation and protects performance.
When you design your solution, put interfaces in a separate assembly referenced by both the host and all extension
assemblies. Do not establish any direct references between your
host and extensions. All of your assemblies will need a reference
to System.ComponentModel.Composition.dll. Your compiled
extensions will need to be placed in a convenient location. You
can specify the build location in the Project Properties dialog.
The host is responsible for managing the CompositionContainer. The CompositionContainer hooks up imports
and exports behind the scenes and must know what exports are
available. Creating the container as a project level variable lets you
clean it up in OnExit. The call to the containers Dispose method
disposes of any parts that implement IDisposable:
Protected Overrides Sub OnExit( _
ByVal e As System.Windows.ExitEventArgs)
MyBase.OnExit(e)
If mContainer IsNot Nothing Then
mContainer.Dispose()
End If
End Sub

Protected Overrides Sub OnStartup( _


ByVal e As StartupEventArgs)
MyBase.OnStartup(e)
If Compose() Then
MainWindow.Show()
Else
Shutdown()
End If
End Sub

The compose method does the actual preparation:


Private Function Compose() As Boolean
Dim cat As New AggregateCatalog

The aggregate catalog allows you to manage several catalogs


together. If a set of catalogs appear together in an aggregate catalog, all matching items within this set of catalogs are discovered. Several different types of catalogs are available, including
DirectoryCatalog, which loads all assemblies in a specified
directory. In your case, Id suggest including the location of
extensions as part of the application settings to allow later configuration. Youll also add the current assembly:

MEF

End Class

Dim extLocation = My.Settings.ExtensionLocation


cat.Catalogs.Add(New DirectoryCatalog(extLocation))

8VcNdj8ji9ZkZadebZci8dhih
7n>cXgZVh^c\EgdYjXi^k^in4
7Z[dgZGVaan!lZhigj\\aZYideg^dg^i^oZl]VidjgXjhidbZgh
gZVaancZZYZY#CdllZldg`dci]Z]^\]ZhikVajZegd_ZXih
ZkZgnildlZZ`h#6cY!lZkZgZYjXZYgZaZVhZi^bZhWn*%#

6\^aZVcYGVaanXVcXjindjgi^bZ"id"bVg`Zi
Wn*%VcY^cXgZVhZegdYjXi^k^inWn'*#
;h_a>kZZb[ijed" 8ID!>cdk^h

=ZVgi]Zl]daZhidgnVcYhZZl]nGVaan^hi]Zdcan
6\^aZA^[ZXnXaZBVcV\ZbZcikZcYdgid\jVgVciZZndjghjXXZhh#
AZVgcbdgZVilll#gVaanYZk#Xdb

'%%.GVaanHd[ilVgZ9ZkZadebZci8dge

VisualStudioMagazine.com April 2009 VISUAL STUDIO MAGAZINE 43

0409vsm_Langlab_32-46.v11

3/19/09

10:57 AM

Page 44

</Language Lab>
Ask Kathleen

The menu caption is retrieved from the MEF metadata.

MEF

While this works, your goal is to make life as easy as possible for
programmers writing extensions. This metadata approach requires they
know to use the exact string "MenuCaption". Its easy to fix this using
strongly typed MEF metadata.

cat.Catalogs.Add(New AssemblyCatalog( _
Me.GetType.Assembly))
mContainer = New CompositionContainer(cat)

End Property

At this point the container is ready to work, but no work has


been requested. A composition batch allows you to specify the
items to evaluate for Import requests when you call the
Compose method. Any object later instantiated via an Import
request will also be evaluated for additional Import requests. In
many cases the first call to Compose will be the only one you
need to perform. Because Compose performs the composition,
it will fail if composition rules are not followed, so the
Try/Catch block provides reporting:
Dim batch = New Hosting.CompositionBatch()
batch.AddPart(Me)
Try
mContainer.Compose(batch)
Catch ex As CompositionException
MessageBox.Show(ex.ToString())
Return False
End Try
Return True
End Function

Theres one more detail specific to VB. The Application


Framework automatically instantiates the specified window and
bypasses your MainWindow property. Disable the Application
Framework and add a Sub Main to the Application.xaml.vb file:
'''<summary>
'''Application Entry Point.
'''</summary>
<System.STAThreadAttribute()> _
Public Shared Sub Main()
Dim app As Application = New Application
app.Run()
End Sub

The Main window of the application uses an


Import attribute on a field. For MEF to satisfy this
request and create the field value, the Main window
itself must be provided via MEFMEF evaluates
Import attributes on anything explicitly added to a
batch and anything that is instantiated via another
Import. You can do this by replacing the
MainWindow method in the base class via
Overloads (new in C#):
<Import(GetType(Main))> _
Public Overloads Property MainWindow() As
Window
Get
Return MyBase.MainWindow
End Get
Set(ByVal value As Window)
MyBase.MainWindow = value
End Set

44

Managed Extensibility Framework offers several catalog types. The


directory catalog searches a file system directory for parts that match your
import requests. This lets your users add extensions just by
dropping assemblies into a specified directory.

VISUAL STUDIO MAGAZINE April 2009 VisualStudioMagazine.com

0409vsm_Langlab_32-46.v11

3/19/09

10:57 AM

Page 45

Ask Kathleen

<Export(GetType(Main))> _
Partial Public Class Main

The Main window uses MEF to discover available extensions


that implement the IExtension interface:
<Import(GetType(IExtension))> _
Private exportExtensions As ExportCollection( _
Of IExtension)

Anything that appears in the catalog or is manually added to the


container through batches and implements the IExtension interface will appear in this collection. Note that this creates a collection of Export objects that contain sufficient information to
instantiate the actual extensions, but they do not yet instantiate
them. This is important to maintain adequate performance.
The Main window fills the menu using standard WPF code:
Private Sub Main_Loaded() Handles Me.Loaded
For Each export In exportExtensions
Dim newItem = New MenuItem()
newItem.Header = export.Metadata("MenuCaption")
Me.ExtensionMenu.Items.Add(newItem)
Next

End Sub

Note that the menu caption is retrieved from the MEF metadata.
While this works, your goal is to make life as easy as possible for
programmers writing extensions. This metadata approach
requires they know to use the exact string "MenuCaption". Its
easy to fix this using strongly typed MEF metadata. To begin,
create an interface:
Public Interface IExtensionMetadata
ReadOnly Property MenuCaption() As String
End Interface

Now create an attribute that parallels this interface. This attribute needs to match the metadata interface. It does not need to
implement the interface, but this is the easiest way to keep them
in sync:

MEF

This causes the application to retrieve the MainWindow via the


property and thus evaluates MEF requests in the Main window.
The Main window exports itself to MEF to match the
MainWindow property import:

<MetadataAttribute(), AttributeUsage( _
AttributeTargets.Class)> _
Public Class ExtensionMetadataAttribute
Inherits Attribute
Implements IExtensionMetadata
Private mMenuCaption As String
Public Sub New(ByVal menuCaption As String)
mMenuCaption = menuCaption
End Sub
Public ReadOnly Property MenuCaption() _
As String Implements IExtensionMetadata.MenuCaption

PERFECTION IN SOFTWARE PROTECTION

Exceptional Software Protection

Software Protection
Document Protection

Order your Free Software Development Kit now!


Phone 1-800-6-GO-WIBU | order@wibu.us

Access Protection
Media Protection

CodeMeter for .NET


3

More than 1000 Key-Storage License Entries

- Different ISVs can share one dongle


3

Secure Expiration Date with a Real-Time-Clock

- Unique Time Certication Feature


- Control Relative and/or Absolute time
3
3

More ways to sell = More sales


Create Student and Version Licenses

Control Network
etwork Licensing

- Control concurrent users


- Control roaming users
3

Create Standby Licenses

- Hot Standby and Cold Standby


- Provide Overow Licenses
3

Pay-Per-Use Counter

WIBU-SYSTEMS USA Inc.


110 W Dayton Street,
Edmonds, WA 98020
United States
www.wibu.us
info@wibu.us

VisualStudioMagazine.com April 2009 VISUAL STUDIO MAGAZINE 45

0409vsm_Langlab_32-46.v11

3/19/09

10:57 AM

Page 46

</Language Lab>
Ask Kathleen

<Import(GetType(IExtension))> _
Private exportExtensions As ExportCollection( _
Of IExtension, IExtensionMetadata)

You are committing to maintaining the interfaces you


release to your customers. If you alter the interface, you will
break their code. Instead you can create a new interface, leaving
the previous interface intact. MEF itself is extensible. If you
encounter versioning or AppDomain isolation problems, you
could create an additional programming model that would
combine the MEF and MAF, however you would reintroduce
some of the complexities of MAF.
MEF also has a direct access API, which you might require,
but the Import/Export attribute model is desirable for most
scenarios in VB or C#. The full extensibility of MEF allows its
use in other scenarios, including dynamic languages, external
definitions and alternate discovery mechanisms.
So far, Ive skipped over the important issues of cardinality
and lifetime. When you place the Import attribute on a single
item, you state that you expect a single item. The standard MEF
container configuration throws an exception if no matches or
multiple matches are found:

This provides a strongly typed MetadataView to simplify access


to export metadata:

<Import(GetType(ITextToDisplay))> _
Private textToDisplay As ITextToDisplay

newItem.Header = export.MetadataView.MenuCaption

If you know there may be multiple matches, you can import


into an IEnumerable or an ExportCollection. If you dont want
an exception thrown if no match is found, you can set the
AllowDefault parameter on the Import attribute to True. If you
dont know how many matches will be discovered, place the
import on a collection and manage getting the correct instance
in your code.
Lifetime refers to whether a single instance of the export is
used for all requests (CreationPolicy.Shared), or a new instance
created for each request (CreationPolicy.NonShared). You
declare the lifetime using a CreationPolicy parameter on the
Export attribute or the RequiredCreationPolicy on the Import
attribute. The default creation policy is Any and if both Export
and Import attributes have a CreationPolicy of Any, the result is
a shared instance. If the CreationPolicies conflict, MEF throws
an exception. This allows you fine grain and flexible control
over instance creation from either the export or import side.
MEF has the capacity to let you build highly decoupled
applications that support customer extensions, granular development, test mocking and good programming design. Its a
good technique to add to your arsenal. VSM

Get
Return mMenuCaption
End Get
End Property
End Class

Your customers can decorate their extensions with this attribute:

MEF

<Export(GetType(IExtension))> _
<ExtensionMetadata("First")> _
Partial Public Class First

You can leverage this metadata by altering the Import request in


the Main window to include a second type parameter:

While Ive answered your question, I dont think Ive solved your
problem yet. At this point, the windows display but do not interact
with each other or the rest of your application. That next step is
easy because MEF makes no distinction between extensions and
host while resolving Import and Export attributes. The sample in
the download uses additional interfaces to provide a string to
extensions from the host as a simple demonstration. Your app will
probably provide more sophisticated functionality such as the
parent window, where extension user controls or specific business objects or application data should be sited.
Its valuable to export classes, not primitive values or structures. The values of reference types will reflect changes as your
application proceeds rather than reflecting only the value MEF
supplied at composition. This also means two-way communications can be provided either through mutable objects that allow
changes, or through immutable objects that expose specific data.
In addition to host/extension interactions, multiple extensions
can communicate with each other using interfaces that are
entirely unknown to the host or initial programmers.
The compiler shortcuts recompiling non-referenced
assemblies and a composable application doesnt maintain references. Avoid problems with out-of-date assemblies by using
Rebuild Solution before testing your application.
MEF is similar to System.AddIn (also called MAF), which I
discussed in April 2008 (see Extend Your Apps with External
Add-Ins). MAF is significantly more complex to use, but solves
additional problems of isolation and versioning. MEF extensions
run in the AppDomain of the host, with the rights of your
AppDomain. This means when using MEF you must trust extensions not to run malicious code, or offer protection via Code
Access Security. MAF solves this problem by creating extensions
in a separate AppDomain, which you can lock down or sandbox.
46

VISUAL STUDIO MAGAZINE April 2009 VisualStudioMagazine.com

Kathleen Dollard (kathleen@mvps.org) is chief technologist for AppVenture


(www.appventure.com), as well as a consultant, author, trainer and speaker.
Shes been a Microsoft MVP for 11 years and an active member of the INETA
Speakers Bureau. She wrote Code Generation in Microsoft .NET (Apress,
2004) and blogs at http://msmvps.com/blogs/kathleen.
GO ONLINE

Use this Locator+ code at VisualStudioMagazine.com to go


directly to these related resources.
READ MORE
VS0904AK Read this article online.

0409vsm_AdIndex_47.v2

3/19/09

4:35 PM

Page 47

Advertising Sales

Ad Index
Advertiser
/n Software Inc.

Page
7

www.nsoftware.com

Accusoft Pegasus

23

www.accusoft.com

AppDev Training

East

29

www.appdev.com

Aspose

Andrew Mintz
National Sales Manager
Phone: 508-532-1433
amintz@1105media.com

C3

www.aspose.com

Atalasoft Inc.

21

www.atalasoft.com

ComponentArt Inc.

14, 15

www.componentart.com

dtSearch Corp.

West
Chris Kourtoglou
Regional Sales Manager
Phone: 650-579-0121
ckourtoglou@1105media.com

National Accounts Director


William Smith
Phone: 603-886-3466
wsmith@1105media.com

Microsoft Account Manager


Danna Vedder
Phone: 253-514-8015
dvedder@1105media.com

39

www.dtsearch.com

ESRI

www.esri.com

Intel Corp.

C4

www.intel.com

Director, Print Production


Jenny Hernandez-Asandas
Phone: 818-734-1520 ext 101
Fax: 818-734-1528
jhernandez@1105media.com

Production Coordinator
Serena Barnes
Phone: 818-734-1520 ext 164
vsmadproduction@1105media.com
sbarnes@1105media.com

LEAD Technologies Inc.

11

www.leadtools.com

Microsoft Corp.

18, 19

www.microsoft.com

Rally Software

43

www.rallydev.com

Software FX

C2,1

www.software FX.com

Visual Studio Magazine

35

http://visualstudiomagazine.com

VSLive! Las Vegas

24, 25

http://vslive.com/

Wayside Technology Group Inc.

www.waysidetechnology.com

ID Statement
Visual Studio Magazine (ISSN 1537-002X) is published
monthly by 1105 Media Inc., 9121 Oakdale Avenue,
Ste. 101, Chatsworth, CA 91311. Periodicals postage
paid at Chatsworth, CA 91311-9998, and at additional
mailing offices. Complimentary subscriptions are sent
to qualifying subscribers. Annual subscription rates for
non-qualified subscribers are: U.S. $34.97, Canada
$52.97 (U.S. funds); International $78.97 (U.S. funds).
Subscription inquiries, back issue requests, and
address changes: Mail to: Visual Studio Magazine,
P.O. Box 1164, Skokie, IL 60076-8164, e-mail
VSMmag@1105service.com or call toll free 888-7688759, fax number 847-763-9564. International calls
847-763-9135. POSTMASTER: Send address changes
to Visual Studio Magazine, P.O. Box 1164, Skokie, IL
60076-8164. Canada Publications Mail Agreement No:
40612608. Return Undeliverable Canadian Addresses
to Circulation Dept. or Bleuchip International, P.O. Box
25542, London, ON N6C 6B2.

Copyright Statement
Copyright 2009 by 1105 Media, Inc. All rights
reserved. Printed in the U.S.A. Reproductions in
whole or part prohibited except by written permission. Mail requests to "Permissions Editor," c/o Visual
Studio Magazine, 2600 El Camino Real, Ste 300, San
Mateo, CA 94403.

Legal Disclaimer
The information in this magazine has not undergone
any formal testing by 1105 Media, Inc. and is distributed without any warranty expressed or implied.
Implementation or use of any information contained
herein is the reader's sole responsibility. While the

information has been reviewed for accuracy, there is


no guarantee that the same or similar results may be
achieved in all environments. Technical inaccuracies
may result from printing errors and/or new developments in the industry.

WIBU-SYSTEMS USA Inc.

45

www.wibu.com

Editorial Index
AAmazon.com Inc.

Corporate Address

www.amazon.com

1105 Media Inc.


9121 Oakdale Ave. Ste 101
Chatsworth, CA 91311
www.1105media.com

ArtOfTest Inc.

12, 48
12, 13

www.artoftest.com

Media Kits

CA Inc.
www.ca.com

13

Capgemini

20

www.us.capgemini.com

Direct your Media Kit requests to Matt Morollo, VP


Publishing.
Phone: 508-532-1418
Fax: 508-875-6622
E-mail: mmorollo@1105media.com

ComponentOne LLC

13

www.componentone.com

Embarcadero Technologies Inc.

13

www.embarcadero.com

Exeros Inc.

13

www.exeros.com

Reprints
For single article reprints (in minimum quantities of
250-500), e-prints, plaques and posters contact:
PARS International
Phone: 212-221-9595
E-mail: 1105reprints@parsintl.com
Online: www.magreprints.com/QuickQuote.asp

IBM Corp.

13

www.ibm.com

InfoStrata Solutions Ltd.

31

www.infostratasolutions.com

Magenic Technologies Inc.

16

www.magenic.com

Northwest Cadence Corp.

20, 21

www.nwcadence.com

List Rental
This publications subscriber list, as well as other
lists from 1105 Media Inc., are available for rental.
For more information, please contact our list manager,
Merit Direct.
Phone: 914-368-1000
E-mail: 1105media@meritdirect.com
Online: www.meritdirect.com

Quest Software Inc.

13

www.quest.com

SAP AG

13

www.sap.com

Sybase Inc.

13

www.sybase.com

VisualStudioMagazine.com April 2009 VISUAL STUDIO MAGAZINE

47

0409vsm_RedReview_48.v4

3/19/09

2:36 PM

Page 48

Developer News

</Redmond
Review>

BY ANDREW BRUST

Whats Old Is New Again


When I wrote my first column for this magazine 15 years ago,
I covered a new advance in database programmability for Visual
Basic programmers. Ive been gone from these pages for a while,
but Im back. And, as an appropriate topic for a return engagement,
I focus on another database programming advance, this time for
.NET developers.
Back then, I explored something called the VB Compatibility
Layer (VBCL), which let VB 3 programmers use version 1.1 of the
Access/Jet Database Engine. VB 3 was the first version of the product
to include its own database engine, and the VBCL ensured the
newest version of that engine would be available to its programmers.
Compatibility was key then, and it remains so todayas Microsoft
seems to have belatedly realized with its cloud computing strategy.
Last month Microsoft announced a major change of course
for SQL Data Services (SDS), its cloud database offering. Although
SDS is not yet released, Microsoft is nonetheless giving the technology a completely different programming interface than the one
it announced more than a year ago. Back then, Microsoft brought
us a product that, while based on a modified version of the SQL
Server we all know, had to be programmed through an interface
and conceptual paradigm that bore very little resemblance to it.

database work (in other words, almost all .NET developers), this first
cut at SDS didnt make much sense. Microsoft had turned SQL Server
into a structured storage repository instead of a relational database,
and had implicitly told developers that if they wanted to move to
the cloud, theyd need to re-design their databases and re-write
their code. Ouch.
To call Microsoft tone deaf on this issue would be an understatement. But eventually the SDS team heard the music, and got
the rhythm. On Feb. 23, at the co-located VSLive!/Microsoft
Developer Conference in San Francisco, Microsoft hinted that they
would re-jigger the SDS model to be relational, and on March 10 it
announced through the SDS team blog that SDS would, in fact, be a
cloud-based SQL Server, accessible via T-SQL over Tabular Data
Stream (TDS), SQL Servers native protocol. Apparently, existing onpremises .NET/SQL Server code will work fine with the new SDS;
only a change in connection string will be necessary to turn SQL
Server code into SDS code.
So Redmond listened to its customers, and the bizarre obsession with copying Amazons SimpleDB Web service is over. Microsoft
has given us a truly simple offering: the SQL Server technology that
most Microsoft developers have been using for a decade and some
have been using since even before my
first column was published.
Whats old is new, I suppose. For
database technologies as well as columnists. Aligning SQL in the cloud to SQL
on the ground is about more than just
common sense. Its about getting things
done. Yes, the cloud, done right, will differ from on-premises technology. It will
offer dynamic scaling and utility-based
pricing. In short, it will lower the barrier to entry for getting applications up and running, and keeping them running smoothly.
But the cloud, done right, will reflect and preserve familiar
on-premises technology, too. Because the cloud isnt just about
how cool it is to run your application up there. Its about easily
provisioning the servers and services you need to run your business down here. SDS 1.0 had its head in the clouds; SDS 1.1 is
appropriately down to earth. A compatibility layer indeed. VSM

Aligning SQL in the cloud to SQL on

the ground is about more than just common sense.


Its about getting things done.

Rather than giving us a database with tables, columns and


T-SQL, Microsoft instead provided us with the ACE model:
Authorities (which were akin to servers), Containers (akin to
databases) and Entities (a cross between data records and
dictionary objects). The ACE model didnt have tables, didnt require
any consistent schema from Entity to Entity and could be accessed
only through SOAP and REST Web service interfaces. Microsoft
promised us relational capabilities for SDS, but appeared set on
providing them by enhancing the ACE model, rather than just giving
us direct access to the SQL Server behind the curtain.
The ACE model is good for basic storage and retrieval of data.
Support for BLOBs means ACE works well for content management
too. But for .NET application developers needing to do mainstream

48

VISUAL STUDIO MAGAZINE April 2009 VisualStudioMagazine.com

Andrew Brust (andrew.brust@26ny.com) is chief, new technology,


for consultancy twentysix NewYork, as well as a Microsoft regional director
and MVP. Hes also the co-author of Programming Microsoft SQL Server
2008 (Microsoft Press, 2008).

Project1

2/24/09

10:18 AM

Page 1

Project1

2/25/09

8:40 AM

Page 1

EVOLVE YOUR CODE.


Parallelism breakthrough.
Find out what your Windows* apps can really do with Intel Parallel Studio.
7KLVDOOLQRQHWRROVHWVLPSOLHVSDUDOOHOLVPIRUPXOWLFRUHIURPDQDO\VLV
DQG FRPSLOLQJ WKURXJK GHEXJJLQJ DQG WXQLQJ 'HVLJQHG IRU WRGD\V VHULDO
DSSVDQGWRPRUURZVSDUDOOHOLQQRYDWRUV
/HDUQPRUHDQGVLJQXSIRU%HWDwww.intel.com/software/parallelstudio

2009, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks of Intel Corporation in the U.S. and other countries. *Other names and brands may be claimed as the property of others.

Potrebbero piacerti anche