Академический Документы
Профессиональный Документы
Культура Документы
v1
2/19/09
1:55 PM
Page 1
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
GETTING DIRECTIONS
.NET developers face adjustments
as they start coding for Microsofts
high-flying collaboration platform.
Project1
1/21/09
11:14 AM
Page 1
Project1
1/21/09
11:15 AM
Page 2
Project5
1/28/09
2:41 PM
Page 1
LEADTOOLS Document
Imaging v 16:
by LEAD Technologies
LEADTOOLS Document Imaging has every
component you need to develop powerful
image-enabled business applications including
specialized bi-tonal image display and
processing, document clean up, high-speed
scanning, advanced compression (CCITT
G3/G4, JBIG2, MRC, ABC) and more.
Multi-threaded OCR/ICR/OMR/
MICR/Barcodes (1D/2D)
Forms recognition/processing
PDF and PDF/A
Paradise #
L05 03201A01 Annotation (Image Mark-up)
C/C++, .NET, WPF - Win32/64
$
99
programmers.com/lead
2,007.
550.99
CALLI
VDI Included
programmers.com/vmware
by Pragma Systems
Best
Word Processing Components
Seller!
TX Text Control is royalty-free,
robust and powerful word processing
software in reusable component form.
Paradise #
F01 0131
711.
99
Mindjet MindManager 8
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.
Unlike the usual linear-based approach of
most productivity tools, MindManager 8
uses mind-mapping technology to let you
capture, organize, and communicate
information using an intuitive visual
canvas. Youll be able to work smarter
and transform your ideas into action
more quickly.
919.
programmers.com/theimagingsource
299.
182.
SlickEdit 2008
for Windows
Telerik RadControls
Multi-Edit 2008
by Telerik
by SlickEdit
SlickEdit 2008 is a cross-platform, multi-language code editor that gives programmers the
ability to code in over 40 languages on 7 platforms. This latest version builds on the companys 20 years of experience in enabling developers and development teams to create, navigate, modify, build, and debug code faster and
more accurately.
Paradise #
M39 19201A01
$
949.
View Premier
Paradise #
V55 66101A01
TX Text Control 14
936.99
New
Release!
by FairCom
FarPoint Spread
for Windows Forms
Single Server
Paradise #
D29 02101A07
c-treeACE Professional
Paradise #
P35 0439
615.
242.99
programmers.com/slickedit
800-445-7899
Prices subject to change. Not responsible for typographical errors.
New
Release!
1-49 User
Paradise #
A30 01201A02
161.99
programmers.com/multiedit
programmersparadise.com
0309vsm_TOC_3-4.v4
2/19/09
11:40 AM
Page 3
Contents
March 2009 VOLUME 19 NO. 3
C O LU M N S
C# CORNER
D E PA RT M E N T S
6 Editors Note
BY MICHAEL DESMOND
39 Index of Advertisers
12
F E AT U R E S
12
Getting Directions
32
18
0309vsm_TOC_3-4.v4
2/19/09
11:41 AM
Page 4
Check out these and other exclusive online articles and tutorials on the Visual Studio Magazine Web site at
Online
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 getting 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 technologies 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
theyve come up with. Whether its Web design, .NET development, or SQL
Server programming, weve got an event that matches your needs. Visit
RedmondEvents.com to learn more about upcoming conferences and shows.
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
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 stringand 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
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 transforming IT through virtualization. The site also features articles,
tips, and timely information about all aspects of virtualization including servers, storage, desktops, applications, and
more. Visit VirtualizationReview.com now to start your
move to a more efficient, powerful virtual environment.
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
Project17
1/19/09
5:24 PM
Page 1
0309vsm_EdNote_6-8.v2
2/19/09
Editors
3:25 PM
Page 6
Note
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 content, but our coverage will expand to include issue-oriented
features, timely news analysis and incisive commentary.
Developers working with tooling as expansive and as powerful as Visual Studio dont 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,
were 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 interaction 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.
Theres a lot going on at VSM as we work to improve the publication, and were anxious to let you know what were up to,
and to hear your opinions about what we might do better.
Its 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 publicationsVSM and the twicemonthly Redmond Developer Newsinto a single, integrated
publication under the title Visual Studio Magazine. The move
blends the best aspects of each magazine, combining VSMs
detailed how-to content and coding tutorials and RDNs indepth 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 challenges, 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 context. They need to know about the tools theyre 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 youve 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. Ive worked on occasion with
Patrick over the past two years, and Ive respected him deeply
for his intelligence, composure and commitment to principle. Patrick is as dedicated and forthright a person as Ive 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 Application Development Trends magazine. Jeffrey Schwartz
arrives as news editor, where hell drive the front-of-the-book
news and review content. Schwartz comes to VSM from RDN,
where he managed the books large news section. Prior to that
he was a senior editor at VAR Business.
As for myself, Ive moved over as editor in chief of RDN
to serve as editor in chief of VSM.
BY MICHAEL DESMOND
editor in chief
Project7
2/10/09
3:39 PM
Page 1
Visit Us at VSLive!
Febuary 23rd-25th at booth #328-330
www.componentone.com/amazingweb
Grids Charting Reporting Scheduling Menus and Toolbars Ribbon Data Input Editors PDF
WinForms WPF ASP.NET Silverlight iPhone Mobile ActiveX
0309vsm_Letters_8.v3
2/19/09
2:47 PM
Page 8
Letters
Letters to Visual Studio Magazine are
welcome. Letters must include your
name, address and daytime phone
number to be considered for publication. 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
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 nonseasoned developers.
Ted Malone,
Colorado Springs, Colo.
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
Wendy Gonchar
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 Becky Nagel
Magazine.com
Executive Editor, New Media
Online News Editor
Associate Editor, Web
Web Producer
Michael Domingo
Kurt Mackie
Gladys Rama
Shane Lee
Rita Zurcher
President
Henry Allain
Id like to further a point Hollis made in his article: Its 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 crisisa shortage of good developers compared to the amount
of software that needs to be writtenis an issue of supply and demand. Theres an inherent
undersupply of good developers, but theres also an oversupply of demand as many clients
just want variations on the same thing. If its more profitable to be a good developer, those
good developers will also create frameworks and tools to help address the demand-side problems as well.
Anonymous,
Posted online
Jeffrey Schwartz
Managing Editor
President &
Chief Executive Officer
Senior Vice President
& Chief Financial Officer
Executive Vice President
Matt N. Morollo
Michele Imgrund
Tracy S. Cook
Neal Vitale
Richard Vitale
Michael J. Valenti
Dick Blouin
Christopher M. Coates
Abraham M. Langer
Erik A. Lindgren
Doug Mashkuri
Vice President,
Attendee Marketing
Chairman of the Board
Carmel McDonagh
Jeffrey S. Klein
Project2
2/11/09
11:06 AM
Page 1
Select a region on the timeline and get the performance data just for that region.
3. Optimize efciently
Now that you know exactly where
to focus your performance-boosting
work, you can start optimizing your
code effectively. Optimize your code
only where it needs to be improved,
and don't try to make unnecessary
changes that will not solve your
performance problem.
ANTS Proler shows you line-level timings, so you can drill down to the specic lines of code responsible
for performance inefciencies.
0309vsm_FirstLooks_8-9.v5
2/19/09
12:18 PM
Page 10
First
PRODUCT LISTINGS
Looks
REVIEWS
Coverity Prevent
Coverity Inc. has improved the support for managed and native code in its static-analysis software. With Coverity Prevent, developers can
automatically scan and analyze C#, C, C++ and
Java source code on their desktops or on the
build server. Its 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 database. 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 buildutility wrapper wraps around the build but
doesnt 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 breakdown 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 classified. Developers cant edit the code from within the Prevent interface, however.
The latest version beefs up VS integration,
enabling developers to perform static analysis 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 Prevents 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,
10
Coverity Prevent
Coverity Inc.
Price: Contact vendor for pricing
Web: www.coverity.com
Phone: 800-873-8193;
415-321-5237
Quince UX
Patterns Explorer
Components vendor Infragistics
Inc. has launched a unique Silverlight 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 patterns 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
0309vsm_FirstLooks_8-9.v5
2/19/09
PRODUCT LISTINGS
12:18 PM
Page 11
REVIEWS
11
0309vsm_F1Sharepoint_12-17.v7
F E AT U R E
2/19/09
4:35 PM
Page 12
SHAREPOINT
Getting Directions
12
0309vsm_F1Sharepoint_12-17.v7
2/19/09
4:35 PM
Page 13
SHAREPOINT
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.
13
0309vsm_F1Sharepoint_12-17.v7
2/19/09
4:35 PM
Page 14
SHAREPOINT
14
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 downloaded from www.codeplex.com/STSDev.
CAML Query Builder
Collaborative Application Markup Language (CAML) can be challenging to build 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 SharePoint 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 information, queries to execute, plus much more. Although the tool isnt as flexible to work
with as some of the other tools out there, the price cant be beat. Its part of SharePoint 2007s 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 preview. Additional information can be found at http://tinyurl.com/9qo9s8.
SPDisposeCheck
Unwary SharePoint developers can easily run into a situation where COM-based
memory doesnt get released by CLR garbage collection. The resulting memory leakage 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
Project2
2/17/09
3:16 PM
Page 1
0309vsm_F1Sharepoint_12-17.v7
2/19/09
4:35 PM
Page 16
SHAREPOINT
files. There are a couple of freeware tools for looking at whats 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 SharePoints Collaborative Application
Markup Language (CAML). The result: Many dev shops have assembled 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
to life with SharePoint. .NET and ASP.NET developers working
with SharePoint must be ready to do things the SharePoint way,
8ji9Zk8dhih###L^i]dji8jii^c\=ZVYh#
]``\
XYe`
:e|de`f
R_U
ceVR^
f
`
j
e
R
deRj
Y`f]U
d
`
Y
h
X`
UVTZUV
Y`f]U
d
`
Y
R_Uh
GVaanhXjhidbZghVgZegdkZcidWZ*%[VhiZgidbVg`Zi
VcY'*bdgZegdYjXi^kZ!hdndjXVcVkd^YXjii^c\]ZVYh#
EajhGVaan^hi]Zdcan6eea^XVi^dcA^[ZXnXaZBVcV\ZbZciegdk^YZg
idZchjgZndjg6\^aZhjXXZhhl^i]VbdcZn"WVX`\jVgVciZZ#
B[Whdceh[WXekjekh=kWhWdj[[ZIkYY[iiFhe]hWcWjmmm$hWbboZ[l$Yec
' %%.GVaanHd[ilVgZ9ZkZadebZci8dge
16
0309vsm_F1Sharepoint_12-17.v7
2/19/09
4:35 PM
Page 17
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 understanding of the product architecture and therefore choosing the
wrong approach to meet specific business requirements.SharePoint is
such a huge platform that its 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 organizations often concludewronglythat 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 doesnt
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
Software Protection
Document Protection
Access Protection
Media Protection
Control Network
etwork Licensing
Pay-Per-Use Counter
17
0309vsm_F2HowTo_16-23.v7
F E AT U R E
2/19/09
12:33 PM
Page 18
B U I L D I N G C U S TO M TO O LS
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
VB.NET
C#
SQL Server
ASP.NET
XML
Other:
18
TECHNOLOGY TOOLBOX
oure writing the same code over and over again with only
minor changes, and youre about to do it again. Stop. If youre
creating a standalone class (either a class that youll call from
your applications code or a class that you can inherit from),build a custom
tool that writes the code for you now and every time youll need it.
0309vsm_F2HowTo_16-23.v7
2/19/09
12:33 PM
Page 19
B U I L D I N G C U S TO M TO O LS
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 doesnt stop the project from building or interfere with the custom tool executing, so if you get that message,
ignore it. However, to ensure that the PostBuild event script executes 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 generate 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 nametextbox. 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 youre 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 registered 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.
Youll need to revisit this option if you change the projects configuration 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: IVsSingleFileGenerator and IObjectWithSite. You must assign your class a
unique GUID to identify it to Windows. Simply add a System.Runtime.InteropServices.Guid attribute to your class and pass it a
19
Project5
12/11/08
4:42 PM
Page 1
BeTheDataGuru
Visual Studio
WPF/Silverlight
SharePoint
SQL Server
Java
COM
PowerShell
Project5
12/11/08
4:43 PM
Page 2
Visit softwarefx.com for interactive demos and more information about our latest products.
0309vsm_F2HowTo_16-23.v7
2/19/09
12:33 PM
Page 22
B U I L D I N G C U S TO M TO O LS
<System.Runtime.InteropServices.Guid( _
"B2429B91-452D-4a95-A355-435337729EFB")> _
<System.Runtime.InteropServices.ComUnregisterFunction> +
Implements _
Microsoft.Win32.Registry.LocalMachine.DeleteSubKey( _
Microsoft.VisualStudio.Shell.Interop. _
IVsSingleFileGenerator
Implements Microsoft.VisualStudio.OLE.Interop. _
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 automatically 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 mostlybut 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 youll use in the CustomTools 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:
End Sub
End If
<System.Runtime.InteropServices.ComRegisterFunction()> _
22
Try
0309vsm_F2HowTo_16-23.v7
2/19/09
12:33 PM
Page 23
B U I L D I N G C U S TO M TO O LS
Instantly Search
Terabytes of Text
N dozens of indexed,
System.Runtime.InteropServices.Marshal. _
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 _
Microsoft.VisualStudio.OLE.Interop. _
IObjectWithSite.SetSite
Me._site = pUnkSite
End Sub
unindexed,
fielded data and
full-text search
options (including
Unicode support
for hundreds
of international
languages)
N file parsers /
converters for
hit-highlighted
display of all
popular file
types
N Spider supports
static and
dynamic web
data; highlights
hits while
displaying links,
formatting and
images intact
h Spider
Desktop wit
h Spider
Network wit
CD/DVDs
Publish for
pider
Web with S
Win & .NET
Engine for
Linux
Engine for
New
64-bit
Return 0
End Function
When VS is ready to generate your code, it calls the IVsSingleFileGenerator interfaces Generate method. VS passes the method the
name of the file, the projects namespace, the files contents, and a
progress bar. You must update the methods 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 GenerateCode 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 boilerplate 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)
1-800-IT-FINDS www.dtsearch.com
VisualStudioMagazine.com March 2009 VISUAL STUDIO MAGAZINE
23
0309vsm_F2HowTo_16-23.v7
2/19/09
1:02 PM
Page 24
B U I L D I N G C U S TO M TO O LS
Generating Code
Youre now finally ready to start writing the code thats 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 _
Microsoft.VisualStudio.Shell.Interop. _
IVsGeneratorProgress) _
As Byte()
If FileContents = "" Then
Throw New Exception("No content")
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 youll 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 youve got the right
version number for VS and the right GUID for the language
youre testing in. For example, did you create a key for C# but then
test your custom tool in a VB project? Its helpful to open RegEdit
and look at the keys youre 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, youll 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 couldnt be found,
then youll know that you have a problem getting your tool into
the GAC.
When youre 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:
End If
Progress.Progress(0, 100)
You now have a working custom tool. True, the interesting work is
still left to do: reading your files input and turning it into real code.
But thats also the fun part. VSM
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 files 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.
24
0309vsm_025
2/19/09
4:47 PM
Page 25
SPOTLIGHT
ON GRAPHICS,
IMAGING AND MAPPING
The following advertising section showcases companies offering solutions
for your graphic, imaging and mapping needs.
25
0309vsm_026
2/19/09
11:37 AM
Page 26
www.mapdotnet.com
MapDotNet with
Silverlight Interface
0309vsm_027
2/19/09
12:46 PM
Page 27
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
Silverlight Interface
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 ESRIs GIS is helping to manage and
improve business operations around the world.
1-800-447-9778
Download a 60 day trial at www.mapdotnet.com
or call us at (850) 893-6741.
Copyright 2009, ISC, all rights reserved.
info@FTSJDPN t XXXFTSJDPN
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.
www.leadtools.com/vsm2009
www.pegasusimaging.com
VisualStudioMagazine.com March 2009 VISUAL STUDIO MAGAZINE
27
0309vsm_028
2/19/09
11:45 AM
Page 28
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 Benets
Document Clean-up
Form Recognition
Annotations
28
Project5
2/6/09
8:48 AM
Page 1
Barcode
Mark-up
DICOM Medical
Multimedia
Develop your application with the same robust imaging technologies used by Microsoft, HP,
Sony, Canon, Kodak, GE, Siemens, the US Air Force and Veterans Affairs Hospitals.
LEADTOOLS provides developers easy access to decades of expertise in color, grayscale,
document, medical, vector and multimedia imaging development. Install LEADTOOLS to
eliminate months of research and programming time while maintaining high levels of
quality, performance and functionality.
Image
Formats:
All
industry
standards
including TIFF, EXIF, PDF, JPEG/JPEG2000, DICOM,
PCL, DWG and hundreds more.
Image Compression: From standard JBIG,
JBIG2, ABIC, JPEG and CCITT G3/G4 to LEADs
specialized ABC, CMP and CMW compression.
Display Controls: Scroll, zoom, pan, magnify
glass, brightness/contrast/gamma, window level.
Image Processing: 200+ filters, transforms and
color conversion functions with extended grayscale
(10 to 16-bit) support.
OCR/ICR/OMR: Full page or zonal multi-threaded
recognition with formatted output including PDF,
DOC and TXT for Win32 and x64.
Barcode: Read/write all industry standard 1D and
2D barcodes (DataMatrix, PDF417, MicroPDF417,
QR Code and more).
Forms Recognition and Processing: Automatically identify forms and extract user filled data.
Document Cleanup/Preprocessing: Deskew,
despeckle, line and border removal, registration
marks and more.
PDF and PDF/A: Read/write raster and text
searchable PDF files.
Annotations: Interactive UI for document
mark-up, redaction and image measurement
(including support for DICOM annotations).
Grayscale Imaging: Display and process signed/
unsigned 10-16 bit, 32 bit data.
0309vsm_030
2/19/09
11:53 AM
Page 30
www.pegasusimaging.com
30
Project2
2/9/09
11:57 AM
Page 1
0309vsm_C#Corner_32-35.v7
2/19/09
C# CORNER
12:45 PM
Page 32
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 typesincluding
whether they are classes
or structs.
BY BILL WAGNER
# 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 behavior their users will expect one day? What capabilities will the .NET Framework expect
from any type?
Answering these questions isnt much work, but its 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 isnt that interesting in itself, but its instructive to look at the code the compiler generates for that anonymous type.
Now its 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.
Lets 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, youre creating public classes unnecessarily, and youre
adding names to your public API that arent necessary. That creates more confusion for your users. They
arent supposed to use some of these classes, and yet, those classes show up in IntelliSense and in your
TECHNOLOGY TOOLBOX
VB.NET
C#
SQL Server 2005
ASP.NET
XML
VB6
32
0309vsm_C#Corner_32-35.v7
2/19/09
12:45 PM
Page 33
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 cant derive a new type from something you cant
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 shouldnt
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
youve created. You should always support or prohibit derivation
explicitly; dont 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 validate state in constructors and know theyre always valid; immutable
types can be shared safely across threads; and immutable types simplify testing because state changes cant affect later methods. However, its overly simplistic to say that every type in your programs
should be immutable; thats 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 reference 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 GetHashCode() 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.
33
0309vsm_C#Corner_32-35.v7
2/19/09
12:45 PM
Page 34
The lesson to take away from these examples: Equals touches many
methods; make sure theyre 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:
using the distance of a point from the origin. You can compare
New 7.0
e
mag
DotI ease
Rel
other.yField + other.yField;
return distanceSquared.CompareTo(
otherDistanceSquared);
}
public int CompareTo(object obj)
{
return CompareTo(
obj as HandCodedPoint);
}
HandCodedPoint
left, HandCodedPoint right)
{
if (left == null)
return false;
else
{
if (left == null)
return right != null;
else
return left.CompareTo(right) < 0;
}
Visit Atalasoft.com for web demos, video tutorials, and a free trial.
www.atalasoft.com
34
0309vsm_C#Corner_32-35.v7
2/19/09
12:45 PM
Page 35
C#
(uint)EqualityComparer<int>.Default.GetHashCode(
this.xField);
return (int)((0xa5555529 * num) +
(uint)EqualityComparer<int>.Default.GetHashCode(
this.yField));
}
public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append("{ x = ");
builder.Append(this.xField);
builder.Append(", y = ");
builder.Append(this.yField);
builder.Append(" }");
return builder.ToString();
}
// Properties
public int x
{
get { return this.xField; }
}
EqualityComparer<int>.Default.Equals(this.yField,
type.yField));
}
public override int GetHashCode()
{
uint num = 0xdd9cb371;
num = (0xa5555529 * num) +
public int y
{
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.
35
0309vsm_AskKat.36-38.v6
Ask
2/19/09
1:27 PM
Page 36
Kathleen
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
A
Silverlight Forms correspond roughly to Pages in Silverlight, and each Silverlight application has exactly
one Page. So, Id like to rephrase your question to
something like this: How can I make it seem as though Im
changing forms? Once you ask the question this way, youre
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.
36
0309vsm_AskKat.36-38.v6
2/19/09
1:47 PM
Page 37
A S K K A T H L E E N S I LV E R L I G H T
{
string text = String.Empty;
if (mOwner.Content != null)
}
System.Diagnostics.Debug.WriteLine(
text + ":" + message);
}
Why does Code Analysis give these errors when the parameter is
obviously used?
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 solution in this case is to formally ignore the warnings. If you rightclick on the warning, youll 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 cant 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
VisualStudioMagazine.com March 2009 VISUAL STUDIO MAGAZINE
37
0309vsm_AskKat.36-38.v6
2/19/09
1:27 PM
Page 38
A S K K A T H L E E N S I LV E R L I G H T
#endif
ByVal e As MenuItemClickEventArgs)
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 missing. 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
wont be made to the method, and the string concatenation wont be
performed.This performance improvement will be small,but can still
prove significant if you call this method a number of times.
MenuItemClickEventHandler( _
Warning 3 CA1034 : Microsoft.Design : Do not nest type 'MenuItem.MenuItemClick2EventHandler'. Alternatively, change its
accessibility so that it is not externally visible.
SilverlightMenuLibrary
Warning 4 CA1003 : Microsoft.Design : Visual Basic generates
This code uses the generic event handler provided by the framework.
The help entry for this Code Analysis warning says you
shouldnt ignore it and that its 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 warning. The automatic usage means changing it isnt a breaking
change. You can suppress the second message globally and just
ignore warnings about event handlers, but you cant suppress the
first globally without missing notification on any other nested public classes. I think its easier to change your delegate declarations
than to explain why youre sticking with the old VB style and managing the suppressions. VSM
SilverlightMenuLibrary
GO ONLINE
38
0309vsm_AdIndex_39
2/19/09
3:44 PM
Page 39
Advertising Sales
Ad Index
Advertiser
Page
Atalasoft, Inc
www.atalasoft.com
ComponentOne
www.componentone.com
East
Andrew Mintz
National Sales Manager
Phone: 508-532-1433
amintz@1105media.com
Copyright Statement
Copyright 2009 by 1105 Media, Inc. All rights reserved.
Printed in the U.S.A. Reproductions in whole or part prohibited except by written permission. Mail requests to
"Permissions Editor," c/o Visual Studio Magazine, 2600 El
Camino Real, Ste 300, San Mateo, CA 94403.
Legal Disclaimer
The information in this magazine has not undergone any
formal testing by 1105 Media, Inc. and is distributed without any warranty expressed or implied. Implementation or
use of any information contained herein is the reader's sole
responsibility. While the information has been reviewed for
5, 27
Intel Corporation
www.intel.com
LEAD Technologies, Inc.
www.leadtools.com
Production Coordinator
Serena Barnes
Phone: 818-734-1520 ext 164
vsmadproduction@1105media.com
sbarnes@1105media.com
ID Statement
Visual Studio Magazine (ISSN 1537-002X) is published
monthly by 1105 Media, Inc., 9121 Oakdale Avenue, Ste. 101,
Chatsworth, CA 91311. Periodicals postage paid at
Chatsworth, CA 91311-9998, and at additional mailing
offices. Complimentary subscriptions are sent to qualifying
subscribers. Annual subscription rates for non-qualified subscribers are: U.S. $34.97, Canada $52.97 (U.S. funds);
International $78.97 (U.S. funds). Subscription inquiries,
back issue requests, and address changes: Mail to: Visual
Studio Magazine, P.O. Box 1164, Skokie, IL 60076-8164,
email VSM@1105service.com or call toll free (888) 7688759, fax number 847-763-9564. International calls 847763-9135. POSTMASTER: Send address changes to Visual
Studio Magazine, P.O. Box 1164, Skokie, IL 60076-8164.
Canada Publications Mail Agreement No: 40612608. Return
Undeliverable Canadian Addresses to Circulation Dept. or
Bleuchip International, P.O. Box 25542, London, ON N6C 6B2.
23
ESRI
www.esri.com
West
William Smith
Phone: 603-886-3466
wsmith@1105media.com
dtSearch Corp.
www.dtsearch.com
Chris Kourtoglou
Regional Sales Manager
Phone: 650-579-0121
ckourtoglou@1105media.com
34
Corporate Address
Corporate Headquarters:
1105 Media
9121 Oakdale Ave. Ste 101, Chatsworth, CA 91311
www.1105media.com
Media Kits
Media Kits: Direct your Media Kit requests to Matt Morollo,
VP Publishing, 508-532-1418 (phone), 508-875-6622
(fax), mmorollo@1105media.com
Reprints
Reprints: For single article reprints (in minimum quantities of
250-500), e-prints, plaques and posters contact:
PARS International
Phone: 212-221-9595
E-mail: 1105reprints@parsintl.com
www.magreprints.com/QuickQuote.asp
List Rental
This publications subscriber list, as well as other lists from
1105 Media, Inc., is available for rental. For more information, please contact our list manager, Merit Direct. Phone:
914-368-1000; E-mail: 1105media@meritdirect.com;
Web: www.meritdirect.com.
C4
27, 28, 29
MapDotNet
www.mapdotnet.com
26, 27
Microsoft Corporation
www.microsoft.com
C2,1,15
16
9
20, 21
C3
2
17
Edit Ad Index
Altova
www.altova.com
11
ComponentOne LLC
www.componentone.com
14
Coverity Inc.
www.coverity.com
10
Infragistics Inc.
www.infragistics.com
10
U2U
www.u2u.be
14, 16
Go to
VisualStudioMagazine.com
to access the stories in this
issue, plus read exclusive
online-only content.
39
0309vsm_PragDev_40.v2
2/19/09
2:07 PM
The Pragmatic
Page 40
Developer
BY BILLY HOLLIS
Whether youre looking for work or looking to hire, one thing you cant
afford to overlook is the importance of a strong interview. This is
particularly true in development, where technical interviews
impose unique demands. Here are a few tips for people on
both sides of the interviewing table.
For Interviewees
The most underused answer in technical interviews is,
I dont know. No one knows all the details on todays platforms. Feeling around for the correct answer to a technical
question makes you look bad.
Dont pad your resume with long lists of technologies
that you supposedly know. Just because a technology was used
at your company and you got within 10 feet of it doesnt mean
you know it or should tout it on your resume.
Bring some sample code, even if the interviewer doesnt
ask for it. About five or six printed pages will do, and it need
not be a complete program or module. This will impress the
people you most want to impress. If the interviewer doesnt
want to see it, that tells you something, too.
Stress the business value of your past contributions to a
company. Most interviewers are a hybrid of business-oriented
and technically oriented. If you have that same balance, it will
make you stand out. If you cant articulate the business value of
your contributions, you need to take stock of yourself. There are
two main possibilities: you simply dont care about the business
side, or your contributions arent really very valuable.
For Interviewers
Dont wing it. If youre doing any significant amount of
interviewing, you owe it to your company to have a list of questions you can ask, so that you dont have to think them up on the
fly. I have a list of about 40 questions that I mix and match,
depending on how the interview goes. (No, you cant have it.)
Ask a combination of technical and soft skillquestions.
You need to gauge technical competence, but non-technical
skills such as teamwork, attitude, process knowledge and so
forth are at least as important. For example: Suppose a project
sponsor lays out a project to you,and you have loosely estimated
that it will take at least six months to do it.Then the sponsor says,
40
Project3
1/21/09
11:34 AM
Page 1
Project2
2/9/09
11:49 AM
Page 1
2009, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks of Intel Corporation in the U.S. and other countries. *Other names and brands may be claimed as the property of others.