You are on page 1of 52

SUMMING UP THE NEW ASP.NET CONTROLS p.

18
Presented by

THE WORLD’S LEADING .NET RESOURCE

2006 Volume 4 Issue3

Constructing a JMS Adapter


for Microsoft BizTalk Server
Create adapters for BizTalk/J2EE interoperability

Leveraging SOA to Web-Enable


Back-End Applications UPCOMING SYS-CON EVENTS

An in-depth look at a real-world services JUNE 5–6, 2006


implementation THE ROOSEVELT HOTEL
NEW YORK, NY
SEE PAGES 46-47

Presorted
Standard
US Postage
JUNE 5–6, 2006
PAID
St. Croix Press THE ROOSEVELT HOTEL
NEW YORK, NY
SEE PAGES 46-47

MARCH 13, 2006


NEW YORK, NY
APRIL 24, 2006
SAN JOSE, CA
June 5-6, 2006
NEW YORK, NY SEE PAGES 34-35

W W W . D O T N E T D E V E L O P E R S J O U R N A L . C O M
SUPERCHARGE
YOUR APPS WITH
THE POWER OF

LOCATION
INTELLIGENCE Enable Location Intelligent web services
110

Single environment for deployment


to desktop or web
Full integration with VisualStudio .NET

Create applications for:


• Web-based store/asset location finders • Visualizing where your customers are
• Analyzing where revenue comes from – and where it doesn’t • Managing assets such as cell towers, vehicles and ATMs

Try it and see for yourself. Visit www.mapinfo.com/sdk


Learn more about the MapInfo Location Platform for .NET, 110

access whitepapers and download free SDKs. 001

Contact us at sales@mapinfo.com
DBA: “I suspect it’s your application server
code that’s causing the problem.”
App Dev: “It must be a database problem.”

Eliminate the finger pointing with WebLOAD Analyzer™.


11010001011010001011010010101010100010110100101010110100010110100011101001010101011

Want to accelerate resolution


of Web performance problems?
You can with WebLOAD Analyzer—the only load testing tool
with root cause analysis for .NET and Microsoft Web applications.
WebLOAD Analyzer employs unique “black box” software to
capture actual problems at multiple synchronized levels, enabling
users to drill down to the individual component. By pinpointing
the root cause of all kinds of application problems, WebLOAD
Analyzer reduces problem resolution time by 60%—significantly
improving application performance and eliminating finger pointing
once and for all.

Get a FREE “No more finger pointing” T-shirt. >> > > Learn more at www.radview.com/analyze

110100010110100010110100101010101000101101

00101010110100010110100011101001010101011

© RadView Software, Limited.All rights reserved. The Smart Choice in Web Application Testing
M a rc h 2 0 0 6 Volume 4 Issue 3

����
Inside DNDJ 10
EDITORIAL

The Art of Progress


By Jeremy Geelan ..................................................................... 7

Constructing a JMS Adapter for BOOK REVIEW

Microsoft BizTalk Server Amazon.com Top 10 .NET Books


Provided by Amazon.com........................................................ 8
CREATE ADAPTERS FOR BIZTALK/J2EE
INTEROPERABILITY
BY WAYNE CITRIN ASP.NET

Summing Up the New ASP.NET Controls


30 By Aaron Reed........................................................................... 18

SQL SERVER 2005

ASP.NET 2.0 Callbacks


USING CALLBACKS TO CREATE A RICH WEB UI
SQL Server Web Services
By Jerry Dixon............................................................................ 24
BY TIM STALL

SOA

Leveraging SOA to Web-Enable


Back-End Applications
By Brian Wilson .........................................................................42
36
BOOK REVIEW

Understanding Base64 Encoding Mono: A Developer’s Notebook


By Dennis Hayes ....................................................................... 48
WHAT IT IS, WHEN TO USE IT, AND HOW TO
WRITE CUSTOM BASE64 ENCODING
BY JAMES McCAFFREY
MONO

Mono 1.1.13 Released


By Dennis Hayes ....................................................................... 50
4 March 2006 • dotnetdevelopersjournal.com
���������������������

���
��������������
��������������
��������
����������������
��������� ���������������������� �����������������������
����������������� � ����� ���������� � ���� ������ ��

���������� �������� ��������� ��������������� �

������������������������������� ������
��������������������������������������� ���� �������������������������������
��������������������������������������������������������������������������������������
�������������������������������������������������������������������������������������������������������������������������������������������������������������������
�������������������������������������������������������������������������������������������������������������������������������������������������
Editorial

EDITORIAL BOARD
dotnetboard@sys-con.com
Editor-in-Chief
Derek Ferguson derekf@speakeasy.net
The Art of Progress
w
Executive Editor e’re not even at the end of “Even though I have for so many
Seta Papazian seta@sys-con.com
Group Publisher the first quarter yet, and years enjoyed the rare honor of working
Jeremy Geelan jeremy@sys-con.com 2006 seems already to have with top-rate technologists and writers BY JEREMY GEELAN
Mobility Editor
Jon Box jbox@psgi.net brought with it as much from all over the world, many of them as
Security Editor
Patrick Hynds phynds@criticalsites.com change in the world of Internet technolo- brilliant at writing as they are at technol- Jeremy Geelan is group publisher of
Open Source Editor gies as all four quarters of 2005 combined. ogy, I wouldn’t have the slightest hesita- SYS-CON Media and is responsible
Dennis Hayes dennisdotnet@yahoo.com
Product Review Editor Despite the headline-grabbing mega- tion in naming Derek Ferguson to be in for the development of new titles
Doug Holland doug.holland@precisionobjects.com
VB Editor deals of ’05, in ’06 the mid-market is still the top percentile of achievers within and technology portals for the
Keith Franklin keithf@magenic.com the engine room of technology M&A, with that group: a remarkably gifted com- firm. He regularly represents
Smart Client Editor
Tim Huckaby timh@interknowlogy.com 95% of deals valued at less than $600M municator and developer – it’s a winning SYS-CON at conferences and trade
BizTalk Editor
Brian Loesgen brian.loesgen@neudesic.com – and there have been dozens of them combo!” shows, speaking to technology
ADVISORY BOARD already. If anyone is in the slightest doubt as audiences both in North America
dotnetadvisors@sys-con.com Many fundamentals seem to be to the width and depth of Derek’s accom- and overseas.
Derek Ferguson derekf@magenic.com
Seta Papazian seta@sys-con.com changing too. Whereas private sector plishments during his four-year reign in
Jeremy Geelan jeremy@sys-con.com
Thom Robbins trobbins@microsoft.com compensation increased only about 2% the hot seat, just glance back through 4jeremy@sys-con.com
John Gomez John.Gomez@eclipsys.com over the 12 months ending December your back issues – or trawl through the
Scott Hanselman scott@hanselman.com
Dean Guida deang@infragistics.com 2005, there’s a sense already that in 2006 digital archives at http://dotnet.sys-con.
John Sharp johns@contentmaster.com
Jacob Cynamon jacobcy@microsoft.com salaries will maybe rise – IT sector salaries com – and remind yourself how amaz-
Chris Mayo cmayo@microsoft.com too, especially with the U.S. unemploy- ingly thorough his interviews were,
Gary Cornell gary@thecornells.com
Joe Stagner joestag@microsoft.com ment rate now having fallen below 5%. whether with the Father of C#, Anders
Peter DeBetta peter@debetta.com
Editor No matter how the economic cycles Hejlsberg (October 2002 and March
Nancy Valentine nancy@sys-con.com might ebb and flow, SYS-CON Media’s 2004), or the vice president of Microsoft’s
Online Editor
Roger Strukhoff roger@sys-con.com passionate coverage of the i-Technologies entire Developer Division, “Soma”
WRITERS IN THIS ISSUE that are increasingly shaping our busi- Somasegar (May 2004).
Wayne Citrin, Jerry Dixon, Jeremy Geelan, Dennis Hayes, nesses, our education, our society, and I know that I speak for Derek when I
James McCaffrey, Aaron Reed, Tim Stall, Brian Wilson
therefore our lives remains consistent. say that throughout those years he has
SUBSCRIPTIONS We have added AJAX Developer’s Journal considered himself privileged to have
For subscriptions and requests for bulk orders,
please send your letters to Subscription Department already this year, along with Web 2.0 been supported by such an outstanding
Subscription Hotline: subscribe@sys-con.com
Cover Price: $6.99/issue Journal; and we have redoubled our effort collection of Microsoft VIPs and regional
Domestic: $69.99/yr. (12 issues)
Canada/Mexico: $99.99/yr. Overseas: $129.99/yr. to offer high-quality education nationwide directors. It’s highly characteristic that
(u.s. banks or money orders). Back issues: $12/ea., through SYS-CON Events such as the he still in his day job – then at Expand
plus shipping and handling.
“Real-World AJAX” series of seminars (in Beyond – managed to find time to write
EDITORIAL OFFICES
SYS-CON Media 135 Chestnut Ridge Rd., March, April, June, and October [http:// code so well that in July 2004, Microsoft
Montvale, NJ 07645 ajaxseminar.com/]) and our innovative named him a Most Valuable Professional
Telephone: 201 802-3000 Fax: 201 782-9638
.NET Developer’s Journal (issn#1541-2849) is conference program: Web Services Edge (MVP) for the .NET Compact Framework.
published monthly (12 times a year) for $69.99 by
SYS-CON Publications, Inc.,135 Chestnut Ridge Road, 2006 Conference & Expo, Enterprise Open The last words of this editorial, as is
Montvale, NJ 07645. Source 2006 Conference & Expo, and Rich right and proper, come from Derek
Postmaster: Send address changes to:
.NET Developer’s Journal, Internet Apps + AJAX Conference & Expo himself:
SYS-CON Publications, Inc.,
135 Chestnut Ridge Road 2006 (http://events.sys-con.com). So, here we are in March of 2006, ready
Montvale, NJ 07645 As far as .NET Developer’s Journal for .NETDJ, Phase II. I look forward to
Copyright © 2006 by SYS-CON Publications, Inc.
All rights reserved. No part of this publication may be reproduced or
goes, there is change too, with our being able to read the magazine purely for
transmitted in any form or by any means, electronic or mechanical,
including photocopy or any information storage and retrieval system, esteemed Founding Editor, Derek enjoyment and – like any parent – to see if
without written permission. For promotional reprints, contact Reprint
Coordinator Dorothy Gil, dorothy@sys-con.com. Ferguson, moving to the position of the “child” I helped to bring into the world
Worldwide Newsstand Distribution
Curtis Circulation Company, New Milford, NJ
mobility editor in order to permit him to is able to exist and, hopefully, even thrive
Newsstand Distribution Consultant: live up to the requirements of his excit- in my absence.
Gregory Associates / W.R.D.S.
732 607-9941 - BJGAssociates@cs.com ing new position as an associate director Please continue to be in touch via
For list rental information:
Kevin Collopy: 845 731-2684, in the Information Technology Group at derek@sys-con.com. I look forward to
kevin.collopy@edithroman.com;
Frank Cipolla: 845 731-3832, Bear Stearns. The incoming editor-in- continuing to see everyone at various
frank.cipolla@epostdirect.com
All brand and product names used on these pages are trade names,
chief is known to all of you…but rather industry and Microsoft events. Bear
service marks, or trademarks of their respective companies. SYS-CON
Publications, Inc., is not affiliated with the companies or products than steal his thunder here let me allow Stearns obligations notwithstanding, I
covered in .NET Developer’s Journal. .NET and .NET-based marks are
trademarks or registered trademarks of Microsoft Corporation in the United him to introduce himself next issue. will of course continue to go anywhere
States and other countries.
Besides it is only fitting that the last that free pizza and soda is provided. :-)
SYS-CON Publications, Inc., reserves the right to revise,
republish and authorize its readers to use the articles issue of .NETDJ with Derek as E-i-C Thanks Derek! We look forward to
submitted for publication.
be an opportunity for me on behalf of seeing Mobility articles, news, and com-
SYS-CON Media to repeat what I have mentary featured strongly in .NETDJ in
declared elsewhere: the rest of 2006.

dotnetdevelopersjournal.com • March 2006


7
Book Review

Amazon.com Top 10 .NET Books President and CEO

10 4
MCAD MCAD/MCSD Fuat Kircaali fuat@sys-con.com
Developing XML Training Guide President, SYS-CON Events
Web Services (70-316): Grisha Davida grisha@sys-con.com
Group Publisher
and Server Developing and
Jeremy Geelan jeremy@sys-con.com
Components Implementing
with Visual C# Windows-Based Applications ADVERTISING
.NET and the .NET Framework with Visual C# and Visual Senior Vice President, Sales and Marketing
Exam Cram 2 (Exam Cram Studio.NET Carmen Gonzalez carmen@sys-con.com
70-320) by Amit Kalani Vice President, Sales and Marketing
by Amit Kalani Miles Silverman miles@sys-con.com
Advertising Director

3
MCAD/MCSD
Robyn Forma robyn@sys-con.com

9
Enterprise Training Guide
Advertising Sales Manager
Solution (70-315): Megan Mussa megan@sys-con.com
Patterns Using Developing and Associate Sales Managers
Microsoft .Net: Implementing Kerry Mealia kerry@sys-con.com
Version 2.0 Web Lauren Orsi lauren@sys-con.com

: Patterns & Applications with Visual C#


PRODUCTION
Practices and Visual Studio.NET
Lead Designer
Microsoft Corporation by Amit Kalani Tami Lima tami@sys-con.com
Art Director

8 2
Applied Programming Alex Botero alex@sys-con.com

Microsoft .NET Microsoft Associate Art Directors


Louis F. Cuffari louis@sys-con.com
Framework Visual Basic Andrea Boden andrea@sys-con.com
Programming .NET Version Video Editor
2003 (Book & Ryan Palmieri ryan@sys-con.com
CD-ROM)
by Jeffrey Richter by Francesco Balena WEB SERVICES
Information Systems Consultant
Robert Diamond robert@sys-con.com

7
Developing
Web Designers
Application Stephen Kilmurray stephen@sys-con.com
Frameworks in Wayne Uffleman wayne@sys-con.com
.NET
ACCOUNTING
Financial Analyst
Joan LaRose joan@sys-con.com
by Xin Chen
Accounts Payable
Betty White betty@sys-con.com

6
MCAD/MCSD Accounts Receivable
PROVIDED BY Self-Paced Gail Naples gailn@sys-con.com

Training Kit:

1
Developing MCAD/MCSD Self-Paced SYS-CON EVENTS
Windows-Based Training Kit: Microsoft President, Sys-con Events
Grisha Davida grisha@sys-con.com
Applications .NET Core Requirements,
National Sales Manager
with Microsoft Visual Basic.NET Exams 70-305, 70-315, Jim Hanchrow jimh@sys-con.com
and Microsoft Visual C#.NET, 70-306, 70-316, 70-310,
Second Edition 70-320, and 70-300 SUBSCRIPTIONS
Microsoft Corporation Microsoft Corporation 201 802-3012
888 303-5282

5
subscribe@sys-con.com
MCAD/MCSD
Self-Paced
CUSTOMER RELATIONS
Training Kit: Circulation Service Coordinators
Developing Web Edna Earle Russell edna@sys-con.com
Applications JDJ Store Manager
with Microsoft Brunilda Staropoli bruni@sys-con.com
Visual Basic .NET and
Microsoft Visual C# .NET,
Second Edition
Microsoft Corporation

8 March 2006 • dotnetdevelopersjournal.com


��������������������������������������

������������������������������������

�������������������������������������
�������������������������������������������

������������������������������������������������������������������
��������������������������������������������
������������������������������������������������������������������

���������������������������������� ������������������������������
����������������������������������������������������������������������
������������������������������������������������������������������������
�������������������������������������������

��������������������������������������
4 ��������������������������������������������������������
����������������������������������������
4 ����������������������������������������������������������������
�����������������������������������������������������
���������������������������
4 ����������������������������������������������������������
�������������������������������������������������������� ��������������������������������������������
���������������������
4 ������������������������������������������������

����������������������������������������������������������������
������������������������������������ ��������������
���������������������
�������������

�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
BizTalk

Constructing a JMS Adapter for


Microsoft BizTalk Server
Create adapters for BizTalk/J2EE interoperability

i
f you need to integrate We’ll start with a discussion of Required Software
Microsoft BizTalk Server adapter architecture, run through If you want to follow the instruc-
(BTS) 2004 with other an example orchestration, build the tions in this article and use the
applications and data adapter, then deploy and run it. The associated sample code, you’ll need
sources, you’re going to need some creation and deployment of adapters to install the following software:
kind of adapter. BTS 2004 ships with can seem like an involved process, • A working development copy of
a few, including the file adapter and but once you get past the details in- Microsoft BizTalk Server 2004 or
the Web services adapter. Other herent in the creation of any BizTalk 2006, including Visual Studio .NET
adaptors, especially ones used to Server adapter, creating an adapter 2003 or 2005 with the appropriate
integrate BTS with popular enter- that bridges between BizTalk Server extensions.
prise software, are available from and J2EE is quite straightforward. • BizTalk Server 2004 SDK Refresh,
third-party vendors. However, if you which can be downloaded at www.
need a JMS (Java Messaging Service) Background microsoft.com/downloads/details.
adapter, or one that supports J2EE This article assumes you have aspx?FamilyID=8A1CA3AF-790C-
facilities such as JNDI (Java Naming passing familiarity with both BizTalk 4261-838A-9F0661C72887&displayl
and Directory Interface), JAAS (Java Server and JMS. It will also help if you ang=en.
Authentication and Authorization have some knowledge of how BTS • BizTalk Server 2004 Adapter
Service), and EJBs (Enterprise Java adapters are used, but you don’t need Wizard, which can be down-
Beans), you’re probably going to a deep knowledge of how they’re loaded at www.gotdotnet.com/
have to build one. This article shows constructed because the necessary Community/UserSamples/Details.
you how to construct a custom information will be presented below. aspx?SampleGuid=c95217fc-4f9f-
adapter that allows BTS to integrate The BTS orchestration used in 4fec-9d68-1aa9456b6ca0.
BY WAYNE CITRIN with JMS. You can also use these this example comes from the first or- • J2SE SDK (J2SDK), version 1.3.1 or
techniques to construct other kinds chestration example in the excellent later.
of adapters, including ones for Java book Microsoft BizTalk Server 2004 • JNBridgePro, which can be down-
APIs that come with custom applica- Unleashed (Sams, 2005), by Scott loaded from www.jnbridge.com. It
tions, or simply call Java libraries Woodgate, Stephen Mohr, and Brian comes with a 30-day free, full-fea-
from BizTalk Server orchestrations. Loesgen. I recommend reading the tured evaluation.
The example in this article shows example in the book and performing • A J2EE application server or special-
how to create a JMS adapter for the actions to create the orchestra- purpose JMS messaging server. This
BizTalk Server using JNBridgePro, tion, but I’m supplying the code for example uses BEA’s WebLogic 8.1
a Java/.NET interoperability tool. those who are not inclined to do so. application server, although it’s easy
to adapt this example to any other
application server or JMS server.
• Download and unpack the sample
code, www.jnbridge.com/biztalk/
JMSAdapterSample.zip. There
are three folders: jmsAdapter,
MyFirstIntegration, and Java clients.
You may place these folders any-
f1 Figure 1: BTS adapter architecture where on your machine.

10 March 2006 • dotnetdevelopersjournal.com


WE HELP YOU DELIVER
THE WHOLE PACKAGE
V E R I O S U P P L I E S T H E B E S T T E C H N O L O G Y, R E S O U R C E S ,
AND EXPERTISE TO SUPPORT YOUR .NET SOLUTIONS

When you partner with Verio, you can


deliver complete solutions for your
customers’ business needs. As your
trusted expert advisor for managed
hosting, we support your application
development with our managed
services and infrastructure from
state-of-the-art Verio data centers.

As a viaVerio® partner, you’ll enhance


your solutions portfolio and add value
to your business by gaining access
to our suite of global products and
services, including managed storage
and security. You’ll also gain peace
of mind in knowing that Verio
is backed by the financial and
operational excellence of NTT
Communications, the world's largest
telecommunications company.

BUILD YOUR BUSINESS BY


PARTNERING WITH THE MANAGED
HOSTING INFRASTRUCTURE EXPERTS.
Nothing turns on the power of
the Internet like Verio products
and services.

CALL 866.237.4121 today to find


out more about how a viaVerio
partnership can complete your
business offering. Or visit:
www.verio.com/partners

Power. Performance. Results.

Verio, viaVerio and the Verio logo are trademarks and/or


service marks of Verio Inc. in the United States and other
countries. All other names are trademarks or registered
marks of their respective owners. ©2005 Verio Inc.
All rights reserved.
BizTalk
AUTHOR BIO: Adapter Architecture ent that communicates with the server The remoting infrastructure used in
Wayne Citrin is the CTO at JNBridge. Figure 1 shows the architecture of via RMI or other chosen protocol. JNBridgePro also supports other com-
He is the architect of JNBridgePro, the adapter. BizTalk Server interacts Figure 2 shows how JNBridgePro munication channels, including TCP/
and has been engrossed in Java with the adapter via adapter frame- supports calls from .NET to Java. For binary and HTTP/SOAP. Therefore, it is
and .NET interop issues since . work code. The adapter framework each Java class, the JNBridgePro proxy equally possible to set up the adapter
NET’s beta days. Previously code calls .NET-side proxy classes, generation tool generates a .NET- so that the .NET and Java sides operate
Wayne was a leading researcher which are proxies of the JMS classes in side proxy class with an equivalent in different processes or on different
in programming languages and this example. We’re using the JNBridge- signature. The proxies are then used machines and communicate through a
compilers, and was on the Com- Pro proxy generation tool to create in the resultant application, where socket-based mechanism.
puter Engineering faculty at a .NET-side proxy class that has an the .NET code calls a Java class by
the University of Colorado, equivalent signature to the corre- calling the equivalent proxy class. The Example Orchestration
Boulder. For more information on sponding Java class. From there control proxy class directs the call through The example orchestration (Figure
Java and .NET interop, visit Wayne’s flows through the .NET-side runtime the JNBridgePro .NET-side runtime 3) is taken from Microsoft BizTalk
blog at www.jnbridge/com/blog. components, across a remoting component, which performs marshal- Server 2004 Unleashed. It represents
connection, and eventually to the ap- ling and serialization. The serialized a simple human resources orchestra-
4citrin@jnbridge.com propriate Java-based JMS client class, request is then sent across a remoting tion in which XML-based employee
which functions as an ordinary JMS cli- connection, where it is received by the records are taken from one HR ap-
Java-side runtime component, which plication. A test is performed on the
unmarshals and deserializes the re- value of the employee’s grade. If it’s 6 or
quest and dispatches it to the proper below (ordinary employee), the record
object. Return values and thrown is forwarded to another HR applica-
exceptions come back in the opposite tion. If it’s 7 or above (executive), the
direction by the same pathway. The record is transformed to a different
.NET-side code runs inside a .NET format and sent to a third HR applica-
CLR (Common Language Runtime), tion, and then the original version of
and the Java-side code runs inside a the record is forwarded to the same
JVM (Java Virtual Machine). (second) HR application as the records
Our adapter architecture example of other employees.
has the .NET and Java sides operating As described in Woodgate’s book,
inside the same process and commu- the orchestration is set up so that the
f2 Figure 2: JNBridgePro architecture nicating via a shared-memory channel. employee records are files, and the
orchestration’s send and receive ports
that connect it to the other applica-
tions are really folders. Once we get
the JMS adapter built and installed,
we will connect the orchestration to
an instance of the adapter at each
of the send and receive ports. Each
instance of the adapter will connect to
a message queue on a particular JMS
server (see Figure 4).

Building and Deploying the


Adapter from the Sample Code
Using Visual Studio .NET, open the
jmsAdapter solution file located in
the jmsAdapter folder. You should be
able to build the project without error.
To deploy the adapter, first edit
the file jmsAdapter.reg. In particular,
edit the lines for OutboundAssem-
blyPath, InboundAssemblyPath,
and AdapterMgmtAssemblyPath so
that these paths are valid for your
machine. Then, launch jmsAdapter.
reg by double-clicking on the icon.
This will install the relevant entries in
the registry. Then launch the BizTalk
Server Administration tool, navigate
to the Adapters folder, right-click on
f3 Figure 3: Example orchestration it, and select New Adapter. Name the

12 March 2006 • dotnetdevelopersjournal.com


BizTalk
These are the classes that will be
accessed from the Java code.
The proxy assembly needs to be
placed in the GAC, so you will need
to sign it. Before generating the proxy
assembly, create a strong name key
(or use the MyFirstIntegration.snk
strong name key that is supplied with
the sample code), and use the Strong
Naming menu item in the proxy gener-
ation tool to indicate that the assembly
will be signed with the indicated strong
name key. Also assign a version num-
f4 Figure 4: Example setup with orchestration, adapter, and JMS server ber to the assembly.
When this is completed, generate
proxies for all the classes using the
Build menu item in the proxy genera-
tion tool.

The Adapter Code


It’s worthwhile to examine the code
for the JMS adapter. There are three
f5 Figure 5: Employee input projects: JMSReceiveAdapter (repre-
senting the portion of the adapter that
receives data from JMS), JMSTrans-
mitAdapter (representing the portion
of the adapter that sends data to JMS),
and CommonJMSAccess (which
contains functionality common to
f6 Figure 6: Employee output both the receive adapter and the send
adapter).
adapter JMS and select JMS from the although you can also do this using the The JMSReceiveAdapter and
pulldown. gacutil.exe program that comes with JMSTransmitAdapter projects were
Next, edit the file jnbproxy.config the .NET SDK. automatically generated by the BizTalk
that can be found in the jmsAdapter Server adapter wizard. We made modi-
folder. This file configures the com- The Proxy Classes fications to the automatically gener-
munications mechanism that governs Note that it is not necessary for you ated code in the following places:
the bridging between the .NET and Java to generate the proxy classes for this • JMSReceiveAdapter.
sides of the adapter. We will be using example, since they have already been JMSReceiverEndpoint.GetRequestM
the shared-memory mechanism. Edit generated. However, if you want to essagesAndSubmit() now contains
the paths for the jvm, jnbcore, bcel, generate them, or simply want to know code to call the JMS client classes
and classpath items so that they are how it’s done, the information is below. and then to submit the received
valid for your machine. (If you are using To create the JMS proxy classes, message to BizTalk Server.
JNBridgePro v3.0 with BizTalk Server launch the GUI-based JNBridgePro • JMSTransmitAdapter.
2004, edit the “Version” attribute of proxy generation tool. Add C:\bea\ JMSAdapterWorkItem.
the shared-memory channel to read weblogic81\server\lib\wljmsclient. SendJMSRequest() now contains
“2.3.0.0” – it is originally “2.2.0.0”; if you jar (the actual path may be different code to receive the message from
are using BizTalk Server 2006 and .NET on your machine. Generate load the BizTalk Server and sent it to the
Framework 2.0, set the “Version” attri- proxies for the following classes and JMS client classes.
bute to “3.0.0.0.”) Save jnbproxy.config all supporting classes:
and copy it to the root folder of the drive • java.util.Hashtable CommonJMSAccess contains the
on which your system is installed (typi- • javax.naming.Context portion of the code that actually does
cally, but not always, C:\). • javax.naming.InitialContext the .NET/Java bridging. The project
Finish deploying the adapter by • javax.jms.QueueConnectionFactory references jmsProxies.dll, which con-
installing the files jmsProxies.dll (from • javax.jms.QueueConnection tains .NET proxies for the Java-based
the jmsAdapter folder), jnbshare.dll, • javax.jms.QueueSession JMS client classes. By calling these
and jnbsharedmem.dll (both from the • javax.jms.Session proxy classes, JNBridgePro bridges
JNBridgePro installation folder) in the • javax.jms.Queue the calls across to the Java-based JMS
Global Assembly Cache (GAC). The • javax.jms.QueueReceiver classes. The actual calls to the proxy
simplest way to do this is to copy them • javax.jms.QueueSender classes are in the class CommonJM-
into the C:\Windows\Assembly folder, • javax.jms.TextMessage SAccess.JMSSendRecv. Note that we

14 March 2006 • dotnetdevelopersjournal.com


BizTalk
Set Up WebLogic Server
Note that this example assumes the
use of WebLogic, but it is easy to per-
form the equivalent actions to set up
your favorite J2EE application server to
work with the example.
Start up the WebLogic Server.
Assuming that you’ve installed the
f7 Figure 7: Executive input WebLogic Server examples along with
the server itself, the simplest way to do
this is to launch it from the Start menu:
Start–>All Programs->BEA WebLogic
Platform 8.1–>Examples–>WebLogic
Server Examples–>Launch WebLogic
Server Examples. Once it has started
f8 Figure 8: Executive output (Exec port) and the Examples index page comes up,
click on the Administration console link
have cached the result of each proxy the example work. It’s beyond the to bring up the Administration console.
call so that one does not have to be scope of this article to go into detail Log in with the administrator user
made each time we attempt to send or on how to use the adapter wizard. ID and password you have specified.
receive a message. Please see the extensive documenta- Using the tree view on the left side of
Also note that a number of pa- tion provided with the wizard. the Administration console, navigate to
rameters have been hardwired into To create an adapter using the Examples–>Services–>JMS–>Servers
the code in CommonJMSAccess. In adapter wizard, create a new project –>examplesJMSServer–>Destinations.
a generally applicable JMS adapter, in Visual Studio .NET 2003 and, under Click on Configure a new JMS Queue
these values should be specified BizTalk Server Projects, select BizTalk and enter the queue name and the JNDI
as adapter properties that can be Server Adapter Project. Make sure the name as queue1, leaving all the other
changed at runtime. In this case, if following options are selected: default settings the same. Repeat the
you are using an application server • The adapter should be able to both process to create queue2 and queue3.
other than WebLogic Server, or if send and receive messages. You may log out of the administration
you are using WebLogic Server with • The receive adapter should be console, but leave WebLogic running.
nondefault parameters, you will need a regular (in-process) adapter
to change these values appropriately and should not support request- Build and Deploy the
and rebuild the adapter. The values response. Orchestration
that need to be changed are: • The receive adapter should have To build and deploy the orchestra-
• In CommonJMSAccess.JMSReceiver, the following endpoint proper- tion, you can either build the orches-
the receive timeout value in ties: QueueName (a string), tration from scratch by following the
receive(). It’s currently set to 500ms. JMSHostName (a string), and instructions starting on page 53 of Mi-
• In both CommonJMSAccess. JMSPortNr (an integer). crosoft BizTalk Server 2004 Unleashed
JMSReceiver and CommonJMS- • The transmit adapter should sup- (“Your First Integration Project”), or
Access.JMSSender, the format of port the alias jms://. It should not just deploy the orchestration from the
URI, the URI used by the JMS client have batch support, and it should sample code as described below by
classes to contact the JMS server not support solicit-response. opening the solution file MyFirstInt-
classes. WebLogic uses a protocol • The transmit adapter should have egration.sln found in the MyFirstInt-
called “t3.” If you are using a different the following endpoint proper- egration folder.
application server, you may need to ties: QueueName (a string), After building the orchestration,
use rmi, iiop, or some other protocol. JMSHostName (a string), and deploy it selecting the Build–>Deploy
• In CommonJMSAccess. JMSPortNr (an integer). menu item in Visual Studio .NET, or
JMSSendRecv, the JNDI names of use the BizTalk Deployment Wizard.
the initial context factory and the The wizard will create a code skel-
queue connection factory. Each eton with the appropriate properties. Configure the Adapter and Bind It
vendor’s application server provides Add the CommonJMSAccess project to the Orchestration
different names for these factories. and modify the code in the JMSRe- If you are using the supplied or-
ceiveAdapter and JMSTransmitAdapt- chestration, everything is configured.
Building and Deploying the er projects as described in the previous If you are creating the orchestration
Adapter Using the Adapter Wizard section. from scratch, create the following send
The adapter code that we supply and receive ports in the BizTalk Server
was created using the BizTalk Server Trying Out the Adapter Explorer:
Adapter Wizard. You can re-create the Now that the adapter has been built • Send port jmsToExecQueue: Create
code using the same wizard, although and deployed, it’s time to set up the a static one-way port. Set Transport
it is not necessary to do so to make example and run the orchestration. Type to JMS, and set Address

16 March 2006 • dotnetdevelopersjournal.com


(URI) to jms://queue2/localhost/7001
(or explicitly set JMSHostName to
localhost, QueueName to queue2,
and JMSPortNr to 7001). Set the
Send Pipeline to Microsoft.BizTalk.
DefaultPipelines.XMLTransmit.
• Send port jmsToHRQueue: Create
a static one-way port. Set Transport f9 Figure 9: Executive output (HR port)
Type to JMS, and set Address (URI)
to jms://queue3/localhost/7001 (or supplied for exactly this purpose. If you are stop the orchestration, and shut down the
explicitly set JMSHostName to localhost, using a different application server, or if WebLogic Server.
QueueName to queue3, and JMSPortNr WebLogic Server is installed in some non-
to 7001). Set the Send Pipeline to default location, you may need to edit the Summary
Microsoft.BizTalk.DefaultPipelines. runtime classpaths before running these This article shows how a JMS adapter
XMLTransmit. .bat files. for BizTalk Server can be constructed using
• Receive port jmsFromInputQueue: the JNBridgePro Java/.NET interoperability
Create a one-way port. Inside this port, Run the Orchestration tool. With this information you should be
add a new receive location locJms- Now that the JMS server, the orchestra- able to construct your own JMS adapter,
FromInputQueue. Set the Transport tion, and the Java clients have all started, we construct adapters to other Java-based
Type to JMS, and set the Address (URI) can now supply data to the orchestration software, or simply call Java libraries from
to jms://queue1/localhost/7001 (or and watch it run. Consult Figure 4 to see BizTalk Server orchestrations, using a Java/.
explicitly set JMSHostName to localhost, the architecture of the solution and how the NET bridging tool such as JNBridgePro.
QueueName to queue1, and JMSPortNr orchestration ports, the JMS queues, and As described, the adapter has a number
to 7001). Set the Receive Handler to the JMS clients relate. of hard-wired parameters that target it
BizTalkServerApplication, and set the First, supply an employee record through to the WebLogic Application Server. It is
Receive Pipeline to Microsoft.BizTalk. the queue1 sender. You will be prompted relatively simple to retarget the adapter to a
DefaultPipelines.XMLReceive. for a grade level. Use grade level 2 (an ordi- different app server, or generalize it so that
nary employee). You will now be prompted the parameters can be assigned at runtime.
Now, bind the ports to the orchestra- for first, middle, and last name, ID number, The creation and deployment of adapt-
tion as follows: and birth date. Make something up (Figure ers can seem like an involved process, but
• Under Orchestrations in the BizTalk 5). The sender program will compile the once you get past the details inherent in
Server Explorer, right click on information in an XML record and submit the creation of any BizTalk Server adapter,
MyFirstOrchestration and select Bind it to the JMS queue named queue1. The creating an adapter that bridges between
• Bind RecvEmpPort to jmsFromInput- JMS adapter will read the record off queue1 BizTalk Server and J2EE is quite straight-
Queue and submit it to the orchestration on the forward.
• Bind SendExecPort to jmsToExecQueue jmsFromInputQueue receive port. As an or-
• Bind SendEmpPort to jmsToHRQueue dinary employee record, it will be output on Resources
• Set the BizTalk Host to the jmsToHRQueue send port, from which • Woodgate, S., Mohr, S., and Loesgen, B.
BizTalkServerApplication the JMS adapter will place it on the queue3 Microsoft BizTalk Server 2004 Unleashed.
• Click on the OK button JMS queue, and the record will be received Sams, 2005.
by the queue3 receiver and displayed (Fig- • BizTalk Server 2004: www.microsoft.
Enlist and start the orchestration. ure 6). com/biztalk
Now, do the same thing with an execu- • BizTalk Server 2004 SDK Refresh: www.
Set Up and Run the tive record. Enter a grade level of 7, plus the microsoft.com/downloads/details.
Java Client Programs additional information (Figure 7). This will aspx?FamilyID=8A1CA3AF-790C-4261-
We have included Java JMS receivers and cause an XML version of the record to be 838A-9F0661C72887&displaylang=en
transmitters; they can be found in the Java submitted on queue1, and received by the • BizTalk Server 2004 Adapter
clients folder. The source code for these JMS JMS adapter from queue1 and submitted Wizard: www.gotdotnet.com/
client programs is supplied, and you are to the orchestration on the jmsFromIn- Community/UserSamples/Details.
encouraged to examine it. They are typical putQueue receive port. A copy of the aspx?SampleGuid=c95217fc-4f9f-4fec-
JMS clients. If you are using a different ap- record will be transformed and output 9d68-1aa9456b6ca0
plication server or have installed WebLogic to the jmsToExecQueue, from where the • Visual Studio.NET 2003: http://msdn.
Server in a nondefault location, you may JMS adapter will submit it to the queue2 microsoft.com/vstudio
need to modify some of the parameters in JMS queue, so that it is displayed by the • J2SE SDK (J2SDK) downloads: http://
the source code, or change the build class- queue2 receiver (Figure 8). In addition, the java.sun.com/downloads
path to reference different Java libraries. original record is output to the jmsToHR- • BEA WebLogic 8.1: http://dev2dev.bea.
Start up a sender client for queue1 (the Queue send port, transmitted to queue3, com/wlplatform
orchestration’s input queue), and receivers and received and displayed by the queue3 • JNBridgePro: www.jnbridge.com
for queue2 and queue3 (the orchestration’s receiver (Figure 9). • Sample code used with this paper:
executive and general employee output When you are done working with the www.jnbridge.com/biztalk/
queues, respectively). There are .bat files example, you can close the JMS clients, JMSAdapterSample.zip

dotnetdevelopersjournal.com • March 2006


17
ASP.NET

Summing Up the
New ASP.NET Controls ASP + .NET 2.0 = productivity

Wizard Control

o
n the eve of the official HotSpotMode or a property for a
release of .NET 2.0, devel- The Wizard control expands on the postback value if using the post-
opers around the world premise of the MultiView and creates pack HotSpotMode. There is also
were anxiously waiting an extremely powerful WYSIWYG edi- a HotSpotMode property on the
and priming their PCs for tor for creating a classic wizard design. HotSpot object to allow you to
a speedy download from MSDN. And The screenshot of the Wizard control have multiple hot spots performing
who could blame them? Microsoft’s in Figure 1 is actually taken from differently.
.NET development platform has been design view rather than at run time
a hit with the developer community and gives you a feel for the rich visual BulletedList Control
ever since the first betas came out editing power of the Wizard control. The BulletedList control is simply
years ago. a way to provide easy generation of
Upon loading Visual Studio .NET dynamic bulleted lists. The control can
2.0 for the first time, many of us were be data bound to a data source and
like kids in a candy store. So much to gives you a number of bullet cus-
play with and so little time! Microsoft tomizations, including circle, square,
has really hit a home run with the numbered, alpha, roman numbers,
suite of new controls they’ve added and custom image.
to the toolkit, which are bound to
make your life a lot easier. So, without HiddenField Control
teasing you too much further, here’s a The HiddenField control allows you
rundown of the new controls you now to store data in a hidden field on the
have at your disposal with ASP.NET rendered HTML. Typically you’d use
2.0. The Wizard control contains a Col- view state, session state, or cookies to
lection of WizardStep objects that are do that, but if you can’t, then this is an
MultiView Control added to the Wizard in the order in alternative. You can modify the data
The MultiView control is essentially which you wish them to appear. Next, stored with the Value property. You can
a container class for another control, Previous, and Finish buttons are auto- also capture client-side changes to the
which is new in .NET 2.0 – the View matically added to each WizardStep to data via a ValueChanged event.
control. The View control is itself a allow for navigation between steps.
container class for other controls. FileUpload Control
BY AARON REED Only one View control from the Mul- ImageMap Control The FileUpload control is simply a
tiView is viewable at one time. You The new ImageMap control lets you replacement for the HTML version of
can use the MultiView’s SetActiveView easily create images with clickable hot the control. The .NET control runs in a
method or ActiveViewIndex property spots in a straightforward and simple very similar manner and has a HasFile
to specify which View will be visible at manner. The control itself is similar to property that indicates whether a file
a given time. the standard Image control with the was selected in the control. You then
The MultiView control is a great ImageUrl property containing the URL have access to methods and proper-
way to facilitate jumping between of the image displayed. However the ties such as SaveAs (saves the file to
edit and read-only modes of database ImageMap adds a few new properties: the server), FileBytes (size of the file),
records. It also has some great built-in • HotSpotMode: An enumeration FileContent (gets a Stream of the file
functionality to assist in creating a indicating whether to have mouse contents), and PostedFile (gets the
wizard look and feel. By adding a But- clicks navigate to a URL or generate HttpPostedFile object for the file itself)
ton, LinkButton, or ImageButton to a postback. to manipulate the uploaded file as
each View in the MultiView and set- • HotSpots: A collection of Circle- needed.
ting the CommandName and Com- HotSpot, RectangleHotSpot, and
mandArgument values, the MultiView PolygonHotSpot objects. These Substitution Control
will automatically navigate between objects derive from the HotSpot The Substitution control provides
Views as directed. Table 1 shows a object and contain properties for a you with a way to display dynamic data
simple view of those values. URL and target if using the navigate on a page while the rest of the data on

18 March 2006 • dotnetdevelopersjournal.com


XML’s Endless Possibilities,

None of the Risk.

Forum XWall™ Web Services Firewall - Reinventing Security

Security should never be an inhibitor to new opportunity: Forum XWall™ Web Services
Firewall has been enabling Fortune 1000 companies to move forward with XML Web
services confidently. Forum XWall regulates the flow of XML data, prevents unwanted
intrusions and controls access to critical Web services.

Visit us at www.forumsys.com to learn more about how you can take your next leap
forward without increasing the risks to your business.

fo r u m syst e m s ™ – t h e l e a d e r i n we b s e rv i c e s s ec u r i t y ™
ASP.NET
AUTHOR BIO: that page may be pulled from cache. Web site. The control hosts a Collec- ing, deleting, sorting, filtering, paging,
Aaron Reed is an assistant While the OutputCache directive may tion of MenuItem objects, which are etc. The 1.x controls are still there for
professor specializing in software indicate that your page is being pulled customizable with images or a variety backward compatibility, but the new
architecture and design and from cache, data connected to a Sub- of styles. You specify a NavigateUrl controls give you a much cleaner and
.NET development at Neumont stitution control will always be fresh. property for each MenuItem object in equally powerful solution to data-bind-
University in Salt Lake City, UT. order to allow for easy navigation. ing problems.
He has worked professionally SiteMapPath Control
in the industry for over 12 years The SiteMapPath control gives you TreeView Control Login Controls
as a lead architect/designer, an easy way to create customizable The TreeView is a flexible and .NET 2.0 comes packed with a full
development manager, and VP breadcrumbs for your entire site. You powerful tree control that can be data suite of controls aimed at assisting in
of development. When he isn’t simple create a site map XML file such bound to a data source. The TreeView the creation and maintenance of login
spending time reading up on as the one shown in Listing 1. The contains a Collection of TreeNode security for your Web application. With
the latest in software develop- SiteMapPath control will then read the objects that can be customized with the tools now available it is possible
ment, Aaron loves spending time XML file and based on the path of the images, NavigateUrls, checkboxes, to create a robust and customized
with his beautiful wife and three current page, it will create the bread- tool tips, different select actions (se- authentication system with no coding
children. crumb dynamically. lect, expand, select and expand), etc. at all.
The controls focus on the concept of
4 aaron@aaronreed.com MenuControl Data Source Controls .NET memberships. Memberships pro-
The Menu control is a great way to Data binding has been revamped in vide a built-in way to validate and store
add customizable pop-out menus to a .NET 2.0. The addition of several new user credentials. Memberships can be
controls that encapsulate the function- stored in SQL Server, Active Directory,
ality from the Connection, Command, or other sources as needed. .NET 2.0
and DataAdapter objects in .NET 1.x also provides a slick Web site admin-
make data binding in .NET 2.0 easier istration tool (shown in Figure 2) that
than it has ever been with little or you can use to visually modify security
no code required to bind controls to and performance settings for your Web
complex data queries. The SqlData- site including, .NET memberships.
Source pulls data from SQL Server, the A brief overview of the login controls
t1 Table 1: Values for MultiView buttons AccessDataSource pulls from Access used to handle these memberships is
databases, and the XMLDataSource listed here:
can pull from XML sources. • Login: The Login control con-
The ObjectDataSource control is tains text boxes for username and
added to allow you to pull data from password as well as a “remember
any type of object. This will be useful me” checkbox. The control is auto-
when manipulating or representing wired for authentication using
the data in code before binding it to a .NET memberships and no code is
control. required if you go that route. If you
Nearly all data manipulations can store your authentication in anoth-
now be handled in these objects. They er way, you can modify the control
f1 Figure 1: A Wizard control in design can handle selecting, inserting, updat- to run your methods.
• LoginView: The LoginView control
is a view that allows you to toggle
automatically between two different
sub views – one for authenticated
users and one for anonymous users.
This is very handy for content panes
that change information based on
whether a user is currently logged in
or not.
• LoginStatus: This control displays a
login link or a logout link based on
the user’s current state. The control
offers full visual customization.
• LoginName: This control displays
the name of the currently logged in
user.
• PasswordRecovery: This control
allows a user to retrieve his pass-
word based on an e-mail used in
registration. If the .NET member-
f2 Figure 2: Web site administration tool – adding a user ships are stored using non-revers-

20 March 2006 • dotnetdevelopersjournal.com


� �������������� ���������������������
ASP.NET
that can be added, moved, deleted,
etc., on an individual basis per user
of your system. .NET 2.0 uses a slick
client-side drag-and-drop technique
to allow the user to move the WebParts
around the page (see in Figure 3).
WebParts can be dropped onto any
WebPartZone control that you have set
up on your page.
Other key controls used in WebParts
f3 Figure 3: WebParts in action – moving one WebPart and dropping it on a different WebPartZone are:
• WebPartManager: Not a visible run-
ible encryption, a new password is The ReportViewer, CrystalReport- time control, this control maintains
generated and sent instead. You can PartsViewer, and CrystalReportSource the WebParts on the screen and
also set the system up to use a secu- controls are used to design, generate, ensures that they all work together.
rity question before e-mailing the and display reports in a visual format • CatalogZone: Allows you to let the
password to the user. that is much easier than anything used user add new WebParts that are not
• ChangePassword: This control in .NET 1.x. currently visible to the page.
allows the user to modify his/ • EditorZone: This control
her password by first providing the DetailsView Control houses different EditorPart con-
original password and then creating The DetailsView control displays a trols (AppearanceEditorPart,
and confirming a new password. single record from a query at a time BehaviorEditorPart,
• CreateUserWizard: This control cre- and does so with every field displaying LayoutEditorPart,
ates a new .NET membership for a on a separate row. The control has full PropertyGridEditorPart) and allows
user by collecting information such functionality for inserting, updating, users to personalize their pages
as username, password, e-mail, etc. deleting, and paging and works great accordingly.
in combination with the GridView • ConnectionZone: Houses
GridView Control control explained above to give the ConnectionPart controls that allow
The GridView control is essentially user master-detail information on a different WebParts to communicate
a revamped and beefed-up DataGrid query. with each other.
control. Those of you who are familiar
with the .NET 1.x DataGrid control FormView Control As you can see, the folks at Microsoft
realize that it was fantastic for quick The FormView control is very simi- have heard a lot of our complaints and
data binding in a grid, but for extended lar to the aforementioned DetailsView, requests from working with .NET 1.x
functionality such as paging, sorting, but rather than displaying all of the and have spent a lot of time coming up
editing, etc., it left a bit to be desired. fields in rows, you display them in with some tremendous additions to
The GridView offers the same easy user-defined templates. The biggest the controls that are already avail-
data binding to the new data source difference here is that you have much able. While .NET 2.0 offers some great
controls listed above, but in addition more control over exactly how the data additions to the language such as ge-
to that it offers fully functional sorting is displayed. It also has built in support nerics and other modifications to the
and paging with no extra code. Simply for data binding, paging, inserting, environment itself, the real treasure
set the AllowSorting and AllowPag- updating, and deleting. awaiting us all is arguably in the great
ing properties to true and the work is enhancements to the ASP.NET toolset.
done. The GridView control also offers WebParts Controls With the combination of variety of
improved ways to allow for editing of Finally, WebParts are one of the purpose and the power and flexibility
records as well as much better support most exciting new features of ASP. these new controls offer, there’s no
for different controls used in columns NET 2.0. Ideal for portal systems and doubt that you’ll find many of them
rather than simple text. personalized Web sites, WebParts allow extremely useful in your next develop-
Another new feature of the Grid- you to easily develop Web site sections ment project.
View is the EnableSortingAndPaging-
Callbacks property, which when set to
Listing 1 Site Map XML File
true, will generate client-side scripting
<?xml version=”1.0” encoding=”utf-8” ?>
to handle the sorting and paging of the <siteMap xmlns=”http://schemas.microsoft.com/AspNet/SiteMap-
GridView without causing an entire File-1.0” >
page post back to the server. This is <siteMapNode url=”default.aspx” title=”Home”
a nice addition for grid-intense Web description=”Home page”>
pages and it functions much as an Ajax <siteMapNode url=”Buy.aspx” title=”Buy”
description=”Buy items” />
DLL would.
<siteMapNode url=”Sell.aspx” title=”Sell”
description=”Sell Items” />
ReportViewer Control </siteMapNode>
The reporting functionality in .NET </siteMap>
2.0 has been revamped and enhanced.

22 March 2006 • dotnetdevelopersjournal.com



� ����� � �� �
� �� ��
� ����� � �

� �� � � ��
� �� �
� �


� �� � � �� � ���� �� �� � �� � �� �� �� ���� �� ������ �� � �� � �� �� �� ��� ��� ���� �� �
� �� � � � � � � �� � � � � � �� � � � � � � � � � � � � � �
� �� �� �� �� �
� �� �� �� �� ���� �� �
� �� �� ��� � ���� �� �� ��� � �� �� �� ���� �� �� ���� �� ��� � �� �� �� ��� � �� ���� �� �

���������������������������������������
��������������������������������������������
��������������������������������������������

�������������������������������������������������������
������������������������������������������������������������
��������� � ����������������������������������������������������������������������������������������������������������������������
���������������������������������������������������������������������������������������������������������������������� ������ �
���������� ������������ �����������������������������������������������������������������������������������������������������
���������������������������������������������������������������������������������������������������������������������������������
������������������������������������� ����������������������������������������������������������������������������������������
�������������������������������������������� ����������������������������������������������������������������������������������

��������������������������������
������������������������������������������������������������������������������������������������������������������������ ���������������������������������������������������������������������� ���������������������������������������������������� ������������������������������������������������������������������������������

� � � � � � � � � � � � � � � � � � � �
� � � � � � � � � � � � � � � � � � � �
SQL Server 2005

SQL Server Web Services


Create and host XML Web services inside SQL Server 2005

hese days, applications HTTP or the TCP protocol. They can AS Clause

t built around a service-ori-


ented architecture (SOA)
are all the rage. Complex
provide support for SOAP, Service
Broker, and Database Mirroring. As
you might guess, the syntax for cre-
The AS clause specifies the com-
munications protocol that the end-
point will use. Here we have speci-
systems can be written as a collec- ating a new endpoint is quite com- fied the HTTP protocol, which is the
tion of services that communicate plex. Because of this, I am going to protocol required for a Web service.
with each other through standard focus solely on the syntax required (TCP is an option for other types of
protocols. When implemented to create a Web service. Listing 1 services, and would have different
properly, these systems can become shows an example of this. We’ll walk settings than those described here.)
immensely flexible, scalable, and through each line in detail. The exact implementation details
easy to maintain. The most common Endpoints are created via the are controlled by a list of specific
SOA designs utilize Web services CREATE ENDPOINT statement. This options included inside parenthe-
as the communications medium, statement consists of four main ses. Those used in our example are
because they can be created and parts: endpoint name, the initial described here:
consumed by disparate systems and state, the AS clause, and the FOR • PATH specifies the URL of the
platforms. This highly useful capa- clause. endpoint. This setting, along
bility has made Web services a very with the SITE setting described
important part of today’s informa- later, fully specifies the URL that
tion systems. will be used to invoke the Web
Up until now, the classic service. (For example, I’ve used
Microsoft implementation of a Web ‘/Employee,’ so the URL would be
service involved a back-end database HTTP://ServerName/Employee.)
server running SQL Server 2000 and • AUTHENTICATION specifies the
a front-end Web server running a type(s) of authentication that
.NET Web service application on IIS. will be used. This is a comma-
Now that SQL Server 2005 is here, we separated list of authentication
have an additional option: we can methods, including those that we
create and host Web services using should all be familiar with: BASIC,
SQL Server alone. In this scenario, DIGEST, NTLM, KERBEROS, and
no Web server is needed. When run- INTEGRATED. These work as
ning on Windows Server 2003 or expected, although additional in-
Windows XP with Service Pack 2, IIS Name and Initial State depth information can be found
is not needed either. These operat- The first two parts are easy: they in SQL Server Books Online. My
ing systems provide the HTTP API, provide a name for the endpoint example used Windows Integrated
also known as HTTP.SYS, which SQL and specify the state of the endpoint authentication only, so I’ve speci-
BY JERRY DIXON Server uses to provide native Web after it is created. The state can be fied INTEGRATED.
service functionality. STARTED, STOPPED, or DISABLED. • PORTS specifies the type of port
In this article I will show how STARTED indicates that the endpoint to use: CLEAR and/or SSL. CLEAR
to create a Web service inside SQL is actively listening for connections indicates a non-encrypted port,
Server. I will show how to define the and will respond to connection which requires clients to use the
service and how to access it from a attempts. STOPPED indicates that HTTP protocol. SSL indicates an
.NET client application. Along the the endpoint will listen for connec- encrypted port, requiring clients
way, we will see how incredibly flexi- tions and will respond to connection to use the HTTPS protocol. If
ble SQL Server’s Web service support attempts, but will refuse the con- required, both settings can be
is. Hopefully, we will also gain an nection and return an error to the used simultaneously. The example
appreciation of how capable a tool client. The last option, DISABLED, uses unencrypted HTTP com-
SQL Server 2005 has become. Let’s indicates that the endpoint will not munications, so the appropriate
get started. listen for connections, nor will it setting is CLEAR.
respond to connection attempts. • CLEAR_PORT specifies the actual
Endpoints STOPPED is the default, but this port that will be used by unen-
SQL Server 2005 provides can be changed either through the crypted communications. If not
Web services through endpoints. CREATE ENDPOINT statement or via specified, port 80 is assumed. In
Endpoints define the properties of a an ALTER ENDPOINT statement at a this example, I’ve used port 8080
connection, which can use either the later time. because my computer has IIS

24 March 2006 • dotnetdevelopersjournal.com


SQL Server 2005
AUTHOR BIO: installed, which means that port The WEBMETHOD clause does In the example, the second WEB-
Jerry Dixon is a senior devel- 80 is already in use. There is also exactly what you would expect; it METHOD clause is almost identical
oper and architect for ACH an SSL_PORT setting that we can defines a single Web method. If a Web to the first, so we’ll move on to the
Food Companies in Memphis, use if needed, and it defaults to service needs multiple methods, then service-wide settings.
Tennessee. Over the past 16 years port 443. My example doesn’t use multiple WEBMETHOD clauses will The final four settings apply to
he has led development projects SSL, so I haven’t included this be needed. In our example, there are the whole Web service, and not to a
for a number of enterprise, mid- option. two methods. The two methods are specific method:
level, and small business organiza- • SITE determines the ServerName quite similar; therefore, I’ll describe • BATCHES specifies whether
tions. While he has fulfilled multiple portion of the Web service URL. just the first one. ad hoc T-SQL statements can
roles as an infrastructure designer, If we use an asterisk (“*”), it The first part of the WEBMETHOD be executed via this service.
database administrator, and soft- instructs the endpoint to use all clause defines the name, or alias, of the DISABLED, the default, prevents
ware developer, he specializes in possible host names that aren’t method. The alias can also include a this. ENABLED allows it. When
XML, SQL and ASP.NET. He is a explicitly reserved. I used this set- namespace, but this is optional. If the enabled, a special method called
co-leader and frequent presenter ting in my example so that both namespace is not included, then the SQLBATCH will be created that
at the Memphis .NET User Group. HTTP://localhost/Employee and namespace from the endpoint is used supports ad hoc queries.
Jerry holds the following Microsoft HTTP://jdixon/Employee would instead. (The endpoint’s namespace • WSDL determines the type of
certifications: MCSD (VB 6.0 work. If we use a plus sign (“+”), will be described in a moment.) After WSDL (Web Services Definition
and .NET), MCDBA (SQL 2000), then the endpoint will use all pos- the alias, additional settings are used Language) document that the
MCSA (Windows 2000 and 2003), sible host names, even if they are to specify exactly how this method will Web service will generate. A value
MCSE (Windows 2000), MCAD reserved. Finally, we could explic- function. Note that these settings are of NONE prevents the WSDL
(.NET), MCT. He resides in Olive itly specify the host name, which included inside parentheses, and that from being generated. DEFAULT,
Branch, MS with his wife and son. would ensure that only that name the parentheses are required. on the other hand, directs that
would be used. • NAME specifies the fully-qualified the WSDL will be generated. In
4 jdixon@achfood.com • COMPRESSION specifies whether name of the stored procedure or those rare cases where a special
client requests for compressed user-defined function that will be WSDL document is needed, you
communications will be honored. invoked by the method. The name can specify the name of a stored
If enabled, GZIP encoding will be must be in the standard database. procedure that returns the special
used when client requests include owner.name format. My example document.
the appropriate HTTP encoding uses a stored procedure named • DATABASE identifies the name
header. Disabled is the default, uspGetEmployeeManagers that is of the database context against
and specifies that compression found in the AdventureWorks data- which the Web methods will be
will not be used even if the client base, within the dbo schema. executed. Our service uses the
properly requests it. I’ve chosen to • SCHEMA determines whether the AdventureWorks database, so
enable compression in the exam- SOAP message for this method that name is included here. If
ple, although I don’t specifically will include an inline XSD schema. DEFAULT is specified instead,
need it. There are three options; NONE, then the default database for the
STANDARD, and DEFAULT. NONE login will be used.
Our example AS clause is now specifies that no schema will be • NAMESPACE specifies the
complete. There are other settings used, while STANDARD specifies namespace for the endpoint.
that can be used, especially when that one will. DEFAULT specifies If DEFAULT is used, or if no
different authentication methods that the setting from the endpoint namespace is specified, then the
are chosen, but those are beyond the itself should be used. If no value namespace will be HTTP://tempu-
scope of this article. Instead, we need is specified, DEFAULT will be ri.org. If a namespace is included
to move on and set up our service assumed. at the WEBMETHOD level, then
options. • FORMAT determines the exact that namespace will override the
content of the method response. one provided here.
FOR Clause The options are ALL_RESULTS,
The FOR clause specifies the ser- ROWSETS_ONLY, and NONE. Our example endpoint is now
vice that the endpoint provides. This ALL_RESULTS instructs the complete. When executed, this state-
can be SOAP, SERVICE_BROKER, or method to return not only the ment creates a Web Service named
DATABASE_MIRRORING. We want output from the stored procedure EmployeeWebService that has three
to create a Web service, so we must or user-defined function, but also Web methods: GetEmployeeMan-
choose SOAP. (Once again, the pos- the row count and any error mes- agers, GetManagerEmployees, and
sible settings vary greatly depending sages or warnings that may exist. SQLBatch.
upon which option we choose, so ROWSETS_ONLY omits everything
I’m going to restrict my explanation but the actual results. NONE sup- Security
to SOAP-specific settings. Consult presses the results too, making this Now that we’ve defined our end-
Books Online for more details.) The option useful only in very specific point, we need to discuss security.
FOR clause consists of one or more circumstances (see SQL Books Endpoints are secured separately
WEBMETHOD clauses followed by Online for details). The example from the functions and procedures
some service-wide settings. uses ROWSETS_ONLY. that they invoke. In effect, this

26 March 2006 • dotnetdevelopersjournal.com


SQL Server 2005
means that a user must have rights ent program. I chose to use a .NET
to invoke both the endpoint and the Windows application for this pur-
function or procedure. For example, pose. (You can’t test an SQL Server
in order to successfully execute all Web service in Internet Explorer
of the features of our demonstration as you can with .NET Web services
Web service, a user would need: because there are no HTTP inter-
• CONNECT permission on the faces and no forms provided.) The
EmployeeWebService endpoint. client program needed an appro-
• EXECUTE permission on the priate WSDL document in order to
uspGetEmployeeManagers stored create the Web service proxy class.
procedure. SQL Server provides this document
• EXECUTE permission on the via a special URL parameter, WSDL,
f1 Figure 1: EmployeeManagers uspGetManagerEmployees stored as in HTTP://LOCALHOST:8080/
procedure. Employee?WSDL. I used the Add
• Individual permissions on Web Reference wizard and pointed
one or more tables in the the browser to that URL. It gener-
AdventureWorks database. (This ated the proxy class for me, and I
is required because BATCHES ran some tests. You can see my test
are ENABLED, and ad hoc T-SQL code in Listing 2, and the results in
statements may be executed. Figures 1, 2, and 3. The test appli-
NOTE: this is not a recommended cation had no clue that this Web
practice and is presented here for service was provided by SQL Server
illustration purposes only.) and not IIS.

Permissions are managed via Summary


GRANT, REVOKE, and DENY state- Now that SQL Server 2005 is
f2 Figure 2: ManagerEmployees ments just as they were in SQL 2000. here, we have an additional option
However, SQL 2005 provides many when it comes to the creation of
more permissions with much greater Web services. We can continue to
granularity. For example, to allow a create them with .NET, or we can
user named Bob to connect to our create them with SQL Server. If
endpoint, you would run the follow- we choose SQL Server then we no
ing statement (see SQL Books Online longer need IIS, and can instead
for more information): use the HTTP API that is included
in the Windows 2003 Servers and
GRANT CONNECT ON ENDPOINT:: in Windows XP Service Pack 2. This
EmployeeWebService to Bob gives us additional flexibility when
designing a service-oriented system.
Testing It also makes SQL Server a more
In order to test the newly created flexible and valuable tool than its
f3 Figure 3: SQLBatch Web service, we need to create a cli- predecessors.

Listing 1: CREATE ENDPOINT ,SCHEMA = STANDARD


CREATE ENDPOINT EmployeeWebService ,FORMAT = ROWSETS_ONLY)
STATE = STARTED ,BATCHES = ENABLED
AS HTTP (
,WSDL = DEFAULT
PATH = ʻ/Employeeʼ
,DATABASE = ʻAdventureWorksʼ
,AUTHENTICATION = (INTEGRATED)
,PORTS = (CLEAR) ,NAMESPACE = ʻhttp://mynamespace.orgʼ)
,CLEAR_PORT = 8080
,SITE = ʻ*ʼ
,COMPRESSION = ENABLED) Listing 2: Test Client Code
FOR SOAP ( Private Sub btnEmployeeManagers_Click( _
WEBMETHOD ʻGetEmployeeManagersʼ ( ByVal sender As System.Object, _
NAME = ʻAdventureWorks.dbo. ByVal e As System.EventArgs) _
uspGetEmployeeManagersʼ Handles btnEmployeeManagers.Click
,SCHEMA = STANDARD
,FORMAT = ROWSETS_ONLY) Dim proxy As EmployeeWebService = _
,WEBMETHOD ʻGetManagerEmployeesʼ ( New EmployeeWebService
NAME = ʻAdventureWorks.dbo.
uspGetManagerEmployeesʼ proxy.Credentials = _

28 March 2006 • dotnetdevelopersjournal.com


CredentialCache.DefaultCredentials End Sub

Dim Result As System.Data.DataSet Private Sub btnSQLBatch_Click( _


Result = proxy.GetEmployeeManagers(1) ByVal sender As System.Object, _
DataGridView1.DataSource = _ ByVal e As System.EventArgs) _
Result.Tables(0) Handles btnSQLBatch.Click

End Sub Dim proxy As EmployeeWebService = _


New EmployeeWebService
Private Sub btnManagerEmployees_Click( _
proxy.Credentials = _
ByVal sender As System.Object, _
CredentialCache.DefaultCredentials
ByVal e As System.EventArgs) _
Handles btnManagerEmployees.Click
Dim SQL AS String
SQL = “SELECT * “ & _
Dim proxy As EmployeeWebService = _
“FROM HumanResources.Department”
New EmployeeWebService

Dim Result As System.Data.DataSet


proxy.Credentials = _ Result = proxy.sqlbatch _
CredentialCache.DefaultCredentials (SQL, Nothing)(0)

Dim Result As System.Data.DataSet DataGridView1.DataSource = _


Result = proxy.GetManagerEmployees(148) Result.Tables(0)
DataGridView1.DataSource = _
Result.Tables(0) End Sub

dotnetdevelopersjournal.com • March 2006


29
ASP.NET

ASP.NET 2.0 Callbacks Using callbacks to create a rich Web UI

w
eb sites are based on formance), you must persist the An Overview of Callbacks
a client-server model. state of the whole page. For exam- Callbacks are a new feature in
While the client (usually ple, all your JavaScript variables and ASP.NET 2.0. They let a client script
a browser) can use cli- controls without viewstate will be call the server without affecting the
ent-side script such as JavaScript to lost. rest of the page (to those who have
do simple tweaking of existing data, heard of AJAX or ATLAS, callbacks
getting new data requires a request to Especially as you move beyond have similar functionality). The pro-
the server. The server does the heavy just basic data entry forms, these cess is:
processing and makes a response problems become more critical. • On the client, a script calls the
back, which redraws the entire Web Examples abound of where you server, passing a string of data
page. Most development required want to just make a small request/ • At the server, a method uses that
these interactions to be atomic response for only part of the page, data, and returns a new string (that
so that each request to the server without re-creating the whole thing. you create) to a receiving function
returns a completely new page. Perhaps for an address section you back at the client
want a user to select a state from • This receiving function is then trig-
The Problem with Postbacks a dropdown, which in turns auto- gered
Postbacks, which are perhaps the matically populates another drop-
most common way to communicate down with all that state’s available These three simple steps enable
between the client and server, do cities? Perhaps you have optional us to implement powerful features.
exactly that. While this works, it has helper buttons such as “Calculate We can trigger the callback from any
several problems: Rate,” which needs to do the calcu- JavaScript function: onchange of a
• Posting back the entire page, as lation at the server. Or perhaps you dropdown, onclick of a button or
opposed to only what you need, have complex controls like a tree- hyperlink, onmouseover of an image,
sends a lot more traffic over the view that let the user cumulatively etc. We can pass any data to the
network. This hurts performance. request more data. While all of server and back by serializing it to a
• Posting back prevents users from these can be done with postbacks, string. We can then have the receiv-
BY TIM STALL doing anything while they wait for the problems with that approach ing function use the returned data to
the server to respond. encourage us to find a better way. set error messages, update control
• Because you’re re-creating the Fortunately there is one: ASP.NET properties, or even modify the DOM
whole page (which also hurts per- 2.0’s callbacks! (like adding dropdown items or table
rows)!
Let’s go over the technical imple-
mentation of the simplest callback,
and then show both some advanced
features as well as the limitations
of callbacks. First, any page with
callbacks must implement System.
Web.UI.ICallbackEventHandler (see
Listing 1).
This has two methods:RaiseCall-
backEvent and GetCallbackResult.
One approach is to use RaiseCall-
backEvent for internal plumbing
and let GetCallbackResult do the real
f1 Figure 1: A single page with multiple callbacks work. RaiseCallbackEvent is fired

30 March 2006 • dotnetdevelopersjournal.com


first; it receives the client side data, At this point, we have the full life First, UserControls can implement AUTHOR BIO:
and stores it in a member variable. cycle of a callback implemented. callbacks just like pages! This lets you Tim Stall is a software
GetCallbackResult is fired second; it Let’s build off of this with some more incorporate callbacks into your reus- developer at Paylocity, an
accesses the client data via the member advanced topics. able controls. independent provider of payroll
variable, does whatever manipulation Second, while callbacks can’t set and human resource solu-
you need, and then returns the new Multiple Callbacks on a Single Page the Response, they can still access all tions. He can be contacted at
string. This return value will be passed A callback requires implementing server resources such as the database, tims@paylocity.com.
to the receiving client function. an interface, but a single page can only session, and page’s viewstate. For
Still in the CodeBehind, we need to implement one interface once. So how example, suppose you want a callback 4 tims@paylocity.com
do some plumbing to register the cli- do we handle pages that need multiple to return a list of employees, excluding
ent-side scripts (see Listing 2). callbacks, each with its own start and the current user. If the current user info
We need to register two client receiving functions? Simple – we prefix was stored in session or viewstate, you
scripts: ReceiveCallback, which receives the data string with metadata to indi- could access that and manipulate the
the callback when returning from the cate which method to trigger. data appropriately at the server. This is
server, and CallServer, which calls the Figure 1 illustrates this concept. helpful because it’s easier to manipulate
server (the names are intended to be First we have multiple client func- data on the server rather than the client
obvious). These steps must always be tions (StartA, StartB), which both call due to the server’s having better data
run, not just in a “not PostBack” block, CallServer function [Step 1], but prefix structures and testability.
so we can abstract them to a method the data string with an “A” or “B,” respec- Third, often you’ll want user interac-
appropriately named “SetupAlways,” tively. The CallServer method still trig- tions to change the page such as adding
and call that in the page load. gers the GetCallbackResult method on or removing table rows. For example,
Meanwhile, at the client we add the server [Step 2], but now this method in postbacks a button click does this by
two simple scripts: StartCallback and strips off the first character and uses it in re-creating HTML for the entire page.
ReceiveCallback (see Listing 3). a switch-case to call either ProcessA or However in a callback, you keep the
StartCallback is a custom function ProcessB [Step 3]. Both processes return existing page, and therefore achieve this
written by the developer whose sole a string, but again prefix it with “A” or by modifying the DOM. Therefore you’ll
purpose is to invoke CallServer and “B,” and return it to the client [Step 4]. want to create client script libraries for
pass in a string of data. You can trig- Finally, the client ReceiveCallback func- easily modifying the DOM – such as
ger it however you want, pass in any tion strips off the first letter, and uses it adding or removing rows, hiding ele-
parameters you want, assemble the to call the appropriate client receiving ments, or updating status messages.
data however you want, and trigger the function, ReceiveA or ReceiveB [Step 5]. In some cases, you can have the server
CallServer function based on whatever You can check the code download create the HTML for you, return that as
logic you want. The CallServer function for an example of this. (Source code is the string, and then set the innerHTML
itself was automatically created in the available by viewing the article online property of a span or div.
previous step. in the DNDJ archives, http://dotnet. Last, when we collect data to send
ReceiveCallback is always triggered sys-con.com/read/issue/archives/, Vol. to the server, it’s often not just a single,
upon returning from the callback. We 4 iss. 3.) primitive, string type. Rather, there
indicated that this was the receiving are other data types (int, bool, dates),
function when we registered it at the Tips For Better Callbacks multiple values, and sometimes even
server. It expects a string that it can use With this infrastructure in place, a collection of objects that we need to
for any JavaScript purpose – such as set- these are several ways to maximize send back to the server. For example,
ting a message or modifying the DOM. your benefit from callbacks. you may have an employee object with

Callback Postbacks
Pro • Doesn’t re-create the entire page • Access to the full-page response
• Lets you asynchronously contact the • Handles cross-browser issues
server from client-script

Con • Can’t set the response • Re-creates the entire page, which is slower
• Need to do your own serialization for request • Loses client-side state
• Not necessarily cross-browser compliant • Blocks user from doing anything else

Useful • You are updating only a portion of the page • Page-wide actions such as “Save” that read
When the entire page
• You want to keep client-side state
• You are redirecting away from the page

t1 Table 1: Differences between callbacks and postbacks

dotnetdevelopersjournal.com • March 2006


31
ASP.NET
an ID (int) and Name (string) and you Let’s run through each of these. A Summary
may want to send a group of these in simple entity class just needs public Callbacks are a great new
the callback. One relatively easy way to fields that can be deserialized (you feature of ASP.NET 2.0. Like any-
handle this is with XML serialization. could use properties, but for this thing they have their pros and
This has four steps: simple purpose they add no benefit). cons.
• Write a simple entity class to hold (See Listing 4.) Having this technique in your
the data You can use the built-in XML arsenal will fundamentally change
• Write a utility method to deserialize serialization methods to write a quick how you develop, open up new
XML into a class utility (see Listing 5). doors that you wouldn’t think
• In the client StartCallback function, You can then easily assemble the nec- possible before, and save you tons
create the XML string essary XML via JavaScript (Listing 6). of time and performance. Given
• In the server, use the utility method Finally, you can deserialize at the how easy callbacks are to imple-
to deserialize this and instantiate the server with the utility method shown ment, it’s a technique well worth
object in Listing 7. learning.

Listing 1 var strData = “user input data here”;


//SERVER CallServer(strData, “”);
#region ICallbackEventHandler Members }

private string _strCallbackData = null; function ReceiveCallback(strReturnData)


{
public void RaiseCallbackEvent(String event //TODO: use the data that you gte back from
Argument) the callback.
{ document.getElementById(“Span1”).innerHTML
_strCallbackData = eventArgument; = strReturnData;
} }

public string GetCallbackResult()


{ Listing 4
//TODO: Modify data here public class EmployeeData
return _strCallbackData + “ modified at {
Callback “ public int Id;
+ DateTime.Now.ToString(); public string Name;
} }

#endregion
Listing 5
public static object DeserializeFromXmlString(
Listing 2 System.Type t,
//SERVER string strXml)
{
protected void Page_Load(object sender,
// Requires namespaces:
EventArgs e)
// using System.IO;
{
// using System.Xml.Serialization;
SetupAlways();
}
XmlSerializer x = null;
StringReader sr = null;
private void SetupAlways()
try
{ {
//setup callbacks: sr = new StringReader(strXml);
string cbReference = x = new XmlSerializer(t);
Page.ClientScript.GetCallbackEventReference( return x.Deserialize(sr);
this, }
“arg”, finally
“ReceiveCallback”, {
“context”); if (sr != null)
string callbackScript = “function sr.Close();
CallServer(arg, context)” }
+ “{ “ + cbReference + “} ;”; }
Page.ClientScript.RegisterClientScriptBlock(
this.GetType(),
“CallServer”, Listing 6
callbackScript, var strData = “<EmployeeData>”
true); + “<Id>” + myID + “</Id>”
} + “<Name>” + myName + “</Name>”
+ “</EmployeeData>”;

Listing 3
//CLIENT Listing 7
function StartCallback() EmployeeData emp = (EmployeeData)Utilities.Deser
{ ializeFromXmlString(
//TODO: assemble the data to send to the typeof(EmployeeData),
callback strXml);

32 March 2006 • dotnetdevelopersjournal.com


u c to r!y
introipd offer
cr tion
subs

A TRULY INDEPENDENT Here’s what you’ll find in


VOICE IN THE WORLD OF .NET every issue of .netdj:
.NET Developer’s Journal is the leading

independent monthly publication targeted at .NET Security Watch


Mobile .NET
developers, particularly advanced developers. It brings
.NET Trends
.NET developers everything they need to know in order
Tech Tips
to create great software.
Standards Watch
Published
Business Alerts
monthly, .NET
.NET News
Developer’s
Book and Software
Journal covers Announcements

everything of interest to .NET Developer’s Journal is for .NET


developers of all levels, especially those “in
developers working with the trenches” creating .NET code on a daily
basis:
Microsoft .NET technolo- • For beginners:
Each issue contains step-by-step tutorials.
gies – all from a • For intermediate developers:
There are more advanced articles.
completely independ-
• For advanced .NET developers:
In-depth technical articles and columns
ent and nonbiased per-
written by acknowledged .NET experts.
spective. Articles are care-

SUBSCRIBE ONLINE!
Regardless of their experience level, .NET
fully selected for their prime Developer’s Journal assumes that everyone
reading it shares a common desire to under-
technical content – technical www.sys-con.com/dotnet/ stand as much about .NET – and the busi-
ness forces shaping it – as possible. Our aim
details aren’t watered down with or Call is to help bring our reader-developers closer

lots of needless opinion and com-

mentary. Apart from the technical content, expert ana-


1 888 303-5282 and closer to that goal with each and every
new issue!

lysts and software industry commentators keep devel-

opers and their managers abreast of the business

forces influencing .NET’s rapid development. SAVE16% ANNUAL


COVER PRICE:

OFF $83.88
Wholly independent of both Microsoft Corporation

and the other main players now shaping the course of


YOU PAY

6999
.NET and Web services, .NET Developer’s Journal

represents a constant, neutral, expert voice on the $


THE ANNUAL COVER PRICE
state of .NET today – the good, the bad, and the
YOU SAVE
ugly…no exceptions. Get 12 issues of .NETDJ
for only $6999! $13.89
OFF THE ANNUAL
COVER PRICE
OFFER SUBJECT TO CHANGE WITHOUT NOTICE
��
��
��
��������������������� �
��
��
���������������������������� ��

����������������������� ��
�������������� ��
�������������������������� ������������ ��

��������������������������� ��������������
������������
��
��

����������

���� �������

�������������������������������������������������������
��������������
�����������������������������������������������������
���������������������������������������������������������� �������������������
������������������������������������� �������������������������������
����������������������������������������������������������������������
������������������������������������������������
�����������������������������������������������
������������������������������� ��������������������������������
�������������������������������������������������������������� �������
�����������������������
�����������������������������������������������������������������
��������������������������������������������������������������� ��������������������������������
�������������������������������������������������������������� �������
����������������������������������������������������������������������� ����������������������

� � � �� ����������������������������������������������������������������
�����������������������������

������������������
��������������������������������������������������������������������� �������������������������������������������������������������� �������
������������������������������������������������������������������������ �������������������

��� ������� ��������������������������������������������������


��
��
�������������������������������������
����� �
����������������������
������������������������������������������

��� ����� ����������������


����� ������������������������������
�������������
������������������
���������������������������������
������������������

COPYRIGHT ©2006 SYS-CON MEDIA ALL RIGHTS RESERVED


�������
������������� �����������
���� ���� ������������� ���
��������� ���� ���� ��������� ������������
����� ����������� ���� ����
���������������������������
������������� ����������� ������������
���� ���� ������������� ��� ������������������� ��������������������������
��������� ���� ���� ��������� ���������������������������������������������������������������������������������������������������
�������������������������������������������� ����������������������������������������
����������������������������������������������������������������������������������������������
����� ����������� ���� ���� ��������������������������������������������������������������������������������������������������
��������������������������������������������������������������������������������������������������� ���������������������������������������������������������������������������������������������
�����������������������������������������������������������������������������������������������

������������� ����������� ������������������������������������������������������������������������������������������������������


���������������������������������������������������������������������������������������������������� ��������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������ ��������������������������������������������������������������������������������������������������
���� ���� ������������� ��� �������������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������
����������������������������������������������������������������������������������������������������
��������������������������������������������������

��������� ���� ���� ��������� �������������������������������������������������������������������������������������������������������


���������������������������������������������������������������������������������������������������
������������������������������������������������������������������
����� ����������� ���� ���� ����������
���������������������������������������������������
������������� ����������� ������������� �����������������������������������������������������������
���� ���� ������������� ��� ��������������������������������������� ������������������������������������������������������������������������������������������������������
�����������������������������������������������������������������������������������������������������
�������������������������������� �������������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������������
����������������������������������������������������������������������������������������������������
����������������������������������������������������������������������������������������������������
��������������������������������������������������������������������������������������������������
�����������������������������������������������������������������������������������������������������
�������������������������������������������������������������������������������������������������
��������������������������������������������������������������������������������������������������
���������������������������������������������������������������������
���������������������������������������������������������������

������������������
���������� ��������������������������������������������
������������������������� ���������������������������
������������������������������������������������������������������������������������������������������� ��������������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������� ���������������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������������ �������������������������������������������������������������������������������������������������������
���������������������������������������������������������������������������������������������������� �������������������������������������������������������������������������������������������������
���������������������������������������������������������������������������������������������� �����������������������������������������������������������
����������������������������������������������������������������������������������������������������
����������������������������������������������������������������������������������������������
���������������������������������������������������������������������������������������������
����������������������� �����������
��������������������������������������
��������������������������������������
����������������������������������������������������������������������������������������������������
������������������������ ��������������������������������������������������������������������������������������������������������
�������������������������������������������������������������������������������������������������
������������������������ ���������������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������� ��������������������������������������������������������������������������������������������������
���������������������������������������������������������������������������������������������������� �������������������������������������������������������������������������������������������������������
�������������������������������������������������������������������������������������������������� ���������������������������������������������������������������������������������������������������
��������������������������������������������������������������������������������������������������� ��������������������������������������������������
�����������������������������������������������������������������������������������������������������
����������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������������
�������������������������������������������������������������������������������
�� �� ��
������������
����������������������������
������������� �����������������������������������������������������������������������������������������������������������
������������������������������������� �������������������������������������������������������������������������������������������������
�����������������������������������������������������������������������������������������������������
����������������������������������������������������� ������������������������������������������������������������������������������������������������������
�� �� �� ��������������������������������������������������������������������������������������������������
���������������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������� ����������������������������������������������������������������������������������������������������
��������������������������������������������������������������������������������������������������� ���������������������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������������� ���������������������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������������� ��������������������������������������������������������������
�����������������������������������������������������������������������������������������������������
�������������������������������������������������������������������������
�� �� �� ������������
����������������������������������������
��������� ��������������������������������
����������������������������������������������� ��������������������������������������������������������������������������������������������������
���������������������������������������������������������������������������������������������
����������������������������������������� ���������������������������������������������������������������������������������������������������
����������������������������������������������������������������������������������������������� �����������������������������������������������������������������������������������������������������
����������������������������������������������������������������������������������������������� ������������������������������������������������������������������������������������������������������
����������������������������� ��������������������������������������������������������������������������������������������������
�������������������������������������������������������������������������������������������������
���������������������������������������������������������������������������������������������������������
�����������������������������������������������������������������������������������������������������
����������������������������������������������������������������� �������������������������������������������� ����������������������������������������������������������������������������������������������

��� �����������������������������
� ���������������������������������������������������������������������

��� ������������������� ���������������� �������������


� ���������������������������������������������������
����������������������������������������� �����������������������������������������
��� ���������������������������������������������������
�������������������������������� ���������������������������������������
� �������������������������������������������������������������������� ��������������������������������������������������������������������������������������������������
���������������������������������������������������������������������������������������������� �����������������������������������������������������������������������������������������������������
��� �������� ������������������������������������������������������������������������������������������������������
� ���������������������������������������������������������������������������������������������� ����������������������������������������������������������������������������������������������������
�������������������������������������������������������������������������������������������������� ������������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������������ ���������������������������������������������������������������������������������������������������
��� ������������������
������������������������������������������������������������������������������������������������������� ������������������������������������������������������������������������������������������������
� �������������������������������������������������������������������������������������������
���������������������������������������������������������������������������������������������������� ����������������������������������������
� ����������������������������������������������
������������������������������������������������������������������
��� �������
� ��������������������������������������������������������������������������������������������
� �������������������������������������
��� �������������
������������������������
� ���������������������������������������������������������������������������������������������� ��������������� ���������������������������������������������
��� �����������������������������
� ��������������������������������������������������������������������������������������������������
����������������������������������
� �������������������� ��������������������������������������������������������������������������������������������� ��������������������������������������������������
��������������������������������������������������������������������������������������������������
��� ������������������������������ ������������������������������������������������������������������������������������������� NOTE: SPEAKER LINE-UP SUBJECT TO CHANGE WITHOUT NOTICE
� �������������������������������������������������������������������������������� �������������������������������������������� VISIT WWW.AJAXSEMINAR.COM FOR THE MOST COMPLETE UP-TO-DATE INFORMATION
Tips & Tricks

Understanding Base64 Encoding


What it is, when to use it, and how to write custom Base64 encoding

i
f you work in a .NET envi- shot in Figure 2 I decode the Base64 as a JPEG image. If you can encode
ronment you have prob- encoded strings back to their original the image as a Base64 string, then
ably come across Base64 byte arrays, using both the built-in you can send the image just like any
encoded data. For example, .NET Framework method and my cus- other message. Another common
Base64 encoding is used in ASP.NET tom implementation, and display in example is sending an ASP.NET Web
for a Web application’s ViewState hexadecimal form. The complete pro- application’s ViewState value (which is
value, as shown in Figure 1. Base64 gram, which produced the screenshot a binary value representing the overall
encoding is also used to transmit in Figure 2, is presented in Listing 3. state of the application) over HTTP
binary data over e-mail. However, if (which is an inherently text-based
you are like most of my colleagues What Is Base64 Encoding? transport protocol). But why go to
(and me until recently) you do not Exactly what is Base64 encod- the trouble of Base64 encoding when
have a thorough understanding of ing? Base64 encoding is a scheme “ordinary” encoding already exists?
precisely what Base64 encoding is that encodes arbitrary binary data as By ordinary encoding I mean regular
and when Base64 encoding should be a string composed from a set of 64 hexadecimal encoding. For example,
used. In the this article I will explain characters. The exact character set can the 40-bit binary data above can be
exactly what Base64 encoding is, be any 64 distinct ASCII characters, represented as a hexadecimal string:
show you how to use the two primary but by far the most common set is 48 65 6C 6C 6F (where the spaces
.NET Framework methods that sup- “A” through “Z,” “a” through “z,” “0” are included just for readability).
port Base64 encoding and decoding, through “9,” “+,” and “/.” For example, The answer is that Base64 encoding
and present a lightweight, custom C# using this character set the 40-bit is more efficient than hexadecimal
implementation of Base64 encoding data: encoding in the sense that Base64
and decoding methods. This article encoding requires fewer characters to
assumes you are a .NET developer, 01001000 01100101 01101100 01101100 represent the same data. Notice that
tester, or manager and have interme- 01101111 the hexadecimal encoding of the 40-
BY JAMES
diate level C# coding skill. After read- bit data above requires 10 characters
McCAFFREY
ing the article you’ll have a solid grasp can be Base64 encoded as the string: while Base64 encoding requires only 8
of Base64 encoding as well as the abil- characters – a 20 percent reduction.
ity to write your own custom encoding SGVsbG8= Because Base64 encoding only
methods. I think you’ll find the ability uses 64 characters, any of the charac-
to use Base64 encoded data is a valu- The trailing “=” character is a ters can be represented with just 6 bits
able addition to your skill set. padding character as I will explain because 26 = 64. Or, put another way,
The best way to show you where shortly. After seeing Base64 encoding using 6 bits you can represent data in
I’m headed in this article is with a for the first time, most engineers have the range 000000b to 111111b, which
screenshot. If you examine Figure 2 an immediate question: Why would is 0d to 63d. This is the key to Base64
you’ll see that I start with the arbitrary anyone want to use Base64 encod- encoding efficiency. The best way to
string “Hello” and use it to generate ing? Base64 encoding is useful when explain how Base64 encoding works is
some binary data. After displaying the you want to transmit binary data over with a picture as shown in Figure 3.
starting binary data in hexadecimal a communication channel that is Suppose the first three bytes of
form, I convert the binary data to a designed to transmit character data. input to be encoded are 48h, 65h,
Base64 encoded string using a method For example, consider e-mail. The and 6Ch. In Figure 3 these values are
from the .NET Framework, and also e-mail protocol SMTP was originally shown in their binary representation:
using my custom encoding method. designed to send and receive only 01001000, 01100101, and 01101100.
Notice the encoding results are the simple text data. However, suppose The first six bits of input, 010010,
same. In the next part of the screen- you want to transmit binary data such have value 18d, which in turn maps

36 March 2006 • dotnetdevelopersjournal.com


to character [18] in the Base64 character you write auxiliary code, which buffers to a Base64 character. For example, 0 AUTHOR BIO:
set, which is “S.” The second six bits of the process by breaking the input data maps to “A,” 1 maps to “B,” and 26 maps Dr. James McCaffrey works for
input – the last two bits of the first byte into manageable-sized chunks. to “a.” I use the normal character set Volt Information Sciences, Inc.,
of input and the first four bits of the but you can use different characters, or where he manages technical
second byte of input – equal 6d, which A Lightweight Custom Base64 change the order for a custom encoding training for software engineers
maps to character “G,” and so on. Notice Encoder scheme. Next I compute two values that working at Microsoft’s Redmond,
that three bytes of input map neatly to The .NET Framework’s ToBase64- will control the encoding algorithm: WA campus. He has worked
four character of output. Because of this String() and FromBase64String() on several Microsoft products,
it is convenient to implement Base64 methods will meet most of your Base64 int numBlocks; including Internet Explorer and
encoding in “blocks” that represent a encoding needs. However what if you int padBytes; MSN Search. James can be
group of three bytes of input, or four are developing a system and need a if ((value.Length % 3) == 0) reached at jmccaffrey@volt.com
characters of output. slightly different encoding scheme? For { or v-jammc@microsoft.com.
instance, you may want to use a differ- numBlocks = value.Length / 3;
NET Support for Base64 Encoding ent character set than the normal{“A”- padBytes = 0; 4 jmccaffrey@volt.com
The .NET Framework supports “Z,” “a”-“z,” “0”-9,” “+,” “/”} set. In this }
Base64 encoding with two methods. section I’ll present a lightweight, custom else
The Convert.ToBase64String() method Base64 encoder written in C# that you {
accepts a byte array as an input argu- can use as a starting point for your numBlocks = 1 + (value.Length / 3);
ment and returns a Base64 encoded own custom encoder. If you search the padBytes = 3 - (value.Length % 3);
string (using the usual 64-character set Internet you’ll find quite a few Base64 }
described in the previous section). The encoding examples. The one I present
Convert.FromBase64String() accepts a here is a hybrid of several I found com- The numBlocks variable represents
string argument (which is assumed to bined with one I wrote recently, and is the number of three-byte blocks in
be a valid Base64 encoded string) and designed for maximum clarity rather the input array, and also the number
returns the corresponding byte array. than for efficiency. The custom encoder of four-character blocks in the output
Using these two methods is very easy. is presented in Listing 1. string. The padBytes variable holds the
Notice both methods belong to the Because I want my customer number of bytes that I will have to pad
Convert class and are static so you do encoder to mimic the interface of the into the output string to bring the size
not need to instantiate an object to use Framework encoder, I begin by creating of the string up to an even multiple of
the methods. The Convert class is part an overall structure of: 4. If the size of input array is an even
of the System namespace. Consider this multiple of 3, then the number of blocks
code snippet: public class MyConverter is just the size of the input divided by 3
{ and there is no padding. For example,
byte[] bytes = new byte[] { 0x5F, public static string if the input has size 27 bytes then my
0xC9, 0xBF, 0x17 }; ToBase64String(byte[] value) encoder will process 27 / 3 = 9 three-
string base64 = Convert. { byte blocks and produce a string with
ToBase64String(bytes); // implementation goes here 9 * 4 = 36 characters. If the input is not
Console.WriteLine(base64); } an even multiple of 3 then there is one
} // class MyConverter extra block and either one or two pad-
This code would produce “X8m/
Fw==” as output. Notice that the input Of course there are many other
has size 4 bytes. The first three bytes (3 * design alternatives, but making the cus-
8 = 24 bits) of input are used to produce tom encoder signature the same as the
the first four Base64 characters (4 * 6 = Framework’s encoder signature makes
24 bits) of output. The last input byte sense. I begin my encoder implementa-
produces the rest of the output, and the tion by declaring an array of the 64 char-
output is padded with “=” characters acters I want to use for my encoding:
to bring the output size up to an even
multiple of 4. The technique to decode char[] base64Chars = new char[]
is similar. The statements { ʻAʼ,ʼBʼ,ʼCʼ,ʼDʼ,ʼEʼ,ʼFʼ,ʼGʼ,ʼHʼ
,ʼIʼ,ʼJʼ,ʼKʼ,ʼLʼ,ʼMʼ,
string encoded = “X8m/Fw==”; ʻNʼ,ʼOʼ,ʼPʼ,ʼQʼ,ʼRʼ,ʼSʼ,ʼTʼ,ʼU
byte[] result = Convert.FromBase64S ʼ,ʼVʼ,ʼWʼ,ʼXʼ,ʼYʼ,ʼZʼ,
tring(encoded); ʻaʼ,ʼbʼ,ʼcʼ,ʼdʼ,ʼeʼ,ʼfʼ,ʼgʼ,ʼh
Console.WriteLine(BitConverter. ʼ,ʼiʼ,ʼjʼ,ʼkʼ,ʼlʼ,ʼmʼ,
ToString(result)); ʻnʼ,ʼoʼ,ʼpʼ,ʼqʼ,ʼrʼ,ʼsʼ,ʼtʼ,ʼu
ʼ,ʼvʼ,ʼwʼ,ʼxʼ,ʼyʼ,ʼzʼ,
produce “5F-C9-BF-17” as output. The ʻ0ʼ,ʼ1ʼ,ʼ2ʼ,ʼ3ʼ,ʼ4ʼ,ʼ5ʼ,ʼ6ʼ,ʼ7
Framework Base64 methods are simple ʼ,ʼ8ʼ,ʼ9ʼ,ʼ+ʼ,ʼ/ʼ };
and straightforward. However, if you are
encoding, transmitting, and decoding This array acts as a lookup table to
large amounts of binary data, it is up to map a decimal value in the range 0 – 63 f1 Figure 1: Base64 encoded ViewState value

dotnetdevelopersjournal.com • March 2006


37
Tips & Tricks
even multiple of three bytes if neces- similar and if you trace through the
sary. I do this so I can process three masking and bit shifting code with
bytes of input at a time. I explicitly a paper and pencil you’ll see how
zero-out array newValue but this is each bye of output is determined.
not necessary because when arrays Once I have the output in byte form,
are declared but not initialized they I can compute the equivalent char-
are filled with the default value for the acter form using my base64Chars
array contents (which is 0 in this case). lookup table:
Next I copy the original input bytes
into the working array newValue. Then for (int i = 0; i < numBlocks * 4;
I declare a byte array named result- ++i)
Bytes with size four times the number resultChars[i] = base64Chars[resu
of input blocks. As explained earlier, ltBytes[i]];
f2 Figure 2: Base64 encoding demonstration each three bytes of input produces
four characters of output. The result- Now all that’s left to do is to pad
(input bytes) Bytes array will hold the output char- the trailing output characters with “=”
acters in byte form pending their con- where necessary:
010010 00 0110 0101 01 10 1100 ......
version to characters. The resultChars
[0] [1] [2] [3]
array will hold the Base64 encoded if (padBytes == 0)
resultBytes[] string result except that it may need ;
XX010010 XX000110 XX010101 XX101101 ... padding with one or two “=” charac- else if (padBytes == 1)
ters. The main processing loop iterates resultChars[numBlocks * 4 - 1]
[0] [1] [2] [3]
through each block of input: = ʻ=ʼ;
18d 6d 21d 45d
resultChars[] else if (padBytes == 2)
‘S’ ‘G’ ‘V’ ‘t’ ... for (int i = 0; i < numBlocks; i++) {
{ resultChars[numBlocks * 4 - 1]
[0] [1] [2] [3]
resultBytes[i * 4 + 0] = = ʻ=ʼ;
f3 Figure 3: Base64 encoding mechanism (byte)((newValue[i * 3 + 0] & resultChars[numBlocks * 4 - 2]
0xFC) >> 2); = ʻ=ʼ;
}
ding bytes required. I do a rudimen- resultBytes[i * 4 + 1] =
tary validation check: (byte)((newValue[i * 3 + 0] & I use the padBytes value I com-
0x03) << 4 | puted earlier and add either two,
if (padBytes < 0 || padBytes > 3) (newValue[i * 3 + 1] & one, or zero “=” characters at the
throw new Exception(“Fatal logic 0xF0) >> 4); end of the result char array. The null
error in padding code”); statement when padBytes has value
resultBytes[i * 4 + 2] = 0 is a bit ugly and you can leave it
Because this article is primarily a (byte)((newValue[i * 3 + 1] & out if you wish. I finish the encoding
tutorial, I have omitted most of the 0x0F) << 2 | routine by converting the result char
error-checking code for clarity. In a (newValue[i * 3 + 2] & array to a string using the overload-
production system you will need to 0xC0) >> 6); ed String object constructor, which
add a lot of additional error checks. accepts a character array, and then I
Next, I set up three arrays where most resultBytes[i * 4 + 3] = return the result string:
of the encoding work is done: (byte)((newValue[i * 3 + 2] &
0x3F)); string s = new string(resultChars);
byte[] newValue = new } return s;
byte[numBlocks * 3];
for (int i = 0; i < newValue. Here is where most of the work is With the custom encoder in place,
Length; ++i) // not really necesary performed. There aren’t many lines you can write code that mirrors
newValue[i] = 0; of code here but they’re a bit tricky. encoding using the .NET Framework
for (int i = 0; i < value.Length; The process is best explained with methods. For example:
++i) a diagram as shown in Figure 3. To
newValue[i] = value[i]; obtain the first character of output, byte[] input = new byte[] { 0x5F,
I need to extract the leftmost six bits 0xC9, 0xBF, 0x17 };
byte[] resultBytes = new of the first byte of the input. To do string output = MyConverter.
byte[numBlocks * 4]; this I can mask by logical ANDing ToBase64String(input);
char[] resultChars = new (in C#, with the “&” operator) with Console.WriteLine(output);
char[numBlocks * 4]; value 0xFC, which is 1111 1100 in
binary. Now if I perform a logical The Custom Base64 Decoder
I declare a byte array newValue right shift two bits (using “ >> 2”), In most situations a custom
which will be a copy of the input byte I will have the leftmost six bits. Base64 encoder is useless with-
array, but expanded in size up to an The other logical operations are out its corresponding decoder.

38 March 2006 • dotnetdevelopersjournal.com


Listing 2 presents one way to write a you encounter Base64 encoding in this is by no means data encryption
Base64 decoder. Because the concepts a system or specification, make sure or a security mechanism – it’s just a
involved in decoding are essentially the you clearly determine what particu- way to deter casual inspection of your
same as those for encoding, I won’t go lar flavor of Base64 encoding is being data.
over the decoding implementation in used. For example, MIME Base64 To summarize, Base64 encoding
detail. encoding specifies that the encoded is a way to represent arbitrary binary
The private ValueOf() method output stream must be represented data as a string composed of charac-
accepts one of the Base64 characters in lines of no more than 76 charac- ters from a 64-character set. Base64
and returns the numeric value that ters each. However, a generic Base64 encoding is useful when you want to
corresponds to the lookup table in the encoding scheme may not have this transmit binary data over a communi-
ToBase64String() method. For example, restriction. cation channel that is inherently text-
if the input character is “A,” the helper The .NET Framework Convert. based, such as SMTP or HTTP. Base64
method will return “A” - 65 = 65 - 65 = 0. ToBase64String() and Convert.From- encoding is more efficient in terms
If you write a custom Base64 encoder Base64String() methods will meet of encoding size than basic hexadeci-
with a different character set, then you’ll the majority of your Base64 needs. mal encoding. The .NET Framework
have to modify the logic in ValueOf() However, knowing how to implement has simple and effective Base64
accordingly. a custom scheme may be useful in methods that will suit most of your
several situations. One possible scenar- needs. However if you need to imple-
Conclusion io is that you inherit a legacy system ment a custom Base64 scheme, you
The most common use of a Base64 with a custom encoding scheme and can use the custom implementation
encoding is to send binary data over you need to decode data from that code presented in this article as a
e-mail in MIME format. The specifica- system. Another possible use of a basis to get started. (Source code is
tions for this particular type of Base64 custom Base64 encoding scheme is available by viewing this article online
encoding are contained in RFC 1421 to provide rudimentary obfuscation in the DNDJ archives, http://dotnet.
and RFC 2045. Because Base64 encod- of data. If you use a custom scheme sys-con.com/read/issue/archives/,
ing is so often associated with MIME, it to encode data being transmitted over Vol. 4, iss. 3.)
is easy to incorrectly assume that this an open communications channel,
is the only kind of Base64 encoding. If you can scramble your data. Of course –Listings on page 40

dotnetdevelopersjournal.com • March 2006


39
Tips & Tricks
Listing 1: A Custom Base64 Encoder

public class MyConverter for (int i = 0; i < numBlocks; i++)


{ {
public static string ToBase64String(byte[] value) resultBytes[i * 4 + 0] =
{ (byte)((newValue[i * 3 + 0] & 0xFC) >> 2);
// Base64 chars resultBytes[i * 4 + 1] =
char[] base64Chars = new char[] (byte)((newValue[i * 3 + 0] & 0x03) << 4 |
{ ʻAʼ,ʼBʼ,ʼCʼ,ʼDʼ,ʼEʼ,ʼFʼ,ʼGʼ,ʼHʼ,ʼIʼ,ʼJʼ,ʼKʼ,ʼ (newValue[i * 3 + 1] & 0xF0) >> 4);
Lʼ,ʼMʼ, resultBytes[i * 4 + 2] =
ʻNʼ,ʼOʼ,ʼPʼ,ʼQʼ,ʼRʼ,ʼSʼ,ʼTʼ,ʼUʼ,ʼVʼ,ʼWʼ,ʼXʼ,ʼ (byte)((newValue[i * 3 + 1] & 0x0F) << 2 |
Yʼ,ʼZʼ, (newValue[i * 3 + 2] & 0xC0) >> 6);
ʻaʼ,ʼbʼ,ʼcʼ,ʼdʼ,ʼeʼ,ʼfʼ,ʼgʼ,ʼhʼ,ʼiʼ,ʼjʼ,ʼkʼ,ʼ resultBytes[i * 4 + 3] =
lʼ,ʼmʼ, (byte)((newValue[i * 3 + 2] & 0x3F));
ʻnʼ,ʼoʼ,ʼpʼ,ʼqʼ,ʼrʼ,ʼsʼ,ʼtʼ,ʼuʼ,ʼvʼ,ʼwʼ,ʼxʼ,ʼ }
yʼ,ʼzʼ,

ʻ0ʼ,ʼ1ʼ,ʼ2ʼ,ʼ3ʼ,ʼ4ʼ,ʼ5ʼ,ʼ6ʼ,ʼ7ʼ,ʼ8ʼ,ʼ9ʼ,ʼ+ʼ, for (int i = 0; i < numBlocks * 4; ++i)


ʼ/ʼ }; resultChars[i] = base64Chars[resultBytes[i]];

int numBlocks; // pad the resultChars array tail with ʻ=ʼ chars
int padBytes; if (padBytes == 0)

;
if ((value.Length % 3) == 0) else if (padBytes == 1)
{ resultChars[numBlocks * 4 - 1] = ʻ=ʼ;
numBlocks = value.Length / 3; else if (padBytes == 2)
padBytes = 0; {
} resultChars[numBlocks * 4 - 1] = ʻ=ʼ;
else resultChars[numBlocks * 4 - 2] = ʻ=ʼ;
{ }
numBlocks = 1 + (value.Length / 3);

padBytes = 3 - (value.Length % 3); string s = new string(resultChars);


} return s;
if (padBytes < 0 || padBytes > 3) } // ToBase64String()
throw new Exception(“Fatal logic error in pad-

ding code”); } // class MyConverter

// create a lengthened and padded input byte array

byte[] newValue = new byte[numBlocks * 3]; Listing 2: A Custom Base64 Decoder


public static byte[] FromBase64String(string s)
for (int i = 0; i < newValue.Length; ++i) // not
{
really necesary
// determine how many trailing ʻ=ʼ signs
newValue[i] = 0;
int last = s.IndexOf(ʻ=ʼ);
for (int i = 0; i < value.Length; ++i)
int padCount = 0;
newValue[i] = value[i];

if (last == -1)
byte[] resultBytes = new byte[numBlocks * 4]; padCount = 0;
char[] resultChars = new char[numBlocks * 4]; else if (last == s.Length - 1)

40 March 2006 • dotnetdevelopersjournal.com


padCount = 1; Listing 3: Base64 Encoding Demo
else if (last == s.Length - 2) static void Main(string[] args)
padCount = 2;
{

try
int numBlocks = s.Length / 4;
{
byte[] result = new byte[numBlocks * 3];
Console.WriteLine(“\nStart Base64 encoding demo\n”);

for (int i = 0; i < numBlocks; ++i)


{ string seed = “Hello”;
byte[] scratch = new byte[4]; Console.WriteLine(“ Seed string to generate some bytes
scratch[0] = ValueOf(s[i * 4 + 0]);
is: ʻ” + seed + “ʼ”);
scratch[1] = ValueOf(s[i * 4 + 1]);
byte[] b = System.Text.Encoding.ASCII.GetBytes(seed);
scratch[2] = ValueOf(s[i * 4 + 2]); // possibly ʻ=ʼ
Console.WriteLine(“ In hexadecimal encoding the bytes
scratch[3] = ValueOf(s[i * 4 + 3]); // possibly ʻ=ʼ
are: “ + BitConverter.ToString(b) + “\n”);

result[i * 3 + 0] = Console.WriteLine(“===============\n”);
(byte)((scratch[0] << 0x02) |
(scratch[1] & 0x30) >> 4) ;
string s1 = Convert.ToBase64String(b);
result[i * 3 + 1] =
Console.WriteLine(“ Using Framework the Base64 encoding
(byte)((scratch[1] & 0x0F) << 4 |
is: “ + s1 + “\n”);
(scratch[2] & 0x3C) >> 2);
string s2 = MyConverter.ToBase64String(b);
result[i * 3 + 2] =
(byte)((scratch[2] & 0x03) << 6 | scratch[3]); Console.WriteLine(“ Using custom method Base64 encoding

is: “ + s2 + “\n”);
} Console.WriteLine(“===============\n”);

byte[] finalResult = new byte[result.Length - padCount];


byte[] b1 = Convert.FromBase64String(s1);
for (int i = 0; i < finalResult.Length; ++i)
string h1 = BitConverter.ToString(b1);
finalResult[i] = result[i];
return finalResult; Console.WriteLine(“ Using Framework the original bytes

} // ToByteArray() are: “ + h1 + “\n”);

private static byte ValueOf(char c) // value for Base64 byte[] b2 = MyConverter.FromBase64String(s2);


character
string h2 = BitConverter.ToString(b2);
{
Console.WriteLine(“ Using custom method original bytes
if (c >= ʻAʼ && c <= ʻZʼ)
are: “ + h2 + “\n”);
return (byte)((int)c - 65);
else if (c >= ʻaʼ && c <= ʻzʼ)
return (byte)((int)c - 71); Console.WriteLine(“\nEnd demo”);
else if (c >= ʻ0ʼ && c <= ʻ9ʼ) Console.ReadLine();
return (byte)((int)c + 4);
}
else if (c == ʻ+ʼ)
catch (Exception ex)
return 62;
{
else if (c == ʻ/ʼ)
return 63; Console.WriteLine(“Fatal: “ + ex.Message);

else Console.ReadLine();

return 0; }
} } // Main()

dotnetdevelopersjournal.com • March 2006


41
SOA

Leveraging SOA to Web-Enable


Back-End Applications
An in-depth look at a real-world services implementation

m
ost organizations today and allow the engineer to study the
have internal applications electrical response based on certain
that span across differ- input signals without even touching
ent systems, networks, the soldering iron.
and technologies. These applica- ADI faced several ongoing chal-
tions would provide more value to lenges that impeded their online tool
customers if only the data that they development. First, tools were often
manage were exposed. In the past, tightly coupled around a particular
this was often difficult due to the product or small group of products.
inability of systems to communicate organizations to build service wrap- These tools provided value to the cus-
with one other. However with Web pers around existing functionality, tomer for a particular part but did not
service standards in place for sev- thereby getting more value out of scale to support multiple parts within
eral years now, services are finally existing systems. Finally, services a given product line. It would often
gaining acceptance throughout the are decoupled from consuming take many months before a new tool
industry. Consequently, service- applications, allowing them to be could be created for new or emerging
oriented architectures (SOAs) have built independently of one another. products.
finally come to fruition as compa- The remainder of this article will Another problem the com-
nies start to rethink how they build explain how the aforementioned pany faced is that the information
enterprise applications. concepts apply to a real-world SOA required building design tools for
In the past, organizations implementation recently built by customers resided within different
typically approached large-scale Analog Devices. existing internal applications and
development efforts as one mono- systems. As with most large organi-
lithic project. This was often due The Need for a Service-Oriented zations, ADI suffered from the dis-
to constraints of the underlying Architecture semination of data throughout their
technology as well as the difficulty Analog Devices, Inc. (ADI) designs, organization. The company needed
of making systems communicate. If manufactures, and markets high- a way to encapsulate the common
applications did communicate, they performance analog, mixed-signal, functionality required by all design
BY BRIAN WILSON
were invariably tightly coupled. and digital signal processing (DSP) tools and make it available for
The concept of SOAs has integrated circuits (ICs) used in signal reuse.
changed the model of large-scale processing applications. ADI’s target Finally, ADI was looking to
application design. Web service audience comprises design engineers leverage a third-party applica-
standards now provide the ability who evaluate semiconductor products tion to build simulation engines
for companies to build core services for many different applications. In that would provide the core value
that provide both business agility an effort to support these customers, for their online design tools. The
and functional reuse; as a result, the company constantly builds Web- product of choice was National
applications become thinner by based design tools to allow for prod- Instrument’s LabVIEW, a powerful
nature and rely on integrated ser- uct evaluation prior to purchasing. third-party application that pro-
vices to do the heavy lifting. These design tools simulate the elec- vides a sophisticated tool suite to
Web service standards also allow trical behavior of an integrated circuit build test and simulation applica-

“Ascompanies look to building future enterprise


applications, strong consideration should be given
to a service-oriented architecture approach”

42 March 2006 • dotnetdevelopersjournal.com


tions. However, LabVIEW was not AUTHOR BIO:
originally designed for distributed Brian Wilson currently has
Web-based applications and expos- over 12 years of consulting,
ing application functionality from architecture, and implementation
this product via the Web was not experience within the industry.
seamless. He is a technical consultant at
A new strategy was needed that Molecular, an Internet consulting
would solve these business and tech- firm in Watertown, MA.
nical issues.
4 bwils06@gmail.com
Approach
ADI, with the help of Molecular,
Inc., decided to build a service-
oriented design tool framework that
would serve as the foundation for
future online design tool develop-
ment. In this architecture there are
two types of services: core business
services and simulation services.
Core business services encap-
sulate functionality that could be
reused by multiple design tools.
These services integrate with the
appropriate internal systems neces-
sary to provide the desired function-
ality as well as adhere to common
Web service specifications. These f1 Figure 1: A high-level illustration of the Design Tool architecture

Advertiser Index
ADVERTISER URL PHONE PG

.NET Developer’s Journal www.sys-con.com/dotnet 888-303-5282 33


.NET Rocks! www.dotnetrocks.com 877-273-4838 29
AJAX Seminar www.ajaxseminar.com 201-802-3022 34,35
CFDynamics www.cfdynamics.com 866-233-9626 21
ESRI www.esri.com/develop 888-288-1277 9
Forum Systems www.forumsys.com 866-333-0210 19
GraphOn www.graphon.com/itsg 800-GRAPHON 23
Hosting.com www.hosting.com 800-446-7627 13
IBM www.ibm.com/middleware/tools 5
IT Solutions Guide www.itsolutions.sys-con.com 888-303-5282 43
iTVcon.com Conference & Expo itvcon.com 201-802-3023 25
JavaOne Conference 2006 java.sun.com/javaone/sf 27
KaPow Technologies www.kapow.com 800-805-0823 Cover III
MapInfo www.mapinfo.com/sdk 800-327-8627 Cover II
Parasoft www.parasoft.com/jdjmagazine 888-305-0041 Cover IV
RadView Software www.radview.com/analyze 888-RADVIEW 3
SOA/EOS Conference www.soaeosconference.sys-con.com 201-802-3022 46,47
Synaptris www.intelliview.com/netj 866-99IVIEW 15
SYS-CON Newsletters www.sys-con.com 888-303-5282 39
SYS-CON Website www.sys-con.com 888-303-5282 49
Telerik www.telerik.com/AJAX 6
Verio www.verio.com/partners 866-237-4121 11
Visual Paradigm www.visual-paradigm.com 408-426-8212 25
General Conditions: The Publisher reserves the right to refuse any advertising not meeting the standards that are set to protect the high edito-
rial quality of .Net Developer’s Journal. All advertising is subject to approval by the Publisher. The Publisher assumes no liability for any costs
or damages incurred if for any reason the Publisher fails to publish an advertisement. In no event shall the Publisher be liable for any costs or
damages in excess of the cost of the advertisement as a result of a mistake in the advertisement or for any other reason. The Advertiser is fully
responsible for all financial liability and terms of the contract executed by the agents or agencies who are acting on behalf of the Advertiser.
Conditions set in this document (except the rates) are subject to change by the Publisher without notice. No conditions other than those set forth
in this “General Conditions Document” shall be binding upon the Publisher. Advertisers (and their agencies) are fully responsible for the content
of their advertisements printed in .Net Developer’s Journal. Advertisements are to be printed at the discretion of the Publisher. This discretion
includes the positioning of the advertisement, except for “preferred positions” described in the rate table. Cancellations and changes to adver-
tisements must be made in writing before the closing date. “Publisher” in this “General Conditions Document” refers to SYS-CON Publications,
Inc. This index is provided as an additional service to our readers. The publisher does not assume any liability for errors or omissions.

dotnetdevelopersjournal.com • March 2006


43
SOA
reusable services speed up the are not experts in Web application ponents that were not dependent
development of future design tool technology. As a result, Web develop- on a particular application. By
applications. ers built the online Web application building a set of core services to
The second set of services and provided the necessary service extract data from existing internal
allowed ADI design engineers to plumbing to expose the simulation systems and databases, future
expose simulation engines built logic. A service-oriented architecture design tools can now easily incor-
in LabVIEW as services. In this made sense for ADI because each porate existing functionality with
architecture simulation services service defined a clear delineation of minimal effort.
are tightly coupled to a particular work between team members. • Web service standards allowed
design tool application. Rather than create a detailed the company to build service
service interface, the team chose to wrappers around existing internal
Architecture expose only one parameter in the systems and applications that
Figure 1 gives a high-level WSDL, a serialized XML Stream of provide a mechanism to expose
illustration of the Design Tool data that adhered to a valid W3C this knowledge externally to cus-
architecture. Each online design XML Schema. By simplifying the Web tomers.
tool is developed as an ASP.NET service interface the team was able • The ability to define service
application and integrates with to focus exclusively on designing the interfaces up front allowed the
the core set of services as needed. XML data structures that would be company to better align its core
The interface to the specific Design passed back and forth, thus abstract- competencies to its areas of
Tool simulation engine (developed ing the Web service technologies expertise. Simulation services
in LabVIEW ) is wrapped in a stan- during initial design. were decoupled from the client
dardized Web service SOAP header Once the XML data contracts applications, allowing each to be
and made available to the client were agreed upon, LabVIEW appli- built independently.
design tool application. cation developers were able to • By streamlining the Web service

“Service-oriented architectures have finally come to


fruition as companies start to rethink how they
build enterprise applications”
Service Development go off and design the simulation interfaces, ADI is able to quickly
The first step was to identify engine independent of the consum- define XML data contracts passed
the core set of services that could ing design tools application. Each between simulation services and
be reused by multiple design tools. simulation engine was compiled as consuming applications.
Common functionality was identi- a shared library.dll, imported into
fied from several internal sources, a .NET Web Service assembly via Conclusion
including ADI’s product database, DLLImport, and then exposed as an As companies look to build-
content management system, FTP internal Web service. ing future enterprise applications,
server, and parametric search appli- The team also took advantage strong consideration should be given
cations. For each of these core ser- of the XSD Sample Code Generator to a service-oriented architecture
vices, a standardized SOAP interface (XsdObjectGen) tool provided by approach. Services provide compa-
was created and made available to Microsoft. Once the data contract nies with a mechanism to unleash
calling applications. was defined as a valid W3C XML knowledge that in the past was
Next, the team defined the ser- Schema, the XsdObjectGen tool gen- trapped within internal applications.
vice interface for the design tool erated a set of managed .NET classes By identifying existing knowledge
simulation engine. This type of (either VB.NET or C#) that was then that could potentially be bundled
service was different from the core used to interface with the service. as business services, companies can
services because it was not intended Application developers interacted reap the benefits of functional reuse,
to be used by future design tools. with the service via method calls loose coupling, and technical plat-
As mentioned earlier, each online rather than by directly manipulating form independence.
design tool consists of a simulation XML. This article has also shown a
application developed in LabVIEW. real-world example how Analog
The development team consisted Benefits Devices implemented a service-
of two groups: design engineers and By leveraging an SOA, ADI oriented architecture to build
Web application developers. Design was able to achieve the follow- out a new online design tools
engineers have the ability to build ing benefits for their Design Tools framework, as well the benefits the
sophisticated simulation engines Framework: company received from using this
using the LabVIEW product, but they • The ability to build reusable com- approach.

44 March 2006 • dotnetdevelopersjournal.com


�������������
��������������� ������� ��������������
�������������������������
��
����������������
������������������������������
� �����������������
��������������������������������

�� ���������������������������
�������������������������

� �������������������������
� �������������������
� ������������ �
���������������������������������2�3���� ���������������
�� ��������������������������������������������
��������������������������� ��
��
�����������������������
���������������������������
�� ��������������������������������������������
�� ������������
���������������������� ��
��
�������������������������������������������������
����������������������������
������������������������������������������������� �� ��������������������
���������������������������������������������������������������� �� ������������
�� �������������
�������������������������������������������������������������������������������������������������������� �� ����������������������������������
�������������������������������������������������������������������������������������������������������� �� ���������������������������
������������������������������������������������������������������������������������������������� �� �����������������������
��������������������������������������������������������������������������������� �� �����������������
�� �� ����������������������������������
��������������������������������������������������������������������������������������������������������� �� �������������������������������������
������������������������������������������������������������������������������������������������� �� �������������������������������
���������������������������������������������������������������������������������������������������������
�����������������������������������������������������������������������������������������������������������
���������������������������������������������������������� �������� ����������������������������������
ALL RIGHTS RESERVED

� ��������������������������
�����������������������������������������������������������������
�������� ����������������������������������
���������������������������������������������������������������������� � ����������������������������
��������������������������������
�� �������� ����������������������������������
COPYRIGHT ©2006 SYS-CON MEDIA

������������������������������������������������������������������ � ���������������������������
�������������
������������������������������������������������������������������������� �������� �����������������������������������������������
����������������������������
������������������������������������������������������������������ � ����������������������������������������������
������������������
������������������������������������������ �� ����������������������������������������������
����������� � ����������������������������������������������
���
����
���
��
���
���� �����

���

���
���
��
����
���

���

���
��
���
���
���
���
��

�����
��


������������
������������
����������
�����������
�������������������������������������

����������������������������������������������� �������������
���������������������������������������������������������������������������������������������������������
����������������
�������������������������������������������������������������������������������������������������������������
���������������������������������������������������������������������������������������������������������
������
�������������������
���������������������������������������
���������������������������������������������
�������������������������������������������������������������������������������������������������������� ���������������������������������������������������
������������������������������������������������������������������������������������������������������������
�����������������������������������������������������
����������������������������������������������������������������������������������������������������������
������ ���������������������������������������������������
���������������������������������������������
������������������������������������������������������������������������������������������������������ ���������������������������������
�����������������������������������������������������������������������������������������������������������
�������������������������������������������������������������������������������������������������������������
���������������������������������������������������

���������������������������������������������������������������������������������������������������������
���������������������������������������������������������������������������������������������������������������
�������������������������������������������������������������������������������������������������������
�����������������������������������������������������������������

�����������������������������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������������������ ����������������������������
������������������������������������������������������������������������������������������ ���������������������������

������������������������������������
�������
������������ ��������������� ����������� ������������
������ ��������� �������� ������
������������������������������������������������ ������������������������������������������������� ��������������������������������������������� �����������������������������������������������
��������������������������������������������� ����������������������������������������� ���������������������������������������������������� �������������������������������������
������������������������������������������� ������������������������������������������� ��������������������������������������������
������������������������������������������ ��������������������������������������������� ���������������������������������������������������
����������������������������������������������� ����������������� ���������������������������������������������
������������������������������������������������������������ �������������������������������������������������������������������
���������������������������������������������������������������������� ���������������������������������������������������������������
����������������������������������������������������������������� ������������������������������������������������������������������
����������������������������������������������������������������� ��������������������������������������������������������������������
������������������������������������������������������������������� �����������������������������������������������������������������
����������������������������������������������������� ����������������������������������������������������������������
�����������������������������������������������������������

�������������� ���������� ���������������� �����������


����� ���� ��������� �����
�������������������������������������������������� ����������������������������������������������� �������������������������������������������������� ���������������������������������������������������
������������������������������������������ ���������������������������������������������� ������������������������������������������������� ��������������������������������������������������
���������������������������������������������� �������������������������������������������� ������������������������������������������������� ������������������������������������������������
������������������������������������������������� ���������������������������������������������� ������������������������������������������� ����������������������������������������������
������������������������������������������������� �������������������������������������������� �������������������������������������������� ������������������������������������������������
����������������������������������������������������������������� ����������������������������������������������������������������� �������������������������������������������������������������������� �����������������������������������������������������������������
��������������������������������������������������������������� ��������������������������������������������������������������� ������������������������������������������������������������������������ �������������������������������������������������������������������
���������������������������������������������������������������������� ��������������������������������������������������������������� ��������������������������������������������������������������������� �����������������������������������������������������������������
����������������������������������������������������������������������� ������������������������������������������������������������������� ������������������������������������������������������������� ������������������������������������������������������������������������
����������������������������������������������������������� ��������������������������������������������������������������� ������������������������������������������������������������������� ��������������������������������������
���������������������������������������������� ���������������������������������������������������������������� ������������������������������������������������������������������������
������������������������������������������������������������������ �����������������������

���������� ���������������� ����������� ������������


������������ ����������� ���������� ������
�������������������������������������������� ����������������������������������������� �������������������������������������������������� ���������������������������������������������������
���������������������������������������������� ������������������������������������������������� ������������������������������������������������ ����������������������������������������������
�������������������������������������������� ������������������������������������������������ ��������������������������������������������������� ������������������������������������������
�������������������������������������������� ���������������������������������������������� ������������������������������������������������ ���������������������������������������������������
����������������������������������������� �������������������������������������������������� ��������������������������������������������������� �����������������������������������������������
����������������������������������������������������������������� ��������������������������������������������������������������� ��������������������������������������������������������������� ��������������������������������������������������������������������
������������������������������������������������������������������ ������������������������������������������������������������������� ������������������������������������������������������������������� ����������������������������������������������������������������������
�������������������������������������������������������������� ����������������������������������������������������������������� ���������������������������������������������������������������� �������������������������������������������������������������������
�������������������������������������������������������������������� ����������������������������� ��������������������������������������������������������������������� ���������������������������������������������������������������
����������������������������������������������������������������� ������������������������������������������������������������������ �����������������������������������������������������������������
�������������������������������������������� ������������������������������������������������������������������� �����������������������������������������������������������������
������������������������������������������������ �������������������������������������

������������ ��������� ������������� �������������


����� ������� ������ ��������
������������������������������������������������ ����������������������������������������������� ����������������������������������������������� ����������������������������������������������
������������������������������������������������� ������������������������������������������������� �������������������������������������������������� �����������������������������������������������
��������������������������������������������������� ����������������������������������������������� �������������������������������������������� ����������������������������������������������
���������������������������������������������������� ���������������������������������������������� ��������������������������������������������� ��������������������������������������������
��������������������������������������������������� ����������������������������������������������� ������������������������������������������ ��������������������������������������������������
���������������������������������������������������������������� �������������������������������������������������������������� ����������������������� �����������������������������������������������������������������
������������������������������������������������ ���������������������������������������������������������������������� ��������������������������������������������������������������������
������������������������������������������������������������� �����������������������������������������������������������������
����������������������������������������������������������������
�������������������������������������������������������������
���������������������������������������������������������������

������������������������������������
���������������
������������������������������

����������������������������������������
��������������������������������������
������������������������������������������������ ������� ��������������������������� �����������������
���������������������������������������
�������������������������������������� �����������������
������������������������������������������������ �������
���������������������� ����������������������� ���������������������
����������������������������������� ����������������������� �����������������������������
������������������������������������
ALL RIGHTS RESERVED

������� ����������������������� �������������������������


�������������������������������������� ��������������� ������������ ������������������������
������������������������������������������������ ������� ��������������������������� ������������������� ����������������
��������������������� ������������������������ �����������������
������������������������������������������ ������������������������� ������������������ ������������������
������������������������� ���������� �������������������
���������������������������������������� ����������������� �����������������������������
������������������������� ������������������������� �����������������������������������
COPYRIGHT ©2006 SYS-CON MEDIA

� ��������������������� ������������������������� �������������������� �������������������


� ��������������������������������������������� ���������� ��������������������������� ��������������
� ����������������������������������� ��������������������� �����������������������������
� ���������������������������������� ���������������� �������������������������������
����������������������������� ���������������� ����������������������

��������������������������������������
Book Review

Mono: A Developer’s Notebook A How-To Book Using Mono on Linux

t
he authors of this book, The chapter on remoting shows
Edd Dumbill and Niel how to display ASP.NET Web pages
Bornstein, are well using the Mono Web Server, XSP.
known in both the Linux It also covers sockets and remot-
and .NET communities, and are ing, and touches on security and
well suited to write a book on the cryptography. This chapter also
Mono project. Edd Dumbill also includes a short introduction to
coauthored Linux Unwired and database access using .NET, includ-
XML-RPC, and is an Editor at Large ing how to create, connect to, and
for O’Reilly books. Niel Bornstein work with MySQL databases, as
also wrote .NET and XML, and is well as disconnected databases.
now a consultant for Novel in the Although this section is well writ-
Linux and open source practice ten, anyone doing any significant
group. database programming will need
This book is one of the O’Reilly other books to fully understand
series of “Developer’s Notebooks,” how to use databases in .NET and
so it is basically a cookbook of Mono.
Title: Mono: A Developer’s Notebook
“how-tos” and is intentionally thin The final chapter is on
Author: Edd Dumbill and Niel M. Bornstein
on theory. This allows the book advanced topics, including config-
Publisher: O’Reilly
to concentrate on the details of uring and building projects under
ISBN #: 0-596-00792-2
exactly how to perform common Linux using config and make, a
tasks; for instance, the book gives Price: US $24.95 section with hints on writing code
the commands needed to download to work on both Windows and
and install Mono, and to compile such as working with files, strings, Linux, running Java code in .NET
and run a simple program on the and regular expressions, but these using IKVM, the Mono basic com-
three main supported platforms: are some of the areas where many piler, and compiling to take advan-
Windows, Linux, and Mac. The developers will hit their first snags, tage of generics.
format used in most of this book is and those snags are what this book The purpose of this book is
to present a “lab exercise” type of is designed to help with. It also to help developers get up to speed
BY DENNIS HAYES task, and then give the solution to covers two of the Mono tools, the on using Mono. It is an excellent
the task in two to four parts. After a disassembler for looking inside book for Linux developers who
Dennis Hayes is an independent description of a task, the first part assemblies, and NUnit for testing. want to learn enough .NET to
software consultant in Atlanta, GA, is a “How do I do that” section that The area with the most extensive get started. It is an excellent book
and has been involved with the shows exactly how to complete coverage is on how to use Gnome for Windows programmers who
Mono project for over three years. the task. The next section, “How it and GTK# for writing GUI interfaces want to get started with .NET on
works,” talks a bit more about how under Linux. The GTK# API is popu- Linux, because it gives details on
4dennisdotnet@yahoo.com the .NET classes work, things to lar with developers coming from a how to install and configure Mono,
watch out for, and often a bit of his- Linux background. The book covers and compile and execute pro-
tory about why a function behaves Linux Gnome tools such as Glade grams in a Linux environment. It
as it does. Some tasks also have a for layout, DocBook for help, Gecko, does this in a very cookbook style
“What about” section that covers GConf, drag and drop, and interna- that does not assume any previous
some “gotchas” or advanced appli- tionalization. When this book was knowledge of Linux. This book is
cations of the technique just dis- written, System.Windows.Forms was not for beginning programmers
cussed. Most tasks conclude with still far from complete, and so it is – it is too shallow and concise for
a “Where to learn more” section, mostly absent from this book. that. This book is meant for expe-
which references the MSDN library As you would expect from these rienced developers who just need
or Internet sites where more infor- two authors, XML is fully covered, a little help with some specific
mation and details can be found. including reading and writing XML tasks.
The book gives an overview of files, the DOM classes, validating I would rate this book a “must
Mono, C#, and the NET framework; XML with DTDs, and serializing have” for programmers getting
it is enough to get started, but and deserializing C# classes to and started with Mono and .NET on
everyone will need more complete from XML files. .NET uses XML in Linux, and the wallet-friendly price
references to complement this many ways, and this book gives a of $24.95 makes this book a real
book. The chapter on the .NET good overview of how to use most of bargain that will pay for itself sev-
framework only covers a few areas them. eral times over.

48 March 2006 • dotnetdevelopersjournal.com


Visit the���
���������������

Website Today!
���������������������������������
���������������������������

24/7
����������������
������������������������������������������
���������������������������������������������������

����������
�������������������������������������������������������������������������������������

�������������
����������������������������������������������������������������������������������������

��������
������������������������������������������������������������������
��������������������
����������
���������������������� ��������������������������������������������������
������������������ ����������������������
������������������������������������ ������������������������������ ��������
��� ����������� �������������������������������������������������������������
�������������������� ������������������������������ �
������������������������ ��������������������������� ����������
������������������� ����������������� ������������������������������������������������������������������������������
������������������� ����
��������������������������� ��������������������������������
��������������������
�����������������������������������������������������������������������

������������������������������������������
Mono

Mono 1.1.13 Released Portable .NET 0.7.4 Released

t
he 1.1.13 version of Mono of access to Intel-based Macs is also Objective C user interface to the C#
has also been released. delaying the porting process, but the back end. There is an interesting
This version will be Mono team is beginning to get more article on it in at http://developer.
shipped with Novel/Suse access to Intel-based Macs. Fixing all apple.com/business/macmarket/
Enterprise products. It also serves as of this will take several months, but imeem.html. (The imeem applica-
a feature freeze point for the upcom- it is being worked on, and Mono will tion is free, and can be downloaded
ing major 1.2 release, with the soon run on Intel-based Macs. from their home page www.imeem.
exception of System.Windows.Forms For Macs running on PowerPC, com). They have also released the
(SWF) and libgdiplus, which are still there is an open source (LGPL) framework under the LGPL, and you
being developed. The 1.1.13 branch framework called Dumbarton, can download the source from their
will also receive back-ports of all which bridges Objtive-C and C#. It developers page, as well as find out
bug fixes until it is replaced with the was written by imeem in response more about it, at www.imeem.com/
1.2 version. 1.1.13 is mostly bug fixes to a need they had while writing developers.aspx.
(including hundreds in the SWF an application with a complex user
namespace). The main additions to interface that needed to run on both Pnet
this release are a completed 64 bit Macs and Windows. The application The new version of Portable.NET
S390 port, an implementation of the connects to a server and provides contains a lot of fixes and enhance-
new 2.0 System.Threading primi- ments in all parts of the project, over
tives, updates to System.Net.Mail 150 in all. More than a third of the
and System.Net.Mime, and typed changes were in System.Windows.
data returns for Sqlite 3. One major Forms, which received more than
enhancement is the inclusion of a 50 changes in this version. One big
printing framework for SWF. This change is that gcc4 can now be used
will not be really usable until Cairo for building Portable.NET.
is updated, but it is still a milestone I A complete list of the improve-
have been looking forward to seeing. ments and downloads of the pro-
More than 70 people worked on this grams and source code can be found
release. at http://dotgnu.org/pipermail/
Scott Hanselman does pod- developers/2006-January/000162.
BY DENNIS HAYES casts and he did one on Mono at html.
http://perseus.franklins.net/han-
Dennis Hayes is an independent selminutes_0005.mp3. Even more Odds and Ends
software consultant in Atlanta, GA, interesting, he has a screencast a wide range of services, such as LSharp is an open source Lisp-
and has been involved with the that shows how to develop using blogging, podcasting, chat, photo like interpreter for .NET. It started out
Mono project for over three years. Mono, then deploy on Windows, or sharing, and others. They felt that running on Microsoft.NET 1.1, but
develop on Windows, then run on the user interface for such an appli- has been updated to .NET 2.0, and
4dennisdotnet@yahoo.com Mono. The screen cast is at www. cation would be complex enough now runs on Mono, with a few rough
hanselman.com/blog/MonoAndIts using a native look and feel, without spots. More information, downloads,
ManyFacetsScreencast.aspx. It is a having users deal with a non-native and tutorials on using Lisp can be
small demo that uses only a simple look and feel. They needed a ver- found at www.lsharp.org.
console application, but if you have sion of Mac, and Windows, but were Sharpdevelop released beta 1 of
never seen a single .exe run on both OK with the Linux version using the SharpDevelop2. One big change is
Windows and Linux, it is worth Mono SWF interface. Their solution that this version is released under
checking out. was to use C# on the server back the LGPL, not the GPL you would
end, and to put as much code as expect. The reason for this is that
Mono on Mac on Intel possible into this back end. They Sharpdevelop is meant to be very
Does Mono work on the new then wrote separate interfaces for extensible, and LGPL allows exten-
Intel based Macs? Not very well, but Windows and Mac. They wrote sions to be closed source. Other
it will. Currently, only the JIT com- the Windows interface in C# using additions are support for code
piler works, and even that does not Visual Studio, SWF, and the Mac coverage and the Mono GAC. It
support garbage collection, so most interface in Coca using Xcode can be downloaded from www.
applications will crash after run- and Objective C. They then wrote icsharpcode.net/OpenSource/SD/
ning a while. There are issues with a framework called Dumbarton Download. It supports the .NET 1.1
stack definitions breaking calls to (named after a bridge in the San Framework, but requires the 2.0
DLLs, and many install issues. Lack Francisco area) that connects the Framework to be installed.

50 March 2006 • dotnetdevelopersjournal.com