Вы находитесь на странице: 1из 44

MARCH 2009 • Vol. 19, No. 3

The Art of the Interview

VisualStudioMagazine.com

E N T E R P R I S E S O L U T
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
O N S F O R .N E T D E V E L O P

GETTING DIRECTIONS

.NET developers face adjustments as they start coding for Microsoft’s high-flying collaboration platform.

+ Generate Code from

Custom File Formats

Create Anonymous Types

for Microsoft’s high-flying collaboration platform. + Generate Code from Custom File Formats Create Anonymous Type s
Your best source for software development tools! ® New LEADTOOLS Document Imaging v 16: dtSearch Engine
®
®
New LEADTOOLS Document Imaging v 16: dtSearch Engine for Win & .NET 64-bit by LEAD
New
LEADTOOLS Document
Imaging v 16:
dtSearch Engine for Win & .NET
64-bit
by LEAD Technologies
Add dtSearch‘s “blazing speeds”
(CRN Test Center) searching and
file format support
Version!
VMware View Premier
Starter Kit
New
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.
dozens of full-text and fielded
data search options
Release!
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
• Multi-threaded OCR/ICR/OMR/
MICR/Barcodes (1D/2D)
• API supports .NET, C++, Java, SQL and more;
new .NET Spider API
View Premier is an Enterprise-class
Desktop and Application virtualization
suite that enables you to take control
of your desktops and applications while
providing storage optimization. The
Starter Kit is the entry level solution
that includes 10 concurrent user licenses
of VMware Infrastructure Enterprise,
vCenter Foundation, ThinApp, View
Composer and View Manager. SnS
is required and sold separately.
View Premier
Single Server
Paradise #
Paradise #
• Forms recognition/processing
V55 66101A01
• PDF and PDF/A
D29 02101A07
Paradise #
“Bottom line: dtSearch manages a terabyte of
VDI Included
L05 03201A01
• Annotation (Image Mark-up)
text in a single index and returns results in
$
949. 99
CALLI
Best
• C/C++, .NET, WPF - Win32/64
programmers.com/lead
less than a second.”
—InfoWorld
$
Seller!
2,007. 99
programmers.com/dtsearch
programmers.com/vmware
Pragma Fortress SSH
—Secure Connectivity
c-treeACE ™ Professional
TX Text Control 14
by FairCom
Word Processing Components
by Pragma Systems
Pragma Fortress SSH provides a comprehensive
secure connectivity framework for enterprise
customers.
The c-treeACE database engine is a high performance
database alternative proven by developers in mission
critical enterprise systems, desktop deployments, and
embedded devices for over 25 years.
TX Text Control is royalty-free,
robust and powerful word processing
software in reusable component form.
• .NET WinForms control for VB.NET and C#
Full-featured server, graphical clients and graphical
management capabilities are all included.
• Complete set of APIs including ADO.NET, LINQ,
C#, C/C++, ODBC, JDBC, VCL, and dbExpress
• ActiveX for VB6, Delphi, VBScript/HTML, ASP
• File formats DOCX, DOC, RTF, HTML, XML, TXT
• Graphical productivity tools
Professional Edition
Pragma Fortress SSH provides:
• Simple deployment
• GSSAPI Kerberos & NTLM authentication
• PDF export without additional 3rd party
tools or printer drivers
Paradise #
• No DBA or ongoing administration
T79 02101A01
• Accelerated SFTP & SCP file transfer
• Low deployment licensing costs
Paradise #
$
• Supports over 1000 sessions
919. 99
• Cross-platform support for all major platforms
F01 0131
Paradise #
• Nested tables, headers & footers, text
frames, bullets, numbered lists, multiple
undo/redo, sections, merge fields
including Windows, UNIX, Linux, and Mac OS X
P35 0439
• Runs console applications & allows history
scroll back within the same session
$
711. 99
• Ready-to-use toolbars and dialog boxes
Download a demo today.
Make your applications faster, easier to deploy,
$
550. 99
New
and more affordable with c-treeACE.
programmers.com/pragma
programmers.com/faircom
programmers.com/theimagingsource
Release!
FarPoint Spread
for Windows Forms
Mindjet MindManager 8
Enterprise Architect 7.1
by Mindjet
Do you harness the wealth of data,
Web pages, and other input that comes
your way every day? Is there a way to
use it more effectively to formulate new
ideas, sharpen your focus, and ultimately
drive your success? New MindManager 8
for Windows is the answer.
New
Release!
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 solu-
tions to their COM, ASP.NET, .NET, BizTalk Server
and SharePoint Server applications.
Visualize, Document and
Control Your Software Project
Unlike the usual linear-based approach of
for Windows
Corporate Edition
• World’s #1 selling development spreadsheet
most productivity tools, MindManager 8
1 User
1-4 Users
• Read/Write native Microsoft Excel Files
uses mind-mapping technology to let you
Paradise #
Paradise #
capture, organize, and communicate
• Cross-sheet formula referencing
F15 17301A02
Paradise #
information using an intuitive visual
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,
test and construct reliable, well under-
stood systems. Additional plug-ins are
also available for Zachman Framework,
MODAF, DoDAF and TOGAF, and to
SP6 0001
• Fully extensible models
F02 01101A01
$
299. 99
$
canvas. You’ll be able to work smarter
integrate with Eclipse and Visual Studio
182. 99
• Royalty-free, run-time free
and transform your ideas into action
more quickly.
2005/2008.
$
936. 99
programmers.com/farpoint
programmers.com/mindjet
programmers.com/sparxsystems
SlickEdit 2008
Telerik RadControls
Multi-Edit 2008
for Windows
by Telerik
by Multi Edit Software
by SlickEdit
SlickEdit 2008 is a cross-platform, multi-lan-
guage code editor that gives programmers the
ability to code in over 40 languages on 7 plat-
forms. This latest version builds on the compa-
ny’s 20 years of experience in enabling devel-
opers and development teams to create, navi-
gate, modify, build, and debug code faster and
more accurately.
Add grid, combo, editing, navigation and charting
functionality to your AJAX and ASP.NET projects.
RadControls for ASP.NET enhances your Web
applications by adding AJAX functionality to your
ASP.NET projects. The suite takes full advantage
of the features included in Visual Studio 2005.
RadControls for ASP.NET helps developers deliver
feature-rich, standards-compliant (WAI-A, WCAG
1.0, XHTML 1.1) and cross-browser compatible
Web applications, while significantly cutting
their development time. RadControls for ASP.NET
includes: RadEditor, RadTabstrip, RadInput,
Multi-Edit 2008 delivers, a powerful IDE,
with its speed, depth, and support for
over 50 languages. Enhanced search
functions include Perl 5 Regular
Expressions and definable filters.
Supports large DOS/Windows, UNIX,
binary and Mac files. File Sync
Integration for: Delphi 6, 7, 2005,
C++Builder 6, BDS 2006 and RadStudio
2007, VB 6, VC 6, VS 2003 & VS
2005. Includes file compare, code
beautifying, command maps, and
New
Release!
Single Developer
1-49 User
Paradise #
Paradise #
Paradise #
M39 19201A01
TB3 01101A01
A30 01201A02
much more.
$
$
242. 99
RadCalendar, RadUpload, RadWindow, RadAjax,
RadGrid, RadCombobox, RadMenu, RadSpell,
RadChart, RadTreeview and more.
615. 99
$
161. 99
programmers.com/slickedit
programmers.com/telerik
programmers.com/multiedit
800-445-7899
programmersparadise.com

Prices subject to change. Not responsible for typographical errors.

COVER COMPOSITE IMGAES FROM ISTOCKPHOTO.COM

COVER COMPOSITE IMGAES FROM ISTOCKPHOTO.COM Contents March 2009 • VOLUME 19 • NO. 3 COLUMNS C#
COVER COMPOSITE IMGAES FROM ISTOCKPHOTO.COM Contents March 2009 • VOLUME 19 • NO. 3 COLUMNS C#

Contents

March 2009 • VOLUME 19 • NO. 3 COLUMNS C# CORNER 32 Create Anonymous Types
March 2009
VOLUME 19
NO. 3
COLUMNS
C# CORNER
32
Create Anonymous Types
Taking a careful look at the capabilities the
compiler gives to anonymous types provides an
excellent tutorial on what you should consider
when you create your types—including whether
they are classes or structs.
BY BILL WAGNER
DEPARTMENTS
6
Editor’s Note
BY MICHAEL DESMOND
8
Letters to the Editor
10
First Looks
Product
Listings
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
10
Review
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
11
39
Index of Advertisers
12
40
The Pragmatic Developer
The Art of the Interview BY BILLY HOLLIS
FEATURES
12
Getting Directions
32
.NET developers face adjustments as they start coding for
Microsoft's high-flying collaboration platform.
BY MICHAEL DESMOND
18
Generate Code from Custom
File Formats
Create a custom tool to provide a flexible and easy way
to generate code on demand.
BY PETER VOGEL
“.NET and ASP.NET developers
working with SharePoint must
be ready to do things
‘the SharePoint way.’”
Michael Desmond, “Getting Directions” p. 12

www.visualstudiomagazine.com

·

March 2009 ·

VISUAL STUDIO MAGAZINE

3

Online

Check out these and other exclusive online articles and tutorials on the Visual Studio Magazine Web site at

VisualStudioMagazine.com

Content

LEARN FROM THE PROS

As a developer you are constantly facing the problem of how to keep up with all the new technologies being released while still get- ting your job done. You keep hearing about solutions to your programming problems but the question is: are they the right solutions for your particular needs? You could spend hours or even days trying to find the answers yourself, or you could let the experts do it for you. Redmond Media Group Events offers a variety of conferences and shows where you can learn about new tech- nologies and what they might offer you, attend in-depth workshops that focus on topics specific to your needs, ask questions of the experts, and interact with your peers to discuss problems they face and what solutions they’ve come up with. Whether it’s Web design, .NET development, or SQL Server programming, we’ve got an event that matches your needs. Visit RedmondEvents.com to learn more about upcoming conferences and shows.

ONLINE ARTICLES

Practical ASP.NET:

Accessing Connection Strings Reliably

In his ongoing series on ASP.NET, Peter Vogel provides an alternative to the default mechanism for accessing connection string—and plugs his next book. LOCATOR+ CODE: VS0903PV1

Practical ASP.NET:

Updating Multiple GridView Rows

Peter Vogel explains how putting updateable controls in the ItemTemplate in a GridView gives developers what they want: the ability for users to change more than one row at a time. The cost is writing some extra code. LOCATOR+ CODE: VS0903PV2

ONLINE TUTORIALS

Classic VB Corner:

Let Me Tell Ya Where to Stick It

In these days of increasingly common least-privileged users, where should you store your application data? Karl E. Peterson drills down on the best approaches to organizing and accessing your system folders. LOCATOR+ CODE: VS0903KP1

Classic VB Corner:

Forward Compatibility

Does anyone really expect to be able to take data from the current version of AppX and use it freely in the previous version of AppX? Of course not! Karl E. Peterson discusses forward compatibility and how data assets simply must move forward from one version of an application to the next. LOCATOR+ CODE: VS0903KP2

GIVE US YOUR FEEDBACK

We at Visual Studio Magazine and VisualStudioMagazine.com are constantly trying to improve the content we provide you and the way that content is presented, both in the pages of the magazine and online. We value your opinions about any aspect of the magazine or our Web site. If you have any comments, criticisms, or suggestions on how we might improve things please feel free to contact us. You can reach us by email at vsmedit@1105media.com or go online at VisualStudioMagazine.com and post your comments.

VirtualizationReview.com

1105 Media recently launched a new Web site devoted exclusively to covering all aspects of IT virtualization. VirtualizationReview.com helps you harness the power of virtualization by delivering news and in-depth coverage of the products, vendors, issues, and technologies transform- ing IT through virtualization. The site also features articles, tips, and timely information about all aspects of virtualiza- tion including servers, storage, desktops, applications, and more. Visit VirtualizationReview.com now to start your move to a more efficient, powerful virtual environment.

your move to a more efficient, powerful virtual environment. What Are Locator+ Codes? Locator+ codes give

What Are Locator+ Codes?

Locator+ codes give you instant access to a feature on Visual Studio Magazine Online. Simply type the Locator+ code into the field in the upper-right corner and click on FIND IT.

.NET NEWSLETTER SIGN-UP

Every week, the .NET Insight e-mail newsletter brings you up-to-date news, technical information, opinions, interviews, and analysis on topics and technologies such as Visual Basic .NET, C#, SQL Server and data access, ASP.NET, wireless, Web services, and XML. Sign up for free at VisualStudioMagazine.com.

PHOTO BY IRA WYMAN

Editor’s Note

WHAT HAPPENS NEXT

By now you’ve no doubt noticed some changes in this month’s issue of Visual Studio Magazine.

There’s a lot going on at VSM as we work to improve the pub- lication, and we’re anxious to let you know what we’re up to, and to hear your opinions about what we might do better. It’s probably best if I start at the top. Back in January our parent company, 1105 Media Inc., announced that it was merging its two developer publications—VSM and the twice- monthly Redmond Developer News—into a single, integrated publication under the title Visual Studio Magazine. The move blends the best aspects of each magazine, combining VSM’s detailed how-to content and coding tutorials and RDN’s in- depth analysis of key issues and technologies. In a sense, RDN and VSM have been two sides of the same coin. RDN gave developers fair warning of what was coming, be it new technologies or newly discovered chal- lenges, and VSM showed them how to work with it. Now these two missions are being united under the VSM banner. The move reflects the fact that developers need con- text. They need to know about the tools they’re mastering, so they can make better decisions on how to use them. To that end, future issues of VSM will deliver the kind of in-depth features, timely technology and product news, plus expert insight that you’ve seen in RDN since 2006. The transition brings significant changes to the VSM staff. I want to take a moment to recognize the outstanding efforts of former VSM Editor in Chief Patrick Meader and Managing Editor Guy Wright, who are both moving on from VSM as part of the transition. I’ve worked on occasion with Patrick over the past two years, and I’ve respected him deeply for his intelligence, composure and commitment to princi- ple. Patrick is as dedicated and forthright a person as I’ve ever run across in my 16 years in IT publishing, and his success over the years at VSM is testament to that. Joining the VSM team are three new faces. Kathleen Richards is the new executive editor and will guide many of the key how-to departments and features at the magazine. Richards was senior editor at RDN and before that at Appli- cation Development Trends magazine. Jeffrey Schwartz arrives as news editor, where he’ll drive the front-of-the-book news and review content. Schwartz comes to VSM from RDN, where he managed the book’s large news section. Prior to that he was a senior editor at VAR Business. As for myself, I’ve moved over as editor in chief of RDN to serve as editor in chief of VSM.

What does it all mean? Quite a lot, actually. The new staff reflects an expanding mission for VSM. The magazine will continue to publish cutting-edge tutorial and how-to con- tent, but our coverage will expand to include issue-oriented features, timely news analysis and incisive commentary. Developers working with tooling as expansive and as power- ful as Visual Studio don’t work in a vacuum, and Visual Studio Magazine will reflect that. This issue is really the first step in the effort to broaden the scope and reach of VSM. In April, we plan to unveil a redesigned publication that is fully aligned with our expanded vision. I want to emphasize that Visual Studio Magazine is here to serve you.With so many big and exciting changes afoot, we’re more anxious than ever to hear the opinions and input of developers and managers.What can we do to improve VSM? What kinds of stories, content, tutorials and interac- tion are you looking for? And how can these things be tuned to help you do your jobs better? We want to hear your ideas— e-mail me at mdesmond@1105media.com.

to hear your ideas— e-mail me at mdesmond@1105media.com. BY MICHAEL DESMOND editor in chief 6 VISUAL

BY MICHAEL DESMOND editor in chief

STUDIO FOR IPHONE CTP NOW AVAILABLE

PDF

Letters

Letters to Visual Studio Magazine are welcome. Letters must include your name, address and daytime
Letters to Visual Studio Magazine are
welcome. Letters must include your
name, address and daytime phone
number to be considered for publica-
tion. Letters might be edited for form,
fit and style. Letters express the views
of the individual authors, and do not
necessarily reflect the views of the
editors, VSM or 1105 Media. Please
send them to Letters to the Editor, c/o
VSM, 16261 Laguna Canyon Road
Ste. 130 Irvine, Calif. 92618; fax
them to 949-265-1528; or e-mail
them to vsmedit@1105media.com.

Agile Arguments

B illy Hollis’ The Pragmatic Developer column (“Is Agile Rock or Disco?” January 2009) brings an interesting point to light: Will Agile survive the times?

However, I think the author missed a different, critical point: Agile is a mindset and not

a process. Truly Agile development is adaptable, and therefore it can work with non- seasoned developers.

Ted Malone, Colorado Springs, Colo.

I’d like to further a point Hollis made in his article: It’s hard to do any development without good developers. Instead of trying to figure out how to make do with not-so-good developers, we need to figure out how to turn those with potential into good developers, and how to encourage the rest to find a more suitable field in which to work. The so-called “software crisis”—a shortage of good developers compared to the amount

of software that needs to be written—is an issue of supply and demand. There’s an inherent

undersupply of good developers, but there’s also an oversupply of demand as many clients just want variations on the same thing. If it’s more profitable to be a good developer, those good developers will also create frameworks and tools to help address the demand-side prob- lems as well.

Anonymous,

Posted online

WF: Change for the Worse?

I suppose out of all the possible changes that might trouble me in Windows Workflow

Foundation (WF) 4.0—as discussed by Kathleen Dollard in her Ask Kathleen column (“Windows Workflow Changes Direction,” January 2009)—the loss of the code activity is the most upsetting. This makes the possibility of making “lightweight” WF activities that accom- plish relatively simple tasks more difficult than necessary. By removing this piece of function- ality, Microsoft has effectively shackled the developer to creating activity libraries. While that

has its place, this seems like the pendulum swinging way too far in the other direction. And frankly, I disagree with Dollard that moving completely to declarative creation of workflows is a good thing. Performance improvements are great, but performance improve- ments that cause the loss of very useful functionality are just wrong.

Marcelo Lopez, Jr., Florida

functionality are just wrong. M arcelo Lopez, Jr., Florida VisualStudioMagazine.com March 2009 • Volume 19 •

VisualStudioMagazine.com

March 2009

Volume 19

No. 3

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

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, Peter Varhol, Bill Wagner

Art Staff

Creative Director Scott Shultz Graphic Designer Erin Horlacher Online/Digital Media Editor, VisualStudio
Creative Director
Scott Shultz
Graphic Designer
Erin Horlacher
Online/Digital Media
Editor, VisualStudio
Magazine.com
Executive Editor, New Media
Becky Nagel
Michael Domingo
Online News Editor
Associate Editor, Web
Web Producer
Director, Web Development
Kurt Mackie
Gladys Rama
Shane Lee
Rita Zurcher
President
Vice President, Publishing
Director of Marketing
Online Marketing Director
Henry Allain
Matt N. Morollo
Michele Imgrund
Tracy S. Cook
Allain Matt N. Morollo Michele Imgrund Tracy S. Cook   President & Chief Executive Officer Senior
 

President & Chief Executive Officer Senior Vice President & Chief Financial Officer Executive Vice President President, 1105 Events

Neal Vitale

Richard Vitale

Michael J. Valenti Dick Blouin

Vice President, Finance & Administration Vice President, Digital Media, Audience Development Vice President, Information Technology & Web Operations Vice President, Digital Media, Advertising Vice President, Attendee Marketing

Christopher M. Coates

Abraham M. Langer

Erik A. Lindgren

Doug Mashkuri

Carmel McDonagh

 

Chairman of the Board

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.

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.

reduces the amount of time taken to find problem code. Select a region on the timeline
changes that will not solve your performance problem. A NTS Profiler shows you line-level timings, so

Download your 14-day, fully functional free trial from www.red-gate.com

"ANTS Profiler took us straight to the specific areas of our code which were the
"ANTS Profiler took us
straight to the specific areas
of our code which were the
cause of our performance
issues."
Terry Phillips Sr. Developer,
Harley-Davidson Dealer Systems
"We were able to improve
performance in parts of
the application up to 10 times,
and our customer noticed the
results. A powerful, instantly
understandable profiler.
Highly recommended."
Dan Ports Lead Developer, Intrigma Inc
A powerful, instantly understandable profiler. Highly recommended." Dan Ports Lead Developer, Intrigma Inc
A powerful, instantly understandable profiler. Highly recommended." Dan Ports Lead Developer, Intrigma Inc
First Looks PRODUCT LISTINGS + REVIEWS
First
Looks
PRODUCT
LISTINGS
+
REVIEWS

Coverity Prevent and Quince UX Patterns Explorer

C

Coverity Prevent

Coverity Inc. has improved the support for man-

aged and native code in its static-analysis soft-

ware. With Coverity Prevent, developers can

automatically scan and analyze C#, C, C++ and

Java source code on their desktops or on the build server. It’s one of the few static-analysis tools that supports both Visual Studio and Eclipse integrated dev environments. The product ships with a Web server, which connects to the help desk or Active Directory server on your network and a back-end data- base. Developers open the Coverity browser and log on to the Web service. Prevent builds the source code, analyzes it based on selected quality and concurrency checkers, and then commits the results to the database. A build- utility wrapper wraps around the build but doesn’t change it. Depending on the number of checkers, the build and analysis typically take three to five times the normal build time. After a run, developers can view a break- down of the code base in the browser: how many files and lines of code, the number of new defects since the last Run ID, and outstanding defects that still need to be inspected and clas- sified. Developers can’t edit the code from with- in the Prevent interface, however. The latest version beefs up VS integration, enabling developers to perform static analy- sis from within VS 2005 and VS 2008. The company has also added support for Windows Vista, Windows Mobile, Windows Automotive and Xbox. In addition, Coverity has extended Pre- vent’s C# functionality with new quality and concurrency checkers. Prevent is the first product to support C# concurrency testing for issues such as deadlocks and race conditions, according to the company. With this upgrade,

it also now offers concurrency modeling to help developers find critical defects in multi- threaded Win32 apps. Prevent is the flagship product in Coverity’s Software Integrity Suite, and the only product that currently supports C#. Upcoming static- analysis tooling will take advantage of Microsoft’s efforts to put annotations into its system header files.

format on various platforms, including ASP.NET, Windows Forms and PHP. Develop- ers can search Quince for commonly used pat- terns based on end user tasks, wireframe map locations and tags. The patterns catalog is set up so that the community can comment on patterns and their experiences in real time. The patterns are aggregated based on com- munity feedback.

Coverity Prevent Coverity Inc. Price: Contact vendor for pricing Web: www.coverity.com Phone: 800-873-8193;

415-321-5237

Web: www.coverity.com Phone: 800-873-8193; 415-321-5237 Yahoo! Inc. and Goo g le Inc. offer p attern libraries,

Yahoo! Inc. and Google Inc. offer pattern libraries, but there isn’t a de facto resource in the .NET and Microsoft space .

Quince Infragistics Inc. Price: No fees; registration required Web: www.community.infragistics.com/ux Phone: 888-448-0097; 609-448-2000

Editor’s Note: Please send product information to New Products Editor, c/o VSM, 16261 Laguna Canyon Road, Ste. 130, Irvine, CA 92618; Phone: 949-265-1565, fax: 949-265-1528; e-mail: vsmedit@1105media.com.

Quince UX Patterns Explorer

ComponentsvendorInfragistics Inc. has launched a unique Sil- verlight 2 application called “Quince” UX Patterns Explorer. The app offers developers a resource for best practices in user experience design and user interface patterns. With Quince, developers can hone their UI design skills with guidance from the community-driven catalog by seeing what pat- terns other practitioners have used and by viewing developer feedback. Developers can also share and upload their own UI patterns. Quince offers guidance on common patterns for complex data entry, label alignment and navigation, among other UI tasks. The library is initially based on tools and practices that the 20-year-old company uses internally, as well as expertise garnered from industry sources. Quince aggregates close to 100 patterns and shows implementations via a carousel

PRODUCT

LISTINGS

+

REVIEWS

Altova MissionKit Boasts XBRL Savvy

LISTINGS + REVIEWS Altova MissionKit Boasts XBRL Savvy PRODUCE READABLE FINANCIAL DOCUMENTS USING XSLT STYLESHEETS.

PRODUCE READABLE FINANCIAL DOCUMENTS USING XSLT STYLESHEETS. StyleVision, a member of Altova’s MissionKit 2009 suite, lets you design human-readable documents from machine-to- machine files in XBRL format. The output options include HTML, RTF, PDF and Word 2007.

lights the location. The other day, I fed XML Spy an XML file con- taining Expression Encoder ScriptCommands. XML Spy generat- ed a schema for it in an instant. Be careful what you ask for when converting an entire database into XML, though. I ended up with 234 files while searching in vain for XML Spy’s cancel button. MapForce is Altova’s flexible tool for mapping and filtering data graphically from one source to another. The source or tar- get can be a database, .EDI document, Web service, Excel 2007 spreadsheet or a lowly .CSV file. MapForce will generate the C# classes you might need to automate data conversions. The third major component, StyleVision, lets you design XLST templates into which you pour data for human consumption. If you’re getting into XBRL, be sure to explore the quarterly report sample and the Word 2007 preview to see the richness of its output. One issue I encountered with MissionKit 2009 was preview- ing a stylesheet as a PDF. Even though I had chosen a full instal- lation, StyleVision strangely prompted me for a 19MB download of the Apache (Java) Formatting Objects processor. Even with that in place, the PDF document still failed to appear. I would expect Altova’s setup kit to automatically install the rendering engine and tell its PDF module where to find it. VSM

Ken Cox is a Canadian .NET programming writer and the author of “ASP.NET 3.5 for Dummies” (Wiley).

I If you handle enterprise-level business intelli-

gence (BI) and financial reporting, it won’t be long

before the front office summons you to deal with

eXtensible Business Reporting Language (XBRL).

XBRL is an XML vocabulary for exchanging busi-

ness and financial data. It’s a standard for machine-to-machine reporting that’s been adopt- ed by the U.S. Securities and Exchange Commis- sion (SEC) and European authorities. Altova, well known for its leadership in all things XML, has updated its products to support XBRL and bundled them into MissionKit 2009 for Enterprise Software Architects. The goal is to give you the tools (but not necessarily the training) to deliver reports compliant with the International Financial Reporting Standards (IFRS). For XBRL beginners, it would have been ideal to have a hands-on walkthrough that starts with a financial database and ends with a valid XBRL doc- ument ready for submission to authorities. Alas, there’s no “XBRL For Dummies” manual included. While each application includes tantalizing tidbits on working with XBRL, I felt like I was solving a jig-

saw puzzle without seeing the entire picture first. XBRL is the “buzz” in Altova’s all-in-one suite, but don’t over- look the features that have long made the individual compo- nents the premier development environment in the XML space. It’s hard to beat XML Spy as an all-round markup editor, validator and XPath query designer. Its Grid view is especially useful for collapsing and exploring very large documents. As you work, the Messages pane reports errors, explains the problem and high-

AT A GLANCE MissionKit 2009 for Enterprise Software Architects Altova Web: www.altova.com Phone: 978-816-1600 Price:
AT A GLANCE
MissionKit 2009 for Enterprise Software Architects
Altova
Web: www.altova.com
Phone: 978-816-1600
Price: $1,739
Quick Facts: Integrated bundle of XML, database, XSLT
designer, validation, and publishing tools with added
emphasis on financial reporting support.
Pros: Handles all popular and emerging XML-based
technologies including the XBRL-compliance standard;
extensive online documentation and Web-based
support; many examples.
Cons: Needs end-to-end walkthrough on producing
XBRL reports; rendering engine for previewing PDF
documents not fully installed.

COMPOSITE IMAGES FROM ISTOCKPHOTO.COM

FEATURE

SHAREPOINT

Getting Directions

.NET developers face adjustments as they start coding for Microsoft’s high-flying workflow and collaboration platform BY MICHAEL DESMOND

SHAREPOINT T imes are tough all over,but it seems somebody forgot to tell that to

SHAREPOINT

T imes are tough all over,but it seems somebody forgot to tell that to the growing ranks of SharePoint developers. Even as general IT and development budgets turn south, industry watchers say

the amount of activity around SharePoint applications and features continues to rise.

Behind the activity is the wildfire growth of Microsoft’s file sharing, collaboration and portal platform, which includes Microsoft Office SharePoint Server (MOSS) 2007 and Windows SharePoint Services (WSS) 3.0 integrated into Windows Server.Last year,the SharePoint business unit surpassed 100 million licenses and $1 billion in total revenue, according to Microsoft. Now organizations are looking to leverage those invest- ments by adding custom functionality and applica- tions to their SharePoint infrastructure. That trend is producing its share of growing pains, as .NET dev shops contend with Share- Point’s unique demands and uneven tooling. At Microsoft’s Tech·Ed Conference in June 2008, Chairman Bill Gates admitted during his keynote Q&A that the company had been caught flat- footed by the amount of development activity around SharePoint.At the time, he said Microsoft was working to make SharePoint developers first- class citizens. Since then, Microsoft has released the free Visual Studio 2008 extensions for SharePoint, which provides Visual Studio project templates for building, debugging and deploying SharePoint projects and applications.The January community technology preview (CTP) of Visual Studio 2008 Extensions for Windows SharePoint Services 1.3 adds 64-bit support, refactoring support for renaming Web parts, and a command-line inter- face for enabling continuous integration and build. The final version is likely due in April, says Paul Andrew,Microsoft technical product manager for the SharePoint Developer Platform. “Microsoft has been scaling up our guidance, and our application and tools, really, really fast,” Andrew says, noting that Visual Studio 2010 will fully integrate SharePoint development support.

tinyurl.com/67e7gk) and Windows SharePoint Services (http:// tinyurl.com/7typk6) Developer Centers. The sites offer step-by-step tutorials, design patterns, best practices and other resources for developers working with the platform. Still, challenges remain.Veteran SharePoint developers complain that a lot of critical insight and guidance remains scattered among dozens of individual blogs and SharePoint-themed sites. “My Google reader is filled with stuff I need to check on, but it’s all scattershot,” says Ruther- ford Wilson, director of product management for Atalasoft Inc., an ISV that in February released Vizit SP, an image-viewing application for MOSS and WSS environments.“There are books, blogs, and that’s about it.” Ryan Thomas, director of the SharePoint practice at consultancy Syrinx Consulting Corp., says developers new to SharePoint are best served by simply wading into the environment. “The first thing I would do is build a Web part. Build and have ‘Hello World’ working in 30 minutes. Then download the SDK and the object model. If you’re going to be a developer, under- stand the object model and learn how to write code,”he says. Thomas advises developers to visit the Microsoft CodePlex site to examine open source SharePoint projects similar to their own. He warns that seasoned .NET developers may find the dynamics around SharePoint devel- opment to be quite different from traditional .NET development. He says SharePoint projects tend to be client-facing, involving frequent and intense interaction with business stakeholders. There’s a good deal of expectation setting that must be addressed, in part because these users are often familiar enough with SharePoint to expect quick results. “VPs, CIOs, business people—they just don’t understand the concept of,‘three weeks and come back with code,’” Thomas says. “It’s very important to talk to them.”

Making the Transition Evidence of the effort to scale up guidance is evident in Web sites like Microsoft’s SharePoint Developer portal (http://tinyurl .com/bsx8k9) and the MSDN-hosted SharePoint Server (http://

SHAREPOINT

Tale of the Tools One of the enduring complaints about SharePoint development has centered around tooling. That situation is now changing, thanks in large part to the release of the Visual Studio extensions for SharePoint and useful utilities like the SPDisposeCheck tool for releasing unused memory. Still, major gaps remain in the SharePoint developer chain. “The extensions are weak, in my opin- ion,” writes Spencer Harbar, a U.K.-based independent SharePoint developer and frequent speaker at Microsoft conferences, in an e-mail interview. “At best the exten- sions are a Band-Aid to bridge the gap between where we are now, and the future of SharePoint dev tools.” Harbar says the extensions fall short for enterprise development, which can expose weaknesses and flaws in the tooling. He adds that the integrated SharePoint tool- ing in Visual Studio 2010 (VS10) should be much better. “I cannot speak much to the VS10 tools without breaking NDAs, but I have complete confidence that they will offer a huge step change in terms of devel- oper tools for SharePoint,”he says. Another issue is the fact that Share- Point environments must run on Windows Server—a nagging issue for developers who prefer to code on their Windows XP or Vista workstations. Microsoft’s Andrew says developers today have two choices: Either run Visual Studio on the same Windows Server OS that hosts SharePoint, or stand up a virtual machine that incorporates Win- dows Server and the target SharePoint envi- ronment. Most shops, he says, opt for the latter solution. Leading component maker Compo- nentOne LLC is among them. The company in January released CTP versions of its SharePoint Web Parts line, which include map, chart and datagrid controls for Share- Point environments. “You need to make sure you have access to a testing environment that is not your development machines, that’s particularly important for SharePoint,” says Dan Beall, product manager for ComponentOne. “Sometimes you have to use remote debug- ging. It’s not as fluid as debugging on a target machine,but one thing you can do is you can have your code write entries to SharePoint log

do is you can have your code write entries to SharePoint log THE SHAREPOINT TOOLBOX S
do is you can have your code write entries to SharePoint log THE SHAREPOINT TOOLBOX S

THE SHAREPOINT TOOLBOX

code write entries to SharePoint log THE SHAREPOINT TOOLBOX S harePoint provides an enormous amount of

S harePoint provides an enormous amount of functionality but can be challenging for new developers trying to deploy solutions to a

CAML Query Builder Collaborative Application Markup Language (CAML) can be challenging to build

SPDisposeCheck

Unwary SharePoint developers can easily run into a situation where COM-based

memory doesn’t get released by CLR garbage collection. The resulting memory

server. Fortunately, there are several free Microsoft and third-party tools that can be used to create Web parts, site definitions, event receivers and more. Here’s a quick rundown of a few timesaving tools that can significantly increase your productivity when building SharePoint applications.

WSPBuilder WSPBuilder provides a nice way to build manifest.xml, .DDF and .WSP solution files quickly and easily from the command line or through a Visual Studio add-in. It traverses a “12” folder structure in VS and generates the appropriate files needed to deploy a solution. It can be downloaded from www.codeplex.com/wspbuilder.

STSDev STSDev can be used to build different SharePoint components such as Web parts and features more easily. Once a project type is selected (note that C# is currently the only supported language), it will create a VS 2005 or 2008 project automatically with the necessary SharePoint files and folder structure. STSDev can be down- loaded from www.codeplex.com/STSDev.

from

scratch. Fortunately, U2U has released a free tool called CAML Query Builder that can be used to build CAML queries visually without having to know a lot about CAML. It will output the proper CAML syntax for use with objects such as SPSiteDataQuery. CAML Query Builder can be downloaded from http://tinyurl.com/9f5ulo.

Business Data Catalog Definition Editor The Business Data Catalog (BDC) allows external data to be integrated into Share- Point that can be bound to built-in MOSS Web Parts or custom controls. To use BDC functionality you create custom .XML metadata files that define connection informa- tion, queries to execute, plus much more. Although the tool isn’t as flexible to work with as some of the other tools out there, the price can’t be beat. It’s part of Share- Point 2007’s SDK 1.2 release. Read more about it at http://tinyurl.com/cpot8a.

Visual Studio Extensions for SharePoint Microsoft has released extensions for VS 2005 and 2008 that can simplify the process of building and deploying List items, Web Parts, Site Definitions and more. At press time version 1.3 for VS 2008 was released as a community technology pre- view. Additional information can be found at http://tinyurl.com/9qo9s8.

leak-

age can cripple performance and cause unexpected crashes and failures. The Microsoft SharePoint Dispose Checker Tool, known as SPDisposeCheck, analyzes custom compiled assemblies so developers can ensure proper disposal of unused resources. Check it out here: http://tinyurl.com/dhn69w.

—Dan Wahlin

SHAREPOINT

“There’s a lot of features in WSS that Microsoft doesn’t really advertise to the rest of the world.”

Anne Thomas Manes, Vice President and Research Director, Burton Group

files. There are a couple of freeware tools for looking at what’s in the log files.” SharePoint developers have come to rely on a growing collection of freely available tools and utilities to help them address the extended tool chain. Microsoft utilities, like the SPDisposeCheck tool, help stamp out troubling memory leakage conditions that can occur with unmanaged component code, while the CAML Query Builder eases the learning curve around SharePoint’s Collaborative Application Markup Language (CAML).The result: Many dev shops have assem- bled ad hoc tool chains to address the unique demands of SharePoint coding.(See“The SharePoint Toolbox,”p.14.)

‘The SharePoint Way’

Ultimately, .NET developers face a subtle challenge in adjusting

says Anne Thomas Manes, vice president and research director at Burton Group. “SharePoint presupposes a bunch of design patterns and you kind of have to build your application around those design pat- terns,” she says. “And if you want your own design pattern, it’s probably not worth the time and effort. Don’t attempt to force fit other design patterns into it, because it will just be a very frus- trating experience.” Andrew draws a parallel with ASP.NET programming proj- ects, where developers typically start off by building a framework to address administration, security, data access and other issues. SharePoint, he says, essentially acts as the framework. “That has the advantage that if you take a SharePoint develop- er, they already know that framework, they don’t have to learn a new framework,”he says. The problem is that the SharePoint framework is so large that

problem is that the SharePoint framework is so large that 16 VISUAL STUDIO MAGAZINE · March

SHAREPOINT

developers often create custom code for features that are already there. Harbar urges developers to look carefully before concluding that a custom Web part or application is necessary. “Easily the most common mistake is not having a core under- standing of the product architecture and therefore choosing the wrong approach to meet specific business requirements.SharePoint is such a huge platform that it’s incredibly easy to start implementing custom code for a task that SharePoint does,”Harbar writes. He adds that developers often make the mistake of assuming that SharePoint is “just .NET,”when in fact .NET developers face a significant ramp in mastering SharePoint dev projects. Even within the SharePoint family there are choices to be made. Manes says that many enterprises today opt to develop for SharePoint Server, when they could achieve similar results and enjoy a more manageable environment by deploying logic to Windows SharePoint Services (WSS) instead. She says organiza- tions often conclude—wrongly—that WSS lacks the features they need to support workflow, coordination, scheduling and other common business processes. “There are a lot of features in WSS that Microsoft doesn’t really advertise to the rest of the world,” Manes says. “I can use a Java portlet and have that be the interface into WSS, because that

works through the Web services interface as opposed to the .NET interface.” Ultimately, Microsoft’s Andrew says that .NET developers must learn to unlearn some of their old assumptions when moving to SharePoint. “One of issues is people taking the approach—and this happens because projects need to be done fast—that their .NET experience will get them through their SharePoint project,”Andrew says.“They do have to learn new skills.” VSM

Michael Desmond (mdesmond@1105media.com) is editor in chief of Visual Studio Magazine.

GO ONLINE

Use this Locator+ code at VisualStudioMagazine.com to go directly to these related resources.

READ

VS0903MD Read this article online, which includes more information about how SharePoint adoption is raising data-management concerns; plus a Q&A with SharePoint development trainer and VSM online columnist Dan Wahlin.

PERFECTION PERFECTION IN IN SOFTWARE SOFTWARE PROTECTION PROTECTION Exceptional Software Protection Software Protection
PERFECTION PERFECTION IN IN SOFTWARE SOFTWARE PROTECTION 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
More than 1000 Key-Storage License Entries
Control Network Licensing
twork Licensing
- Different ISV´s can share one dongle
- Control concurrent users
Secure Expiration Date with a Real-Time-Clock
- Control “roaming“ users
- Unique Time Certification Feature
Create “Standby“ Licenses
WIBU-SYSTEMS USA Inc.
110 W Dayton Street,
Edmonds, WA 98020
- Control Relative and/or Absolute time
- Hot Standby and Cold Standby
United States
More ways to sell = More sales
Create Student and Version Licenses
- Provide Overflow Licenses
www.wibu.us
info@wibu.us
Pay-Per-Use Counter

ILLUSTRATION FROM ISTOCKPHOTO.COM

FEATURE
FEATURE

BUILDING CUSTOM TOOLS

Generate Code from Custom File Formats

Create a custom tool to provide a flexible and easy way

to generate code on demand.

BY PETER VOGEL

TECHNOLOGY TOOLBOX VB.NET C# SQLServer ASP.NET XML Other:
TECHNOLOGY TOOLBOX
VB.NET
C#
SQLServer
ASP.NET
XML
Other:

Y ou’re writing the same code over and over again with only minor changes, and you’re about to do it again. Stop. If you’re creating a standalone class (either a class that you’ll call from

your application’s code or a class that you can inherit from),build a custom

tool that writes the code for you now and every time you’ll need it.

You’re already using a custom tool every time you add a dataset to an application. VS sets the CustomTool property of the dataset’s .XSD to MSDataSetGenerator. Whenever you close the .XSD file—or, in Visual Studio 2008 (VS 2008), whenever you switch away from the file—VS passes MSDataSetGenerator the contents of the .XSD file, which MSDataSetGenerator then con- verts to code for the .XSD’s code file and hands back to Visual Studio. You can design your own input format and write your own custom tool to generate code for you. Once you build your custom tool, you simply have to enter its name in the CustomTool property

of the file with your input. VS takes care of the rest (see Figure 1, opposite page). Using a tool to generate repetitive code ensures consistency and reliability. It guarantees that your code generates the same way every time, reducing the amount of testing you have to do. Using a custom tool can also make you more productive, provided that entering the specifica- tions is faster than writing the code. If you decide you need to enhance your generated code, just modify your custom tool to incorporate your insights.Your class will be regenerated automati- cally with the new version of the code the next time you build your project.

BUILDING CUSTOM TOOLS

BUILDING CUSTOM TOOLS Using a tool to generate repetitive code ensures consistency and reliability. Installing to

Using a tool to generate repetitive code ensures consistency and reliability.

Installing to the GAC Automatically Creating a custom tool (also called a “single file generator”) pres- ents one problem.VS is a Windows application that calls a custom tool directly, so your custom tool must integrate with Windows and COM.You can create your custom tool in .NET, but you must make your tool available from Windows. To enable VS to call your tool,you must register it with Windows, add at least one registry key to let VS know your custom tool exists, and install your tool in the Global Assembly Cache (GAC). This means you must give your DLL a strong name. The good news is that you can configure VS so that all of these operations happen every time you compile your application. More good news: Most of the support for creating a custom tool is boilerplate and is identical from one custom tool to another.You only have to write it once and then copy and paste it to any other tool you create. You can build a custom tool in a variety of ways. I use the Microsoft.VisualStudio.Shell.Interop.IVsSingleFileGenerator and Microsoft.VisualStudio.OLE.Interop.IObjectWithSite interfaces.To create a custom tool,begin by creating a class library in the language of your choice and then add to it references to the Microsoft.VisualStu- dio.OLE.Interop and Microsoft.VisualStudio.Shell.Interop libraries.

and Microsoft.VisualStudio.Shell.Interop libraries. FIGURE 1 Code-Generation Output The

FIGURE 1 Code-Generation Output The CodeGenerationInput.xml file has had its custom tool property set to SiteProcessor. When you switch away from the file, the SiteProcessor custom tool produces the code that Visual Studio put in the CodeGenera- tionInput.Generated.cs file.

Next, configure your project to have VS call the gacutil utility to put your DLL in the GAC after your application compiles. First, find the full path to wherever gacutil.exe is installed on your computer.In VS,open the Project Properties for your application.If you’re working in Visual Basic, select the Compile tab and click on the Build Events button. If you’re working in C#, simply select the Build Events tab. Add these lines to the PostBuild event textbox (replace <full path to gacutil> with the path to your copy of gacutil.exe):

"<full path to gacutil>\gacutil.exe" -u "$(TargetName)" "<full path to gacutil>\gacutil.exe" -i "$(TargetPath)"

The first line (which uses the TargetName parameter) removes any existing version of your tool from the GAC. The second line (which uses the TargetPath parameter) installs the current version of your tool into the GAC. When I build a project, I sometimes get an error message that states Microsoft.VisualStudio.Shell.Interop is “not registered for COM interop.”This doesn’t stop the project from building or inter- fere with the custom tool executing, so if you get that message, ignore it. However, to ensure that the PostBuild event script exe- cutes every time you recompile your DLL, set the dropdown list underneath the PostBuild textbox to “When the build updates the project output.” To install your project in the GAC successfully, you must gen- erate an .SNK file that holds a digital signature (a“strong name”).Go to the Signing tab and check the “Sign the assembly” option. From the dropdown list you just enabled, select <New…> to display the Create a Strong Name Key dialog. Enter a valid file name in the“Key file name”textbox. The resulting file can be read with Notepad, so if you want to ensure that no one but you has access to the file, enter a password in the dialog; if you’re not worried about that, then uncheck the password option before clicking on the OK button.

Integrating with Windows and COM The next step is to configure your project to have your DLL regis- tered with COM/Windows every time you build it. Still in Project Properties, find the “Register for COM interop” checkbox on the Build tab (for C#) or Compile tab (for Visual Basic) and check it. You’ll need to revisit this option if you change the project’s configu- ration setting (for example, if you switch from Debug to Release), because the option is cleared when the configuration changes. As part of supporting COM, you also must go to the Application tab and click on the Assembly Information button. Check the “Make assembly COM-Visible”option on the resulting dialog. Your custom tool must implement two interfaces: IVsSingle- FileGenerator and IObjectWithSite. You must assign your class a unique GUID to identify it to Windows. Simply add a System.Run- time.InteropServices.Guid attribute to your class and pass it a

higher level, depend on the source that’s clearly on top. Our most popular product, Chart FX
for interactive demos and more information about our latest products. Data visualization for every need, every

Data visualization for every need, every platform

BUILDING CUSTOM TOOLS

Rather than rewrite these methods each time you create a custom tool, use a set of variables to hold the values and just update those variables from one tool to another.

GUID. In VS 2008, you can generate a GUID by selecting Create GUID from the Tools menu. In VS 2005, open the VS Command window and run the guidgen utility. Both methods open the Create GUID dialog. Regardless of how you start the tool, pick option 4 to generate a GUID compatible with the Guid attribute (the result will be enclosed in braces that you’ll need to delete after pasting the GUID into your code). Once you’re done, your class declaration will look like this in Visual Basic:

<System.Runtime.InteropServices.Guid( _ "B2429B91-452D-4a95-A355-435337729EFB")> _ Public Class TextGenerator Implements _

IVsSingleFileGenerator

Implements

IObjectWithSite

For VS to know about your custom tool, you need to add at least one key to the Windows registry. The easiest way to do this is to add two methods to your application: one to add the key and one to delete it. With the right attributes on those methods, they will be called auto- matically when your custom tool is registered or deregistered with Windows. (The changes you make to your project ensure that your tool is registered and deregistered each time you build it.) The code in these two methods is mostly—but not completely— boilerplate.You need to specify the version of VS that the custom tool works with,provide a GUID that identifies the language of the projects that your tool will work with,provide the name you’ll use in the Cus- tomTools property and give a description. In addition, you have to copy the GUID you generated for the GUID attribute into this code. Rather than rewrite these methods each time you create a custom tool, use a set of variables to hold the values and just update those variables from one tool to another. This VB code creates a tool for C# projects in VS 2008 called TextGenerator:

Shared VSVersion As String = "9.0" Shared CSLangGUID As String = _

"{fae04ec1-301f-11d3-bf4b-00c04f79efbc}"

Shared ToolName As String = "TextGenerator" Shared ToolDesc As String = _ "Generates a class from text input" Shared ToolGUID As String = _ " B2429B91-452D-4a95-A355-435337729EFB "

<System.Runtime.InteropServices.ComRegisterFunction()> _

Public Shared Sub RegisterClass(ByVal typ As Type) Dim key As Microsoft.Win32.RegistryKey key = CreateSubKey( _ "SOFTWARE\Microsoft\VisualStudio\" & VSVersion & _ "\Generators\{" & CSLangGUID + "}\" & ToolName & "\") key.SetValue("", ToolDesc) key.SetValue("CLSID", "{" + ToolGUID + "}") key.SetValue("GeneratesDesignTimeSource", 1) End Sub

<System.Runtime.InteropServices.ComUnregisterFunction> + Public Shared Sub UnregisterClass(ByVal type As Type) Microsoft.Win32.Registry.LocalMachine.DeleteSubKey( _ "SOFTWARE\Microsoft\VisualStudio\" & VSVersion & _ "\Generators\" & CSLangGUID & "\" & ToolName & "\", _ False) End Sub

If you want to support more than one language (for instance, if your tool works equally well in both C# and VB projects), just write out two keys: one for each language. The language GUID to use for VB is 164B10B9-B200-11D0-8C61-00A0C91E29D5.

Using Standard Code For the four methods required by the interfaces your class has to implement, you can use the same code for every custom tool you create. For example, the code for the GetSite and SetSite methods never changes:

Private _site As Object

Public Sub GetSite( _ ByRef riid As System.Guid, ByRef ppvSite As _ System.IntPtr) Implements _

IObjectWithSite.GetSite

If Me

site

= Nothing Then

Throw New _

System.ComponentModel.Win32Exception(-2147467259)

End If

Dim objectPointer As IntPtr = _

GetIUnknownForObject(Me site) Try

BUILDING CUSTOM TOOLS

BUILDING CUSTOM TOOLS QueryInterface(objectPointer, riid, ppvSite) If ppvSite = IntPtr.Zero Then Throw New _

QueryInterface(objectPointer, riid, ppvSite) If ppvSite = IntPtr.Zero Then Throw New _

System.ComponentModel.Win32Exception(-2147467262)

End If

Catch

End Try

End Sub

Public Sub SetSite(ByVal pUnkSite As Object) Implements _

IObjectWithSite.SetSite

Me

site

= pUnkSite

End Sub

The GetDefaultExtension method provides the extension that VS will add to the file containing your generated code, so you may need to change it. This example causes VS to create a file with the format filename.generated.cs:

Public Function DefaultExtension( _ ByRef pbstrDefaultExtension As _ String) As Integer Implements _

IVsSingleFileGenerator.DefaultExtension pbstrDefaultExtension = ".generator.cs" Return 0 End Function

When VS is ready to generate your code, it calls the IVsSingleFile- Generator interface’s Generate method.VS passes the method the name of the file, the project’s namespace, the file’s contents, and a progress bar. You must update the method’s two ByRef/out parameters with an array of bytes containing your generated code and the length of your array.You should set the array parameter to nothing and the length parameter to 0 if your code generation fails.

Rather than rewrite the Generate method for every custom tool, have the Generate method create a class called CodeGenerator and call a method on it named GenerateCode.Always pass the Gen- erateCode method the name of the file, the project Namespace, the file contents and the progress bar that VS passes to the Generate method. As a result, the Generate method becomes a set of boiler- plate code that looks the same in every custom tool:

Dim generatedCode() As Byte

Try Dim cg As SiteGenerator = New CodeGenerator generatedCode = cg.GenerateCode(wszInputFilePath, _ wszDefaultNamespace, bstrInputFileContents, _ pGenerateProgress)

Instantly Search Terabytes of Text ◆ dozens of indexed, unindexed, fielded data and full-text search
Instantly Search
Terabytes of Text
◆ dozens of indexed,
unindexed,
fielded data and
full-text search
options (including
Unicode support
for hundreds
of international
languages)
◆ file parsers /
converters for
hit-highlighted
display of all
popular file
types
◆ Spider supports
static and
dynamic web
data;
highlights
DesktopwithSpider DesktopDesktopwithwithSpiderSpider
hits
while
NetworkwithSpider
NetworkNetworkwithwithSpiderSpider
displaying links,
formatting and
PublishPublishPublishforforfor CD/DVDsCD/DVDsCD/DVDs
images
intact
WebwithSpider WebWebwithwithSpiderSpider
◆ API supports .NET, C++, Java, databases, etc.
New .NET Spider API
EngineEngineEngineforforfor WinWinWin&&&.NET.NET.NET
New
New
EngineEngineEngineforforfor LinuxLinuxLinux
The Smart Choice for Text Retrieval ®
since 1991
64-bit
64-bit
◆ “Bottom line: dtSearch manages a terabyte of text
in a single index and returns results in less than a
second” – InfoWorld
◆ “For combing through large amounts of data,”
dtSearch “leads the market” – Network Computing
◆ dtSearch “covers all data sources
Web-based engines” – eWEEK
powerful
◆ dtSearch “searches at blazing speeds” – Computer
Reseller News Test Center
See www.dtsearch.com for hundreds more reviews,
and hundreds of developer case studies
Contact dtSearch for
fully-functional evaluations
1-800-IT-FINDS • www.dtsearch.com

BUILDING CUSTOM TOOLS

BUILDING CUSTOM TOOLS When you’re ready to start generating code , replace the line in your

When you’re ready to start generating code, replace the line in your GenerateCode method that sets the generatedCode variable with a line that sets the variable to a string containing your code.

rgbOutputFileContents(0) = _

AllocCoTaskMem(generatedCode.Length) System.Runtime.InteropServices.Marshal.Copy( _ generatedCode, 0, rgbOutputFileContents(0), _ generatedCode.Length) pcbOutput = generatedCode.Length

Catch pcbOutput = 0 rgbOutputFileContents(0) = IntPtr.Zero End Try

Generating Code You’re now finally ready to start writing the code that’s unique to your code generator. Start with a standard version of your CodeGenerator class, which writes to the output file the parameters passed to it from the Generate method. This code lets you check that your custom tool works and is getting passed what you expect:

Public Function GenerateCode(ByVal FilePath As String, _ ByVal Namespc As String, ByVal FileContents As String, _ ByVal Progress As _

IVsGeneratorProgress) _ As Byte()

If FileContents = "" Then Throw New Exception("No content") End If Progress.Progress(0, 100) Dim generatedCode As String generatedCode = "Namespace: " & Namespc & ", " & _ "File name:" & FilePath & ", " & _ "File contents:" & FileContents Progress.Progress(100, 100) Return System.Text.Encoding.UTF8.GetBytes( _ generatedCode)

End Function

You must start a new copy of VS to test your custom tool. After the new copy starts, create a project, add a file, fill it with some text, and set the file’s CustomTool property to the name of your custom tool. In VS 2008, your custom tool runs as soon as you switch focus away from the file; in VS 2005, you can run your custom tool by closing the file. In either version of VS, you can also right-click on the file in Solution Explorer and select “Run custom tool.

Whatever method you choose, you should see a new file added under your existing file with the file extension you specified in the GetDefaultExtension method and holding the output from your GenerateCode method. Of course, it might not work the first time. Problems usually are related to registering your custom tool with Windows. If this is the case, the message you’ll get will typically say that your custom tool cannot be found. A number of typical problems can occur. First, the GUID you used in the GUID attribute on your class might be different than the Guid you set the ToolGUID variable to. Second, the two methods that add and remove the keys to the Windows registry might be wrong. Check that you’ve got the right version number for VS and the right GUID for the language you’re testing in. For example, did you create a key for C# but then test your custom tool in a VB project? It’s helpful to open RegEdit and look at the keys you’re generating to see if they look like the other keys in the Generators section. Finally, your custom tool might not have gotten into the GAC. If a problem exists with your PostBuild event, you’ll see a message in your Output window. You can also try removing your custom tool from the GAC by using gacutil –u nameofyourproject. If you get a message stating that your assembly couldn’t be found, then you’ll know that you have a problem getting your tool into the GAC. When you’re ready to start generating code, replace the line in your GenerateCode method that sets the generatedCode variable with a line that sets the variable to a string containing your code. This example creates a “Hello,World”class:

generatedCode = "namespace " & Namespc & _ "{public class NewClass{public string" & _ " SayHello(string Name){return ""Hello, "" + Name;}}}";

You now have a working custom tool. True, the interesting work is still left to do: reading your file’s input and turning it into real code. But that’s also the fun part. VSM

Peter Vogel (peter.vogel@phvis.com) is a .NET consultant, author and instructor living in Goderich, Ontario, Canada.

GO ONLINE

Use this Locator+ code at VisualStudioMagazine.com to go directly to these related resources.

READ & DOWNLOAD

VS0903PV Read this article.

Special Advertising Section

Special Advertising Section SP O TLIGHT ON GRAPHICS, IMAGING AND MAPPING The following advertising section showcases

SPOTLIGHT ON GRAPHICS, IMAGING AND MAPPING

The following advertising section showcases companies offering solutions for your graphic, imaging and mapping needs.

The following advertising section showcases companies offering solutions for your graphic, imaging and mapping needs.
Setting a New Standard in Geospatial Application Development A t ISC, our mission is to
Setting a New Standard in
Geospatial Application Development
A t ISC, our mission is to provide you with the best tools
and software you will find for fulfilling your organization’s
The MapDotNet UX product line includes:
geospatial visualization and analysis needs. The MapDotNet
product line is a perfect fit for any organization that supports
Microsoft’s .NET platform and is looking for cost-effective
geospatial solutions.
MapDotNet UX is the comprehensive Web-enabled
geospatial platform for enterprise applications and Web sites.
MapDotNet UX brings a new level of user experience to the
MapDotNet series with extensive support for Windows
Presentation Foundation (WPF) and Silverlight, as well as
AJAX. With a focus on user experience, MapDotNet UX is
the toolkit for GIS integration with consumer-based
mapping platforms.
• MapDotNet UX Studio: a tool for designing interactive
maps for Silverlight, WPF and AJAX applications. It
includes utilities for tile cache management and spatial
data transfer, with support for Microsoft SQL Server 2008.
• MapDotNet UX Web Services: WCF-based Web services
that provide an open interface for server-based spatial data
services and the MapDotNet WPF map rendering engine,
which takes advantage of accelerated graphics hardware. It is
licensed per server, not per processor.
• MapDotNet UX SDK: WPF and Silverlight 2.0 controls, a
Virtual Earth™ tile handler for use in AJAX applications, and
an extensive class library.
MapDotNet is
a product of
www.mapdotnet.com
Setting the standard in geospatial application development. MapDotNet with Silverlight Interface Interactive Mapping is

© Copyright 2009, ISC, all rights reserved.

60 day trial at www.mapdotnet.com or ca ll us at (850) 893 - 6741 . ©
Setting the standard in geospatial application development. Interactive Mapping is our Passion An entire GIS
Setting the standard in geospatial application development.
Interactive Mapping
is our Passion
An entire GIS platform designed to
allow you to rapidly visualize, manage
and analyze geographic data. The
MapDotNet Platform consists of
MapDotNet UX for Silverlight & WPF
MapDotNet with
and MapDotNet Server for AJAX.
Silverlight Interface
Download a 60 day trial at www.mapdotnet.com
or call us at (850) 893-6741.
© Copyright 2009, ISC, all rights reserved.
GIS—Better Decisions through Modeling and Mapping Our World ESRI Philosophy ESRI believes that better information
GIS—Better Decisions through
Modeling and Mapping Our World
ESRI Philosophy
ESRI believes that better information makes for better decisions.
Our reputation is built on contributing our technical knowledge,
our special people, and our valuable experience to the collection,
analysis, and communication of geographic information. Founded
in 1969, ESRI is the leading developer of GIS software with more
than 300,000 clients worldwide.
Contact us today to learn how ESRI’s GIS is helping to manage and
improve business operations around the world.
1-800-447-9778
info@
Copyright © 2009 ESRI. All rights reserved. The ESRI globe logo, ESRI, ArcGIS, www.esri.com, and @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.

VisualStudioMagazine.com

·

March 2009 ·

VISUAL STUDIO MAGAZINE

27

LEAD Technologies, Inc. is the publisher of LEADTOOLS, the world leader in imaging components for
LEAD Technologies, Inc. is the publisher of LEADTOOLS, the world leader in imaging components
for developers. LEADTOOLS SDKs are used by virtually every Fortune 1000 company, including
Microsoft, HP, Kodak, Sony, GE and Siemens.
LEADTOOLS provides developers easy access to decades of expertise in developing color, grayscale,
document, medical, vector and multimedia imaging technology. Install LEADTOOLS to eliminate
months of research and development, and add high levels of quality, performance and functionality.
Key Features and Benefits
• Load and save over 150 formats to disk or SharePoint servers.
• Specialized bi-tonal image display and processing.
• High speed scanning with TWAIN 2.0 and WIA including support for unattended batch scanning.
• Fast and Accurate Forms Recognition and Forms Processing.
• Convert images to documents with multi-threaded OCR/ICR/OMR.
• Detect, read and create linear and 2D barcodes.
• Improve recognition performance & image quality with document image clean up tools.
• Efficiently store and transmit images with the industry’s best compression engines.
• Bitonal, Color and Extended Grayscale Compression and Processing.
• Specialized versions of LEADTOOLS for document, color, medical and multimedia development.
• Industry Leading Technical Support.
Barcode
Document Imaging Engine
Document Clean-up
Load and save over 150 different formats including PDF/A and XPS. Add specialized bitonal image
processing, viewing, high speed scanning, annotations, and document image compression to your
business applications. Includes a powerful document clean-up engine to despeckle, deskew, remove
lines, borders, hole-punches and inverted text and make other corrections. Display features include
fast view port rotation for instant rendering and optimized scale to gray and favor black. Maximize
scanner performance with auto-detection of the fastest settings for image acquisition from TWAIN 2.0
and WIA devices. Mark-up images with the industry’s most comprehensive and highly customizable
annotation engine including notes, pointers, redactions, highlights, stamps, measurement tools and
audio/video. Save disk space and network bandwidth with LEAD’s advanced bitonal image compression
algorithms for JBIG2, MRC, CCITT G3/G4 and JPEG 2000. Automatically recognize and classify forms.
Convert images to editable documents with multi-threaded OCR/ICR/OMR modules. Detect, read and
write a wide variety of linear and 2D barcode symbols.
Medical Imaging Engine
Form Recognition
Develop state-of-the-art imaging applications for use by the healthcare industry with high and low
level DICOM data manipulation and secure DICOM communication. A customizable display container
features built in viewing tools. Extend PACS access to the Internet, including web based reading and
consulting with HTML or rich clients and web services. Support for extended grayscale and color image
processing and compression such as JPEG, JPEG 2000 and MPEG-2. LEADTOOLS provides high level
support for waveforms, printing, digital signatures, overlays, softcopy presentation, modality LUT,
VOI, LUT and DICOM annotations and graphics objects. Includes sample source code for DICOM server
and client services to query, retrieve, store and Modality Worklist.
Imaging Engine
Incorporate digital imaging functionality into your applications. Load, save and convert over 150 formats
including TIFF, EXIF, PDF and PSD supporting a wide range of color spaces and compression types
including JPEG, JPEG XR, JPEG 2000, CCITT G3/G4, LZW and ZIPLIB. Easily capture from screen and any
32/64 bit TWAIN 2.0 or WIA compliant device. Apply image transforms, color space conversion and 200+
region aware image processing routines. Speed up development with high level display controls with
built-in features such as pan, zoom and magnify, thumbnail browser and imaging common dialogs.
Annotations
Multimedia Imaging Engine
Enable your Windows and Web applications with multimedia capture, playback, conversion and
editing. Create and burn DVDs with menus. Easily add TCP/UDP network streaming and HD broadcast.
Load, save and convert MP4, AVI, MPEG, MP3, WMV, 3GP, OGG, FLV (YouTube and HD Flash) and other
file types. Add support for portable devices including iPhone/iPod, PSP, ZEN, Zune, SmartPhone and
others. Encode, decode and transcode with LEAD’s optimized software codecs including H264, MPEG4,
H263, and MPEG-2 or any third party codecs. LEAD multiplexers and demultiplexers such as MPEG-2
Program and Transport, MP4, OGG and FLV are available.
LEADTOOLS SDKs feature LEAD’s iCompress™ Technologies.
Free 60 Day Evaluation!
www.leadtools.com/vsm
866 530-3399
Document Form Recognition & Processing Barcode Mark-up DICOM Medical Multimedia Develop your application with
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.
convert MPEG, AVI, WMV, MP4, MP3, OGG, ISO, DVD and more. LEADTOOLS SDKs feature LEAD’s iCompress™

Free 60 Day Evaluation!

www.leadtools.com/vsm

LEADTOOLS SDKs feature LEAD’s iCompress™ Technologies. Free 60 Day Evaluation! www.leadtools.com/vsm 866 530- 3399

866 530-3399

each offering the ir own individual set of benefits. ImagXpress and ImageGear are the flagship imaging

Barcode

Capture • Photo Image Enhancement • Video Compression, Decompression • PDF, TIFF and More www.pegasusimaging.com
Capture • Photo Image Enhancement • Video Compression, Decompression • PDF, TIFF and More www.pegasusimaging.com
Capture • Photo Image Enhancement • Video Compression, Decompression • PDF, TIFF and More www.pegasusimaging.com
Capture • Photo Image Enhancement • Video Compression, Decompression • PDF, TIFF and More www.pegasusimaging.com

www.pegasusimaging.com

ILLUSTRATION FROM ISTOCKPHOTO.COM

C# CORNER
C# CORNER

ANONYMOUS TYPES

Create Anonymous Types

Taking a careful look at the capabilities the compiler gives to anonymous types provides an excellent tutorial on what you should consider when you create your types—including whether they are classes or structs. BY BILL WAGNER

whether they are classes or structs. BY BILL WAGNER TECHNOLOGY TOOLBOX VB.NET C# SQLServer2005 ASP.NET XML
TECHNOLOGY TOOLBOX VB.NET C# SQLServer2005 ASP.NET XML VB6
TECHNOLOGY TOOLBOX
VB.NET
C#
SQLServer2005
ASP.NET
XML
VB6

C # developers create types every day. But how often do developers think about how well

their types behave with the type system? Do they write the methods and define the behav-

ior their users will expect one day? What capabilities will the .NET Framework expect

from any type?

Answering these questions isn’t much work, but it’s probably a bit more than you do today. Taking a look at the capabilities the compiler gives to anonymous types also serves as an excellent tutorial on what you should consider when you create your types. Begin by creating a simple C# program that creates an anonymous type and prints each of the values in the sequence of those objects (see Go Online,p.35,to access a sample listing).The program isn’t that inter- esting in itself,but it’s instructive to look at the code the compiler generates for that anonymous type. Now it’s time to create a modified version of the code generated for this type (see Listing 1, p. 35). The modified version changes many of the names because the compiler uses special characters for anonymous types to avoid collisions with user-created names.Also, the compiler creates a generic class, which it uses for some other optimizations. Let’s examine the important design decisions and the features added to the anonymous type. First, the accessibility of the class is internal. How often do you create internal classes? If your default choice is public, you should change that habit. How many classes do you create that will never be accessed outside of the current assembly? Are those public? If so, you’re creating public classes unnecessarily, and you’re adding names to your public API that aren’t necessary. That creates more confusion for your users. They aren’t supposed to use some of these classes, and yet, those classes show up in IntelliSense and in your

C# CORNER

» ANONYMOUS TYPES

API docs. This essentially pollutes your users’experience with your application. You should always choose the least-visible access to achieve your goal. Anonymous types are sealed. This is an obvious choice because you can’t derive a new type from something you can’t name. Your job is somewhat more difficult. You need to examine your types and make an explicit decision to support or deny derived classes from your type. If you believe developers shouldn’t extend your type, make that statement explicit by using the sealed keyword. If you believe developers will want to extend your type, pay careful consideration to where derived types will want to extend or change the behavior of your type. Make those methods virtual and provide explicit guidance on the extension points you’ve created. You should always support or prohibit derivation explicitly; don’t leave it to client developer interpretation.

Check the Anonymous Type Next, you should check whether the anonymous type is immutable. (VB.NET supports both mutable and immutable anonymous types.) Immutable types are simpler for many reasons:You can vali- date state in constructors and know they’re always valid; immutable types can be shared safely across threads; and immutable types sim- plify testing because state changes can’t affect later methods. How- ever, it’s overly simplistic to say that every type in your programs should be immutable; that’s simply not practical.You should prefer immutable types whenever possible. When design issues force you to create mutable types, you should understand that those types are more complicated, will introduce more errors and will introduce more complications in testing. The more related data fields in a type, the more complicated the relationships are. There are three methods added to every anonymous type by the C# compiler: overrides of Object.ToString(), Object.Equals() and Object.GetHashCode(). Object.ToString() helps in even this small sample. You can print the anonymous type object instead of writing extra code to print each of the fields from the anonymous type. Over the course of a larger application, a proper ToString() method makes it easier to use your type any time you want to display the information in an object for your users, or even in the debugger for other developers.You should always create a ToString() method that displays the best choice of information for your type. The overrides of Object.Equals() and Object.GetHashCode() force anonymous types to use value semantics rather than refer- ence semantics. That means two objects are equal if they contain the same information, rather than if they refer to the same object. If you modify Equals(), you do need to create a corresponding GetH- ashCode() to ensure that objects that are equal always return the same hash value. When you create your own types, you can choose to follow either reference semantics or value semantics. In general, types that are primarily data-storage types should follow value semantics. Types that are primarily defined by their behavior should follow reference semantics. Once again, make that an explicit decision: Determine which makes more sense for your type, and implement that appropriately.

Critique on Anonymous Types Of course, nothing is perfect, including the implementation of anonymous types by the C# compiler. When you create your own types, you should consider additional decisions as part of every type you create. The first of these is related to equality semantics. The Object.Equals() override uses the ultimate base class,System.Object. As of .NET 2.0, you have a generic interface for equality: IEquat- able<T>.Anytime you override System.Object.Equals(),you should implement IEquatable<T> for your type. For example, you should add IEquatable<T> support if your type is coded by hand:

internal sealed class HandCodedPoint :

IEquatable<HandCodedPoint>

The implementation of Equals() is a strongly typed version of the System.Object override. Notice that you can now defer the imple- mentation of System.Object.Equals to your strongly typed version:

#region IEquatable<AnonymousTwo> Members public bool Equals(HandCodedPoint other)

{

return (((other != null) && EqualityComparer<int>.Default.Equals( this.xField, other.xField)) && EqualityComparer<int>.Default.Equals( this.yField, other.yField));

}

#endregion

public override bool Equals(object value)

{

return Equals(value as HandCodedPoint);

}

If you’ve created your own version of Equals() and implemented IEquatable<T>, you should create your own operator == and operator !=. Because you’ve already written the logic in your IEquatable<T> method, you can reuse that implementation in your operator ==.Your operator != is the inverse:

public static bool operator ==(HandCodedPoint left, HandCodedPoint right)

{

if (left == null) return right == null; return left.Equals(right);

}

public static bool operator !=( HandCodedPoint left, HandCodedPoint right)

{

return !(left == right);

}

C# CORNER

» ANONYMOUS TYPES

The lesson to take away from these examples: Equals touches many methods; make sure they’re all consistent. You should also consider implementing IComparable<T> (and the non-generic IComparable) if your type has an obvious ordering relation. This point type has an obvious ordering relation:

those distances and define an ordering relation on points:

public int CompareTo(HandCodedPoint other)

{

is greater than nothing: if (other == null ) New 7.0 DotImage Release The .NExT Step
New 7.0 DotImage Release The .NExT Step In Document and Photo Imaging DotImage 7.0—More Powerful,
New 7.0
DotImage
Release
The .NExT Step In Document
and Photo Imaging
DotImage 7.0—More Powerful,
with Zero-Footprint Imaging, and
3 Months of Free Gold Support.
New features to our already powerful imaging toolkit include PDF/A
support, AJAX Vector Annotations including FreeHand, WPF annota-
tions, and more. Use templates in our AJAX Wizard to create zero-
footprint web applications in C# and VB.NET—Take document and
photographic imaging to the .NExT step.
Visit Atalasoft.com for web demos, video tutorials, and a free trial.
Atalasoft, Your .NET Imaging Partner
Call us toll free at 866-568-0129
www.atalasoft.com

return 1; int distanceSquared = xField * xField + yField * yField; int otherDistanceSquared = other.xField * other.xField + other.yField + other.yField; return distanceSquared.CompareTo( otherDistanceSquared);

}

public int CompareTo(object obj)

{

return CompareTo( obj as HandCodedPoint);

}

Implementing IComparable implies you have also defined operator > and operator <. You’ve already written the algorithm, so all you need to do is add the signature and call the methods you’ve already written:

public static bool operator >( HandCodedPoint left, HandCodedPoint right)

{

if (left == null) return false; else return left.CompareTo(right) > 0;

}

public static bool operator <(

HandCodedPoint left, HandCodedPoint right)

{

if (left == null) return right != null; else return left.CompareTo(right) < 0;

}

HandCodedPoint implements both ICom- parable<T> and IEquatable<T>, so you should add the operators >= and <=:

public static bool operator >=( HandCodedPoint

C# CORNER

» ANONYMOUS TYPES

left, HandCodedPoint right)

{

return (left == right) || (left > right);

}

public static bool operator <=(HandCodedPoint

left, HandCodedPoint right)

{

return (left == right) || (left < right);

}

This is a fair amount of work and I don’t recommend adding it to every single type you create. However, you should give it some thought and make sure you know when you should and shouldn’t care about certain behaviors. Obviously it doesn’t make any sense to define an ordering relation between windows or many other types you create. Anonymous types include a fair amount of code to imple- ment the behavior that you would expect on every type.You should follow the same guidelines and create methods that all your users will expect or implement in their own version. You should also

spend some time thinking of the basic behavior that’s expected of your types, and create that behavior for your users. Rather than just ignoring the basic behavior, decide which behavior should be implemented in your type and create it. VSM

Bill Wagner, 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#” (Addison-Wesley Profes- sional, 2008), has been a commercial software developer for the past 20 years. He is a Microsoft Regional Director and a Visual C# MVP. His interests include the C# language, .NET Framework and soft- ware design. E-mail Bill at wwagner@srtsolutions.com.

GO ONLINE

Use these Locator+ codes at VisualStudioMagazine.com to go directly to these related resources.

READ & DOWNLOAD

VS0903CC Read this article and download the sample code online.

C#

REPRESENTATION OF AN ANONYMOUS TYPE

sample code online. C# REPRESENTATION OF AN ANONYMOUS TYPE internal sealed class AnonymousOne (uint)

internal sealed class AnonymousOne

(uint)EqualityComparer<int>.Default.GetHashCode( this.xField); return (int)((0xa5555529 * num) +

(uint)EqualityComparer<int>.Default.GetHashCode(

{

// Fields private readonly int xField; private readonly int yField;

this.yField));

// Methods

}

public AnonymousOne(int x, int y)

{

public override string ToString()

this.xField = x; this.yField = y;

{

StringBuilder builder = new StringBuilder(); builder.Append("{ x = "); builder.Append(this.xField); builder.Append(", y = "); builder.Append(this.yField); builder.Append(" }"); return builder.ToString();

}

public override bool Equals(object value)

{

var type = value as AnonymousOne; return (((type != null) &&

}

EqualityComparer<int>.Default.Equals(this.xField, type.xField)) &&

// Properties public int x

EqualityComparer<int>.Default.Equals(this.yField,

{

type.yField));

get { return this.xField; }

}

}

public override int GetHashCode()

public int y

{

{

uint num = 0xdd9cb371; num = (0xa5555529 * num) +

get { return this.yField; }

}

}

LISTING 1 This code is similar to the code created by the compiler for anonymous types. The compiler creates a generic type in order to reuse some code. Also, the compiler generates names that are illegal for handwritten code to avoid collisions with user-defined types.

AskKathleen

DISPLAY MULTIPLE PAGES IN SILVERLIGHT

BY KATHLEEN DOLLARD

Learn how to display multiple pages in Silverlight and discover the tools and controls that ship with it; track down a bug in a case statement; and take advantage of helpful tips for trying to obtain a clean Code Analysis.

Technologies mentioned in this article include Silverlight, Windows Presentation Foundation, Visual Studio Team System, Visual Basic and C#.

Q How can I change forms in Silverlight so my application

works in exactly the same way in both my Silverlight

and WinForms applications?

A Silverlight Forms correspond roughly to Pages in Sil- verlight, and each Silverlight application has exactly one Page. So, I’d like to rephrase your question to

something like this: “How can I make it seem as though I’m changing forms?” Once you ask the question this way, you’re halfway to the answer.You provide a page that acts as a container for user controls,and each user control corresponds to a form in your existing application (see Figure 1).Pages can have only one content element, so you generally use a container such as a grid to hold your user controls. The grid is a nice container to use because it lets you overlay controls when needed; it also lets you include features that behave consistently across all your user controls.This is similar to using a Master Page in ASP.NET.

Q I’ve heard there’s a TreeView control for Silverlight 2.0, but I don’t see it in the toolbox. I’m having a hard time figuring out what controls are in Windows Presentation

Foundation [WPF] and Silverlight, respectively.

A Microsoft is releasing controls for both WPF and

Silverlight as Toolkits. This avoids delaying the

release of important tools until a normal ship cycle.

In addition to the controls it ships with, Silverlight has a preview of a Visual State Manager in the main tool, while WPF has a preview in the WPF Toolkit. The Silverlight Toolkit also includes a preview of an Implicit Style Manager that recreates some functionality that’s inherently part of WPF.

The Visual State Manager in Silverlight allows you to describe states for controls, and defaults for what the controls should look like when they’re in each state. It also allows you to dictate how long the transition into a given visual look should take (the length of the animation). When creating applications, programmers can override the standard state appearance with their own. The Blend tooling for this is extremely good, making it much easier to customize controls than in WPF, where individual styles and triggers are needed to provide this functionality. The Implicit Style Manager introduced to Silverlight as a preview in the Silverlight Toolkit allows you to apply the style based on type, rather than by requiring an explicit style declaration on each instance of each control. This isn’t as automatic as the WPF approach because each control is based on a container that applies styles as a theme, and the container must be placed in each user control. Also, you can’t change the theme at runtime. The good news is that the Silverlight Toolkit contains a great set of themes to get you started.

Q I have a bug in a case statement that I don’t understand.

This code works correctly when the direction is right or

below. It throws an InvalidOperationException when

None (the default) is passed, which it shouldn’t do. Direction is an enum. Can you tell me what’s wrong?

Select Case mDirection Case Direction.Right location = New Point(mPopup.ActualWidth, 0)

Case Direction.Below Or Direction.None

location = New Point(0, -mPopup.ActualHeight) Case Else Throw New InvalidOperationException() End Select

ASK KATHLEEN

»

SILVERLIGHT

A This is an easy mistake to make because Or acts as a bitwise or Boolean operator depending on the operands. In this case, the operands for

the Or operator in the line I’ve highlighted act as a bitwise operator. I’m going to guess that the value of Directions.None is zero, which is a good choice for the default value.If that’s true, the result of the Or operation is Direction.Below. This is why it works for everything except the value of Direction.None. Just use a comma to separate the different values you wish to match:

Case Direction.Below, Direction.None

If you make this mistake in C#, you fix it by using two adjacent switch statements with no break statement:

switch (mDirection)

{

case Direction.Right:

location = new Point(mPopup.ActualWidth, 0); break; case Direction.None:

case Direction.Below:

location = new Point( 0, -mPopup.ActualHeight); break; default:

break;

}

-mPopup.ActualHeight); break ; default : break ; } FIGURE 1 Display Several Silverlight “Forms”

FIGURE 1 Display Several Silverlight “Forms” Simultaneously. Silverlight runs in a browser, so there’s only one Page that serves as the RootVisual or visual entry point for your application. You can’t change the RootVisual as your application runs. When your application needs to display several “forms” at different times, create one Page to serve as a navigation container and switch out user controls that contain the “forms” of your application. The Page might be empty or contain visual elements common to all of your user controls.

Q I’m trying to get a clean Code Analysis. Unfortunately, the code in one of my classes is giving Code Analysis warnings. My boss says we need to comply fully with Code Analysis

without suppressing any messages. The code looks like this:

private void WriteMessage(string message)

{

string text = String.Empty; if (mOwner.Content != null)

{

text = mOwner.Content.ToString();

}

System.Diagnostics.Debug.WriteLine( text + ":" + message);

}

The warning is:

CA1801 : Microsoft.Usage : Parameter 'message' of 'Class1.WriteMessage(string)' is never used. Remove the parameter or use it in the method body.

Why does Code Analysis give these errors when the parameter is obviously used?

The

compiler removes the Diagnostics.Debug line when com- piling.If you check the IL through Reflector,you’ll see that

the only code using the parameter and variable doesn’t exist within the Release Assembly. Interestingly, the same code in VB gives a sec- ond warning:

A

Code

Analysis

analyzes

the

Release

Assembly.

CA1804 : Microsoft.Performance : 'MenuProvider.WriteMes- sage(String)' declares a variable, 'text', of type 'String', which is never used or is only assigned to. Use this variable or remove it.

There are a few ways to work around these problems, but your boss is making a mistake when he insists on setting a goal for full Code Analysis compliance without suppressing any items. A good solu- tion in this case is to formally ignore the warnings. If you right- click on the warning, you’ll have the option of ignoring it in an external file or in the source code. I much prefer suppressing the messages in source code and always including a Justification. This lets other coders know why you decided to ignore the warning. You can’t just remove the code with conditional compilation because other code is calling the method. A slightly more complex approach would be to alter the class to be a partial class and add a new declaration for a partial method with the same signature

ASK KATHLEEN

» SILVERLIGHT

You can’t just remove the code with conditional

compliation because other code is calling the method.

(name and parameters) as your WriteMessage method. You don’t need a second class declaration; instead, change the existing one to include the keyword partial. Then wrap your actual WriteMessage method entirely in a #if DEBUG directive:

partial void WriteMessage(string message);

#if DEBUG partial void WriteMessage(string message)

{

// Code as above

}

#endif

When you compile this code for debugging,Visual Studio will find the real WriteMessage method, and the method will work as expected. When you compile for release, the DEBUG constant will be missing, so your implementation of WriteMessage will be miss- ing. Due to the partial class declaration, the compiler will remove all calls to your WriteMessage method. This only works because your method is private and void.It also provides a slight runtime performance improvement because calls won’t be made to the method, and the string concatenation won’t be performed.This performance improvement will be small,but can still prove significant if you call this method a number of times.

Q I’m trying to get a clean Code Analysis run for some Visual Basic code, but I’m getting the following warnings:

Warning 3 CA1034 : Microsoft.Design : Do not nest type 'Menu- Item.MenuItemClick2EventHandler'. Alternatively, change its accessibility so that it is not externally visible. SilverlightMenuLibrary

Warning 4 CA1003 : Microsoft.Design : Visual Basic generates EventHandler delegates for events that use the following pattern: Event MyEvent(ByVal Sender As Object, ByVal e as MyEventArgs). Change the event that defines EventHandler 'MenuItem.MenuItemClick2EventHandler' to use EventHandler<T> by defining the event type explicitly, e.g. Event MyEvent As EventHandler(Of MyEventArgs). SilverlightMenuLibrary

Warning 4 (and possibly Warning 3) is related to this declaration:

Public Event MenuItemClick(ByVal sender _ As Object, ByVal e As MenuItemClickEventArgs)

How do I fix this?

A Prior to the introduction of generics in .NET 2.0 (VS 2005), each unique event with a unique set of parameters needed an explicit declaration of a delegate that corre-

sponded to the event signature. By convention, these events were named with the name of the event followed by “EventHandler.” If you checked the code in Reflector—which is still free, but now dis- tributed by Red Gate Software Ltd.—you’d see a delegate within the class that was generated by the compiler:

Public Delegate Sub _ MenuItemClickEventHandler( _ ByVal sender As Object, _ ByVal e As MenuItemClickEventArgs)

Code Analysis is warning you that there’s a nested delegate. This was appropriate for the generated delegate because it limited the potential for naming collisions. If you’d like to quiet the errors, you can use the code suggested by the second error:

Public Event MenuItemClick _ As EventHandler( _ Of MenuItemClickEventArgs)

This code uses the generic event handler provided by the framework. The help entry for this Code Analysis warning says you shouldn’t ignore it and that it’s a breaking change. This warning holds true for C#, but not for VB. The only downside of this style of event declaration is a few extra lines of code of IL in the assembly, which hardly justifies saying you should never suppress the warn- ing. The automatic usage means changing it isn’t a breaking change. You can suppress the second message globally and just ignore warnings about event handlers, but you can’t suppress the first globally without missing notification on any other nested pub- lic classes. I think it’s easier to change your delegate declarations than to explain why you’re sticking with the old VB style and man- aging the suppressions. VSM

Kathleen Dollard (kathleen@mvps.org) is a consultant, author, trainer and speaker. She’s been a Microsoft MVP for 10 years and is an active member of the INETA Speakers Bureau. She wrote “Code Generation in Microsoft .NET”(Apress,2004),is the founder and principal of GenDot- Net 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

VS0903AK Read this article online.

Advertising Sales

Ad Index

 
  Advertiser Page
  Advertiser Page

Advertiser

Page

Atalasoft, Inc

34

www.atalasoft.com

East
East

ComponentOne

7

www.componentone.com

Andrew Mintz National Sales Manager Phone: 508-532-1433

amintz@1105media.com

dtSearch Corp.

23

www.dtsearch.com

ESRI

5, 27

www.esri.com

 

Intel Corporation

C4

West
West

www.intel.com

 

Chris Kourtoglou Regional Sales Manager Phone: 650-579-0121

ckourtoglou@1105media.com

LEAD Technologies, Inc. www.leadtools.com

27, 28, 29

MapDotNet

www.mapdotnet.com

26, 27

Microsoft Corporation

www.microsoft.com

C2,1,15

William Smith Phone: 603-886-3466

Jenny Hernandez-Asandas

Phone: 818-734-1520 ext 101 Fax: 818-734-1528

Pegasus Imaging Corporation 27, 30, 31 www.pegasusimaging.com

 

wsmith@1105media.com

jhernandez@1105media.com

Rally Software

16

www.rally.com

Serena Barnes Phone: 818-734-1520 ext 164

Red Gate Software www.red-gate.com

9

Danna Vedder Phone: 253-514-8015

Software FX, Inc. www.softwarefx.com

20, 21

dvedder@1105media.com

vsmadproduction@1105media.com

sbarnes@1105media.com

Tallcomponents BV

C3