SOFTWARE DEVELOPMENT NETWORK

68
Nummer 101 mei 2009 SDN Magazine verschijnt elk kwartaal en is een uitgave van Software Development Network www.sdn.nl IN DIT NUMMER O.A.: Implementing KeyValueCoding in Delphi Prism < Designing Recoverable and Restartable SSIS Packages < Green Computing: Sparen door te Delen < Silverlight Web Parts in SharePoint < ADO.NET Entity Framework Overview < SOFTWARE DEVELOPMENT NETWORK MAGAZINE 101 Women in Technology

Transcript of SOFTWARE DEVELOPMENT NETWORK

Page 1: SOFTWARE DEVELOPMENT NETWORK

Nummer 101 mei 2009 SDN Magazine verschijnt elk kwartaal en is een uitgave van Software Development Network

www.sdn.nl

IN DIT NUMMER O.A.:

Implementing KeyValueCoding in Delphi Prism <

Designing Recoverable and Restartable SSIS Packages <

Green Computing: Sparen door te Delen <

SilverlightWeb Parts in SharePoint <

ADO.NET Entity Framework Overview <

SOFTWARE DEVELOPMENT NETWORK

MAGAZINE

101Women in

Technology

Page 2: SOFTWARE DEVELOPMENT NETWORK

Advertentie Macaw

Page 3: SOFTWARE DEVELOPMENT NETWORK

magazine voor software development 3

ColofonUitgave:Software Development NetworkZeventiende jaargangNo. 101 • mei 2009

Bestuur van SDN:Remi Caron, voorzitterRob Suurland, penningmeesterJoop Pecht, secretarisMark Vroom, vice-voorzitter

Redactie:Rob Willemsen ([email protected])

Aan dit magazinewerd meegewerkt door:Maurice de Beijer, Rolf Craenen, Marcel vanKalken, Stefan Kamphuis, Marcel Meijer,Mirjam van Olst, Johan Parent, Joop Pecht,Sandra de Ridder, Maarten van Stam,Bob Swart, Marianne van Wanrooij,Rob Willemsen en natuurlijk alle auteurs!

Voorpagina:v.l.n.r. Sandra de Ridder (UX), Mirjam vanOlst (IW) en Marianne van Wanrooij (IW)Foto: Maarten de Meijer

Listings:Zie de website www.sdn.nl voor eventuelesource files uit deze uitgave.

Vormgeving en opmaak:Reclamebureau Bij Dageraad, Winterswijkwww.bijdageraad.nl

©2009 Alle rechten voorbehouden. Niets uitdeze uitgave mag worden overgenomen opwelke wijze dan ook zonder voorafgaandeschriftelijke toestemming van SDN. Tenzijanders vermeld zijn artikelen op persoonlijketitel geschreven en verwoorden zij dus nietnoodzakelijkerwijs de mening van het be-stuur en/of de redactie. Alle in dit magazinegenoemde handelsmerken zijn het eigen-dom van hun respectievelijke eigenaren.

AdverteerdersMacaw 2Avanade 12MI Consultancy 16Sybase iAnywhere (ADS) 19Aladdin 25Bergler 26Microsoft 34-354DotNet b.v. 41Barnsten/Embarcadero 48VNU 54Sogeti 67Bridge Incubation Group b.v. 68

Adverteren?Informatie over adverteren en de adverten-tietarieven kunt u vinden op www.sdn.nlonder de rubriek Magazine.

Dit 1e magazine na nummer 100 is al weer een speciale editie; 1tje waarbij we internnogal wat gediscussieerd hebben over hoe duidelijk te maken dat dit eenbijzondere uitgave is.De uitkomst van al die discussies is bekend: die heb je immers nu in handen. Dat is dus watervan terecht gekomen is, van het Women In Technology idee: “Zou het niet aardig zijn om 1magazine compleet te vullen met vrouwelijke input?”. Waar ging de discussie dan over, zul jeje wellicht afvragen…

“Moeten we dat in een special doen en hoe moet die er dan uitzien?”Vooral dus over de vraag of we dit blad als iets heel bijzonders moesten brengen – de fysiekevorm van het blad van een A4-rechthoek transformeren in vrouwelijke richting, een blondeomslag met bijzonder make-up/opmaak … en de overige ideeën onthoud ik je – of juist alsiets heel normaals, want dat is wat we eigenlijk zouden willen … een werkomgeving waarinhet net zo normaal voor mannen als voor vrouwen is om hun inzet te tonen, hun creativiteitte benutten, mooie en nuttige software te bouwen, samen te werken, enz. Uiteindelijk zijn wetoch een beetje op een compromis uitgekomen, zoals in ons polderlandje wel (veel) vakergebeurt, met op de coverfoto – die had je toch al gezien, zeker?! - de 3 (!) vrouwelijkeSDN-orgo’s als een special item.

“Is dat eigenlijk wel nodig, die speciale aandacht voor dat onderwerp?”Als ik het aan mijn vrouwelijke collega’s zelf vraag, dan is extra aandacht niet nodig. Maar wezijn het met z’n allen eens dat de ICT branche een duf imago heeft. “Een wereld voor nerdsen geeks”. Terwijl het – en niet alleen voor meisjes - een interessante keuze kan zijn vooriedereen die creatief bezig wil zijn en oplossingsgericht wil denken en werken, samen wilwerken en wil kennisnetwerken, allemaal aspecten die software development met zich mee-brengt. Rob Willemsen – redacteur van dit blad – is Informatica docent in het HBO. Hij gafaan dat al heeeeeel veel geprobeerd is, en zonder veel succes. Het afgelopen jaar waren bijzijn school ca. 5% meisjes onder de 1e jaarsstudenten, en dat was een stijging van 400%t.o.v. het jaar ervoor. Echt waar! In studierichtingen waarin naast het I-woord (I van Informa-tica) ook het C-woord (C van Communicatie) voorkomt ligt de deelname van meisjes echtveel hoger: 30% is daar niet ongebruikelijk.

“Denk je dat dat lukt dan, enkel artikelen van vrouwelijke hand?”Het blad heeft niet als doel aan te tonen dat er een kwaliteitsverschil is tussen mannen envrouwen. Aan de kwaliteit van de al aanwezige vrouwen ligt het niet: dit magazine doetkwalitatief absoluut niet onder voor eerdere edities waarin de – kwantitatieve! - verhoudingtussen de sexes altijd veel dichter in de buurt lag van de werkelijkheid binnen de ICT-wereld.Dat er competentieverschillen zijn, moge duidelijk zijn. Dit komt de samenwerking binnenprojecten alleen maar ten goede en is ook een veelgehoorde reden waarom bedrijven graagmeer vrouwen aan zouden willen nemen voor technische functies. En ja … het lukte!

“Ok, let’s give it a try then!”En zie hier … vanuit alle networks zijn er artikelen aangeleverd die geschreven zijn doorvrouwen, werkzaam in de ICT-wereld! Het kan dus! Willen we dingen (laten) veranderen, danmoeten we o.a. bij de vroege jeugd beginnen en rolmodellen kunnen daar een positieveinvloed bij hebben. Dit ene SDN-magazine zal de verhoudingen op middelbare, hogere enwetenschappelijke onderwijsinstellingen heus niet door elkaar schudden, maar alle beetjeskunnen helpen. Daarnaast heb ik (toch wel goede) hoop dat software voor de huidige jeugd– die de 1e lichting ‘digital natives’ vormen – dusdanig gemeengoed is en ook uitermateverbonden met hun communicatie en samenwerking, dat automatisch meer jeugdigen,jongens én meisjes, geïnteresseerd zullen raken in hoe je dat soort spul nu maakt en ook hoeje daarvoor nieuwe toepassingen kunt bedenken.Laten wij in ieder geval proberen zo veelmogelijk voorbeelden te stellen, en hierbij dus onze inbreng!

Wat vind je dan zoal in dit WIT-magazine?Een stuk of 13 artikelen van dameshand, goed voor zo’n 50-55 pagina’s leesvoer. De startvan een nieuwe komische column DevTweet door Marianne van Wanrooij & SanderHoogendoorn, waarvan de inhoud o.a. via discussie op Twitter gevoed wordt, en de regulierecolumns … de enige male-only ingrediënten in dit magazine.

Marianne van [email protected]

Voorwoord:Women in Technology

Page 4: SOFTWARE DEVELOPMENT NETWORK

SDN EVENT26 juni 2009Hotel HoutenHouten

Inhoud03 Voorwoord: Women in TechnologyMarianne van Wanrooij

04 Inhoudsopgave

05 Implementing KeyValueCodingin Delphi Prism

Joanna Carter

08 Agenda

09 What’s New in WCF 4.0?Michèle Leroux Bustamante

13 Designing Recoverableand Restartable SSIS Packages

Jessica M. Moss

17 Green Computing:Sparen door te Delen

Astrid Hackenberg

20 Using Windows Presentation Foundationand Line-of-Business Data in MicrosoftOffice Clients

Beth Massi

27 Silverlight Web Parts in SharePointMirjam van Olst

36 HP NonStop: 30 Jaar Ontwikkelingin NonStop Transactieverwerking

Frida Robben

38 ADO.NET Entity Framework OverviewJulia Lerman

42 DevTweetMarianne van Wanrooij en Sander Hoogendoorn

43 The WebHub Way of ThinkingAnn Lynnworth

49 ASP.NET onder de Motorkap:“De performance van ASP.NET is slecht”

Michiel van Otegem

50 Requirements ManagementHoudt de Kikkers in de Kruiwagen

Frédèrique Harmsze

55 Business Intelligence: Theorie en PraktijkLiesbeth Smits

58 Creating Help Systems with Help & ManualLoy Anderson

63 Interesting things: Trojan RigiditySander Hoogendoorn

64 Using jQuery UI in DotNetNuke ModulesSarah Darkis

Page 5: SOFTWARE DEVELOPMENT NETWORK

This example uses the Monobjc bridgelibraries, so you will need to ensure thatthese are installed before proceedingany further

Joanna Carter

ImplementingKeyValueCoding

in Delphi PrismCreating the test projectThis example uses the Monobjc bridge libraries, so you will need to en-sure that these are installed before proceeding any further.Start by ensuring that your Windows VM is available, opening DelphiPrism and creating a new Monobjc application called KVOExample.If you haven't installed Monobjc in a location the project can find on itsown you may have to re-establish the References section of the pro-ject to point to your installed location for Monobjc.

A value-key coding compliant classThe first thing we need to do is to define the class for the object whoseproperties we wish to display on a form. So, add a new class to theproject, called Customer.

namespace KVOExample.Interface.nib;

interface

uses

Monobjc.*;

type

[ObjectiveCClass("Customer")]

Customer = public class(NSObject)

private

fName: NSString;

protected

public

[ObjectiveCMessage("name")]

method getName: NSString;

[ObjectiveCMessage("setName:")]

method setName(value: NSString);

property Name: NSString

read getName

write setName;

end;

As you will see, it is necessary to do slightly more coding than for astandard Delphi Prism class if we want this class to be usable by theObjectiveC runtime.

1. The class has to derive from NSObject (at least).2. The class has to be marked with the ObjectiveCClass Attribute.3. Any property that is to be involved in Key-Value coding has to be

of a type that ObjectiveC can recognise.4. Properties must be represented by two public methods: a getter

and a setter.5. Property getter and setter methods can be named as desired but

they must also be labelled with an ObjectiveCMessage attributewhich follows the naming convention that ObjectiveC expects:"<propertyName>" and "set<propertyName>".

IntroductionIf you’ve ever used .NET bindings to connectUI widgets to properties of objects in a Win-Forms project, this article will demonstrate howto design Delphi Prism classes that can useCocoa bindings to achieve the same ease ofform design when writing an application forOS X.One of the nice features available to develo-pers using the Cocoa frameworks, is the con-cept of Key-Value coding. The basic premiseof this feature is to implement the Observer de-sign pattern, allowing one object to respond tochanges to the properties of another.However, once implemented, another benefitbecomes available; Cocoa bindings use theKey-Value pattern to support, amongst otherthings, the connection of UI controls to pro-perties of business objects, allowing the UIcontrol to be updated automatically when theproperty of the object changes and, also, theproperty of the object to be set when a newvalue is entered into the UI control.Whereas, with simple Key-Value coding, aController can listen to changes on an objectand then interpret those changes into messa-ges to a UI control, bindings completely re-move the need for any "glue code" in betweenthe object being observed and the UI controlsthat are displaying the values of an object'sproperties.

DELPHI

magazine voor software development 5

Page 6: SOFTWARE DEVELOPMENT NETWORK

Of course, as far as ObjectiveC is concerned, you need not have aproperty declaration at all; that is included for ease of coding fromother Delphi Prism classes.

method Customer.getName: NSString;

begin

result := fName;

end;

The getter method is just a simple return of the private field's value.

method Customer.setName(value: NSString);

begin

WillChangeValueForKey("name");

fName := value;

DidChangeValueForKey("name");

end;

However, the setter method has to contain calls to the two methodsof NSObject that will, in turn, notify those objects that are registeredas having an interest in changes to instances of this class.

Creating the editing formNow we have created a business class, we can focus attention oncreating a form on which we can edit an instance of that class.On the OS X side of things, open Interface Builder, navigate to the In-terface NIB file within the project directory and open it. You should seesomething like this :

Fig. 1: The new Nib file

If it is not already showing, double-clicking on the Window icon willopen the main form, which should look like this :

Fig. 2: The new form

We shall not be using the toolbar, so that can be removed and oneButton, one Text Field and two Labels can be added, to give us a formthat looks like this :

Fig. 3: The completed form ControllerInspector

Now, switch to the ApplicationController icon in the NIB window andadd the Actions and Outlets you see in the next image :

Fig. 4: Created Actions and Outlets

In order for these Actions and Outlets to appear in the Delphi Prismclass declaration, you will need to connect the button to the setCuto-merName action, the nameEdit outlet to the Text Field and the name-Label outlet to the right hand of the two Labels on the form.Once these changes are made, we need to save the NIB and thatshould complete our work in Interface Builder.

Completing the controller classChanging back to Visual Studio, we now need to make our DelphiPrism project aware of the changes that have been made to the NIBwhich we have just edited.In the Solution Explorer, expand the Interface.nib node until you cansee the designable.nib node. Right-clicking on this node should dis-play a menu which includes the entry "Run Custom Tool"; clicking onthis item will update the designable.pas source file to include thechanges we have just made to the NIB in Interface Builder.

MAGAZINE6

DELPHI

Page 7: SOFTWARE DEVELOPMENT NETWORK

In designable.pas, you should now see a class declaration that lookslike this :

[ObjectiveCClass]

ApplicationController = public partial class(NSObject)

public

var [ObjectiveCField] nameEdit: NSTextField;

var [ObjectiveCField] nameLabel: NSTextField;

[ObjectiveCMessage('setCustomerName:')]

method setCustomerName(sender: NSObject);

partial; empty;

end;

Having updated the ApplicationController class to this stage, we cannow switch to the ApplicationController.pas file in the solution, andcomplete any code required to link up the form to an instance of ourCustomer class.

type

ApplicationController =

public partial class(Monobjc.Cocoa.NSObject)

private

fCustomer: Customer;

method AfterConstruction; partial;

protected

public

method AwakeFromNib; partial;

method setCustomerName(sender: NSObject); partial;

end;

As you can see, the setCustomerName method is now implementedin the separate ApplicationController.pas unit but, since we need thecontroller to hold an instance of our Customer class, we also need toadd a private field and to implement the awakeFromNib method tohook up the controls to the Name property of our Customer object.

method ApplicationController.AfterConstruction;

begin

fCustomer := new Customer();

end;

We could use Cocoa Bindings to connect both the Text Field and theLabel to the Customer but, since the Label only needs to observechanges to the Customer and not make them, we will only use KVOto update the Label.

method ApplicationController.AwakeFromNib;

begin

First, we will use Cocoa Binding to connect the Text Field :

nameEdit.BindToObjectWithKeyPathOptions(

"value", fCustomer, "name", nil);

But, for the Label, we need to make this ApplicationController the ob-server for the Name property of the Customer object :

fCustomer.AddObserverForKeyPathOptionsContext(

self, "name",

NSKeyValueObservingOptions.NSKeyValueObservingOptionNew,

nil);

end;

Implementing a KVO handler methodHaving told the Customer to tell us when its Name property changes,we need to provide a method that KVO can call when the property

changes. In ObjectiveC, the method signature would be observeValu-eForKeyPath:ofObject:change:context: which can be defined in DelphiPrism like this :

method ApplicationController.

observeValueForKeyPathOfObjectChangeContext(

keyPath: NSString; object: NSObject;

change: NSDictionary; context: NSObject);

begin

The "change" NSDictionary parameter contains one or more key-valuepairs, depending on the type of change that has occurred in the ob-ject that is being observed; in this example, all we are interested in iswhether the value of any property of the observed object has changed.

Cocoa defines a set of string constants as part of the NSKeyValue-Observing framework; these are replicated, in Mono, as the NSKey-ValueObserving static class which contains static fields for theconstants. In this example, we are interested in retrieving the NSKey-ValueObserving.NSKeyValueChangeKindKey entry in the change dic-tionary, in order to ascertain the kind of change that has occurred tothe observed object.

The value held in the NSKeyValueObserving.NSKeyValueChange-KindKey entry in the dictionary is of the NSKeyValueChange enumtype so, because direct casting of ObjectiveC types is not possible inDelphi Prism, we have to carefully convert the Id type of the value re-turned from the dictionary entry to the NSValueChange type.

var changeKindAsID: Id :=

change[NSKeyValueObserving.NSKeyValueChangeKindKey];

The Id type is, essentially, an untyped pointer so, first, we have to con-vert the value to an NSNumber using the CastTo<T> generic methodthat is a part of the Id class in Monobjc.

var changeKindAsNSNumber: NSNumber :=

changeKindAsID.CastTo<NSNumber>();

Next, because we want to compare this value to a member of anenum, we need to further convert this NSNumber value to the appro-priate member of the NSKeyValueChange enum.

var changeKind: NSKeyValueChange :=

NSKeyValueChange(changeKindAsNSNumber.UnsignedIntValue);

There is no direct cast from an NSNumber to an enum so, instead,we have to cast the unsigned integer value of the NSNumber instance,obtained by using the UnsignedIntValue method of the NSNumberclass. Finally, we can compare the value, obtained from the dictionary,with the NSKeyValueChange.NSKeyValueChangeSetting enum valuethat will tell us if this notification is the result of a change to the valueof a property to which we want to react.

if changeKind = NSKeyValueChange.NSKeyValueChangeSetting

then

begin

Having ascertained that this notification is for a value change, we can

magazine voor software development 7

Cocoa defines a set of string constantsas part of the NSKeyValueObservingframework

DELPHI

Page 8: SOFTWARE DEVELOPMENT NETWORK

now determine which property has changed, simply by checking thevalue of the keyPath parameter.

if keyPath = "name" then

Now that we know that there was a value change to the "name" pro-perty of the object we are observing, we can obtain the new value byreading it from the NSKeyValueObserving.NSKeyValueChangeNewKeyentry in the dictionary.

label.ObjectValue :=

change[NSKeyValueObserving.NSKeyValueChangeNewKey];

end;

end;

One last thingFinally, we can respond to the button press by setting the Custo-mer.Name to a fixed value:

method ApplicationController.setCustomerName(

sender:NSObject);

begin

fCustomer.Name := "CodeGear";

end;

Putting it to the testHaving created all the necessary code for this example, all that is leftis to build the application in Visual Studio, find the KVOExample.appfile produced and run it.Clicking on the button will set the Customer Name to "CodeGear".Editing the value in the Text Field should set the Name property on theCustomer, thus triggering an update of the right-hand Label on theform.

Joanna Carter

Joanna works as a consultant soft-ware engineer, specialising in OOarchitecture analysis and design,troubleshooting and debugging.She has worked in the UK and Eu-rope and is a regular speaker andauthor for the UK Developers Groupand has also spoken at the SDNconference. Most of her articles/pre-

sentations have been on OO architecture and coding, design pat-terns and refactoring. She has also held OO masterclasses in theUK and US. She has developed an Object Persistence Frameworkfor use with Delphi and C#, Delphi and C# versions of the ModelView Presenter framework and has hosted Birds of a Feather ses-sions on these subjects at BorCon on at least two occasions. Jo-anna is presently working at writing applications for OS X in bothObjectiveC and Delphi Prism. When she is not tied to a computer,she can be found doing some serious photography using anythingfrom 4x5 field cameras to state of the art digital SLRs.

AGENDA2009

Microsoft DevDays 2009, Den Haag www.DevDays.nl . . . . . . . . . . . . . . . . . . . . . .27-29 mei

SDN Event - Hotel Houten, Houten . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26 juni

SDN Magazine Nr. 102 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28 augustus

EKON, Mainz . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 - 9 oktober

SDN: Software Development Conference 2009

Papendal, Arnhem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19 - 20 oktober

TechEd Developer EMEA 2009, Berlijn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 - 6 november

Microsoft PDC, Los Angeles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17 - 20 november

SDN Magazine Nr. 103 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20 november

Genoemde data onder voorbehoud

ConclusionCocoa UI controls can be connected to properties of objects by, either,Cocoa Bindings or Key-Value Observing. This article demonstratedhow to create an example project which used Cocoa Bindings to con-nect a Text Field, and KVO to connect a Label, to the same propertyof an object, prompting multiple updates to different controls from thesame property of an object. •

DELPHI

8 MAGAZINE

Page 9: SOFTWARE DEVELOPMENT NETWORK

magazine voor software development 9

Michèle Leroux Bustamante

What’s New in WCF 4.0?

When the ServiceHost is initialized, an endpoint will be automaticallycreated for each contract implemented by the service type - for eachbase address provided. When you combine this behavior with defaultbinding configurations and behavior settings, configuration-free hos-ting actually seems plausible.

Serialization enhancementsThe new DataContractResolver will provide new extensibility hooksuseful for customizing CLR type mapping for the DataContractSeria-lizer. This can be useful for simple overrides such as altering the nameand namespace for CLR types written to the wire, for overriding whichCLR types are involved in serialization, and for dynamically managingknown types.

Queued Messaging ReceiveContextIn order to guarantee exactly once delivery of messages from a queuein Microsoft Message Queuing (MSMQ) you must work with trans-actional queues and the WCF service operation must participate inthe playback transaction. If an exception is thrown while processingthe message, the service can guarantee the message doesn’t get lostby returning it to the queue - either the originating queue, the deadletter queue or a poison message queue, depending on configurationand MSMQ versions. This is quite useful, but has limitations in thatthere is no way to ensure that the same service processes the failedmessage the next time it is pulled from the queue, not to mention thattransactions are expensive.

WCF 4.0 introduces ReceiveContext as an alternative technique forprocessing queued messages. The thrust of this new technique is thatthe message is not pulled from the queue until the message is suc-cessfully processed by the service. A ReceiveContext is associatedwith the message once it is “peeked” by a service and if an exceptionis thrown and the message cannot be completed, it remains in thequeue but can also remain locked by that particular service to retryprocessing. This reduces overhead since the message need not betransmitted over the network again to another service. ReceiveContextprovides a way to explicitly complete the message so that it can beremoved from the queue on success. ReceiveContext guarantees atleast once delivery when used without transactions, and whencomposed with transactions it guarantees exactly once delivery withperformance benefits.

An early look at forthcoming WCF featuresThe .NET Framework 4.0 will be released with Visual Studio 2010 - bringing with it a plethoraof new WCF features. WCF 4.0 will solve many pain points related to configuration, tracing anddiagnostics, serialization and messaging. In addition this release will include exciting newenterprise-ready features such as service discovery and routing, and when combined with thepower of WF 4.0 Workflow Services will greatly simplify how developers incorporate asynchro-nous programming models to offset expensive IO-intensive operations and improve overallapplication performance and throughput.In this article I will provide a high level summary of features we know today will be released withWCF 4.0 - to provide you with a well-rounded view of the forthcoming release.

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

The idea is that you provide better binding configuration and behaviordefaults for your specific application’s requirements, and the runtimepicks up those defaults when it initializes the ServiceHost. Listing 1illustrates providing default settings for WS2007HttpBinding andseveral behavior defaults. They are noted as defaults by using anempty string (“”) for the binding and behavior name.

<bindings><ws2007HttpBinding>

<binding name="" maxReceivedMessageSize="1000000" ><readerQuotas maxArrayLength="1000000"

maxStringContentLength="50000"/><security mode="Message">

<message clientCredentialType="UserName"negotiateServiceCredential="false"establishSecurityContext="false" />

</security></binding>

</ws2007HttpBinding></bindings><behaviors>

<serviceBehaviors><behavior name="">

<serviceMetadata httpGetEnabled="true"/><serviceCredentials>

<userNameAuthenticationuserNamePasswordValidationMode=

"MembershipProvider"/></serviceCredentials><serviceAuthorization

principalPermissionMode="UseAspNetRoles" /><serviceThrottling maxConcurrentCalls="30"

maxConcurrentSessions="1000"/></behavior>

</serviceBehaviors></behaviors>

Listing 1: Binding and behavior defaults in WCF4.0

.NET

Page 10: SOFTWARE DEVELOPMENT NETWORK

Web programmingSince the release of .NET 3.5 it is much easier to build WCF servicesthat bypass SOAP processing requirements including Plain-Old-XML(POX), Java Script Object Notation (JSON) and Representational StateTransfer (REST) - the latter of which is an architectural approach for de-signing POX or JSON services. These techniques fall under the webprogramming model for WCF services. Microsoft also released theWCF REST Starter Kit which considerably improves productivity whenbuilding services for this web programming model. The WCF RESTStarter Kit includes the following:

• Many Visual Studio templates for the most common scenarios forPOX, REST and Atom/Pub.

• New features to support better error reporting to the browser.Supporting types are WebProtocolException and new behaviorsinstalled with WebServiceHost2 and WebServiceHost2Factory.

• A much needed extensibility hook for HTTP requests throughRequestInterceptor.

• The ability to more easily override HTTP verbs for clients that don’tsupport PUT and DELETE.

• Cached operation responses with WebCacheAttribute.• Tons of code samples illustrating how to work with these features.

The idea behind releasing the starter kit was to get these features intothe hands of RESTful WCF developers so that they could providefeedback on features so that .NET 4.0 can include the most relevantfeatures and include any refinements. Thus, many of these featureswill be included in the WCF 4.0 feature set.

Basic Profile 1.2As you may be familiar, there are a number of standards bodies thatdrive specifications implemented by platforms like WCF, including:W3C (www.w3c.com), OASIS (www.oasis-open.org) and WS-I(www.ws-i.org). The goal of the latter is to simplify how the plethora ofstandards is implemented in vendor platforms. In WCF, BasicHttpBinding supports Basic Profile (BP) 1.1 which is based on SOAP 1.1.This profile is grossly out of date, it does not support WS-Addressingsemantics or MTOM. Thus, a new profile was born - BP 1.2. This newprofile addresses errata for BP 1.1 and includes support forWS-Addressing and MTOM. WCF 4.0 will support this profile.

NOTE: Do not confuse BP 1.2 (based on SOAP 1.1) with BP 2.0(based on SOAP 1.2) which is still a work in progress.

Service discoverySpeaking of protocol support, WCF 4.0 includes a long-awaitedimplementation of WS-Discovery. This specification documents amulticast protocol that issues SOAP messages over UDP. Servicesthat implement discovery endpoints can receive probe messages fromclients that wish to discover services within their subnet. In addition,services can announce themselves to clients listening for announce-ments. Figure 1 illustrates the flow of communication between clientsand services.

Fig. 1: Discovery probes and announcements from a high level

Discovery messaging works because communication endpoints arewell-known UDP addresses. WCF 4.0 makes it very easy toimplement service discovery with a few simple steps:

• Services that wish to be discoverable implement a discoveryendpoint and enable discovery with a service behavior.

• Services that wish to send discovery announcements enableannouncements as part of the discovery behavior.

• Clients that wish to probe services within the subnet use a built-inDiscoveryClient and supply heuristics for searching for the desiredservices.

There are many architectural scenarios that can implement discovery,and this will be the subject of a future article.

Router serviceRouters can be very useful when you need to introduce load balancingusing custom heuristics, content-based or priority routing, versioningscenarios, or when you need to introduce a security boundarybetween remote clients and services that live behind the DMZ.Implementing a custom router is a significant undertaking but WCF4.0 aims to relieve this effort by supplying us with a built-in routerequipped to work with one-way, two-way and duplex messaging.

You host the new RouterService as you would any other WCF serviceand then configure routing rules using a filter table and a set ofassociated filters. The filters are ultimately evaluated to determine thecorrect downstream service endpoint to forward messages to. Thisarchitecture is illustrated in figure 2.

Fig. 2: Configuring the RouterService in WCF 4.0

Many filtering options are available through a simple configuration suchas XPath queries for content-based routing and queries based on theSOAP action header. There are also extensibility hooks available fordeeper control over filters and routing decisions.

MAGAZINE10

WCF 4.0 includes implementationof WS-Discovery

Microsoft also released theWCF REST Starter Kit

.NET

Page 11: SOFTWARE DEVELOPMENT NETWORK

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

• Increased visibility through correlated WF tracking and WCF tracingevents.

• Greatly simplified approach to implementing asynchronousprogramming models, for example issuing downstream service callsin parallel and correlating responses.

• Implementing declarative (XAMLX) services which provide analternative to deploying, updating and versioning - and make itpossible to deploy Workflow Services to the cloud.

High-performance tracingWCF 4.0 trace events are based on Event Tracing for Windows (ETW)which significantly enhances tracing and diagnostics performance.From a high level the architecture of ETW is simple: event providerspush events to sessions under a registered provider ID, controllers areused to enable or disable sessions that collect events and associateproviders with sessions, sessions can optionally persist events to alog, consumer applications listen to real-time session events or pickevents up from trace logs. ETW is buffered to reduce contention whenpersisting events to a file-based trace log. Figure 3 illustrates thisarchitecture.

Fig. 3: WCF Tracing and WF Tracking with ETW

Both WCF and WF share the same ETW event provider so that acorrelated view can be presented for WF tracking events and WCFtracing events - very useful for trouble-shooting Workflow Services.Furthermore, Dublin provides a friendly interface to enabling andconfiguring tracking and tracing through IIS Manager.

ConclusionThe new features in WCF 4.0 traverse a number of areas includingconfiguration, tracing, serialization, message queuing, servicediscovery, routing and workflow services. All of these new featuresspecifically address pain points that developers have with earlierversions of WCF.

This article originally appeared in the 2009/April issue ofasp.netPRO magazine and is reprinted with express permis-sion of Penton Media (www.aspnetpro.com).

Additional resources• Learning WCF, O’Reilly 2007 (reprinted for VS 2008, August 2008)

www.thatindigogirl.com (get all the latest book code here!)• Michele’s blog: www.dasblonde.net• IDesign: www.idesign.net •

magazine voor software development 11

Michèle LerouxBustamante

Michèle Leroux Bustamante is ChiefArchitect of IDesign Inc., MicrosoftRegional Director for San Diego, Mi-crosoft MVP for Connected Sys-tems. At IDesign Michele providestraining, mentoring and high-endarchitecture consulting servicesfocusing on service-oriented archi-

tecture, interoperability, scalability, security, and globalization. Herspecific technology focus includes WCF, federated security plat-forms and tools, CardSpace, Azure and Oslo. She is a member ofthe International .NET Speakers Association (INETA), a frequentconference presenter, conference chair for SD West, and isfrequently published in several major technology journals. Michèleis also Program Advisor to UCSD Extension. Her latest book isLearning WCF (O’Reilly 2007, updated August 2008) – see herbook blog here: www.thatindigogirl.com. Reach her at [email protected], or visit www.idesign.net and her main blog at www.das-blonde.net.

.NET

.Net TIP:Microsoft TagNa het kopen van een nieuwe Windows Mobile phone (HTCTouch HD) met een onbeperkte internetverbinding moet er hetuiterste uit de kast gehaald worden om alle mogelijkheden vandeze telefoon te benutten.Het is inmiddels gewoon om internet als informatiemedium tegebruiken. Nu werkt het nog met links. Nieuwsbladen, tijd-schriften, bushokjes … je kunt het zo gek niet bedenken of erstaan links. Maar het kan sneller en makkelijker met MicrosoftTag.

Microsoft Tag is een online applicatie die een Tag kan generen.Naast de online applicatie is er een mobile plugin waar decamera geactiveerd kan worden. Deze Tag kan wordengelezen door jouw Windows mobile Phone.Een tag ziet er als volgt uit:

Download nu de plugin op http://www.microsoft.com/tagJordy van Paassen - VXCompany

Page 12: SOFTWARE DEVELOPMENT NETWORK

Advertentie Avanade

Page 13: SOFTWARE DEVELOPMENT NETWORK

magazine voor software development 13

SQL Server Integration Services PackagesSQL Server Integration Services, a component of SQL Server 2005and 2008, allows developers to create packages that contain workand data flows to perform a variety of tasks, such as populating a datawarehouse through an extraction, transformation, load (ETL) processand performing database maintenance on an automated schedule.Along with using connection managers to access data sources, SSISpackages are tightly tied to the metadata associated with the datasources, including the object names and data types. Designing SSISpackages can be an art, and using best practices while architectingyour entire solution can save you a lot of heartache in the end.

Common SSIS package execution problemsEven if your SSIS package’s business logic has been designedperfectly, at some point a package execution will likely fail. We cangroup many of the reasons for a package error into several categories.• Category 1: External System Downtime contains failures that relate

to an inability to reach an external system. This could be due to theintranet/internet not responding, a server participating in anunexpected downtime, or similar reasons.

• Category 2: Unexpected Data includes problems with the sourcedata, which contain data type mismatches and arithmetic overflows.

• Finally, Category 3: Metadata Change issues occur because of achange to a table name, column name, or data type. MetadataChange errors happen because SSIS packages are tightly tied tothe metadata of the original source.

Recoverability and restartabilityRecoverability is the idea that a failure of an execution will nevercorrupt the state of the application. In an SSIS package, this meansthat if an execution fails, no data is lost or corrupted, and any effectsfrom a failed execution do not affect a later execution of the same pac-kage or any other associated package or query. No discussion of re-coverability would be complete without mentioning transactions, whichare typically found in databases as an application of recoverability.Following the four principles of transactional systems, atomicity, con-sistency, isolation, and durability, will result in a recoverable system.

Jessica M. Moss

Designing Recoverable andRestartable SSIS PackagesDue to unexpected data, server downtime, or a myriad of other reasons, a SQLServer Integration Services (SSIS) package will inevitably fail at some point in itslifetime. Initially designing your package to handle these situations will savesupport time and cost. This article introduces methods intended to create arecoverable and restartable package.

Restartability allows you to restart an application to pick up where thelast execution left off. In an SSIS package, if the last execution resul-ted in a failure, the restart will begin at the point of failure. On the otherhand, if the last execution was successful, a later execution will startat the beginning of the package. If multiple tasks must run in the eventof a failure, the SSIS package can be configured to handle this as well.

When to use recoverability and restartabilityin an SSIS package?For a majority of SSIS packages, recoverability and restartability shouldbe the top design concern. Whether in the form of an ETL process orperforming database maintenance, the package will be managing dataor manipulating something in a database. In particular, an ETLprocess typically needs high reliability and cannot lose a single record.If a package fails in the middle of a data load, you must have theability to recover your data. Once you’ve designed your package tohandle recoverability, you can focus on restartability without having toworry about losing any data. In an ideal system, the SSIS package willrerun without any manual manipulation of the data and begin at thelocation of the last failure.

Designing recoverability and restartability in an SSIS packageBecause of the importance of recoverability and restartability whenrunning SSIS packages, we will take a look at a few methods toaddress this concern.

TransactionsOne method to create recoverability in an SSIS package is to utilizepackage transactions. Transactions built into SSIS use the MicrosoftDistributed Transaction Coordinator (MSDTC) and can be set to run forthe entire package, a container that encloses tasks, or a task itself.Similar to database transactions, any failure within these items willundo the work already completed by the other items included in thetransaction.This method ensures that any database commands enclosed in thetransaction will either all execute or none of them will complete. Thisis especially useful in the scenario where you cannot delete a recordin a staging table until you ensure the entry is in the final table, andconversely, if the entry has made it into the final table, you want toensure the deletion from the staging table to prevent reloading. Usinga transaction can assist in an error from any of the three errorcategories.Keep in mind that a transaction cannot contain any file based tasks,such as create, delete, move, as it cannot rollback those particular

For a majority of SSIS packages,recoverability and restartability shouldbe the top design concern

DATABASES

Page 14: SOFTWARE DEVELOPMENT NETWORK

operations. If the rollback process should include file based operations,you will need to code the opposite operation in the event of a failurein the package.

To set up a transaction in your SSIS package that will not allow dirtyreads nor allow other transactions to modify the current set of data, se-lect the package/containers/tasks that you want included in the trans-action and set the properties as shown in table 1.

Table 1: Transaction properties

Database snapshotAnother method to make a package recoverable utilizes databasesnapshots. SQL Server 2005 first introduced database snapshots,and other relational database management systems (RDBMS) may ormay not include similar functionality. In this scenario, the package takesa database snapshot, which will store any changes to the databasefollowing the time the snapshot was taken. If the package executionfails in any way, the package restores the latest snapshot, wiping outany changes that took place during the package execution, thus re-turning the database to its original version.This snapshot method wipes the slate clean in the event of a failedload. It will reset the entire database in case of a partial load due to anExternal System Downtime or an insert failure due to UnexpectedData. You can then fix the source data if needed and rerun the pac-kage.

This method can only be used if no other applications will be modify-ing the database at the same time your SSIS package runs, as it doesnot differentiate between changes made by your SSIS package andany other application. A slight performance overhead associated withwriting to the database snapshot when the database changes affectsthe SSIS package as well.

To implement this method in your SSIS package, add an Execute SQLTask in the Control Flow that precedes all other tasks. This task con-tains a T-SQL script similar to listing 1. Encapsulate all package logicin a Sequence Container, and attach a Failure precedence constraintfrom the Sequence Container to a second Execute SQL Task. Thistask contains the T-SQL script, found in listing 2, to restore and thendrop the database snapshot. Set a second precedence constraint toexecute on Success and attach it from the Sequence Container to athird Execute SQL Task, which contains a T-SQL script, found in listing3, to drop the snapshot. Find a picture of a sample package using thissnapshot logic in figure 1.

CREATE DATABASE AdventureWorksSnapshot ON

( NAME = AdventureWorks_Data,

FILENAME = 'C:\SSIS\AdventureWorksSnapshot.ss' )

AS SNAPSHOT OF AdventureWorks

Listing 1: Create snapshot T-SQL statement

USE master

GO

RESTORE DATABASE AdventureWorks FROM

DATABASE_SNAPSHOT = 'AdventureWorksSnapshot'

GO

DROP DATABASE AdventureWorksSnapshot

Listing 2: Restore snapshot T-SQL statement

DROP DATABASE AdventureWorksSnapshot

Listing 3: Drop snapshot T-SQL statement

Fig. 1: Database snapshot package

Create data subsetsIn this method to make an SSIS package recoverable, the SSIS pac-kage contains logic to chunk the source data into smaller pieces inorder to reduce the subset that does not process successfully. Eachsection of data is inserted into the final destination using a bulk insertcommand that only commits on the insertion of all records in the sub-set. The entire subset fails if one record fails.This method has the benefit of completing as much of the processingas possible without corrupting the data. The SSIS package will notload the subset of data that contains Unexpected Data to allow you tofix the data before rerunning that subset of data, but all other subsetswill load.Keep in mind a few things when working with this method. If you needan aggregate value over your subsets, this could complicate your logic.Also, this could slow down your processing by creating a semi-itera-tive approach rather than the normally used set-based approach ofloading data.

To implement one variation of this method, create an SSIS package tofilter the data by modified date. Add an Execute SQL Task to the SSISpackage that executes the T-SQL found in listing 4 and stores the re-sult set into an object variable. Add a ForEach Loop that enumeratesthrough each of the dates, assigning the value to a variable of a stringdata type. Within the ForEach Loop, use a Data Flow Task that per-forms the insert using the previously assigned variable. Find a pictureof a sample package using this data subset logic in figure 2.

SELECT DISTINCT

CONVERT(varchar(10),ModifiedDate,101) as ModifiedDate

FROM Sales.SalesOrderDetail

WHERE ModifiedDate NOT IN (

SELECT DISTINCT FullDateAlternateKey

MAGAZINE14

Property Name Property Value

IsolationLevel RepeatableRead

TransactionOption Required

P

DATABASES

Page 15: SOFTWARE DEVELOPMENT NETWORK

FROM AdventureWorksDW2008.dbo.FactInternetSales fact

INNER JOIN AdventureWorksDW2008.dbo.DimDate dim

ON fact.OrderDateKey=dim.DateKey)

Listing 4: Distinct dates T-SQL statement

Fig. 2: Create data subset package

CheckpointsTo make a package restartable, SSIS has a feature called checkpointsthat keeps track of the tasks that have executed successfully and thestate of the variables and configurable values at the time of failure. If apackage execution fails, the checkpoint file created will tell the packageto start at the task that failed during the previous execution.Checkpoints allow you to automatically start the package at the pointof failure. If an External System Downtime caused the failure, you canrestart the package and it will not need to redo any of the work it hadcompleted successfully, and it can pick up right at the failed task. Inthe same vein, if an Unexpected Data or Metadata Change problemoccurred, you can fix the issue, knowing that the package will get backonline and runs as soon as possible.Keep in mind that checkpoints only work with Control Flow Tasks.Also, if you need to rerun the entire package after a failed run, you willneed to delete the checkpoint file. Finally, this method doesn’t allowyou to pick and choose where the package next starts up; it will alwaysstart at the task that most recently failed.

To implement checkpoints in your SSIS package, set the FailPacka-geOnFailure property to True on each task that you would to partici-pate in the restartability, and set the properties on the package asshown in table 2.

Table 2: Checkpoint package properties

magazine voor software development 15

Process control tableCreating a process control table is another way to enable restartabi-lity in an SSIS package. This process control table will contain a list ofthe tasks that have run successfully. If the execution of an SSISpackage fails, those tasks not yet completed will not be entered intothe process control table. The next time the package run, thepackage will only run the remaining tasks. After a successful execution,the package deletes all tasks’ records from the process control table.The process control table gives a higher level of control over theexecution of the package. You can create an SSIS package that hasparallel flows and ensure the execution of each task appropriately.Also, if you determine after the SSIS package has already run that youneed to rerun a task that has already run or prevent a task fromrunning, you can simply modify the table, and the SSIS package willpick it up during its next run. This method will handle restartability thatneeds to occur after a package failure due to any of the three errorcategories. Using this method incurs extra development time of crea-ting the process table, handling the conditional logic within the SSISpackage, and creating a standard for task name management. Thismethod should only be undertaken if such fine grain control as men-tioned above proves necessary.

To create the process control table, run the T-SQL script found in lis-ting 5. In an SSIS package, add a Sequence Container that containsan Execute SQL Task. This task should contain the T-SQL statementfound in listing 6 and will retrieve a single row from the processcontrol table that tells the package which tasks to run. The single rowresult set should put the values into string variables representative ofthe columns from the query. In this example, create two variables:Task1 and Task2. Connect a precedence constraint from the ExecuteSQL Task to another Sequence Container that uses the expressionfound in listing 7. This prevents the Sequence Container from runningif the task name is in the process control table. Add two Execute SQLTasks inside the inner Sequence Container, and set up a transactionon this Sequence Container to ensure both statements run atomically.The last Execute SQL Task will insert the task name into the processcontrol table; the T-SQL statement can be found in listing 8. Followthe same procedure of adding the inner Sequence Container and twoExecute SQL Tasks to create a second task grouping. Finally, add asuccess precedence constraint from the outer Sequence Containerto an Execute SQL Task. Use the T-SQL statement in listing 9 todelete all tasks from the process control table once all executionfinished. See the final package in figure 3, which shows the layout anddesign of all tasks.

CREATE TABLE [dbo].[ProcessControl](

[Package] [varchar](50) NOT NULL

,[Task] [varchar](50) NOT NULL)

Listing 5: Create process control table T-SQL statement

SELECTISNULL(SUM(CASE WHEN Task = 'Task1'

THEN 1 ELSE 0 END),0) AS Task1,ISNULL(SUM(CASE WHEN Task = 'Task2'

THEN 1 ELSE 0 END),0) AS Task2FROM dbo.ProcessControl

WHERE Package = 'SDN_ProcessControl'

Listing 6: Get task list T-SQL statement

@Task1 == 0

Listing 7: Precedence constraint expression

INSERT INTO dbo.ProcessControlVALUES ('SDN_ProcessControl','Task1')

Listing 8: Update process control table T-SQL statement

Property Name Property Value

CheckpointFileName C:\SSIS\checkpoint.xml

CheckpointUsage IfExists

SaveCheckpoints True

DATABASES

Page 16: SOFTWARE DEVELOPMENT NETWORK

DELETE dbo.ProcessControl

Listing 9: Delete process control table T-SQL statement

Fig. 3: Process control package

Jessica M. Moss

Jessica M. Moss, a Microsoft SQLServer MVP and business intelli-gence mentor with Solid QualityMentors, is certified as an MCDBA,MCTS: SQL Server 2005 BI, and anMCITP: SQL Server 2005 BI. Shehas been working with SQL Server2005 since its release and has par-ticipated in many warehousing and

reporting solutions. Jessica enjoys working with the local commu-nity and is a regular speaker at user groups, code camps, and con-ferences. You can read about her work on her blog,http://www.jessicammoss.com.

DATABASES

ConclusionThis article covered a number of methods that can create amore reliable SSIS package. Each method has advantages anddisadvantages, as discussed in each section. As with any application,implement the methods that make the most sense for your organiza-tion and your specific package scenario. If you can use one or acombination of these methods in your original design, you will end upwith a more reliable, recoverable, and restartable SSIS package. •

MAGAZINE16

Advertentie MI Consultancy

Page 17: SOFTWARE DEVELOPMENT NETWORK

magazine voor software development 17

helaas wel voor moet worden betaald. Ook wanneer een processorniets doet, wordt er de nodige energie verbruikt, helaas. Herken jedeze situatie?

Waarschijnlijk is het grootste probleem dat we helemaal geenrekening houden met green computing tijdens ons ontwikkelproces.We vinden het gewoonweg niet belangrijk genoeg. Er worden geeneisen gesteld ten aanzien van green computing, maar wel aan schaal-baarheid, performance en beschikbaarheid. Sterker nog, vaak staande eisen die we stellen green computing in de weg. Beschikbaarheidwordt vaak opgelost met meer en redundante hardware. Schaalbaar-heid betekent vaak dat we uitgaan van het scenario dat we de maxi-male load op ieder willekeurig moment aan moeten kunnen; opnieuwresulteert dit in veel hardware.

Wat is green computing?Waar hebben we het eigenlijk over wanneer we over green compu-ting praten? Bij green computing denken we na over hoe we softwareen infrastructuur kunnen ontwikkelen die vriendelijk zijn voor het milieu.We denken na over hoe we applicaties kunnen ontwerpen en realise-ren die het gebruik van resources minimaliseren. Bij green computingwordt vaak alleen aan infrastructuur gedacht, maar de software-architect en -ontwikkelaar hebben minimaal evenveel invloed.Zij nemen dagelijks diverse beslissingen die een positieve of negatieveinvloed hebben op green computing.Is green computing voor iedereen interessant? Ik denk van wel. Wehebben met elkaar natuurlijk een morele verantwoordelijkheid, maarer is ook een andere reden. De belangrijkste reden om na te denkenover green computing is geld! De hoeveelheid energie die wordtverbruikt is natuurlijk aanzienlijk voor een organisatie, en hiervoor moetworden betaald. In de toekomst kunnen we verwachten dat dekosten, maar ook zeker de belastingen, voor energie zullen toenemen.Green computing betekent dat er minder energie wordt gebruikt,en dus dat er bespaard kan worden. Dat is toch voor iedereeninteressant?

Green computing == delenHoe begin je met green computing? De basisgedachte van greencomputing is om niet alles voor jezelf te willen hebben, maar dat jejuist gaat delen. Eigenlijk is green computing niets meer of minder danalles eerlijk delen. Dit klinkt logisch maar is helaas voor de meeste

Astrid Hackenberg

Green Computing:Sparen door te Delen

Als ontwikkelaar en architect hebben wij veel invloed op onze leefomgeving; hier moeten we watmee! Veel mensen gebruiken thuis groene stroom of zijn op andere manieren bezig met eenbeter milieu. Denk je hierover ook na wanneer je software ontwikkelt? Het idee van greencomputing gaat gelukkig steeds meer leven: wij als software bouwers moeten bijdragen aan eenbeter milieu. Dit artikel geeft een overzicht van green computing. Het gaat uiteindelijk allemaalover delen, simpel toch, dus begin er vandaag nog mee!

Wat is het probleem?In de basis is het probleem eenvoudig: we verbruiken als IT-industrieteveel energie. Deze energie moet worden opgewekt en dit is niet goedvoor de CO2-uitstoot, en daarmee slecht voor het milieu. Deze ener-gie wordt gebruikt om onze computers in leven te houden. De CPU eetenergie, de disks eten energie, maar ook de koeling van onze reken-centra verbruikt veel energie. De hoeveelheid energie die doorcomputers wordt opgeslokt is enorm. Je moet denken aan ongeveer2% van alle energie die wordt verbruikt in een gemiddeld West Euro-pees land! De benodigde energie schijnt iedere vijf jaar ook nog eenste verdubbelen. Kortom, het is substantieel! Ook wij, als developers enarchitecten, kunnen ons dit aantrekken. Jarenlang zijn wij verwenddankzij de wet van Moore. De hoeveelheid rekenkracht, disk engeheugen kon niet op. Het tijdperk dat we er serieus over nadachtenom ons programma zo klein en efficiënt mogelijk te maken ligt al verachter ons. Kortom, wij consumeren al die resources zonder enignadenken.

Fig. 1: De wet van Moore

Zo ontwikkelen wij b.v. de meeste van onze code niet alleen op eensingle-processor machine, maar ook voor een single-processormachine. Het is niet ongebruikelijk dat deze code vervolgens op eenserver komt te draaien die meerdere processoren heeft. Dat betekentdat de code draait op een machine die een overvloed heeft aanrekenkracht waar geen gebruik van wordt gemaakt, maar waar

ARCHITECTURE

Page 18: SOFTWARE DEVELOPMENT NETWORK

ontwikkelaars en architecten niet vanzelfsprekend. Wij realiseren vaakproducten waarvan we eisen dat deze exclusief en zelfstandig op eenmachine draaien. Deze software heeft dan specifieke afhankelijkheden,anders dan een eventueel ander product. Om conflicten te vermijdeneisen we exclusiviteit.Het delen wordt vaak gerealiseerd door virtualisatie. Dit is een begrip

dat de laatste jaren steeds meer aan populariteit heeft gewonnen.In basis is virtualisatie niets anders dan het idee om met elkaarresources te delen. Virtualisatie kan klein beginnen en uiteindelijkeindigen in cloud computing. Recentelijk kwam ik bij Microsoft devolgende tabel tegen met virtualisatieniveaus:

Tabel 1: Virtualisatieniveaus

De meeste organisaties verkeren momenteel op niveau 1, al heeftniveau 2 de laatste tijd sterk aan populariteit gewonnen. Aan deniveaus kunnen ook technologieën worden gekoppeld. Deze techno-logieën zijn weergegeven in tabel 2.

Tabel 2: Technologie-aspecten voor virtualisatie

Op ieder niveau zijn er verbeteringen mogelijk. In de rest van dit arti-kel worden de niveaus in meer detail beschreven en wordt er inge-gaan op de mogelijke design- en implementatie-verbeteringen.

Wat kun je doen op niveau 0?Dit is het niveau waar alles lokaal draait, op de eigen machine dus. Opdit niveau wordt er eigenlijk niets gedeeld. Toch zijn er op dit niveauverbeteringen mogelijk. Er wordt namelijk energie verbruikt. Wanneerwe de hoeveelheid benodigde energie naar beneden kunnen brengenis dat dus ook winst.Traditionele ontwerpen houden vaak op geen enkele wijze rekeningmet de hoeveelheid energie die nodig is. Bij veel operating systems isdaar al wel over nagedacht. Vaak heeft dit geresulteerd in eenslaap/wachtstand-mode waarin de computer aanzienlijk minder ener-gie verbruikt. Onze software staat echter een dergelijke mode vaak inde weg omdat we resources blijven claimen. Denk hierbij bijvoorbeeldaan connecties die we open hebben staan, ook op het moment dat erniets gebeurt in de applicatie. Verder gebruiken we in onze applicatiesvaak een overdaad aan data. Deze data moet van disk komen (enweer worden teruggezet). De disk is vaak niet de duurste resource,maar blijft toch een resource die energie nodig heeft. Heb je ooit naarje applicatie gekeken met de gedachte om de hoeveelheid disk-

access te beperken?Verder raad ik iedereen aan om eens met een device driver program-meur te praten. Bij deze programmeurs staat een minimaal en efficiëntdesign nog steeds hoog op de prioriteitenlijst. Een applicatie-ontwerpwaarbij zo min mogelijk gebruik gemaakt wordt van de processor enhet geheugen is ook efficiënter met energiegebruik.

Wat kun je doen op niveau 1?Op dit niveau beginnen we met delen. De eerste stap is vaak eengemeenschappelijke database-server, maar ook mail-, internet-, file-en print-servers worden gedeeld. Dit is het niveau waarop client/server applicaties worden ontwikkeld. Wanneer gekozen wordt vooreen n-tier architectuur wordt vaak ook een applicatie-servergeïntroduceerd. Van niveau 0 naar niveau 1 is een flinke stap voor-waarts. Op dit niveau kan ook nog de nodige consolidatie plaatsvin-den. Heb je echt al die servers nodig? Het is aan de applicatie-programmeur om er voor te zorgen dat de applicatie geen exclusivi-teit nodig heeft, en dat is een essentiële voorwaarde om te kunnendelen. De software-architect speelt op dit niveau ook een belangrijkerol. Het is aan de architect om te zorgen dat er een architectuur en in-frastructuur komt waarin kan worden gedeeld. Het is bijvoorbeeldmakkelijker om met elkaar dezelfde SQL Server instantie te delen danwanneer het noodzakelijk is om én Oracle én SQL Server op een sys-teem te delen. Zorg als architect voor een enterprise architectuurwaarin delen mogelijk is! Dit is ook het niveau waarop ik thuiswerkenzie. Maak het dus mogelijk om thuis te werken. Zorg dat je remote bijmail, files en andere resources kunt komen, b.v. door gebruik van VPN.Thuiswerken past prima in het plaatje van green computing!

Wat kun je doen op niveau 2?Dit is het niveau waaraan de meeste mensen denken wanneer ze hetwoord ‘virtualisatie’ horen. Dit is het niveau waarop alle data wordtgeconsolideerd op een SAN in een rekencentrum. Dit is het niveauwaar virtualisatiesoftware zoals Microsoft Virtual Server of VMWarewordt gebruikt.Op dit niveau gaan we nadenken over het optimaal gebruiken vanonze servers. Een zeer aansprekend voorbeeld voor software-ontwik-kelaars is de virtualisatie van de OTAP-omgeving. Het is toch nietnoodzakelijk om voor iedere omgeving binnen de OTAP een fysiekeserver beschikbaar te hebben … logisch toch?Maar er zijn meer mogelijkheden. Je kunt b.v. bedenken om de print-of applicatie-server ’s avonds te stoppen en in de ochtend weer testarten. Het starten en stoppen van virtuele machines is standaardfunctionaliteit die kan worden toegepast.Wat kunnen wij doen als ontwikkelaars? Zorg ervoor dat je applicatiegeen directe afhankelijkheid heeft van de onderliggende hardware.Zorg ervoor dat jouw applicatie kan draaien in een virtuele machine!

Wat kun je doen op niveau 3?Dit is het niveau waarop de droom van alles delen werkelijkheid wordt.We delen resources in ‘de cloud’ en richten niet meer onze eigenrekencentra in. We maken gebruik van de schaalgrootte die voordeligis voor het totale energieverbruik. Heel eenvoudig: 2 servers die voor50% worden belast zijn nadeliger voor het milieu dan 1 server waarop2 virtuele omgevingen draaien waardoor de machine voor 100% wordtbelast.

Veel leveranciers zijn momenteel bezig om cloud computing te reali-seren. Partijen als Amazon en Google hebben of richten grote reken-centra in om ons te voorzien van cloud computing. Ook Microsoftbegeeft zich nadrukkelijk op dit front met het Azure Services Platform.

MAGAZINE18

Thuiswerken past prima in het plaatjevan green computing!

Virtualisatie- Naam Applicatie Infrastructuur Locatie EigenaarniveausNiveau 0 Local Dedicated Fixed Gedistribueerd InternNiveau 1 Logical Shared Fixed Gecentraliseerd InternNiveau 2 Data Shared Virtueel Gecentraliseerd Intern

centerNiveau 3 Cloud Software as Virtueel Virtueel Virtueel

a Service

V

Virtualisatie- Technologie-Aspectenniveaus Naam Server Opslag NetwerkNiveau 0 Local Standalone PC Lokale disk GeenNiveau 1 Logical Client/ server File server LAN

N-tier Database server

Niveau 2 Data center Server SAN WAN/ VPNvirtualisatie

Niveau 3 Cloud Cloud platform Cloud storage Internet

ARCHITECTURE

Eigenlijk is green computing niets meerof minder dan alles eerlijk delen

Page 19: SOFTWARE DEVELOPMENT NETWORK

Ook binnen cloud computing kennen we verschillende varianten:• Software as a Service (SaaS)• Attached services• Cloud platformsDe verschillende typen cloud computing zijn weergegeven in figuur 1.

Fig. 2: Verschillende typen cloud computing

Ook bij cloud computing zijn er dus nog diverse keuzes te maken. Deene keuze heeft een voordeliger effect voor green computing dan deandere. Nog steeds blijft gelden: des te meer je deelt, des te beter.Toch blijft het ook noodzaak om bewust voor een leverancier en eendatacentrum te kiezen. Hoe gaan de leveranciers met energie om?Waar is het rekencentrum gebouwd? Een rekencentrum in Finland isminder kosten kwijt aan koeling dan een rekencentrum in Zuid-Spanje.

De keuze voor cloud computing levert de ontwikkelaar het meestewerk op. Een applicatie ontwikkelen voor de cloud vereist namelijkspecifieke design- en programmeervaardigheden. Is een applicatiewerkelijk altijd beschikbaar? Wat wanneer dit niet het geval is?

Het ontwerp van de applicatie moet hier mee om kunnen gaan. Demeeste cloud leveranciers bieden momenteel een eigen API. Je moetkennis opdoen van deze API. Daarnaast zijn er op dit moment geenrelationele databases beschikbaar in de cloud, maar wordt alle datahiërarchisch opgeslagen. De applicatie moet daar mee om kunnengaan. Kortom veel werk aan winkel!

ConclusieVandaag is een goed moment om na te gaan denken over greencomputing. Alle middelen en technieken zijn voorhanden om het beterte gaan doen. Dit is een goede zaak voor het milieu, maar zeker ookvoor onze portemonnee. Green computing is niet alleen iets voor ‘dieander’, maar is ook voor ons als software-ontwikkelaars van belang.Misschien hebben wij wel de meeste impact wanneer het green com-puting betreft. We zouden wellicht labels moeten gaan toekennen aanonze software die aangeven hoe “groen” we zijn. De IT zou niet deeerste branche zijn waar dit gebeurt. Laten we in ieder geval beginnenmet te delen!Op z’n minst kunnen we beginnen bij onze eigen com-puters. Hoe efficiënt is jouw software? Staat jouw ontwikkelcomputeraltijd aan? Gebruik je een slaapstand? Een aardige start voor greencomputing is te vinden op op http://www.eco-button.com/ •

ARCHITECTURE

Astrid Hackenberg

Astrid Hackenberg is mede-oprich-ter van Class-A en werkzaam alsadviseur, trainer en coach. Haarwerkgebied is het Microsoft appli-catie platform en dan met name ser-veroplossingen gebruikmakend vanBizTalk Server, SQL Server, Share-Point Server.

Advertentie Sybase iAnywhere

Page 20: SOFTWARE DEVELOPMENT NETWORK

MAGAZINE

Exposing Line-of-Business (LOB) data to Office clientsBefore jumping into building the WPF control you need to think abouthow you can access data in your databases. There are a lot ofoptions when thinking about how to expose your LOB data to Officeclients. For instance, you may already have a service-orientedarchitecture at the enterprise that exposes data contracts andprocesses that you can consume from Office clients. Or maybe youhave a small business and have decided to expose a simple servicethat returns and consumes n-tier data sets directly. Or you alreadyhave a custom LOB data entry system using custom business objectsand you want to reuse the business layer in the Office client. Becauseyou can consume data in Office clients the same way you do in otherWindows applications the same types of decisions need to be made.Because there is only going to be simple CRUD (Create-Retrieve-Update-Delete) operations in this example, I will expose an Entity DataModel via ADO.NET Data Services. This allows you to get a secureservice up and running in minutes. I will not spend much time on thisbut I’ll show the basics. For more information on ADO.NET DataServices please read the article “Using Microsoft ADO.NET DataServices” in the MSDN library.

To quickly build a data service for this example, create a new ASP.NETWeb Application named NorthwindDataService and add a new itemADO.NET Entity Data Model (EDM) to the project that is generatedfrom the Northwind database called NorthwindModel. Next add a newitem and select ADO.NET Data Service and name it Northwind. (Pleasenote: You will need Visual Studio 2008 Service Pack 1 in order to getthese new item templates.) For testing, set the service to allow fullaccess to all the entities in the model (but do not forget to lock it downlater if you deploy to production). For this example I also am passingdetailed errors which you will not want to do in production either.

Public Class Northwind

Inherits DataService(Of NorthwindEntities)

' This method is called only once

' to initialize service-wide policies.

Public Shared Sub InitializeService( _

ByVal config As IDataServiceConfiguration)

config.SetEntitySetAccessRule("*", _

EntitySetRights.All)

config.UseVerboseErrors = True

End Sub

End Class

Beth Massi

Using Windows PresentationFoundation and Line-of-BusinessData in Microsoft Office ClientsWindows Presentation Foundation (WPF) is avector-based presentation system for buildingWindows client applications with visually stun-ning user experiences. WPF is an alternative toWindows Forms for designing user interfacesthat uses a markup language called ExtensibleApplication Markup Language (XAML) toprovide new techniques for incorporating UI,media, and documents.Although Office solutions you build with VisualStudio are designed to work with WindowsForms controls, you can use WPF controls inyour solutions as well. Any UI element that canhost Windows Forms controls in a Visual Stu-dio Tools for Office solution can also host WPFcontrols. One major benefit of using WPF con-trols in Office is that you are able to provideworld-class data visualizations that are notpossible with Windows Forms controls in aninstantly familiar end-user application. Even thesimplest controls that display data are oftenbetter off as WPF controls in Office applicati-ons because they better match the UI stylesused in the latest versions of Office. Using WPFcan make your add-ins look built into the Officeapplications themselves, providing a betteruser experience. In this article I will create adocument customization for an Excel 2007Workbook that is used by the NorthwindTraders shipping department that pulls Orderdata from the Northwind database through anADO.NET Data Service. The customization willdisplay the order details in an Action Pane builtwith WPF and will allow users to update theorder data through the data service.

Even the simplest controls that displaydata are often better off as WPFcontrols in Office applications

UXINFORMATION

WORKER

20

Page 21: SOFTWARE DEVELOPMENT NETWORK

Now that the data is exposed as an ADO.NET Data Service you canbuild the Office client which will consume this service.

The Excel document customizationTo create a document customization for Excel, add a new project tothe solution and select Office 2007 Excel Workbook which is availablein Visual Studio 2008 Professional and higher. Since I am building adocument customization and not an Add-In this means that code willonly run on the specific document as opposed to running in the Excelapplication over any document that is opened. After the project isadded, Visual Studio asks if you want to import an existing Excel work-book or create a new one. For this example create a new one namedthe same name as the project, i.e. NorthwindClientExcel.xlsx. Afteryou specify this, the project is created and the Excel designer opens.The next step is to add the data service reference. Right-click on theproject, select Add Service Reference. Click the Discover button andit should find the ADO.NET data service in the solution calledNorthwindDataService. Name the service reference NorthwindService.This will generate the proxy to the service and the entity types on theclient.

Data binding in ExcelNow that the service reference is created you can retrieve a list ofOrder entities that have not been shipped yet and display them in thefirst sheet of the workbook. But you will also want to show the OrderDetails and display the Quantity and Product that should be shipped.You will do this using an Excel Action Pane by setting up a master-detail view of the data. So as the user scrolls through the Order rows,the Action Pane will display the Order Details in a WPF GridView. Theuser only needs to make changes to the Order rows so this designwill work well. The magic control you use in Excel to bind data to rowsis called the ListObject. This object can easily bind to a WinformsBindingSource just like any other Winforms control. To set up the datasource so it can be bound to a BindingSource, you need to create aBindingList(Of Order) so that list change notifications are communica-ted to the UI. You also need to add code to the Order partial class onthe client so that property change notifications are also sent.

So first create a new class named Order and place it in the sameNamespace as the NorthwindService service reference that was justadded. This is where the client proxy objects are generated for you. Inorder to extend these classes with your own code, just place it into thesame Namespace. (Here's a Visual Basic tip, you know you've got itright if you see the Order properties and methods in the Declarationsdrop down above the editor for the Order class.) You need to fire achange notification on all of the properties of the Order so I've placedcode to do this in all the xxxChanged() partial methods. Take a look atthe code download for how to do this.Next you need to create a BindingList(Of Order). I'm going to create aclass called MyOrdersList that inherits from this which will alsoencapsulate the calls to the ADO.NET Data Service. MyOrdersList willuse the data service context on the client (NorthwindService in thiscase) to retrieve and update the Orders. In this example you do notwant to allow adds or deletes because orders are going through aworkflow and our shipping department is only updating the informa-tion on an order, specifically the ShippedDate. So you need to over-ride AddNewCore and RemoveItem to prevent this. Also override theOnListChanged so that the Order entity can be marked as updated.

There are also couple housekeeping fields for saving and for exposinga HasChanges property. The interesting code to notice here is that theMergeOption is specified on the data service client to OverwriteChan-ges after the save, as opposed to the default AppendOnly. This meansthat after the changes are saved it will refresh the existing Order entityinstances with changes from the database. Here is the beginning of theMyOrdersList class that handles this:

magazine voor software development 21

Imports NorthwindExcelClient.NorthwindService

Imports System.ComponentModel

Public Class MyOrderList

Inherits BindingList(Of Order)

Private DataServiceContext As New _

NorthwindEntities(New _

Uri(My.Settings.ServiceURI))

Private _hasChanges As Boolean

Private _isSaving As Boolean

Public ReadOnly Property HasChanges() As Boolean

Get

Return _hasChanges

End Get

End Property

Sub New()

MyBase.New()

Me.DataServiceContext.MergeOption = _

Services.Client.MergeOption.OverwriteChanges

End Sub

Protected Overrides Function AddNewCore() As Object

Throw New NotSupportedException( _

"You cannot add items to the list.")

Return Nothing

End Function

Protected Overrides Sub RemoveItem( _

ByVal index As Integer)

Throw New NotSupportedException( _

"You cannot remove items from the list.")

End Sub

Protected Overrides Sub OnListChanged( _

ByVal e As System.ComponentModel.ListChangedEventArgs)

If Not _isSaving Then

'The Order partial class is implementing

' INotifyPropertyChanged so this will work

If e.ListChangedType = _

ListChangedType.ItemChanged Then

Me.DataServiceContext.UpdateObject(Me(e.NewIndex))

_hasChanges = True

End If

MyBase.OnListChanged(e)

End If

End Sub

Before I write the code that will retrieve and save the orders, I will bindthis to a ListObject and get it onto the Excel worksheet. Since you willhave to interact with the list of orders from Sheet1 as well as theAction Pane displaying the details, it is easiest to create a property onthe Workbook itself that exposes the MyOrdersList. Double-click onthe ThisWorkbook in the project and switch to the Code view andcreate a property to expose the OrderList.

Now build the project and open the Data Sources window. Add a newObject Data Source and select MyOrderList then Finish. Drag theMyOrderList onto the designer for Sheet1, just drop it into the first cell,and it will generate all the columns for every property on the Order.

You can also change the name of it on the Design tab and I'll changethis one to OrderListObject as shown in figure1.

UXINFORMATION

WORKER

Page 22: SOFTWARE DEVELOPMENT NETWORK

Fig. 1: Drop data sources directly onto Excel sheets to set up databinding automatically

Unfortunately it drops all the columns regardless if you select a droptarget of none or not in the data sources window. Right-click on thecolumn and select Delete from the drop-down menu to delete acolumn (do not press the delete key, use the context menu). For thisexample remove the first three and the last three columns that it drop-ped. Another quirk of the ListObject is that you will need to set anydate fields to Text format. The ListObject will not let you change datevalues if the formatting isn't set to text. You do this by selecting thecolumn then right-click, select Format Cells, and then select Text fromthe list. This is usually OK to do because the data source, in this casethe Order, enforces the data type to be a date.

You can be explicit about setting the data source and binding tocolumns in the startup event handler of the sheet as shown here:

Public Class Sheet1

Private Sub Sheet1_Startup() Handles Me.Startup

Dim myApp = NorthwindExcelClient.Globals.ThisWorkbook

Me.OrderBindingSource.DataSource = myApp.OrderList

Me.OrderListObject.SetDataBinding( _

Me.OrderBindingSource, "", _

"ShippedDate", _

"Freight", _

"ShipName", _

"ShipAddress", _

"ShipCity", _

"ShipRegion", _

"ShipPostalCode", _

"ShipCountry")

Me.OrderListObject.AutoSelectRows = True

myApp.LoadOrders()

End Sub

You should notice that the last line calls a method on ThisWorkbookto load the orders. In order to load the order entities you will write aquery against the ADO.NET data service next.

Querying and saving orders via the data serviceLooking back to the MyOrdersList class you can now write a methodfor returning the list of orders that have not yet been shipped. Call theservice to return a list of unshipped orders, add them all to MyOrder-List and then raise the list changed event to notify the Excel ListObjectto refresh its UI as shown here:

Public Function LoadOrders() As Integer

Me.Clear()

Me.RaiseListChangedEvents = False

Dim orders = From o In Me.DataServiceContext.Orders _

Where o.ShippedDate Is Nothing _

Order By o.OrderDate

For Each o In ordersMe.Add(o)

Next

Me.RaiseListChangedEvents = TrueMe.OnListChanged(New _

ListChangedEventArgs(ListChangedType.Reset, 0))Return Me.Count

End Function

You will also need a way to load the order details, shipper and productentities when requested. This will happen as the user selects rows ofdata and you need to display these details in the Action Pane. Bydefault these entity references and collections are not loaded so youneed to do this explicitly. This is a good thing in this case because itavoids transferring unnecessary data if the user doesn't select theOrder row in the sheet. Here is the code to load the details:

Public Sub LoadOrderDetails(ByVal o As Order)If (o IsNot Nothing) Then

If o.Shipper Is Nothing ThenMe.DataServiceContext.LoadProperty(o, _"Shipper")

End IfIf o.Order_Details Is Nothing OrElse _

o.Order_Details.Count = 0 ThenMe.DataServiceContext.LoadProperty(o, _

"Order_Details")For Each detail In o.Order_Details

detail.Order = oIf detail.Product Is Nothing Then

Me.DataServiceContext.LoadProperty(detail, _"Product")

End IfNext

End IfEnd If

End Sub

Finally you need a method that submits changes back to the dataservice. This is easily done by calling SaveChanges on the servicecontext which sends all the changes that were made in the clientthrough the service, i.e. Me.DataServiceContext.SaveChanges(). Inthis example they are not sent in a single batch, therefore if one orderfails to update the ones before the failure will still be saved. Depen-ding on your scenario you can opt to use a batch request by passingthat flag in the call to SaveChanges. You also may need to put morerobust error handling here depending on what kind of failures youanticipate in your applications. Simple error handling is done for thisexample in the Action Pane which you will build next.

Creating an Excel action pane using WPFNow you are ready to design the Action Pane that will display the orderdetails. The control will display this in a simple read-only GridView thatmatches the Excel blue gradients and fonts. It will also provide astatus message area and a Save and Refresh button. Refresh willre-load the orders from the service and Save will send the changesback. (Later I’ll show how you can hook up Excel's save button to dothe same thing.) It will also run a couple of animations when rows areselected in the sheet to draw the user’s attention to the Action Pane.This is because by default Action Panes are displayed on theright-hand side of the spreadsheet.

MAGAZINE22

In order to display WPF in a WindowsForm control you use the WinformsElementHost as a container for yourWPF control

UXINFORMATION

WORKER

Page 23: SOFTWARE DEVELOPMENT NETWORK

In order to display WPF in a Windows Form control, including Officesolutions built with Visual Studio, you use the Winforms ElementHostas a container for your WPF control. This is found in the WPF Inter-operability Tab on your toolbox. When you drop this control onto thedesigner you can immediately select the WPF user control to display.So first we need to build a WPF user control.Add a new item to the project and select WPF category on the leftand then choose WPF User Control, I named it WPFActionPane forthis example, and click OK. Take a look at the code sample for the fullXAML source code which describes the layout and data bindings ofthe controls as well as the styles used to make the GridView have anice Excel-friendly look. The following code listing highlights the basics:

<UserControl x:Class="WPFActionPane"...<UserControl.Resources><Storyboard x:Key="LoadingStoryBoard">...<Storyboard x:Key="UpdateStoryBoard">...<Style x:Key="GridViewStyle" TargetType="TextBox">...<Style x:Key="ListViewStyle" TargetType="ListView">...<Style x:Key="ListViewItemStyle"

TargetType="ListViewItem">...<Style x:Key="GridViewColumnHeaderStyle"

TargetType="GridViewColumnHeader">...</UserControl.Resources>

<Grid Height="Auto" Width="Auto" Name="MainGrid"><Grid.RowDefinitions>...

<StackPanel Orientation="Horizontal"><Button Height="40" Name="cmdSave" ...<Button Height="40" Name="cmdRefresh" ...

</StackPanel><StackPanel Grid.Row="1">

<TextBlock Name="txtShipper"Width="Auto" Height="25"Text="{Binding

Path=Shipper.CompanyName,StringFormat=Ship via \{0\}}"

Foreground="DarkBlue" /><TextBlock Name="txtOrderDate"

Width="Auto" Height="25"Text="{Binding

Path=OrderDate,StringFormat=Ordered \{0:D\}}"

Foreground="DarkBlue"/></StackPanel><Image Grid.Row="2" Source="northwindlogo.gif" /><Grid Grid.Row="2" Background="White" Name="ListGrid">

<ListView ItemsSource="{Binding Path=Order_Details}"Style="{StaticResource ListViewStyle}"ItemContainerStyle="{StaticResource ListViewItemS-

tyle}"Name="ListView1" Margin="4" IsEnabled="True"BorderThickness="0"><ListView.View>

<GridView ColumnHeaderContainerStyle="{StaticResource GridViewColumnHeaderStyle}"><GridViewColumn Header="Product">

<GridViewColumn.CellTemplate><DataTemplate>

<TextBoxText="{Binding Path=Product.Product-

Name}"Style="{StaticResource GridViewStyle}"/>

</DataTemplate></GridViewColumn.CellTemplate>

</GridViewColumn><GridViewColumn Header="Quantity">

<GridViewColumn.CellTemplate><DataTemplate>

<TextBox Text="{Binding Path=Quantity,StringFormat='n0'}"Style="{StaticResource GridViewStyle}"

/>

</DataTemplate></GridViewColumn.CellTemplate>

</GridViewColumn></GridView>

</ListView.View></ListView>

</Grid><Grid Grid.Row="3">

<TextBox Name="txtStatus"...</Grid>

</Grid>

</UserControl>

The code that calls the load and save on the orders will be here sincethis control will interact directly with the list of Orders. In the code-behind of the WPFActionPane it also animates the control by runningthe StoryBoards defined in the XAML when either the order details aredisplayed or when the status messages at the bottom of the panechanges. Note that I also included the images referred by the XAMLabove into the project and set their Build Action to Resource in theproperties for the files in the Solution Explorer.

First pass the reference to the list of Orders into the WPF control andthen set it as the DataContext. This will trigger all the data bindings tohook up to the currently selected Order’s details as noted by the databindings in the XAML above. For instance, if you want to display theshipper’s company name then specify the Shipper.CompanyNamepath on the Order object contained in the list. The code for the WPFuser control is as follows:

Imports NorthwindExcelClient.NorthwindServiceImports System.Windows.DataImports System.Windows.Media

Partial Public Class WPFActionPane

Private _orderList As MyOrderListPublic Property OrderList() As MyOrderList

GetReturn _orderList

End GetSet(ByVal value As MyOrderList)

_orderList = valueMe.DataContext = _orderList

End SetEnd Property

Private Sub cmdRefresh_Click() Handles cmdRefresh.ClickMe.LoadOrders()

End Sub

Private Sub cmdSave_Click() Handles cmdSave.ClickMe.SaveOrders()

End Sub

Public Function SaveOrders() As BooleanDim msg = “Orders could not be saved.” & vbCrLfTry

‘Save changes back to the data serviceIf Me.OrderList.SaveChanges() Then

msg = “Orders saved.”End If

Me.SetMessage(msg)

Catch ex As ExceptionMe.SetMessage(ex.ToString())

End TryEnd Function

Public Sub LoadOrders()Dim msg = “”

magazine voor software development 23

UXINFORMATION

WORKER

Page 24: SOFTWARE DEVELOPMENT NETWORK

TryDim count = Me.OrderList.LoadOrders()msg = String.Format(“{0} orders returned.”, count)

Me.SetMessage(msg)Me.ButtonStack.Visibility = _

Windows.Visibility.VisibleCatch ex As Exception

Me.SetMessage(ex.ToString())End Try

End Sub

Public Sub DisplayOrderDetails(ByVal o As Order)If o IsNot Nothing Then

Me.OrderList.LoadOrderDetails(o)Dim view = _CollectionViewSource.GetDefaultView(Me.DataContext)

view.MoveCurrentTo(o)

Me.ListGrid.Visibility = Windows.Visibility.VisibleMe.ListView1.SelectedIndex = -1Dim story = CType(Me.Resources(“LoadingStoryBoard”),_

Animation.Storyboard)story.Begin()

End IfEnd Sub

Public Sub SetMessage(ByVal msg As String)Me.txtStatus.Text = msgDim story = CType(Me.Resources(“UpdateStoryBoard”), _

Animation.Storyboard)story.Begin()

End Sub

End Class

Now you can create the Action Pane. Add a new item to the projectand select Actions Pane Control from the Office group. I named itOrdersActionPane. This opens up the Windows Forms User Controldesigner and you can drop any Windows Forms controls on here. Toadd the WPF user control open the WPF Interoperability category inthe toolbox and you should see the ElementHost control. Drag thatonto the Actions Pane user control, click the smart tag in the upperright, and then select the WPFActionPane control as the hostedcontent and dock it in the parent container. You also need to set thefont of the OrdersActionPane to Calibri 11 point.

In the code behind for the OrdersActionPane set the OrderList for theWPF control and add a handler to listen to the position changed eventon the OrderBindingSource that is hooked up as the DataSource of theListObject on Sheet1. When the position changes the WPF control isnotified to display the selected Order’s details. There are many waysto integrate WPF and Windows Forms to manage data sourcecurrency but for this example let’s keep it simple. The code for theOrdersActionPane is below:

Imports System.Data.Services.ClientImports NorthwindExcelClient.NorthwindService

Public Class OrdersActionsPane

Private Sub OrdersActionsPane_Load() Handles Me.Load‘Pass in our data source to the WPF controlMe.WpfActionPane1.OrderList = _

NorthwindExcelClient.Globals.ThisWorkbook.OrderList‘When the position changes in the spreadsheet,‘ display the order details in the WPF controlAddHandler _

NorthwindExcelClient.Globals.Sheet1. _OrderBindingSource.PositionChanged,

AddressOf Me.DisplayOrderDetailsEnd Sub

Private Sub DisplayOrderDetails( _ByVal sender As Object, _ByVal e As EventArgs)Dim source = TryCast(sender, BindingSource)If source IsNot Nothing Then

If source.Position > -1 ThenMe.WpfActionPane1.DisplayOrderDetails( _

TryCast(source.Current, Order))End If

End IfEnd Sub

End Class

You are almost ready to test this out. The last thing you need to do isload the Actions Pane when the application starts as well as exposea LoadOrders to our Sheet. This is because if you are adding charts,pivot tables or other types of controls for data analysis you cannot relyon the Action Pane loading the data, you need the sheet to be able tocall upon it explicitly. You will also hook up the Excel BeforeSave eventso that save can be called on the orders when users click the normalsave button on the Excel toolbar. So back in the ThisWorkbook classenter the following code under the code you wrote previously:

Private _orderActions As New OrdersActionsPane

Private Sub ThisWorkbook_Startup( _ByVal sender As Object,_ByVal e As System.EventArgs) Handles Me.Startup'Load the action paneMe.ActionsPane.Controls.Add(_orderActions)

End Sub

Public Sub LoadOrders()_orderActions.WpfActionPane1.LoadOrders()

End Sub

Private Sub ThisWorkbook_BeforeSave( _ByVal SaveAsUI As Boolean, _ByRef Cancel As Boolean) Handles Me.BeforeSave_orderActions.WpfActionPane1.SaveOrders()

End SubEnd Class

Hit F5 and try it out. You will see all the Orders that have not shippedload into the sheet. As you select a row, the details are displayed in theAction Pane and an animation that shows the Northwind logo fadesinto and out of view so that it draws the user's attention to the ActionPane on the far right. Modify any of the fields in the Sheet and click thesave button to save your changes back to the service. Figure 2 showsthe Excel client as a new row is being selected and the transition istaking place on the WPF control on the Action Pane.

Fig. 2: The Excel client with a WPF control on the Action Pane as anew row is being selected

MAGAZINE24

UXINFORMATION

WORKER

Page 25: SOFTWARE DEVELOPMENT NETWORK

This example is included in a complete Office Business Application(OBA) sample that is available online at http://code.msdn.micro-soft.com/OBANorthwind. The Excel client in that example also inclu-des how to create a pivot table and chart that refreshes when the datacomes back from the service. The other pieces of the sample showhow to build a complete OBA solution using Outlook, Word and aSharePoint workflow and can be used independently so I encourageyou to have a look.

Using WPF in business applications built for Office is easy to do andprovides a much better user experience and look-and-feel thantraditional Windows Forms controls. You can easily make your add-insand document customizations appear like they are truly part of theOffice application itself. WPF makes it possible to provide stunningvisualizations on top of your line-of-business data in an applicationthat is very familiar to the end user. Enjoy! •

Beth Massi

Beth is a Program Manager on theVisual Studio Community Team atMicrosoft and is responsible forproducing and managing contentfor business application developers,driving community features andteam participation onto MSDN De-veloper Centers (http://msdn.com),and helping make Visual Studio one

of the best developer tools in the world. She also produces regu-lar content on her blog (http://blogs.msdn.com/bethmassi),Channel 9, and a variety of other developer sites and magazines.As a community champion and a long-time member of theMicrosoft developer community she also helps with the San Fran-cisco East Bay .NET user group and is a frequent speaker atvarious software development events. Before Microsoft, she wasa Senior Architect at a health care software product company anda Microsoft Solutions Architect MVP. Over the last decade shehas worked on distributed applications and frameworks, web andWindows-based applications using Microsoft development toolsin a variety of businesses. She loves teaching, hiking, mountain bi-king, and driving really fast.

UX TIP:404 error pagina, hoe het ook kan…Een 404 error pagina hoeft niet altijd het einde van het bezoekaan je site te betekenen. Goed ontworpen 404 error pagina’skunnen ervoor zorgen dat de bezoeker op je website blijft enalsnog de informatie vindt waar hij naar op zoek was. Laat debezoeker weten waarom de pagina die hij/zij probeert te ope-nen niet weergegeven kan worden en biedt alternatieve moge-lijkheden, zoals een zoekmogelijkheid en (beknopte) navigatie.Meer informatie over 404 error pagina’s en inspirerende voor-beelden zijn te vinden ophttp://www.smashingmagazine.com/2009/01/29/404-error-pages-one-more-time/.

Advertentie Aladdin

Page 26: SOFTWARE DEVELOPMENT NETWORK

Advertentie Bergler

Page 27: SOFTWARE DEVELOPMENT NETWORK

INFORMATIONWORKER

UX

magazine voor software development 27

applicatie. Designers openen vervolgens hetzelfde project in MicrosoftExpression Blend en gebruiken Blend voor het creëren van de userinterface. Door het gebruik van verschillende tools mogelijk te makenkunnen zowel developers als designers gebruik maken van eenomgeving die is afgestemd op hun specifieke wensen en eisen.

In de Silverlight plugin zit het Silverlight .Net Framework. Het Silver-light .Net Framework is een uitgeklede versie van het gewone .NetFramework. Als je ontwikkelt voor Silverlight, heb je dus niet alleclasses uit het gewone .Net Framework tot je beschikking.Aan de ene kant is dit een noodzaak, omdat eindgebruikers andersvoor het draaien van een Silverlight applicatie het volledige .NetFramework van ongeveer 200MB zouden moeten downloaden eninstalleren, in plaats van de 5MB van het Silverlight .Net Framework.Aan de andere kant is het ook logisch, omdat bepaalde classes nietvaak gebruikt zullen worden in applicaties die op de client draaien. Eenvoorbeeld hiervan is de System.Data.SqlClient namespace diegebruikt wordt voor het benaderen van een SQL Server database.Aangezien de SQL Server database meestal op de server zal draaienen niet op de client, zul je deze namespace niet missen bij hetontwikkelen van een Silverlight applicatie.

Mirjam van Olst

SilverlightWeb Parts in SharePoint

Wat is Silverlight?De meeste mensen zullen inmiddels waarschijnlijk wel weten watSilverlight is. Voor de zekerheid toch nog even een samenvatting:• Silverlight is een browser plugin• De huidige versie van Silverlight is versie 2

- Versie 2 is in oktober 2008 gelanceerd- Versie 2 biedt ondersteuning voor het gebruik van ManagedCode in Silverlight applicaties

• Om een snelle download mogelijk te maken is de plugin minder dan5MB groot

• Silverlight is cross-browser, cross-platform; het draait bijvoorbeeldin Internet Explorer, Firefox en Apple Safari browsers en het draaitop zowel Windows als Apple besturingssystemen

• De Silverlight applicatie draait dus op de client, niet op de server!

Silverlight maakt het mogelijk om visueel sensationele en interactieveoplossingen te bouwen die in de browser draaien. Omdat de code inde browser draait, erft de Silverlight applicatie ook de eigenschappenvan de browser. Dit betekent dat de code maar beperkte rechten heeftop de client. De reden hiervoor is dat je natuurlijk niet wilt dat eenSilverlight applicatie die je in je browser bekijkt toegang heeft totbijvoorbeeld je harde schijf.

In Silverlight is het, net als in gewone ASP.NET pagina's en usercontrols, zo dat de user interface en de styling van een controlvolledig los staan van het gedrag van het control. Je gebruikt zelfsverschillende programma's voor het ontwikkelen van de logica en deuser interface. Developers gebruiken hun vertrouwde Visual Studio2008 omgeving voor het ontwikkelen van de logica van de Silverlight

Het gebruik van het three layered application pattern bij het bouwen van Silverlightweb parts in SharePointMet behulp van Silverlight kunnen applicaties met een rijke user interface gebouwd worden.Deze applicaties leven in de browser en kunnen bijvoorbeeld in een HTML pagina geplaatstworden. Daarnaast kunnen Silverlight applicaties ook in web parts gebruikt worden. Door hetgebruik van Silverlight applicaties in SharePoint web parts krijg je the best of both worlds. Metde rijke user interface mogelijkheden van Silverlight kunnen prachtige, grafische web partsgebouwd worden met bijvoorbeeld mogelijkheden voor 3D en grafieken. Daarnaast zorgt hetgebruik van Silverlight ervoor dat er minder pagina refreshes nodig zijn, waardoor het gebruikvan de applicatie voor de gebruiker prettiger en sneller is. Tegelijkertijd kan gebruik gemaaktworden van bijvoorbeeld de collaboratie- en search-mogelijkheden van SharePoint.Dit artikel legt uit welke stappen nodig zijn om een Silverlight web part in SharePoint te bouwenen ook op welke manieren data uit de SharePoint omgeving in het Silverlight web part gebruiktkan worden.

Omdat de Silverlight applicatie opde client draait is het niet mogelijk omdata of applicaties op de server directte benaderen

Page 28: SOFTWARE DEVELOPMENT NETWORK

Omdat de Silverlight applicatie op de client draait is het niet mogelijkom data of applicaties op de server direct te benaderen. Je kunt dushet SharePoint Object Model niet direct aanspreken en je kunt dataniet direct uit databases op de server lezen. Toch wil je de data uit dedatabase, of een andere externe data bron, natuurlijk wel graaggebruiken in je applicatie. Geen nood, want Silverlight ondersteunt hetgebruik van (web) services. Dit kunnen SOAP services zijn diegebouwd zijn met Windows Communication Foundation (WCF), ofgewoon HTTP of REST services. Ook RSS feeds kunnen primagebruikt worden voor het opvragen van data die in Silverlight web partsgetoond wordt.

Het voorbeeld: een Silverlight foto web partAls voorbeeld zullen we een Silverlight foto web part voor SharePointgaan bouwen. Het web part toont een rij thumbnails met foto’s uit eenbepaalde databron. Als je een foto selecteert, dan wordt boven de rijmet thumbnails de grote foto getoond. Het mooie aan dit web part is,dat je met dit ene web part foto’s uit meerdere databronnen kunttonen, terwijl de code van het web part zelf niet verandert. In ditartikel zal ik laten zien hoe je foto’s uit een SharePoint picture librarykunt tonen en hoe je foto’s van Flickr kunt tonen.Voordat we kunnen beginnen met het bouwen van het web partmoeten we eerst SharePoint configureren zodat de SharePoint webapplicatie het gebruik van Silverlight ondersteunt.

SharePoint configureren voor SilverlightIk ga ervan uit dat je een SharePoint omgeving hebt opgezet waaropminimaal SP1 en de December Cumulative Update voor WSS enMOSS geïnstalleerd zijn. Daarna moet je de volgende stappendoorlopen om Silverlight web parts voor SharePoint te kunnenontwikkelen:• Installeer Visual Studio 2008 met SP1• Installeer het .Net Framework 3.5 SP1• Installeer de Silverlight Tools voor Visual Studio 2008 SP1• Voeg de System.Web.Silverlight.dll file toe aan de Global Assembly

Cache. De dll is normaal gesproken te vinden in de C:\ProgramFiles\Microsoft SDKs\Silverlight\v2.0\Libraries\Server directory

• Registreer het .xap MIME type voor de web applicatie waarin je hetweb part wilt hosten. Dit doe je door de properties van de webapplicatie in IIS te openen en dan op het tabje HTTP Headers opMIME Types te klikken. Voeg als Extension .xap toe en als MIMEType application/x-silverlight-app.

Fig. 1: Het toevoegen van het .xap MIME type

28 MAGAZINE

• Voeg de Silverlight elementen toe aan de web.config. De juiste toe-voegingen kunnen gevonden worden op http://www.zimmer-gren.net/archive/2008/03/19/how-to-get-up-and-running-with-the-silverlight-2-0-blueprints-for-sharepoint-2007.aspx.

De SharePoint omgeving is nu geschikt voor het gebruik van Silverlightin pagina’s en web parts. Je kunt nu beginnen met het bouwen van hetSilverlight foto web part.

Het three layered application patternHet three layered application pattern is een software design pattern.Bij het three layered application pattern wordt de code opgebouwd inverschillende lagen, waarbij het idee is dat elk van deze lagen aan tepassen is, zonder dat de andere lagen hier last van hebben.De drie lagen zijn als volgt gedefinieerd:• Presentation. De presentatielaag levert de user interface van de

applicatie. Dit kan zijn in de vorm van een Windows Form voor eensmart client applicatie, maar het kan ook een .aspx pagina, een.ascx control of een Silverlight control zijn.

• Business. De businesslaag implementeert de business logica vande applicatie. De businesslaag bestaat vaak uit meerderecomponenten, die binnen de businesslaag allemaal hun eigenfunctie hebben.

• Data. De datalaag geeft toegang tot externe systemen zoals data-bases en web services.

Figuur 2 geeft een grafische overview van de verschillende lagen encomponenten van het three layered application pattern.

Fig. 2: Het three layered application pattern

Een groot voordeel van het three layered application pattern, dat ookbij het bouwen van Silverlight controls erg duidelijk naar voren komt,is dat een developer de logica van de business- en de datalaag kanontwikkelen, terwijl een designer vervolgens het design van de pre-sentatielaag kan implementeren. Omdat ik absoluut geen designerben, zal ik bij het bouwen van het Silverlight Foto web part nauwelijksdesign toevoegen, maar ik zal wel gebruik maken van het three layeredapplication pattern. Hierdoor kan een designer later het design van deuser interface aanpassen en verfraaien, zonder dat daarvoor de logicavan het web part aangepast hoeft te worden.

Meer informatie over het three layered application pattern kun je nale-zen op http://msdn.microsoft.com/en-us/library/ms978689.aspx.

Het aanmaken van de Visual Studio solutionDe eerste stap in de implementatie van het web part is het aanmakenvan het web part zelf. Maak hiervoor een project aan in Visual Studio

INFORMATION

WORKERUX

Page 29: SOFTWARE DEVELOPMENT NETWORK

2008 op basis van het ASP.NET Web Application project type. Ik noemhet project Presentation.WebPartUI. Omdat we meerdere projectenaan de solution toe zullen voegen, krijgt de solution de naam Silver-lightFotoWebPart.

Fig. 3: Het aanmaken van de solution en het Presentation.WebPartUI project

Visual Studio maakt zelf bij het aanmaken van een web applicationproject een App_Data folder, een default.aspx file en een web.configfile aan. Deze zijn niet nodig voor het bouwen van een web part enkunnen dus uit het project verwijderd worden.

De tweede stap in het realiseren van het Silverlight foto web part ishet aanmaken van een Silverlight Applicatie project waarin de Silver-light Control zal worden opgeslagen. De naam van dit project kanPresentation.SilverlightUI zijn. Bij het aanmaken van dit project zal jegevraagd worden waar je de HTML pagina wilt hosten waarin je deSilverlight applicatie kunt testen. Kies hierbij voor de derde optie “Linkthis Silverlight control into an existing Web site” en voeg het toe aanhet Presentation.WebPartUI project. Dit zal het testen en deployen vande Silverlight applicatie straks vergemakkelijken.

Fig. 4: Het aanmaken van het Presentation.SilverlightUI project

Fig. 5: Het aanmaken van een Silverlight test pagina in het Presen-tation.WebPartUI project

De derde stap is het aanmaken van het project dat zorgt voor hetophalen van de data uit de Flickr website en de SharePoint picturelibrary. Dit project zal geen specifieke Silverlight componenten bevat-ten. Het project zal echter wel ‘gereferenced’ worden vanuit hetPresentation.SilverlightUI project. Daarom zal het project tochaangemaakt worden als een Silverlight Application project. Je kuntnamelijk vanuit een Silverlight project alleen maar referencen naarandere Silverlight projecten. Het Silverlight project wordt immers opde client uitgevoerd en heeft alleen de beschikking over de Silverlightruntime. Je kunt dus niet referencen naar een project dat gebruikmaakt van de volledige .NET runtime.De naam van het project zal Data.ServiceAgents zijn. Ook voor ditproject geldt dat er een testpagina aangemaakt moet worden in hetPresentation.WebPartUI project. Na het aanmaken van het projectkunnen zowel de Page.xaml als de App.xaml files uit het project ver-wijderd worden, omdat dit project alleen data access zal verzorgen.

Het vierde en laatste project dat aangemaakt moet worden iswederom een Silverlight Application project met de naamBusiness.Entities. Dit project zal alleen de assembly file als deliverablehebben en er hoeft voor dit project dan ook geen testpaginaaangemaakt te worden. Dit heeft te maken met het feit dat er geen.XAP package gedeployed hoeft te worden, maar alleen maar een.DLL file die gereferenced wordt door het Presentation.SilverlightUIproject. Ook in dit project kunnen dus de Page.xaml en de App.xamlfiles na het aanmaken weer verwijderd worden.

Hiermee is de volledige structuur in Visual Studio opgezet. De projec-ten zijn als volgt over de drie lagen van het three layered applicationpattern verdeeld:• Presentation => Presentation.WebPartUI en Presentation.Silver-

lightUI• Business => Business.Entities• Data => Data.ServiceAgents

De volgende stap is het schrijven van de code!

De codePresentation.WebPartUIWe beginnen met het schrijven van de code voor het web part.Hiervoor maken we in het Presentation.WebPartUI project een nieuweclass aan met de naam SilverlightWebPart.cs. De class zal overervenvan System.Web.UI.WebControls.WebParts.WebPart.In de OnLoad functie wordt de ScriptManager aan de paginatoegevoegd.

magazine voor software development 29

Vink bij het aanmaken van je Silver-light project aan dat je het wilt testenin een bestaande website. Dit zal hettesten en het deployen van de Silver-light applicatie vergemakkelijken

INFORMATION

WORKERUX

Page 30: SOFTWARE DEVELOPMENT NETWORK

protected override void OnLoad(EventArgs e){

base.OnLoad(e);

// Script manager instance may appear only once on a pageScriptManager scriptManager =

ScriptManager.GetCurrent(Page);if (scriptManager == null){

scriptManager = new ScriptManager();Controls.Add(scriptManager);

}}

Listing 1: Toevoegen van de ScriptManager aan de pagina

Maak een property DataSource aan die gebruikt wordt om aan tegeven of het web part foto’s moet tonen uit een SharePoint picturelibrary of van Flickr.

private string _dataSource = "SharePoint";

/// <summary>

/// Wwebpart property to determine data source of pictures

/// </summary>

/// <value>The datasource</value>

[WebBrowsable(true)]

[Category("Web Part Settings")]

[WebDisplayName("Data Source")]

[WebDescription("The data source of the pictures.")]

[Personalizable(PersonalizationScope.Shared)]

public string DataSource

{

get { return _dataSource; }

set { _dataSource = value; }

}

Listing 2: DataSource Web Part property

Gebruik vervolgens de CreateChildControls functie om het Silverlightcontrol te laden. De _dataSource property wordt meegegeven aan hetSilverlight control met behulp van de InitParameters property van hetSilverlight control.Hiermee is de code voor het Presentation.WebPartUI project al klaar!

protected override void CreateChildControls()

{

// instantiation of the silverlight control

Silverlight silverlightControl = new Silverlight();

silverlightControl.ID = "SilverlightWebpart";

silverlightControl.Source =

“/wpresources/Macaw.IWS.Moss2007.SilverlightDemo.

Presentation.WebPartUI/WebPart-

Macaw.IWS.Moss2007.SilverlightDemo/ClientBin/

Silverlight.UI.xap";

silverlightControl.Width =

new System.Web.UI.WebControls.Unit(100,

System.Web.UI.WebControls.UnitType.Percentage);

silverlightControl.Height =

new System.Web.UI.WebControls.Unit(600);

silverlightControl.InitParameters =

String.Format("DS={0}", _dataSource);

Controls.Add(silverlightControl);

}

Listing 3: Het laden van het Silverlight control

30 MAGAZINE

Business.EntitiesDe volgende stap is het aanmaken van een class MyPhoto in hetBusiness.Entities project. In deze class creëren we één entity met tweeproperties: Url en ThumbUrl. Doordat de class gebruik maakt van het.NET Framework 3.5 kunnen we hier gebruik maken van de automa-tic properties mogelijkheden van C# 3.0. Hierdoor kan deze code intwee regels geschreven worden.

public string Url {get; set;}public string ThumbUrl {get; set;}

Listing 4: MyPhoto entity

Presentation.SilverlightUIIn het Presentation.SilverlightUI project moeten we nog een klein stukjeondersteunende logica schrijven. Open hiervoor App.xaml.cs. Dezefile wordt aangemaakt op het moment dat het Silverlight Applicationproject wordt aangemaakt en bevat logica voor bijvoorbeeld hetstarten van de Silverlight applicatie. In de Application_StartUp functievoegen we wat code toe voor het initialiseren van de DataSourceparameter die we meegegeven hebben vanuit het Presentation.Web-PartUI project.Deze functie zorgt er nu voor dat de constructor van de Page.xaml.cspagina wordt aangeroepen met de datasource als parameter.

private void Application_Startup(object sender, StartupEventArgs e)

{string dataSource = null;if (e.InitParams != null && e.InitParams.Count > 0){

dataSource = e.InitParams["DS"];}this.RootVisual = new Page(dataSource);

}

Listing 5: Het initialiseren van de datasource parameter

Ga nu naar de Page.xaml control in het Presentation.SilverlightUI pro-ject. Hierin staat standaard al een grid gedefinieerd. Deze kunnen wegewoon laten staan, we halen alleen de breedte en de hoogte van degrid weg. Vervolgens voegen we twee rijen toe aan de grid, deonderste rij is 110 pixels hoog, de bovenste rij zal zo hoog zijn als datnodig is. Vervolgens voegen we aan de onderste rij een ListBox toewaarin we de collectie van thumbnails horizontaal weergeven.Aan de bovenste rij voegen we een Image toe voor het weergeven vaneen grote foto. De hoogte van de Image is 350 pixels, dus de boven-ste rij zal een hoogte van ongeveer 350 pixels krijgen.Figuur 6 is een schematische weergave van de opbouw van het webpart. De bedoeling is dat als je op één van de thumbnails in de on-derste listbox klikt, deze vergroot weergeven wordt in de bovenste rij.

Fig. 6: Schematische weergave van het web part

INFORMATION

WORKERUX

Page 31: SOFTWARE DEVELOPMENT NETWORK

<UserControl x:Class="Presentation.SilverlightUI.Page"

xmlns="http://schemas.microsoft.com/winfx/2006/

xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<Grid x:Name="LayoutRoot" Background="White">

<Grid.RowDefinitions>

<RowDefinition Height="*"/>

<RowDefinition Height="110"/>

</Grid.RowDefinitions>

<ListBox x:Name="listPhotos" Grid.Row="1"

SelectionChanged="listPhotos_SelectionChanged">

<ListBox.ItemTemplate>

<DataTemplate>

<StackPanel Orientation="Horizontal">

<Image Source="{Binding ThumbUrl}"

Width="120" Height="80" />

</StackPanel>

</DataTemplate>

</ListBox.ItemTemplate>

<ListBox.ItemsPanel>

<ItemsPanelTemplate>

<StackPanel Orientation="Horizontal"/>

</ItemsPanelTemplate>

</ListBox.ItemsPanel>

</ListBox>

<Image x:Name="detailImage" Grid.Row="0" Height="350" />

</Grid>

</UserControl>

Listing 6: Page.xaml

In de Page.xaml.cs wordt getest of de datasource die gebruikt moetworden voor het laden van de foto’s SharePoint of Flickr is en aan dehand daarvan wordt bepaald waar de foto’s opgehaald moetenworden.De parameter die meegegeven wordt aan de functies GetListItems-FromSharePoint en GetItemsFromFlickrProfile is een Lambda expres-sie. Een Lambda expressie is een functie die geen naam heeft, ofteweleen anonieme functie, die wordt toegekend aan een variabele. Viadeze variabele is de Lambda expressie dan aan te roepen. In dit gevalwordt de functie GetListItemsFromSharePoint aangeroepen met deLambda expressie, maar als je naar de definitie van GetListItems-FromSharePoint gaat zie je dat de parameter een Action delegate isdie als argument een IEnumerable van MyPhotos mee krijgt. Meer in-formatie hierover vind je bij de uitleg van de code uit het Data.Ser-viceAgents project.

Tenslotte bevat deze class een eventhandler die ervoor zorgt dat dethumbnail die geselecteerd wordt als grote foto weergegeven zalworden.

public Page(string dataSource)

{

InitializeComponent();

if (dataSource == "SharePoint")

{

GetItemsFromSharePointList sharePointProxy =

new GetItemsFromSharePointList();

sharePointProxy.GetListItemsFromSharePoint(photos =>

listPhotos.ItemsSource = photos);

}

else if (dataSource == "Flickr")

{

GetItemsFromFlickr flickrProxy =

new GetItemsFromFlickr();

flickrProxy.GetItemsFromFlickrProfile(photos =>

listPhotos.ItemsSource = photos);

}

}

private void listPhotos_SelectionChanged(object sender,

SelectionChangedEventArgs e)

{

MyPhoto photo = (MyPhoto)listPhotos.SelectedItem;

BitmapImage bmi = new BitmapImage(new Uri(photo.Url));

detailImage.Source = bmi;

}

Listing 7: Page.xaml.cs logica

Data.ServiceAgentsIn het Data.ServiceAgents project voegen we een Service Referencetoe die verwijst naar de SharePoint list web service. Om deze refe-rence toe te kunnen voegen moeten we tijdelijk Anonymous Access opde web applicatie toestaan. Dit is in te stellen in IIS door rechts teklikken op de web site van de SharePoint web applicatie en vervol-gens naar het tabje Directory Security te browsen. Hier klik je op deEdit button onder Authentication and access control. Checkvervolgens de Enable anonymous access checkbox.Nu kun je de service reference naar http://<webapplicatie>/_vti_bin/lists.asmx aanmaken. Visual Studio zal nu een proxy class genererendie de functies van de web services beschikbaar stelt.

Fig. 7: Het toevoegen van de referentie naar de SharePoint list webservice

De volgende stap is het toevoegen van de class GetItemsFromSha-rePointList aan het Data.ServiceAgents project. In deze class makenwe een private Action delegate aan en een functie voor het ophalenvan de data uit SharePoint met behulp van de list web service.Omdat het web part de foto’s ophaalt met behulp van een call naar eenweb service zal het ophalen van de foto’s asynchroon zijn. Met behulpvan de Action delegate _processPhotos specificeren we wat er moetgebeuren nadat de foto’s opgehaald zijn.

magazine voor software development 31

Omdat het web part de foto’s ophaaltmet behulp van een call naar een webservice zal het ophalen van de foto’sasynchroon zijn

INFORMATION

WORKERUX

Page 32: SOFTWARE DEVELOPMENT NETWORK

Een delegate in C# is ongeveer hetzelfde als een pointer in C of C++.Een delegate houdt een referentie naar een functie vast. Als de dele-gate wordt meegegeven als parameter van een functie kan de vanuitdie functie door de delegate onthouden functie aangeroepen worden.Een Action delegate is een soort void functie die geen return waardeheeft, maar die alleen een actie uitvoert. De actie kan gedefinieerd wor-den als een functie die aangeroepen wordt, maar ook als een Lambdaexpressie. In dit geval roepen we de functie GetListItemsFromShare-Point in de Page.xaml.cs van het Presentation.SilverlightUI project aanmet een Lambda expressie als parameter. We hebben deze variabelenodig om tijdens het uitvoeren van de asynchrone actie te onthoudenwelke code er uitgevoerd moet worden als de asynchrone actieklaar is.

private Action<IEnumerable<MyPhoto>> _processPhotos;

/// <summary>

/// Start an asynchronous service call to get my photos

/// and register a callback method to process the result

/// when it comes in.

/// </summary>

/// <param name="processPhotos">A method that takes

/// one parameter - a collection of MyPhoto - and no result

///</param>

public void GetListItemsFromSharePoint(

Action<IEnumerable<MyPhoto>> processPhotos)

{

_processPhotos = processPhotos;

ListsSoapClient proxy = new ListsSoapClient();

proxy.GetListItemsCompleted +=

proxy_GetListItemsCompleted;

// Build XML elements for querying SharePoint list

XElement fieldRef = new XElement("FieldRef");

fieldRef.SetAttributeValue("Name", "Created");

fieldRef.SetAttributeValue("Ascending", "FALSE");

XElement orderBy = new XElement("OrderBy", fieldRef);

XElement query = new XElement("Query", orderBy);

XElement viewFields = new XElement("ViewFields");

XElement queryOptions = new XElement("QueryOptions");

proxy.GetListItemsAsync(

"Barcelona", "", query, viewFields, "10",

queryOptions, "");

}

Listing 8: Asynchroon ophalen van data uit de SharePoint picturelibrary

De list items worden opgehaald met behulp van de GetListItemsAsyncmethode. In de parameters wordt de naam van de lijst (in mijn gevalBarcelona), de sortering (in het Query element) en het maximumaantal records dat er teruggegeven moet worden (10) meegegeven.Op het moment dat alle list items zijn opgehaald zal de eventhandlerGetListItemsCompleted afgevuurd worden. Hiermee wordt de functieproxy_GetListItemsCompleted aangeroepen. In deze functie wordenmet behulp van een eenvoudige LINQ query de juiste waarden aan develden in de MyPhoto entity toegewezen. Bij een SharePoint picturelibrary geldt dat de url van de foto is opgeslagen in het ows_Enco-dedAbsWebImgUrl veld en dat de url van de thumbnail is opgeslagenin het ows_EncodedAbsThumbnailUrl veld. Vervolgens wordt deAction delegate uitgevoerd met als paramater de IEnumerable van deMyPhoto entities om de binnen gekomen foto’s te gaan verwerken.

Dit houdt in dat op dit moment de ItemSource van de listPhotos uit dePage.xaml.cs in het Presentation.SilverlightUI project zijn waarde krijgttoegekend.Ik zal in dit artikel niet de volledige code voor het ophalen van de datavan Flickr weergeven. De manier waarop het ophalen van data van deFlickr site werkt is vrijwel gelijk aan de manier waarop je data uit eenSharePoint picture library ophaalt. Het belangrijkste verschil zit hem inhet feit dat je een andere web service aanroept (namelijk die van Flickren niet de SharePoint list web service) en dat de XML die de webservice terug geeft er iets anders uit ziet. De volledige solution is tedownloaden op de SDN web site.

private void proxy_GetListItemsCompleted(

object sender, GetListItemsCompletedEventArgs e)

{

if (e.Error != null)

{

MessageBox.Show(e.Error.ToString());

}

else

{

XElement result = e.Result;

var photos =

from x in result.Elements().First().Elements()

select new MyPhoto

{

Url = x.Attribute("ows_EncodedAbsWebImgUrl").Value,

ThumbUrl = x.Attribute(

"ows_EncodedAbsThumbnailUrl").Value

};

_processPhotos(photos);

}

}

Listing 9: LINQ query om de foto en thumbnail urls uit de resultatente halen

DeploymentAls je al deze stappen hebt uitgevoerd is je code klaar om gedeployedte worden. Het gaat voor dit artikel te ver om uitgebreid te beschrijvenhoe deze componenten in een SharePoint Solution package verpaktkunnen worden. Meer informatie hierover is te vinden online te vinden:• http://msdn.microsoft.com/en-us/library/ms413687.aspx.• http://www.sdn.nl/SDN/Artikelen/tabid/58/agentType/View/Proper-

tyID/2892/Default.aspxWel zal ik aangeven welke files er gedeployed moeten worden en waardeze dan terecht zouden moeten komen.• De web part assembly, Presentation.WebPartUI.dll, moet gede-

ployed worden naar de bin directory van de web applicatie.In mijn geval is het pathC:\Inetpub\wwwroot\wss\VirtualDirectories\moss2007dev\bin.De assembly kan ook naar de GAC gedeployed worden, maar datis geen best practice.

• De Silverlight controls moeten naar de ClientBin gedeployed wor-den. Deze zou op diverse plekken kunnen staan, maar ik zal hemuitrollen naar de wpresources folder van de web applicatie C:\Inet-pub\wwwroot\wss\VirtualDirectories\moss2007dev\wpresour-ces\SilverlightFotoWebPart\ClientBin. De Silverlight controls zijningepakt in de Presentation.SilverlightUI.xap file. Dit is eigenlijk eenzip file. Als je de file hernoemt naar .zip kun je de inhoud ervanbekijken. Als een gebruiker een pagina opvraagt met een Silverlightcontrol zal het .xap bestand gedownload worden naar de compu-ter van de gebruiker. Vervolgens zal de Silverlight plug in die op decomputer van de gebruiker geinstalleerd is de .xap file uitpakken.

MAGAZINE32

INFORMATION

WORKERUX

Page 33: SOFTWARE DEVELOPMENT NETWORK

Voor het SilverlightFotoWebPart hebben we alleen de Presenta-tion.SilverlightUI.xap file nodig, deze bevat

- Business.Entities.dll

- Data.ServiceAgents.dll

- Presentation.SilverlightUI.dll• Tenslotte moet alleen nog het automatisch aangemaakte Silver-

light.js file gedeployed worden. Deze wordt uitgerold naar de wpre-sources folder van de web applicatie, dus naarC:\Inetpub\wwwroot\wss\VirtualDirectories\moss2007dev\wpre-sources\SilverlightFotoWebPart.

Als de files naar de juiste locatie gedeployed zijn kun je het web parttoevoegen aan een pagina in de SharePoint omgeving en het resultaatuit figuur 8 hieronder bewonderen! •

Fig. 8: Het resultaat, het Silverlight foto web part

magazine voor software development 33

Mirjam van Olst

Mirjam van Olst werkt als Share-Point Technology Consultant voorhet Information Worker SolutionCenter bij Macaw. Zij heeft in de af-gelopen 4 jaar aan diverse Share-Point implementaties gewerkt. Opdit moment werkt zij als SharePointArchitect aan een aantal projectenmet MOSS 2007, waaronder een

intranet voor een grote verzekeringsmaatschappij in Nederland.Daarnaast geeft Mirjam regelmatig presentaties en schrijft zijartikelen over MOSS 2007-gerelateerde onderwerpen.

Delphi TIP:Unicode Console OutputDelphi 2009 ondersteunt Unicode, maar console I/O onder-steunt alleen AnsiStrings.Toch kun je ook daarmee Unicode strings naar de consoleschrijven, als je de string eerst omzet naar UTF-8 (een Ansi-String met een variabele aantal (tussen 1 en 4) bytes per teken).Dit kan bijvoorbeeld als volgt:

program ConsoleUTF8;

{$APPTYPE CONSOLE}

uses

Windows, SysUtils;

begin

SetConsoleOutputCP(65001);

WriteLn(Output, UTF8String('[���������������������� ����������]'));readln

end.

Je zal wellicht niet meteen cyrillic tekens zien: die zie je name-lijk alleen als je in het console window Lucida Console als fontgebruikt.Het is niet noodzakelijk om te beginnen met de UTF-8 BOM,maar dat kan wel zinvol zijn als je de console output in een bestand wilt "opvangen" en later wilt bewerken. Anders kan deBOM achterwege blijven.

INFORMATION

WORKERUX

Page 34: SOFTWARE DEVELOPMENT NETWORK

Advertentie Microsoft

Page 35: SOFTWARE DEVELOPMENT NETWORK

Advertentie Microsoft

Page 36: SOFTWARE DEVELOPMENT NETWORK

CORESYSTEMS

36SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK BEELDMERK

FULL-COLOUR

SOFTWARE DEVELOPMENT NETWORK DIVISIES

CONFERENCE

MAGAZINE

EVENTS

.NET

.NL

DELPHI

5 0 c y a a n1 0 0 g e e l

5 0 z w a r t1 5 c y a a n

SOFTWARE DEVELOPMENT NETWORK SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

HP NonStop: 30 Jaar Ontwikkelingin NonStop TransactieverwerkingHP NonStop computers hadden al een heel leven langgedraaid onder de naam Tandem Computers, voordatze door HP werden ontdekt. En dat was niet zomaareen ontdekking: het hele datacenter van HP wereldwijdis inmiddels volledig uitgerust met deze bijzondere,krachtige machines. Maar wat maakt deze HP NonStopcomputers dan zo bijzonder? Vanwaar deze apartenaam? En waarom is software ontwikkelen op een HPNonStop zo ontzettend leuk om te doen?Om de eerste vraag te beantwoorden moeten we echteven terug naar het begin: in 1974 is al de basis gelegdvoor de huidige NonStop computers. Natuurlijk warenze nog niet zo snel en efficiënt als de huidige versies,maar de grondleggers hadden in die tijd al zeer goedeideeën over hoe de computer moest functioneren: zemoesten continu beschikbaar zijn, de data-integriteitmoest gegarandeerd kunnen worden, de performancemoest onder verschillende omstandigheden goed blijven en er was nagedacht over het beveiligen van gegevens.Kortom, ideeën die hun tijd ver vooruit waren! Één nadeel: ze waren kostbaar. Dat maakte dat de doelgroep zich beperkte tot de bankwereld en de groteindustrie die ze inzetten om de eerste stappen in elektronische transactieverwerking te zetten voor de effectenhandel en de salarisverwerking.

20 jaar aaneengesloten aan

De naam NonStop komt voort uit het gegeven dat ze continu be-

schikbaar moeten zijn en wie denkt dat dit een loze belofte is, heeft het

mis: er zijn behoorlijk wat NonStop computers die pas na 20 jaar ver-

vangen zijn en in de tussentijd niet uit geweest zijn. Ze hebben met

recht de naam NonStop.

Frida Robben

HP NonStop feiten:- 1976: De eerste NonStop computer wordt verkocht aan de Citybank

- 1979: Bij de US Treasury Department verwerkt een NonStopcomputer wekelijks voor US$10 miljard aan financiële transacties

FouttolerantieEen van de redenen dat ze vol continu aan kunnen blijven is het dubbel uitvoeren van de meest essentiële hardwareonderdelen. Ookwordt gebruik gemaakt van fouttolerantie, waarbij het mogelijk is omin een van de hardwareonderdelen in een vroeg stadium een probleemte signaleren en dit aan te merken als single point of failure. Daaropwordt dit onderdeel vervangen terwijl het systeem blijft draaien. Hetmag duidelijk zijn dat dit single point of failure een belangrijk gegevenis: wanneer het systeem op twee plaatsen tegelijk in de hardware eenfailure constateert zal het systeem geen garanties meer kunnen geven

dat het blijft draaien. Dit komt overigens zo weinig voor dat op de huidige HP NonStop computers een beschikbaarheidgarantie vanmeer dan 99,998% afgegeven wordt.

Data-integriteitEn dan het onderwerp dat al dichterbij software-ontwikkeling komt:de veiligheid van gegevens en de data-integriteit. Deze waren vanaf deeerste NonStop computer al een belangrijk onderwerp. Zo belangrijkzelfs dat het operating system niet voor niets de naam Guardian kreegen de tool TMF (Transaction Management Facility) ontwikkeld werd.

HP NonStop feiten:- 1981: Nasdaq gebruikt NonStop computers voor securities

transaction processing

- 1986: Tandem introduceert de eerste fault-tolerant SQL database,NonStop SQL

Binnen het Guardian-OS zijn diverse tools beschikbaar: SAFECOMvoor toegangsbeveiliging, FUP als File Utility, TEDIT om te editen, INSPECT om te debuggen, SPOOLCOM voor outputafhandeling,SCUP voor het beheer van de schermlayouts en zo is er nog een aantal tools die standaard bij een NonStop computer horen.

Transaction Management FacilityZo ook TMF, dat een speciale plaats inneemt: met deze tool wordentransacties vanaf binnenkomst tot aan de bevestiging gecontroleerdverwerkt. Op elk moment tijdens die verwerking kan zo nodig eentransactie ongedaan gemaakt worden door een transactie-rollback.

TMF en programmeertalenVanuit elke ontwikkeltaal die beschikbaar is op een NonStop systeemkan TMF aangeroepen worden. Een transactie kan goed eindigen, ofabnormaal eindigen, waarna een rollback gedaan wordt om de wijzi-ging ongedaan te maken, zoals in dit COBOL-voorbeeld hieronder:

E0020.READ INPUTFILE MOVE INPUTFILE.KEY TO ACCOUNT.KEYREAD^FILE ACCOUNTIF READ-OK

BEGIN-TRANSACTIONIF INPUTFILE.AMOUNT < 0

SUBTRACT INPUTFILE.AMOUNT FROM ACCOUNT.BALANCEWRITE^FILE ACCOUNTIF WRITE-OK

END-TRANSACTIONELSE

ABORT-TRANSACTIONEND-IF

END-IFEND-IF

E0099.

Listing 1: COBOL TMF-voorbeeld

Transactie = wijziging patiëntendossierMaar wat wordt er onder een transactie verstaan? Het hoeft namelijk

Page 37: SOFTWARE DEVELOPMENT NETWORK

magazine voor software development 37

Frida Robben

Frida Robben werkt als TechnologySpecialist voor Sogeti Nederland. Zijheeft ruim 20 jaar ervaring met hetwerken op HP NonStop machines inverschillende bedrijven, met name ineen bankomgeving.

niet per definitie financieel te zijn. Een transactie kan ook heel anderegegevens omvatten, b.v. gevoelige overheidsdata of data over energieverbruik per huishouden in een energiebedrijf, patiëntengege-vens in een ziekenhuis, of de afhandeling van de logistiek van een vervoersmaatschappij. Het beeld dat alleen financiële instellingen meteen NonStop computer werken is daarmee achterhaald. En juist in dehuidige internationale bedrijfsontwikkeling waarbij internet en een beschikbaarheid van 24 uur per dag erg belangrijk geworden is, is HPNonStop een uitkomst.

HP NonStop feiten:- 1997: NonStop Java beschikbaar op NonStop computers vanaf

versie NonStop Kernel

- 2001: Intel Itanium processor in NonStop

Dagelijks miljoenen gebruikersHet is erg aannemelijk dat de meeste mensen bijna dagelijks, zonderhet te weten, gebruik maken van HP NonStop: vrijwel alle betaal- engeldautomaten in Nederland staan in verbinding met een HP NonStopcomputer en de meeste telebankierschermen van de verschillendebanken werken op HP NonStop. Hieruit kun je concluderen dat Javainmiddels veel gebruikt wordt op deze computer, in combinatie met deverschillende HP NonStop tools.

HP NonStop feiten:- 2008: Compound Statements in SQL

- 2009: HP NonStop connectivity products voor database-connecties naar ODBC en JDBC

ProgrammeertalenOp een HP NonStop kun je programmeren in de talen COBOL,C/C++, SQL en JAVA. Tevens is er een native taal beschikbaar TALmet libraries waarin standaard TAL-routines zijn opgeslagen voor al-lerlei standaard werkzaamheden, zoals READ^FILE en WRITE^FILE.

SQL en Java op HP NonStopOm gebruik te kunnen maken van Java in combinatie met SQL-tabel-len hoef je binnen Java alleen maar een referentie te leggen naar destandaard SQL-class met een select-commando:

import java.sql.*;Statement myStatement = myConnection.createStatement();// De select kan nu uitgevoerd worden en // het resultaat gaat naar object r:ResultSet r = myStat.executeQuery(

"SELECT * from $DATA1.DBASE.EMPL");// het resultaat is een String dat op het// beeldscherm gedisplayed wordt:while (r.next())

System.out.println("Column 1: " + r.getString(1));

Listing 2: JAVA op NonStop

Fig. 1: Anno 2008 NonStop AutoTMF

AutoTMFNonStop AutoTMF is een verlengstuk van TMF, waarbij applicaties ookworden beschermd die zelf oorspronkelijk niet TMF aanroepen. AutoTMF werkt erg simpel: tijdens de verwerking van het programmadat geen TMF aanroept, is AutoTMF op de achtergrond aan het monitoren wat het programma aan het doen is. Als zo’n programmanaar een audited file of database gaat schrijven, start AutoTMF eenautomatische transactie. Als het programma naar een niet-audited fileof database schrijft, doet AutoTMF niets.

AutoTMF en JavaOm door middel van Java databasemutaties in een SQL/MX databasete doen moet je een class aanroepen: com.tandem.tmf.Current, ofde Java Transaction API (JTA). Je kunt de default API-TMF gebruikenvoor Java transactie-verwerking door middel van een referentie naarUserTransaction, welke gebaseerd is op TMF:

import javax.transaction.UserTransaction;import com.tandem.jta.JTAFactory;// Referentie naar UserTransaction UserTransaction utx = JTAFactory.getUserTransaction();// Start transactionutx.begin();// Do work// Commit transactionutx.commit();

Listing 3: TMF gebaseerde transactieverwerking

Zelf aan de slag?Als je zelf Java op een HP NonStop wilt proberen, maar je werkt nietop een HP NonStop computer, dan heb je nu de mogelijkheid om hette simuleren! Met de plugin Eclipse HP NonStop kun je simuleren datje gebruikt maakt van HP NonStop Java met SQL en TMF. De plug-inis te downloaden van de website van HP, installeer deze en neem eenkijkje in de wereld van HP NonStop!

Er zijn 3 stappen voor nodig:1: Download en installeer Cygwin, een Linux-like omgeving, vanaf

http://www.cygwin.com.2: Download de HP NonStop Eclipse plugin vanaf de website van

HP: http://h20293.www2.hp.com/portal/swdepot/displayProductInfo.do?productNumber=HSB99V1

3: Installeer de plugin: zie de afbeelding hieronder. •

Page 38: SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK BEELDMERK

FULL-COLOUR

SOFTWARE DEVELOPMENT NETWORK DIVISIES

CONFERENCE

MAGAZINE

EVENTS

.NET

.NL

DELPHI

5 0 c y a a n1 0 0 g e e l

5 0 z w a r t1 5 c y a a n

SOFTWARE DEVELOPMENT NETWORK SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

.NETDATABASES

Data modeling vs. the databaseTypically, developers must interact directly with the database to getdata into and out of the application. This means that you need to havea fairly good understanding of the structure of the database - its tables,views and stored procedures, constraints, schemas and data types,required parameters for stored procedures and the schema of the datathat will be returned. Once you have gotten past this barrier, you thenneed to write plenty of code to reshape the returned data into yourapplication’s objects. If you are writing an application where users canmodify data, you then have to extract property values from objectsand related data in order to send them back to the data store.By having a data model at the application level that better representsyour business domain objects, the developer can focus on applica-tion development, rather than on interacting with the database.

Data modeling at the application level is not a new concept. There area number of ORM tools available to Visual Studio developers such asnHibernate and ORMapper. Visual Studio’s LINQ to SQL is also a modeling tool which works specifically with SQL Server and leveragesthe LINQ query language built into C# and Visual Basic.

The ADO.NET Entity Framework differs from these ORMs in a numberof ways. To begin with, Entity Framework was created so that deve-lopers could program against not just any data model, but an EntityData Model (EDM). The EDM is Microsoft’s realization of Entity Relati-onship Modeling which has been around for over 35 years. The criti-cal word in there is “relationship”. ERM and EDM define a model by itsentities and its relationships. The relationships are first class citizens inthis model rather than being metadata about how entities relate to oneanother. Another critical difference is how Entity Framework is able tomove from the conceptual model to the database and back.

The Entity Data Model in Entity FrameworkEntity Framework uses an Entity Data Model along with additional metadata that enables your program to automatically figure out howto move between objects expressed using the model and the data-base. Entity Framework includes a set of Visual Studio design tools, in-cluding the Entity Data Model Wizard. This wizard allows you to quicklycreate a model based on an existing database. To demonstrate this,I’ll use a simple SQL Server database as an example, although thereare a number of other ADO.NET database providers that now supportthe Entity Framework (and more that will be released in the future).

Figure 1 shows a diagram of the tables in the example database whichdescribes a simple sales system. The focal point is the Person table.A related SalesPerson table provides additional details about thosepeople who are sales people. In the same way, a Customer table provides additional details about those who are customers. There is anOrder table that uses foreign keys to link back to the associated Customer and SalesPerson. Additional details about people and cus-tomers are stored in the PersonalDetails and CustomerTypes tables.

Fig. 1: Database schema

Julia Lerman

ADO.NETEntity Framework Overview

A few years ago, Microsoft’s Data Accessteam began showing developers a new direction for ADO.NET, the Entity Frame-work. This new framework, released in August 2008 as part of Visual Studio 2008SP1, brings data modeling into the handsof the developers. This version of the EntityFramework is the beginning of a long-termstrategy for ADO.NET, and part of a largerdata access and modeling strategy for Microsoft’s applications in general.This article aims to give readers an over-view of the ADO.NET Entity Framework, itsbenefits and some of its current pitfalls aswell as an understanding of where the current version fits into the larger picture.

The ADO.NET Entity Framework differs from ORMs in a number of ways

38

Page 39: SOFTWARE DEVELOPMENT NETWORK

Assuming that you instruct the Entity Data Model Wizard to bring in allof the tables from the database, it will create a data model, shown infigure 2, in your application that looks very similar to the databaseschema.

Fig. 2: Entity Data Model

But looks can be deceiving. If you investigate a bit more closely youmay notice that each entity has a set of scalar properties and a set ofnavigation properties. And if you look even more closely, you will notice that there are no foreign keys. The Order entity has neither aCustomerID property nor a SalesPersonID property; the Customer entity does not have a CustomerTypeID property. The relationship between one entity and another is not defined by a foreign key, but by a navigation property. The Order entity has a Navigation Property that is a reference to the Customer it is related to.And the Customer entity has an Orders Navigation property that is areference to the collection of related orders. These are called Navigation Properties because they define how to navigate from oneentity to another.

What this means is that you don’t have to worry about using JOINs toconnect entities to one another. Entities are naturally bound to oneanother as you query, as you work with entity objects and as you senddata back to the database.

While this EDM is the default data model created by the wizard, thereare actually a host of customizations you can do to the model. Figure3 shows the same model after I have modified it to redefine the Customer and Salesperson entities as derived entities of a Person.You can build inheritance directly into the data model. Additionally, notice in this version of the model that I have combined the Person andPersonalDetail entities into one entity. Even though it points back totwo separate tables in the database, I don’t ever have to worry abouthow that works. Whether I am querying data or modifying it and sending updates back to the database, the Entity Framework will takecare of mapping my entities back to the database. I have also renamedsome of the Navigation properties so that they are more logical. For example, Customer.Orders was originally Customer.Order, butsince that property refers to many orders, as defined by the 1 to Many(1:*) relationship, the pluralized name is more logical.

Fig. 3: Customized Entity Data Model

There are many more things that you can do to customize a model,from “decorative” changes such as renaming or even removing properties, to architectural changes like building in inheritance.

From the data model to classesOne of the jobs of Entity Framework’s designer is to automatically generate classes from the entities in the model. This is the default behavior and can be overwritten in a variety of ways: from writing yourown generator to hooking your custom classes into E.F. I’ll focus onthe default behavior in this article.

Each entity becomes a class which inherits from EF’s EntityObjectclass. The EntityObject class provides the entities with the mecha-nisms they need to plug into the framework. In figure 4, you can seea class diagram showing the Customer entity and its properties alongwith the properties, methods and interfaces that it inherits from theEntityObject class. Notice that the code generator added a factorymethod (CreateCustomer) and four change tracking methods to theCustomer class.

Fig. 4: Generated customer entity class with its base EntityObjectclass and E.F. interfaces

With the model and its classes in hand, it’s time to look at some Entity Framework programming features.

magazine voor software development 39

No worries about JOINs

.NETDATABASES

Page 40: SOFTWARE DEVELOPMENT NETWORK

Querying against the Entity Data ModelThe Entity Framework provides a number of ways to query against thedata model. The original query syntax created for this purpose is called Entity SQL. Entity SQL is based on standard SQL query langu-ages but has additional features that enable it to work specifically withthe Entity Data Model. As with T-SQL, you construct an Entity SQLquery expression as a string and then use Entity Framework’s querymechanisms to execute the query. When querying, you can return objects or simply stream the data back as a DataReader. Underneaththe covers, Entity Framework reads the data model and additional metadata to translate the entities and properties in to their related tables and objects, and then communicates with the specific database provider, e.g., SqlClient, to have the EDM query translatedinto a store command.

Use Entity SQL to return objects or streamed dataThe Entity SQL language is very rich with over one hundred operatorsand functions, allowing you to do all of the standard variations on queries whether you are requesting single entities, shaping data withprojections, nesting queries or performing joins.Querying against the first version of our example EDM, listing 1 showsa simple query that requests person entities while navigating into therelated PersonalDetails entity to express a filter.

SELECT VALUE p FROM MyEntities.People as p

WHERE p.PersonalDetails.MaritalStatus=”Married”

ORDERBY p.LastName

Listing 1: Entity SQL using navigation properties

The query in listing 2 uses projection to return shaped data. It beginswith Customers, then pulls in the related Person data as well as anyOrders that the customer may have. When projection is used, theVALUE keyword is not required.

SELECT c, c.Person, c.Orders FROM MyEntities.Customers as c

Listing 2: Entity SQL projection

EF has two ways to execute an Entity SQL query. The most typicallyused is the ObjectQuery which will not only cause the query to execute, but will materialize objects from the resulting data. These objects are instantiated from the classes that were generated from theEntity Data Model.

The other mechanism for executing queries is with the EntityClient APIwhich, like other ADO.NET providers, e.g., SqlClient, allows you tocreate connections and command and return a DbDataReader. Inother words, EntityClient returns streamed data and does not materialize objects. This is convenient for tasks such as reporting ormoving data around. It differs from using SqlConnections andSqlCommands because the query is expressed in terms of the EDMand the data returned is in the shape of the EDM entities. ObjectQueryexecution also uses SQLClient under the covers to execute its queries.

LINQ to EntitiesLINQ (Language INtegrated Query) is an enhancement to C# and Visual Basic that was introduced in Visual Studio 2008. When the Entity Framework team first learned about LINQ and saw its queryingpower, it was obvious that it would be a huge benefit to developersusing the Entity Framework. LINQ to Entities is an implementation ofLINQ that is particular to working with entities. The entity classes generated from the EDM provide strongly typed classes that allow developers to write queries leveraging strong typing and Intellisense inC# and VB. The following LINQ queries shown in listings 3 and 4,match the Entity SQL examples above.

==VB==

From p In MyContext.People _

Where p.PersonalDetails.MaritalStatus=”Married”

Order By p.LastName

==C#==

from p in MyContext.People _

where p.PersonalDetails.MaritalStatus==”Married”

order by p.LastName

select p

Listing 3: LINQ to Entities using navigation properties

==VB==

From c In Context.Customers _

Select c, c.Person, c, c.Person, c.Orders

==C#==

from c in Context.Customers _

select c, c.Person, c.Orders

Listing 4: Simple LINQ to Entities projection

LINQ to Entities queries always materialize objects.

Because a LINQ to Entities query is already a query, you don’t needto create a separate query object to execute it as you do with EntitySQL.

Change tracking and updating Entity objectsBy default, objects that are created as the result of a query are managed by the Entity Framework’s ObjectContext. This contextkeeps track of modifications not only to the scalar properties, but alsoto the relationships between objects. The ObjectContext has a SaveChanges method which reads all of thechanges as well as any new or deleted objects and sends the appropriate commands to the database to perform updates.If you create new objects under the management of the ObjectCon-text, it will also take care of relationships. In other words, if you wereto create a new Order and a new set of Order Line items in memory,and you specify that the line items are children of that order, the ObjectContext will do the necessary work to automatically insert thisgraph into the database with the necessary foreign key information.

Between queries and updatesRetrieving data as entities and saving changes back to the data storeis only the surface of what Entity Framework provides. Not only do theEF APIs provide a lot of flexibility to modify the behavior of these critical tasks, but the core of the API enables you to work with the instantiated entity objects in a very granular way. You have the abilityto create custom business logic throughout the entity classes, controlthe behavior of how Entity Framework performs its various operationson the instantiated objects and even control transactions and database connections . For both LINQ to Entities and Entity SQL, thereare a number of ways to impact performance, from pre-compilingLINQ queries or caching the Entity SQL’s expressions. Using thesefeatures means that the expensive task of generating the store querydoes not need to be repeated.

You can also control how objects are managed by the ObjectContext.

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK BEELDMERK

FULL-COLOUR

SOFTWARE DEVELOPMENT NETWORK DIVISIES

CONFERENCE

MAGAZINE

EVENTS

.NET

.NL

DELPHI

5 0 c y a a n1 0 0 g e e l

5 0 z w a r t1 5 c y a a n

SOFTWARE DEVELOPMENT NETWORK SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

40

Microsoft’s vision for Entity Frameworkis large and long-term

.NETDATABASES

Page 41: SOFTWARE DEVELOPMENT NETWORK

Drawbacks of a version one productMicrosoft’s vision for Entity Framework is large and long-term. What wehave currently in Visual Studio 2008 is only the first iteration. There aredefinitely a lot of things about EF today that make it a challenging product for developers to work with. As the architecture of your application becomes more complex, you will need to invest more inunderstanding and manipulating EF’s underpinnings. Some of the bigger drawbacks in the current version are the limited Stored Procedure support (which should be considered with the understan-ding that query compilation is one of EF’s core features), challengeswith change-tracked entities when you need to move them acrosstiers (ASP.NET, Web/WCF Services), limitations when working with verylarge models and lack of support for agile and domain driven design.There are also quite a few technical nuances (i.e. gotchas) that youshould be aware of so they don’t surprise you along the way. Forexample, users of ORM products, including LINQ to SQL, are accus-tomed to related objects being loaded automatically and might realizesurprising results if they assume that Entity Framework does the same- which it does not. Making assumptions about the behavior of relationships between objects can also get you into a pickle, so it’simportant to spend some time learning about how methods like attaching, adding and detaching impact the objects.

For many, the prospect of working with the EDM and getting ahead ofthe curve for aligning with Microsoft’s data strategy is worth the extraeffort that it will take to build large, multi-tiered applications with thistechnology. And there are plenty of developers who are tackling it andworking on V1 deployments. While others have chosen to wait untilversion 2, where there will be vast improvements in the designer, forstored procedures, for n-tier development and for Domain and Agiledevelopers, they are taking advantage of the lead time to start learningthe core concepts and ins and outs of EF.

Julia Lerman

Julia Lerman is the author of O’Reilly’s “Programming Entity Fra-mework” and is the leading inde-pendent authority on the EntityFramework which she has beenusing and teaching the technologysince its inception. Julie is well

known in the .NET community as a Microsoft MVP, ASPInsiderand INETA Speaker. She is a prolific blogger, a frequent presen-ter at technical conferences around the world, including DevCon-nections and TechEd and she writes articles for many well-knowntechnical publications. You can read her blogs at www.thedata-farm.com/blog.

Many are designing applications in a way that they will be able to plugEF in to the data layer when they are ready to embed it into their soft-ware.

A number of Microsoft tools already lean on Entity Framework, mostnotable ADO.NET Data Services. You’ll also find technologies likeASP.NET Dynamic Data Controls which are able to rely on an EDMand the Entity Framework for its back-end data.

As more developers learn and use the Entity Framework, you’ll findmore and more resources and coding patterns to help you along theway. There are already a lot of resources online and a number of bookson Entity Framework at your disposal. •

.NETDATABASES

Advertentie 4DotNet

Page 42: SOFTWARE DEVELOPMENT NETWORK

DevTweet: One of the Boys -Women in Technology

DevTweet’s zijn de conversaties tussen Marianne van Wanrooij en Sander Hoogendoorn overde (on)zin die IT-ers bezig houdt: Software-ontwikkeling met een knipoog. Regelmatig zullenook gasten worden uitgenodigd. Volg ze ook op Twitter via @mariannerd en @aahoogendoorn!

Suffers from writers block! Have to finish my column for the@SDNMagazine “Women in Technology” issue.

@mariannerd Still struggling with the subject? I handed in my "regular" column - not dealing with WIT. When's the final deadline?

@aahoogendoorn I woke up this morning with an idea. deadlinewas 13/4, for columns it's a bit easier. so friday has to do. ;-)

@aahoogendoorn Too bad we don't have too much time.. we couldhave co-write it... a man vs. woman kind of thing LOL

@mariannerd That would have been cool. We could have set it up ina conversation style, maybe even Twitter style. What if we twitteredthis ...

@aahoogendoorn I like the idea! It can be funny and to the point...(at least every response has to be short :-) )

@mariannerd Normally my responses are longer - like most women(in IT), let alone exceptions (like you).

@aahoogendoorn I'm an exception? .. I'm not a model develo-per....but a model's just an imitation of the real thing.

@mariannerd If you're an exception, that would be BECAUSE youare indeed a MODEL developer.

@mariannerd With your looks it's more likely you'll create an excep-tion with many male developers. A BufferOverflowException per-haps?

@aahoogendoorn A BufferOverflowException? As long as they knowhow to handle it! And otherwise I will give them more Runtime ;-)

@mariannerd Maybe that's why there so little female developers? Ittakes a nerd to understand nerd jokes? Maybe too few female au-tists?

@mariannerd I tried to think of all WIT I've met over the past 20years. Quite a few. But when it comes to writing code, I can literallycount them

@mariannerd Why are there so few female developers?

@aahoogendoorn Girls don't choose an IT education. It's the image(nerd/geeks), thinking it's too difficult, the fact it's male dominated.

@mariannerd So it's because there's too many men in IT that the-re's not enough girl developers?

@aahoogendoorn That's a rhetorical question..;-) But it is one of thereasons why girls don't choose an technical education.

@mariannerd Rhetorical or not. I guess there are so many men insoftware development because it's so binary. Not how most womenthink :-)

@aahoogendoorn Would you use the opposite explanation for whythere are so few male nurses?

@aahoogendoorn Studies shows that girls THINK it's too complexand therefore dull. Wrong image... never a dull moment in my work :-).

@mariannerd It can’t be complexity - women are supposed to bemulti-tasking, aren't they? Or, in our case: multi-threading.

@mariannerd Although I have to say that the idea of studying with40 girl nurses to me does not sound very scary.

@aahoogendoorn So now you know why I've chosen software development. LOL

@mariannerd However, the idea of studying with 50 male nerds ismore scary. Marvel Heroes, Hitchhiker's Guide, 42, Star Wars allday?

@mariannerd Thought you chose IT because your sense of humor matches that of male nerds? Think Ghostbusters. You probably digSouth Park too.

@aahoogendoorn I love South Park... especially the phrase: Respect my authority !!!

@mariannerd O no, they killed Kenny. My favorite episode is whereCartman hates Family Guy, and the one where Canada is on strike,and ...

@aahoogendoorn I chose IT because I like the no nonsense mentality,always learning new things, the creative side...

@aahoogendoorn...Also the high level of expertise and the knowledgesharing (e.g. at events) is awesome. I guess that’s the geeky part of it.

@mariannerd No nonsense mentality? You've probably never workedfor large consultancy firms... But I agree on the creative part.

@mariannerd And I agree on knowledge sharing - but isn't that a typical female thing? So there should actually be more WIT...

@mariannerd But on the other hand, it also requires hard logic thinking, something a lot of women are less good at. ;-)

@aahoogendoorn I think the lack of logical thinking by women is notthe biggest problem. The female devs I know are VERY good at it!

@mariannerd I love women that think logical. There should be muchmore of them - TomTom would definitively go out of business.

@aahoogendoorn Hmm where would that put me... I always get lostwhen I actually use TomTom!

@mariannerd That's not YOU getting lost, it's TomTom. Developed by male developers?

@aahoogendoorn Another problem for most women... lack of confidence.. (and men having too much)

@mariannerd Most men only PRETEND to be self confident. But youknew that, didn't you?

@aahoogendoorn ... and I thought faking was a women's thing!

@mariannerd Woody Allen shouts (when Annie Hall leaves him): "Andby the way, I faked all my orgasms"

@mariannerd Makes you wonder what kids of relationship a male anda female nerd would have. Watching Comedy Central, laptops on laps?

@aahoogendoorn Oh yeah and quality time through MSN ;-)

@mariannerd MSN while both on the same sofa, watching South Parkand sharing code examples. Actually sounds like lots of fun.

@aahoogendoorn Nah…I've had a similar experience. only the SouthPark part didn’t add up. Bottom line it didn't work out! LOL

@aahoogendoorn One advantage of working as a female developer..no queues at the bathroom at events!

@mariannerd That's a good one. And of course lots of nerdy develo-pers staring at you like. Don't you get tired of that?

@aahoogendoorn Hmm.. Getting tired of nerdy men looking at me? I wouldn't be a good presenter if that would bother me, now would I?

@mariannerd You're fast. Developers stare at me too when I'm presenting, but I hope that's different.

@mariannerd So concluding you might say that girls do not get into ITbecause there's too many male nerds.

@mariannerd I read an article yesterday that stated that certain ant colonies in the US reproduce without sex, no more male ants required.

@aahoogendoorn I feel sorry for those ants ;-)

@mariannerd So, if Darwin is right, and this ant pattern gets picked upby humans, the problem of too many male developers should soon besolved.

@aahoogendoorn ...male developers reproducing by themselves!?Wow... talk about scary! The nurses too?

@mariannerd You can't publish that in SDN Magazine....

@aahoogendoorn Let’s find out!

@aahoogendoorn Btw... are you putting this together for the column?

@mariannerd Eh... I thought you were putting this together actually. Ha ha. Typical man / woman mistake?

@aahoogendoorn I can do it... no probs... Typical female way to solveproblems.

@mariannerd Haha. I counted on that – call it my male intuition.

@aahoogendoorn Yeah! Sure ;-)

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK BEELDMERK

FULL-COLOUR

SOFTWARE DEVELOPMENT NETWORK DIVISIES

CONFERENCE

MAGAZINE

EVENTS

.NET

.NL

DELPHI

5 0 c y a a n1 0 0 g e e l

5 0 z w a r t1 5 c y a a n

SOFTWARE DEVELOPMENT NETWORK SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

42

Page 43: SOFTWARE DEVELOPMENT NETWORK

DELPHI

magazine voor software development 43

Indeed, WebHub contains many threads (pun intended), or groups offunctionality. When taken together, they enable you to create a web application which can carry a New York rush-hour quantity of traffic.You can build anything from off-Broadway static sites to Wall Streetbusiness-suit applications to Paris cafes. We have a portfolio section on www.href.com, and you are invited tohave a look there to see what some of our customers have built overthe years, often on small budgets. WebHub sites easily support a million dynamic page requests per day ... and more, if you throw morethan $2500 worth of hardware at the problem.

Fig. 2: Snail shell

Ann Lynnworth

The WebHub Way of Thinking

Fig. 1: Woven strands form cables which suspend the BrooklynBridge in New York

The observation that I would like to start with is the almost inconcei-vable strength of individual strands when woven suitably together. Forme, this is evident in the Brooklyn Bridge (see figure 1), where eachcable is made of 4 main strands, each consisting of 19 wires and, intotal, containing over 391km of wire (see ref. 1)!

Explaining WebHub is a little like showing wire after wire of an intricatestructure, hoping that the listener will imagine how they combine together.

In the early days of the world wide web (1994), I was lucky enough to learn HTML from an expert who worked in a makeshift office on the second floor of a warehouse near San Francisco,and CGI-WIN from Robert Denny, the author of WebSite (a great product subsequently side-linedby Microsoft's HTTP-server, IIS). Internet lifetimes have gone by since then, and yet, lookingback, some ideas have withstood the trial by fire of Windows OS upgrades, Delphi migrating toCodeGear, Unicode, CSS, the iPhone ... At HREF Tools in 1995, we created WebHub, a totally-cool, extremely-flexible web develop-ment framework for Delphi. I have worn quite a few hats at HREF, but revealing WebHub's secrets has been my passion all along.With this article, I invite you to peek inside the world of WebHub, to learn from our way of thinking about web development with Delphi, and to aim for a better world wide web.

Explaining WebHub is a little like showing wire after wire of an intricatestructure, hoping that the listener willimagine how they combine together

Page 44: SOFTWARE DEVELOPMENT NETWORK

The second metaphor to conjure up appears in figure 2 - the snail -illustrating the notion of slow but steady progress. WebHub evolutionmay not always go in a straight line, but it moves consistently towardsomething greater. Similarly, many web sites start in a fairly primitivestate, and evolve over time, as the owners become more ambitiousand the developers become more skilled. The WebHub frameworksupports entry-level static sites, simplistic dynamic sites and full-featured database-driven sites. Throughout that evolution, WebHubdevelopers can use one syntax, one paradigm, one approach. Over the lifetime of a web site, that saves hundreds of hours and potentially tens of thousands of dollars.Yes, WebHub can help you build static sites with great ease. In thesection below on teamwork, there are some examples of re-usable droplets, and page definitions. Any page can be exported to a staticfile; all pages can be exported by a single verb on the main applica-tion object. So while I use WebHub to build dynamic sites for my dayjob, I also use it to maintain static sites for relatives and friends!

Four essential facetsEvery web application has one job, which is to process requests thatarrive over HTTP, calculate the answer and optionally perform anyother task(s), and then return that answer in the appropriate format(HTML, CSS, XML, etc.).(A ‘web application’ as defined for this article is a dynamic web sitewhich probably has database-driven content and may, or may not,look and feel like a Windows application).

Let's have a look at four essential facets of WebHub which combineto accomplish that job elegantly and super-fast: teamwork, overall architecture, consistent url with save-state, and Delphi hooks.

TeamworkYou may have noticed that some people are more left-brained, logical,and methodical than others. An optimized web development teamneeds one or more left-brained people to write the logic in Delphi (orPHP or C#) and to do the database work. That team also needs someright-brain talent to design the page layout, choose the color scheme,imagine the best user interface, create graphics, logos, and so on. Once in a great while, a single person has strong talent in both areas,but usually, almost always, a web site moves forward best with a teamof at least two people.To keep our story simple, consider the left-brained person(s) to be the

Delphi developer and the right-brained person(s) to be the web artistin charge of the HTML. In reality, sometimes the Delphi developer willdo a bit of HTML or CSS coding, and sometimes the web artist willoffer an observation that leads to better logic.

Supporting teamwork means ensuring that each person can do theirwork without interfering with the other person, and without waiting toolong between tasks for some shared resource. To talk concretely, thismeans dividing up the web site assets into at least two groups of files:one set for the Delphi coder and one set for the web artist. It is theneasy to use version control, and everyone can work pretty much inparallel.

WebHub, by default, keeps all web page definitions in plain-text filesoutside the Delphi application. Every detail about the page layout, colors and user interface can be altered without recompiling or evenstopping the Delphi application.

For any web artist who uses Dreamweaver, we have a custom plug-in which provides live content directly in "design mode" - and thismeans 100% live, 100% accurate content. The web artist can enjoyall the normal benefits of Dreamweaver plus context-sensitive help forediting any WebHub expression, shortcuts for testing, and a built-in reference to all WebHub commands.Most importantly, the web artist can accomplish great things with afairly minimal understanding of WebHub, components, and databaseissues, while the Delphi developer can keep the Delphi IDE as homebase.

Now that we have a file-based territory for each side of the brain, let'stalk about iterative development. There are few organizations with theluxury of completely specifying a software project in advance of itscommencement. Rather, someone builds a prototype and then featu-res are refined according to priorities and budget.You may be surprised to learn that the syntax in the external files actively assists with iterative development, via the "sketch" tag... thiswill become clear shortly.WebHub uses its own markup language, which is a superset of HTML,with special tags to mark out pages, reusable droplets, text substitution macros, plus expressions for calls to reusable pieces. Thismarkup language is called WebHub-HTML, or W-HTML for short, andis saved in "teko" files (*.whteko).

A WebHub page definition file (*.whteko) can contain any number ofpage, droplet or macro definitions, in any order. Page attributes can beshared by all, or some, pages within that file. We wanted to convey theidea that our files could contain more than just one web page, and wechose the word 'teko' (from Esperanto, where it means "briefcase")as the keyword. To remember the file extension, think of (WebHub +teko) = .whteko, "a briefcase of declarations." Full documentationabout the .whteko file format can be found at http://webhub.com/dyn-help.

Within any page, droplet or macro, you can use a WebHub expression.A few examples will help you get the pattern quickly:

(~mcHelloWorld~)

(~waHelloWorld.execute~)

(~waHello.execute|world~)

Inside Delphi, you can make use of any WebHub expression by saying

pWebApp.SendMacro(name-here);

WebHub includes about 35 built-in commands, of which JUMP is themost commonly used. The JUMP command outputs an <a href_tag>to "jump" the surfer to the desired page. Details vary based on configuration settings for the type of HTTP server software and anyoptional filters.

Thus (~JUMP|home|Home Page~) could generate any of the following,depending on configuration settings, in a web app identified as "a",for the surfer using session number 123:

• <a href="/scripts/runisa.dll?a:home:123">Home Page</a>• <a href="/a:home:123">Home Page</a>• <a href="http://www.href.com/a:home:123">Home Page</a>• <a href="/a/home/123">Home Page</a>

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK BEELDMERK

FULL-COLOUR

SOFTWARE DEVELOPMENT NETWORK DIVISIES

CONFERENCE

MAGAZINE

EVENTS

.NET

.NL

DELPHI

5 0 c y a a n1 0 0 g e e l

5 0 z w a r t1 5 c y a a n

SOFTWARE DEVELOPMENT NETWORK SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

44

To keep our story simple, consider the left-brained person(s) to be theDelphi developer and the right-brained person(s) to be the web artist incharge of the HTML

DELPHI

Page 45: SOFTWARE DEVELOPMENT NETWORK

Listing 1 shows a minimalist .whteko file:

<!DOCTYPE whteko PUBLIC

"-//HREF//DTD whteko stage 2.14//Strict//EN//"

"http://webhub.com/dtd/0214/whteko.dtd">

<whteko>

<whpage pageid="home">

<html><head>

<whdroplet name="drHeadTags" show="yes">

<title>(~pageid~)</title>

<style type="text/css">

body { font-family:Verdana, Arial; }

</style>

</whdroplet>

</head>

<body>

<p>hello this is a page with id (~pageid~).</p>

<p>(~JUMP|home|show again~)</p>

<p>(~JUMP|clock|check server time~)</p>

</body></html>

</whpage>

<whpage pageid="clock">

<html><head>(~drHeadTags~)</head>

<body>

<p>The time on the server is

(~CentralInfo.WebTimeLocal~).</p>

<p>(~JUMP|clock|show again~)</p>

<p>(~JUMP||back home~)</p>

</body></html>

</whpage>

</whteko>

Listing 1: A WHTEKO file containing two page declarations (homeand clock)

In Dreamweaver and in the WebHub editor, syntax highlighting makesthe code much easier to read. Figure 3 shows a subset of listing 1, withcolors, to give you the idea.

Fig. 3: Part of listing 1, showing syntax highlighting within Dreamweaver

What to notice in listing 1:1. A droplet is used to define a portion of the header within the home

page. The droplets are called (re-used) on the clock page.2. Links from one page to another are generated by the JUMP macro

as needed at calculation time; see lines 27 and 28 in figure 3. Whenthe target PageID is omitted as in line 28, the default PageID is filled in automatically.

3. The doctype allows content to be validated by suitable programs(including Dreamweaver)

4. Parentils surround WebHub expressions, e.g. (~pageid~) and(~drHeadTags~)

magazine voor software development 45

This .whteko file would be loaded by the WebHub application (compiled in Delphi), and all the content would be available for usewhen the web pages are served.

The relationship between EXEs and AppIDs is many-to-many. A single EXE can load many AppIDs (albeit one at a time). An AppIDcan be loaded by many EXE instances. To see more examples, you may visit http://demos.href.com wherewe have more than 3 dozen WebHub demos. All include full-source(Delphi code plus WHTEKO code). Please feel free to browse throughthem. Use the [Source] link in the page footer of each demo to explore the source code. All the "lite" demos can be loaded bywhLite.exe as they all use the same basic components.

In today's world, teamwork often involves players in more than onecountry, with strengths in different human languages ("lingvos"). Winning web sites cater for visitors from multiple countries and providecontent in more than one lingvo.With its full Unicode support within Delphi, Delphi 2009 offers us a tremendous leg up in terms of development for such a multi-lingvoworld. We definitely recommend that you use Delphi 2009 if any ofyour database or other source data is in Unicode format.The WHTEKO files are generally in UTF-8 format; Delphi 2009 userscan use UTF-16.

Regardless of the Delphi version, WebHub has built-in support fortranslating content to multiple lingvos. This is ideally done usingDreamweaver, where a translator can set the design-lingvo to theirown native lingvo and immediately see how the page would look usingtheir wording. Even without Dreamweaver, a translator can enter trans-lations for words, phrases and entire droplets if needed. On a public site, the application will operate with a default lingvo. Forour sites, the default lingvo is English, so any macros or droplets whichhave not yet been translated will appear in English. Meanwhile all trans-lated content will appear in the surfer's selected lingvo.

Fig. 4: WebHub architecture

DELPHI

Page 46: SOFTWARE DEVELOPMENT NETWORK

A seemingly minor but actually tremendously powerful feature of WebHub is that its expressionscan be nested, to a large degree. A macro can calla droplet; the droplet can call another macro; thatmacro can call a web action component, which cancall another macro. Thus control can go back andforth between .whteko and .pas as often as needed.Not all web artists master the concepts of dynamiccontent, subroutines and variables; for those thatdo, WebHub is an excellent fit.

Overall architecture: runner, hub, application(s)The WebHub architecture is fairly straightforward. Itconsists of three moving parts: (a) a runner; (b) thehub; and (c) your application(s). See figure 4 for adiagram.

The runner (yellow circle "5" in figure 4) is a smallprogram which receives the request from the HTTPserver. When used with Microsoft IIS, the runner isan ISAPI DLL; with Apache, the runner is an exe tosupport CGI-BIN. As new HTTP servers come on the market, we addor modify the runners to adapt to them. We have phased out the firstrunner from 1995, which was for the CGI-WIN interface.

The Hub (yellow-6) is the process controller. It aggregates requestsfrom the runner(s), assigns session numbers to newly arriving surfers,and directs traffic to the least-busy application instance available toserve the request. The Hub makes WebHub scalable.

For a low-traffic web site (roughly 1 to 5 dynamic requests per 5 seconds), running one instance of your application (yellow-7) is probably sufficient. (Of course, it depends on how long your averagepage request takes to calculate, which often depends on the speed ofyour database connection. As they say, "your mileage may vary.")For a high-traffic web site, it helps significantly to run two or more instances of your application. The Hub then directs traffic to the instance most ready to handle the request. The application calculates the page and hands the response back tothe runner, which hands it back to the HTTP server. For really high-traffic sites or for very old-hardware scenarios, the functionality of a web site can be divided up, with each group of pagesand features being associated with an Application ID ("AppID"). A greatway to eliminate bottlenecks on a site is to find the feature which ismost popular and/or slowest, and give it its own AppID. That allowsall other page requests to go through at an easy pace because a dedicated instance is available for the troublemaker.

WebHub saves state across applications. Even if you use multiple AppIDs, the surfer will not notice any problem or data loss. Surfer datais easily shared among WebHub EXEs, even if they are running on different machines, as long as those machines share a network drive.You can start by putting all features under a single AppID, and ifneeded, later separate one feature out into its own AppID, or, in extreme cases, onto a dedicated separate server.

Coming back for a moment to the JUMP macro, part of the simplicityof WebHub is that linking to a page is just a matter of referencing thePageID, e.g. (~JUMP|home|Home Page~), where "home" is the PageID and "Home Page" is the visible phrase seen by the surfer. (Yes,the visible phrase can be a graphic image and you can add furtherHTMLtags if needed.) If a particular page, say "CalcReport", needed to be moved to a separate AppID, you would simply change JUMP|CalcReport|... toJUMP|NewAppID:CalcReport|... and that would take the surfer to theNewAppID.

Fig. 5: WebHubAdmin provides a way to see inside the Hub

The Hub runs as a non-gui service, and a helper program named WebHubAdmin is used to find out what is going on. Figure 5 showsthe "Connected Panel" of WebHubAdmin, where you can see theWebHub applications that are running.In figure 5, there are three columns worth pointing out: Process, AppIDand PID. The Process column lists the name of the EXE running. TheAppID column lists the string identifying the WebHub application. ThePID is the process identifier as provided by the operating system. Ifyou analyze the PIDs carefully, you will find that every Process is a separately running instance of the EXE. The Process named "WHLITE"runs many times, once for each "lite" demo.

A WebHub developer license includes a 1-cpu, 1-EXE unlock codefor use on the developer's computer and the same capacity on oneproduction server. A developer can build unlimited EXEs in sequence;the limit is on the number of EXEs running at the same time.Unlocking the Hub to support more EXEs or more CPUs requires amore expensive license. The idea behind the pricing is that you can get started for a reasona-bly small amount of money (considering that almost all technical support is included), and most of your payments are deferred in timeuntil you complete your project and deploy it for your customer in ahigh-traffic or significantly complicated scenario. Presumably by thattime you are financially benefiting from your use of the WebHub framework.

Consistent URLsOne of the early decisions in the design of WebHub was to use completely consistent URLs for all requests. In particular, we allowedfor 4 parameters:• AppID: the application identifier• PageID: the page identifier, e.g. "home" or "clock" in listing 1• SessionID: the surfer's session number• Command String: a string containing any further details, formatted

as desiredIn other words, all custom data fields went into the command string.

In 1995, WebHub URLs looked like this:

http://localhost/cgi-win/runwin.exe?

appid:pageid:sessionid:command

The separator character was originally a colon (':') and can be

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK BEELDMERK

FULL-COLOUR

SOFTWARE DEVELOPMENT NETWORK DIVISIES

CONFERENCE

MAGAZINE

EVENTS

.NET

.NL

DELPHI

5 0 c y a a n1 0 0 g e e l

5 0 z w a r t1 5 c y a a n

SOFTWARE DEVELOPMENT NETWORK SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

46

DELPHI

Page 47: SOFTWARE DEVELOPMENT NETWORK

configured as slash ('/') instead. When Microsoft added IIS to the operating system, WebHub URLs usually looked like this:

http://localhost/scripts/runisa.dll?

appid:pageid:sessionid:command

Then we added the Coolness Layer, which was an ISAPI filter enabling short URLs by sitting between Microsoft IIS and the runner,and WebHub URLs could look like this:

http://localhost/appid:pageid:sessionid:command

On domains using only one AppID, this could be shortened to

http://localhost/pageid:sessionid:command

In 2002, we retired the Coolness Layer in favor of StreamCatcher, anISAPI filter which, among other things, recognized web robots basedon their user agent. (While not all web robots play fair and use a clearuser agent string, the important ones such as googlebot do.) Detec-ted web robots could be assigned a pre-arranged session number,and this session number could be hidden from the URL. This meantthat links to WebHub pages in Google, Yahoo, etc., could omit thesession number, and when used by humans, would receive a sessionnumber. A WebHub URL when using StreamCatcher for google couldlook this clean:

http://localhost/pageid

When a WebHub developer wants to add support for StreamCatcher,he or she makes a few adjustments to the application-level configu-ration file and the "server profile", and thereafter, the JUMP macro automatically generates short URLs instead of long ones.

The point is that by keeping a simple, consistent set of parameters inthe URL, we were lucky enough to survive 14 years of HTTP serversoftware changes without any need to change the syntax of the JUMPmacro.That is not to imply that our upgrade path has been completely trivial,it has not. However, we have provided wizards and conversion toolsfor the pieces that needed converting, as well as free technical supportfor most customers needing assistance.

Hooks to DelphiThe fourth major strand deals with the way that we hook from aWHTEKO file into Delphi. There are quite a few ways to get either pro-perty values or complex calculated values from Delphi. We saw oneexample of obtaining a component property value in the minimalistexample in listing 1:

(~CentralInfo.WebTimeLocal~)

CentralInfo is the reserved component name of the TwhCentralInfocomponent, and WebTimeLocal is a property which returns the timeon server (local to the server, not local to the surfer).

Thus obtaining the value of any string, integer, or TStringList propertyis easy.In additional, obtaining any data entered by the surfer into a form onany page within the web application is also easy. Let's say you had aninput field named "email", you could display the data entered into thatfield using

(~email~)

and you could access it in Delphi using

pWebApp.StringVar['email']

What about more complex requirements? WebHub has a "web actioncomponent" which can be used to trigger any behavior and outputany result. The component is called by name, so if you name it "waHello" (for web-action-hello), you could hook to it like this:

(~waHello.execute~)

and you could pass it parameters like this

(~waHello.execute|a,b,c~)

In the component's OnExecute method, you would write your calcu-lation and/or response code. The component's response will be addedinto the output stream at the exact point where the page designer cal-led it.

Generally, WebHub pages are created from top to bottom. However,there is a unique feature called an ANCHOR. A page designer can setan ANCHOR at any point on the page, and subsequently back-fill con-tent into that position by calling ANCHORMODIFY. This means youcan build shared droplets which are generic, with details filled in "a bitlater" when some Delphi code has done the necessary database look-ups. This is not always needed, but occasionally it enables the impossible.

Listing 2 shows what the OnExecute event handler might look like.

procedure TDM001.waHelloExecute(Sender: TObject);

begin

pWebApp.Response.Send('<p>hello!</p>');

end;

Listing 2: OnExecute event handler for a web action componentwhich says hello

Weaving the strandsNow you may start to put the pieces together. Let's look at a realexample that you can follow in your web browser. A request to

http://www.href.com/hrefsite:rubicon

is transformed by StreamCatcher into

http://www.href.com/scripts/runisa.dll?hrefsite:rubicon

and is then sent by Microsoft IIS to our runner (runisa.dll), which asksthe Hub for a new session number, and the EXE serving the AppID"hrefsite" will respond. That EXE contains WebHub components whichenable it to know what should happen on the page with id "rubicon".This page happens to be a product-information page, so a series ofstandard droplets are sent out to give information about the product,Rubicon. When the EXE has finished building the web page, the datagoes back to the runner, back to IIS, and back to the surfer's

magazine voor software development 47

The point is that by keeping a simple,consistent set of parameters in theURL, we were lucky enough to survive14 years of HTTP server softwarechanges without any need to changethe syntax of the JUMP macro

DELPHI

Page 48: SOFTWARE DEVELOPMENT NETWORK

browser to be displayed. The time to calculate this page is 31 millise-conds, as reported in the page footer for anyone interested. This webapplication is running on a server bought in 2005, with 1 Xeon-pro-cessor. Eight (8) WebHub application instances running eight differentAppIDs are on that server. With newer hardware, performance couldbe much quicker – but this is fast enough for our little web site.

To be continued…

References:1. http://www.endex.com/gf/buildings/bbridge/bbridgefacts.htm •

Ann Lynnworth

Ann Lynnworth was born near Boston, Massachusetts USA at theright time to catch the informationtechnology wave. In 1978, shefound she could not resist learningto program fancy macros for Word-Perfect, and she has never been af-raid to pick up a manual and/orguess her way into a new techno-logy. She started her "Software Doc-

tor" consulting business in 1983 on Apple's early computers,published WordStar at Your Fingertips, wrote Situation Analyst forthe IBM PC, helped create Ronstadt's Financials and then joinedXL/Proteus to learn all about Paradox and a bit about SQL. Skip-ping ahead to 1994, Ann learned Delphi and soon co-foundedHREF Tools and has worn many hats with the internet tools com-pany, the most enjoyable of which was producing “Tech TalkRadio” for several years for WebHub customers. A dynamic spea-ker with an unusual point of view, Ann has had rave reviews fromattendees in training seminars and at technical conferences. Annholds an associate art's degree from Simon's Rock College anda bachelor’s degree in psychology from Wellesley College, also inMassachusetts.

DELPHI

.Net TIP:Visual Studio 2008 SP1 i.c.m. LINQ partial classimplementatieEr zit een bug in SP1 van VS2008 bij de implementatie van eencustom partial class op een LINQ dbml. De custom class (metusings) zorgt ervoor dat de [dbml].designer.cs los komt te han-gen van de dbml. Zet de usings die nodig zijn in de custom par-tial class implementatie binnen de namespace. Dan komt hetprobleem niet voor.

Richard van der Meel - VX Company

Advertentie Barnsten Embarcadero

Page 49: SOFTWARE DEVELOPMENT NETWORK

.NETASP

ASP.NET is beter dan ASPNatuurlijk is de performance van ASP.NET an sich niet slecht. Door allerlei slimmigheden is de performance van ASP.NET juist uitermategoed, zeker in vergelijking met ASP “Classic”. ASP “Classic” heeft namelijk twee nadelen als het gaat om performance: het wordt uitge-voerd door een interpreter en het is gebaseerd op Single ThreadedAppartment (STA) threading, dat eigenlijk alleen geschikt is voordesktop applicaties. ASP.NET daarentegen is (JIT) gecompileerd envolledig multi-threaded. Hoe kan het dan dat een ASP.NET applicatiedie functioneel gelijk is aan z’n voorganger in ASP “Classic” zoveellangzamer is? Dat komt vooral omdat ASP.NET ons lui maakt.

In ASP.NET wordt van alles voor ons verzorgd, zoals het behoud vanwaardes in inputvelden en het invoegen van JavaScript op plaatsenwaar we dynamische functionaliteit wensen. Voor de gemiddelde applicatie is dit allemaal heel handig en zit het ons niet in de weg. Maarals we de extremen opzoeken, dan kan dit soort handigheid enorm inde weg gaan zitten. Zo ook in het voornoemde project. Als iemand demoeite had genomen om te kijken naar de grootte van de HTML, danhad men meteen gezien dat daar iets niet helemaal goed ging. De pagina’s waren gemiddeld 6-7 keer zo groot als in ASP “Classic”en konden tot ca. 7 MB (!) groot zijn. Die HTML moet ten eerste gegenereerd worden, maar moet vervolgens ook nog eens over hetnetwerk en dat kan even duren, zelfs in een intern netwerk.

Voor een goede performance moet je de moeite nemenIk zei net “als iemand de moeite had genomen” … en dat is precieswaar het bij performance meestal om draait. Je moet de moeite nemenom vooraf na te denken wat een bepaalde programmeeropdracht voorperformancegevolgen kan hebben. Je moet de moeite nemen om per-formance te testen. Je moet de moeite nemen om je testresultaten teanalyseren en om te zetten in verbeteringen. 90% Van de performan-ceproblemen (en dus verbeteringen) zijn eenvoudig op te sporen envaak ook nog eens eenvoudig op te lossen. De onderstaande tips kunnen je hierbij helpen.

Tip 1: Doe altijd een performancetestEen performancetest doen is eigenlijk helemaal niet zo moeilijk. Er zijnverschillende tools die je hierbij kunnen helpen. Een oude favoriet is deWeb Application Stress Tool (WAS) van Microsoft (zie http://sup-port.microsoft.com/kb/313559). Hiermee kun je een script maken datrequests afvuurt op een webserver. Om het makkelijk te maken kun jeeen script “opnemen” in je browser.

Tip 2: Gebruik Performance MonitorMet Performance Monitor kun je sleutelwaardes van je webserver in degaten houden. Voor ASP.NET zijn er allerlei zaken die je met Performance Monitor in de gaten kunt houden, zoals Request WaitTime en Requests Queued. CPU- en geheugengebruik geven vaakook al veel inzicht. Heeft de CPU vrijwel niets te doen, maar is de per-formance erg slecht, dan is de thread pool waarschijnlijk leeg en staanveel threads te wachten op I/O operaties. In dat geval zou je eens kunnen kijken of Async Pages een oplossing zijn.

Tip 3: Maak handige meetpunten in je applicatieEr zijn verschillende manieren om meetpunten aan te leggen. Je kuntmet Windows Management Instrumentation (WMI) zelf performancecounters maken die je kunt bekijken met Performance Monitor (ziehttp://www.ondotnet.com/pub/a/dotnet/2003/04/07/wmi.html). Ook kun je een debug log aanleggen met log4net (zie http://log-ging.apache.org/log4net/) of een van de vele andere logging biblio-theken. Met Enterprise Library (zie http://www.codeplex.com/entlib)kun je beide. De vraag is dan natuurlijk wat goede momenten zijn omte loggen en wat je dan moet loggen. Hiervoor is het handig om de levenscyclus van een request te kennen. Door te meten bij Applica-tion_BeginRequest en Application_EndRequest kun je precies bepalen hoe lang een request bezig is om van begin tot eind afgehandeld te worden. Wil je dit alleen weten van een pagina, danmoet je loggen op Application_PreRequestHandlerExecute en Application_PostRequestHandlerExecute.Het is ook altijd goed om te kijken hoe lang het renderen van de HTMLduurt en daarvoor kun je aan het begin en eind van de Render methode van de pagina loggen. Tot slot kun je de grootte van de pagina opvragen in Application_EndRequest met HttpContent.Cur-rent.Request.ContentLength, hoewel je dat uiteraard ook zelf in eenbrowser kunt bekijken. •

magazine voor software development 49

ASP.NET onder de Motorkap:

“De performance van ASP.NET is slecht”Onlangs werd ik bij een project gehaald dat last had van ernstige performanceproblemen. Pagina’s die in het oude ASP “Classic” systeem in enkele seconden getoond werden deden erin de nieuwe ASP.NET applicatie 20-25 seconden langer over. De eerste reactie van de klant wasdan ook dat de performance van ASP.NET slecht is. Helemaal ongegrond is die reactie niet.

Michiel van Otegem

Michiel van Otegem is een van depioniers op het gebied vanASP.NET. Hij schrijft, spreekt engeeft hierover training. Hij is mede-eigenaar van de community websiteASPNL.com en schrijver van“ASP.NET 3.5 - de basis”, “XML - debasis” en “Sams Teach YourselfXSLT in 21 Days”. Voor zijn continue

inzet voor de .NET community heeft Michiel al 6 jaar op rij de MVPAward van Microsoft ontvangen. Michiel is werkzaam bij BataviaLabs als Chief Software Architect.

90% van de performance problemen zijneenvoudig op te sporen

Page 50: SOFTWARE DEVELOPMENT NETWORK

UXGENERAL

Frédèrique Harmsze

Fig.1: Needs, features en requirements

Needs: wat hebben ze nodig?Wat hebben die gebruikers die je hebt geïdentificeerd nodig? Eenvoorbeeld kan zijn dat “de medewerkers van het bedrijf op de hoogtewillen blijven van de laatste ontwikkelingen over de reorganisatie”.Ik vind het soms best lastig om samen met mijn opdrachtgever te bepalen wat eigenlijk de needs zijn van de gebruikers, omdat iedereenliever in termen van features praat. Je hoort dan “we willen een blogvoor de directie op ons intranet”.Maar wie wil dat eigenlijk en waarom? Omdat iemand dat cool en web2.0 vindt? Of omdat de medewerkers het belangrijk vinden om op dehoogte te blijven en te kunnen reageren, terwijl de directie eigenlijk helemaal geen tijd heeft voor het schrijven van blogs? Of omdat dedirecteurs het belangrijk vinden om ideeën te delen met de medewer-kers en daar ook feedback op te krijgen? En waarom wil de directiedit? Om een gevoel van betrokkenheid te creëren? Om goede ideeënte verzamelen?Je zit goed als je belandt bij een need die is geënt op een businesscase, b.v. “die betrokkenheid vermindert het verloop en bespaart zowervingskosten en inwerktijd, en de feedback vervangt de inhuur vaneen extern bureau”.

50SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK BEELDMERK

FULL-COLOUR

SOFTWARE DEVELOPMENT NETWORK DIVISIES

CONFERENCE

MAGAZINE

EVENTS

.NET

.NL

DELPHI

5 0 c y a a n1 0 0 g e e l

5 0 z w a r t1 5 c y a a n

SOFTWARE DEVELOPMENT NETWORK SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

Requirements ManagementHoudt de Kikkers in de KruiwagenRequirements management, is dat nog wel van toepassing als je websites en intranet-ten maakt met een standaardproduct als SharePoint? Ja, het blijft belangrijk, maar kieswel een vorm die past bij je project. Het doel van requirements management is immersniet om bureaucratie te genereren, maar om je project in de hand te houden én om tezorgen dat de gebruikers krijgen wat ze nodig hebben. Anders vliegen de enthousiasteteamleden en hun ad hoc oplossingen je om de oren.

Needs, features en requirementsBij het ontwikkelen van een systeem moet je natuurlijk eerst bepalenwat eigenlijk het doel is. Wie zijn de beoogde gebruikers en waar hebben die behoefte aan: wat zijn hun needs? Vervolgens zoek je uitwelke features aan die gebruikersbehoeften kunnen voldoen. En danwerk je in de requirements uit hoe dat moet functioneren.

Wie zijn de gebruikers en andere stakeholders?Aangezien we een systeem maken voor gebruikers, moet je zo snelmogelijk een duidelijk beeld krijgen van die gebruikers. Wat voor mensen zijn dat, in wat voor situatie zitten ze, wat hebben ze tot hunbeschikking en hoe voeren ze hun taken uit? Hoe doen ze b.v. hunwerk, als je het hebt over een intranet?Naast de gebruikers zijn er ook andere stakeholders, zoals aandeel-houders en helpdesk-medewerkers, die niet direct gebruik maken vanhet systeem, maar die er b.v. wel baat bij hebben als anderen dat goeddoen.

Een handig hulpmiddel om grip te krijgen op de gebruikers zijn personas: de personificatie van belangrijke gebruikersgroepen. Je baseert die personas op gegevens over doelgroepen en gebruikers-statistieken. En je geeft ze een verhaal, zodat iedereen zich gemakkelijkkan verplaatsen in die persona bij het bedenken en toetsen van slimmeoplossingen. Een voorbeeld: Jantien Smit is een ervaren sales-mede-werker die veel onderweg is. Dat geeft haar een heel ander perspec-tief dan Pieter de Vries, die net begonnen is bij HR.Schrijf dus op wie de stakeholders zijn, en schrijf ze uit als als perso-nas wanneer je aan een systeem werkt waarbij gebruikersvriendelijk-heid erg belangrijk is.

Het doel van requirements management is immers niet om bureaucratie te genereren …

Een handig hulpmiddel om grip te krijgen op de gebruikers zijn personas

Page 51: SOFTWARE DEVELOPMENT NETWORK

Maak daarom een overzicht van de needs, en vermeld daarbij de gebruiker (of algemener: de stakeholder) die deze need heeft. En ditmag een simpel lijstje zijn …

Features: wat moet het systeem dus bieden?Als je weet wat de gebruiker nodig heeft, bedenk je welke functiona-liteit voldoet aan deze eisen en wensen. Dit is de overstap van het probleemdomein naar het oplossingsdomein. Iedere feature die je bedenkt is een antwoord op een van de geformuleerde needs. Als gebruikers b.v. op de hoogte willen blijven van de nieuwste ontwikke-lingen op een bepaald gebied, kun je een pagina maken met een overzicht van de laatste informatie, een nieuwsbrief aanbieden, en notificaties mogelijk maken. Maak dus een overzicht van de features en zet bij iedere feature bijwelke need hij hoort. Je kunt gewoon een lijst maken, maar ook eendiagram waarin je onderlinge afhankelijkheden uitdrukt, als die belangrijk zijn. Ik zet ze zelf graag in een lijst op een projectsite in SharePoint.PS: Ik gebruik de term ‘feature’ hier in de betekenis van ‘functionali-teit’, zoals dat ook gebeurt in het Rational Unified Process. Dus niet inde technische zin, als de features die je b.v. in SharePoint kunt definiëren in XML.

Requirements: hoe moet het dan werken?De globale features werk je uit in gedetailleerde requirements. Eenveelgebruikte definitie van requirement is “a software capability neededby the user to solve a problem to achieve an objective” [Leffingwell enWidrig, 2000]. Ze geven als tweede optie dat de software-capabilitymoet voldoen aan een contract, standaard of zo iets formeels, maarik leg de nadruk liever op de gebruiker.Als b.v. een nieuwsbrief een van de features is, dan staat in de requi-rements dat de gebruiker een abonnement op de nieuwsbrief moetkunnen nemen, veranderen en opzeggen, en bovendien dat hij moetinloggen om dat allemaal te doen. Dit zijn functional requirements.Ieder van deze requirements is als het goed is geassocieerd met eenfeature en daarmee ook met een need, dus je weet waarom je die requirement realiseert: om aan die gebruikerswens te voldoen. De functional requirements worden ondersteund door non-functionalrequirements: randvoorwaarden of kwaliteitseisen los van directe gebruikersfunctionaliteit. Voorbeelden zijn performance, veiligheid engebruiksvriendelijkheid, maar ook zaken als beheerbaarheid en schaal-baarheid. Maak dus een overzicht van functional requirements, ge-groepeerd op de feature waar ze bij horen, en een overzicht van denon-functional requirements.

De requirements beherenHoe groter en complexer je project en je systeem, des te belangrijkerwordt het dat je de verzamelde requirements actief beheert. Leffingwellen Widrig definiëren requirements management als een systematischeaanpak om de requirements van het systeem te achterhalen, organi-seren en documenteren, en een proces om overeenstemming tussende klant en het projectteam te verkrijgen en behouden over de veran-deringen in de requirements van het systeem. [Leffingwell en Widrig,2000]

Proces: wie doet wat en hoe?Requirements management gaat niet over het gebruik van geavan-ceerde tools. Het gaat erom dat je achterhaalt en bijhoudt welke func-tionaliteit je moet ontwikkelen en wat de status daarvan is, en dat deopdrachtgever en het team hiervan hetzelfde beeld hebben. In je

projectaanpak spreek je af hoe je omgaat met de requirements. Wiedoet wat in de levenscyclus van de requirements: hoe leg je ze vast,wie moet ze langs welke weg goedkeuren, enz.Daarbij kun je natuurlijk allerlei tools gebruiken, vooral als je een lang-lopend project doet met veel requirements. Een voorbeeld van eentool waarin je je proces kunt beheren is Eclipse. Je definieert alle elementen van je standaardproces en geeft er de benodigde instructies en templates bij. En aan het begin van je project maak je jeproces specifiek door b.v. in te vullen wie de gedefinieerde rollen opzich neemt. Ook als je agile werkt en Scrum kiest als proces, kom je niet om requirements heen, al schrijf je die niet in detail uit. Tijdens een kortsprintje in Scrum zijn die requirements bevroren; aan het einde van datsprintje kijk je of het toch anders moet.

Fig.2: Het proces vastleggen in Eclipse

Scope en prioriteit: wat doen we nu eerst?Vanaf het begin stel je met de opdrachtgever vast wat de scope vanje project is: welke needs adresseer je wel en welke (nog) niet, welkefeatures ga je daarvoor maken, en welke requirements moet je dusrealiseren? Als je bepaalde needs wel besproken hebt, maar ze nietbinnen de scope van dit project passen, schrijf dat dan op. En stelvast welke prioriteit de requirements krijgen, zodat je weet welke eventueel kunnen vervallen voor deze versie van het systeem.Overwegingen bij het bepalen van de scope en de prioriteiten zijn bij-voorbeeld: hoe belangrijk en urgent is de gebruikerswens, zijn anderefeatures afhankelijk van deze, hoe tijdrovend en riskant is de realisatie?Neem dus in de lijsten van needs, features en requirements op of zein de scope zitten en wat hun prioriteit is.

Requirements vastleggen: use cases, wireframes en prototypescreenshotsIn maatwerkprojecten leg ik requirements vaak vast in use cases (Unified Modeling Language). Daarin beschrijf ik per functionele een-heid stap voor stap de specificatie van wat de gebruiker doet, b.v.voor het geval waarin hij een nieuwsbriefabonnement aanvraagt. Datkan gewoon in tekst in een gestructureerd Word document, met af-beeldingen van schermen en eventueel diagrammen, als de flow ingewikkeld is. Sinds ik SharePoint projectsites tot mijn beschikkingheb, zet ik die documenten in de projectsite, evt. gekoppeld aan eenlijst met alle use cases, om documenten over dezelfde requirementsbij elkaar te houden. En straks hebben we ook de nieuwe modelleer-taal M en de tool Quadrant tot onze beschikking.

magazine voor software development 51

“Requirements management gaat niet over het gebruik van geavanceerde tools”

Neem dus in de lijsten van needs, features en requirements op of ze inde scope zitten en wat hun prioriteit is

UXGENERAL

Page 52: SOFTWARE DEVELOPMENT NETWORK

Wireframes zijn handig om de requirements vast te leggen voor systemen waarin schermen belangrijker zijn dan functionele eenhedenwaarin de gebruiker een aantal stappen moet doorlopen. In een wire-frame schets je welke elementen waar op de pagina’s moeten staan.Je kunt wireframes overal in tekenen, maar Axure is een tool die hetgemakkelijk maakt om ze te maken en beheren. Je hoeft bijvoorbeeldelementen die in verschillende wireframes staan slechts op één plek bijte houden.

De laatste tijd doe ik echter veel projecten waarin we SharePoint con-figureren, maar niets programmeren. Dan ga ik geen standaard func-tionaliteit uitschrijven in use cases. In die projecten klik ik meteen eenprototype in elkaar. De opdrachtgevers zien in het prototype beter watik bedoel dan in een tekstdocument. Om hun beslissingen vast te leg-gen documenteer ik de functionaliteit en interface van het prototype inscreenshots en lijstjes met instellingen. Als een collega op basis hier-van contenttypes en templates in XML-code gaat maken, dan zet ikinstellingen in kopieerbare tabellen in Word of Excel. In de echt kleineprojecten kan ik zelfs in het prototype de benodigde templates bakken.

Fig. 3: Een wireframe in Axure

Voortgang van de requirements: hoever zijn we?Vooral als je systeem veel requirements heeft en er veel mensen in hetteam mee bezig zijn, is het belangrijk om goed bij te houden hoe hetermee staat: is de requirement uitgewerkt en goedgekeurd? Is hij gerealiseerd in het systeem en is dat getest, opgeleverd en geaccep-teerd? En wie is er functioneel en technisch verantwoordelijk voor dezerequirement?Dus: hou de status van je requirements bij en geef bij een opleveringaan welke requirements daarin gerealiseerd zijn.

Veranderingen in requirements: beslissen, vastleggen en communicerenTijdens het project zullen er altijd requirements veranderen! De oorzaak kan zo triviaal zijn als een interpretatieverschil dat je strak moettrekken, maar een stakeholder kan voortschrijdend inzicht hebben. Ofde omstandigheden veranderen, zoals bij een reorganisatie of eennieuwe wet die extra maatregelen vergt. Veranderingen zijn niet erg,mits je de requirements goed beheert en dus beheerst. Een wijziging op een goedgekeurde requirement vergt zorgvuldigchange management. Wat is de impact van de gewenste wijziging?Hoe belangrijk is zij? Op basis daarvan moet de opdrachtgever beslissen of de wijziging nu echt gewenst is, en kijkt het projectteamof de wijziging nu ook uitgevoerd kan worden. In een complexer project richt je voor deze beslissingen een Change Control Board in.

En als de wijziging inderdaad doorgaat, zorg dan ook dat de uitvoer-der en de tester weten wat de laatste versie is en wat ze dus preciesmoeten doen.Een SharePoint projectsite helpt bij het beheren van de aangevraagdechanges, en specificatiedocumenten en hun versies. De versie diedaar staat is altijd de laatste. En je kunt een workflow opzetten voor degoedkeuring van de requirements. Conclusie: bepaal de impact van de wijzigingen, besluit over de uitvoering, documenteer de besluiten en de wijzigingen, en communi-ceer ze goed naar alle betrokkenen.

Fig. 4: Voorbeeld van een dashboard voor requirements management in een SharePoint team site.

Traceability: iedere requirement heeft een traceerbare herkomstEen van de kernwoorden het verhaal van requirements managementis traceability: je moet de herkomst van iedere requirement kunnentraceren. Welke gebruikersbehoefte moet hij vervullen? Wie heeft datgezegd en wat waren de overwegingen? Is er iets aan veranderd tij-dens het project?Je bouwt niets waarvoor niet duidelijk is waarom het nodig is.

Doordat je weet waar de requirement vandaan komt, kun je hem opwaarde schatten en prioriteren. Als er iets verandert, weet je waar datimpact op heeft. En wanneer het systeem eenmaal in gebruik geno-men is, kun je onderzoek naar het gebruik van het systeem in contextplaatsen.Gebruikt niemand de functionaliteit? Dan toch eens kijken wat de onderliggende wens was en wat we nog meer gedaan hebben omaan die wens te voldoen.

Requirements management loopt door na de opleveringVoor projectleden is de oplevering van een werkende site vaak heteinde van hun inspanningen. Maar die site begint zijn leven pas. De gebruikers gaan ermee aan de slag, en die willen dan toch meer ofiets anders. Zolang iemand de site verder ontwikkelt, blijft requirements manage-ment nodig. Zelfs als je de vervolgstappen niet projectmatig neemt,en je geen budget hoeft te vragen voor wijzigingen. Wat krijg je an-ders? Je plaatst op verzoek van de ene gebruiker een knop, en eenmaand later vraagt een ander weer een andere knop. Je systeem looptvol met onderdelen die niemand blijkt te gebruiken en waarvan niemand weet waarom ze er op staan. Maar ze zitten gebruikers welin de weg. En de gebruiker moet steeds weer wennen aan nieuwefunctionaliteit.

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK BEELDMERK

FULL-COLOUR

SOFTWARE DEVELOPMENT NETWORK DIVISIES

CONFERENCE

MAGAZINE

EVENTS

.NET

.NL

DELPHI

5 0 c y a a n1 0 0 g e e l

5 0 z w a r t1 5 c y a a n

SOFTWARE DEVELOPMENT NETWORK SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

52

Tijdens het project zullen er altijd requirements veranderen

Je bouwt niets waarvoor niet duidelijk is waarom het nodig is

UXGENERAL

Page 53: SOFTWARE DEVELOPMENT NETWORK

Dus:• Kijk of de wijziging past in het interactieconcept, de bestaande

structuur, de stijl;• Bepaal voor iedere wijziging wat de onderliggende wens is en voor

welke gebruikersgroepen het van belang is. Wat levert het op?• Bepaal de impact van de wijziging voor andere gebruikers. Riske-

ren ze een overload of verwarring, oftewel wat kost het de gebrui-kers aan extra energie?

• Bepaal wat de impact is op het beheer. Kost het de beheerdersextra energie of wordt het systeem instabieler?

• Besluit met de verantwoordelijken of je de wijziging doorvoert, endocumenteer dit.

ReleasesWijzigingen die programmeerwerk en dus uitrol vergen, doe je in geplande releases. Wijzigingen die je kunt doorvoeren door de configuratie van een Sharepoint-site aan te passen hoeven niet per sein releases. Maar je kunt het wel zo insteken, als de configuratie-wijzigingen zo belangrijk zijn, dat je ze expliciet moet communicerennaar de gebruikers, en dat je duidelijk de oude en de nieuwe versie wiltkunnen onderscheiden.

Governance: plan het intranetbeleidRequirements management past in het bredere kader van governance.Met name in de context van intranetten krijgt dat onderwerp veel aan-dacht de laatste tijd. Organisaties hebben goed bestuur nodig, en datgeldt ook voor de intranetten die de organisaties ondersteunen. Nietalleen gedurende het ontwikkeltraject, maar juist ook nadat het live isgegaan. Het intranet is een levend systeem, dat de juiste kant op moetgroeien. Dit vergt, zonder in te gaan op de meer technische aspecten,duidelijkheid over bijvoorbeeld:• De geldende functional en non-functional requirements;• Templates en richtlijnen voor het beheer van sites en content, in

bijvoorbeeld een stijlgids en policies;• Verantwoordelijkheden: Wie is bijvoorbeeld verantwoordelijk voor

de navigatiestructuur, de best bets in de zoekfunctie, en de con-tent op de verschillende plaatsen in de site? En hoe is dat preciesgeregeld, met stuurgroepen, redactieraden, goedkeuringswork-flows, champions en dergelijke?

• Wijzigingen: Gezien de verantwoordelijkheden, hoe gaan we ommet wensen voor wijzigingen? Waar kunnen gebruikers feedbackgeven, hoe kunnen redacteurs wijzigingen aanvragen, en wie gaatdaar op welke manier over besluiten? En wat zeggen de statistie-ken? Een site owner van een projectsite spreekt zijn gebruikers vaaken hij kan b.v. wijzigingen in zijn locale site-menu zelf doorvoeren,maar alleen het portal team mag een nieuwe knop op de portal-homepage zetten, na goedkeuring van de portal-eigenaar. En alsde afdeling Financiën op hun afdelingsite een koppeling wil met eenander systeem, dan moeten ze de ontwikkeling daarvan zelf betalen.

• ‘Life cycle management’ van sites en content: hoe vraag je eennieuwe site aan, en wat gebeurt er met informatie die een jaar langniet gewijzigd of gelezen is?

• De werking: trainingen, help en communicatie. Wie verzorgt de on-dersteuning?

Maak een governance plan, waarin je de verantwoordelijkheden enprocessen rond wijzigingen vastlegt.

ConclusieRequirements management is belangrijk tijdens het ontwikkeltrajecten zolang je doorwerkt aan het levende systeem. Cruciaal is dat je nietzomaar wat bouwt, maar alleen requirements realiseert die gefundeerdzijn in gebruikerswensen. Daarvoor moet je altijd inzicht hebben in degebruikers en hun wensen. Je kunt lichtgewicht requirements management doen in eenvoudigeprojecten, aan de hand van simpele afspraken en lijstjes in bijvoor-

beeld een projectsite, maar maak wel een plan voor de governance naoplevering. Requirements management zorgt dat alle kikkers in dekruiwagen doorrijden in de juiste richting, zelfs wanneer het pad debocht om gaat vanwege voortschrijdend inzicht.

Referenties• Dean Leffingwell and Don Widrig, Managing software requirements

– A unified approach (Addison Wesley, 2000)• Tools Database Working Group, INCOSE Requirements Manage-

ment Tools Survey http://www.incose.org/ProductsPubs/pro-ducts/rmsurvey.aspx

• Microsoft, Governance Resource Center http://technet.micro-soft.com/en-us/office/sharepointserver/bb507202.aspx •

magazine voor software development 53

Frédérique Harmsze

Frédérique Harmsze werkt als Infor-mation Worker Consultant bijMacaw. Sinds ze in 1994 bij hetCERN begon met surfen op hetWorld Wide Web, houdt ze zichbezig met de vraag hoe je informa-tie kunnen delen en andere takenkunnen uitvoeren in een elektroni-

sche omgeving. Eerst in haar promotieonderzoek naar een modelvoor natuurwetenschappelijke artikelen op internet. Vervolgens alsanalist bij een ontwerpbureau, waar ze werkte aan complexe web-sites. En de afgelopen vijf jaar bij Macaw, waar ze zich in het In-formation Solution Center richt op de functionele kant van deontwikkeling van intranetportalen en samenwerkingsites. Ze doetprojecten voor onder andere ziekenhuizen, onderwijsinstellingenen multinationals. Daarbij gebruikt ze SharePoint 2003 en MOSS2007. Blog: http://blog.frederique.harmsze.nl

Delphi TIP:Delphi PrismDelphi ontwikkelaars die voor het eerst met Delphi Prism werken, en dus Visual Studio voor hun neus krijgen, kunnenmaar moeilijk wennen aan de key-mappings. Via het menuTools - Customize ... kunnen deze mapping aangepast worden.

Klik op het customize form op de Keyboard knop.

Kies het Debug.Start commando; verwijder de F9, die er al staaten typ F5 in de ‘Press shortcut keys:’ edit-box. Klik op Assign.Hetzelfde voor het Debug.Togglebreakpoint commando: verwijder F5 en assign F9.Als er iets verschijnt in ”Shortcut currently used by” moet dezeeerst opgezocht en verwijderd of reassigned worden.

UXGENERAL

Page 54: SOFTWARE DEVELOPMENT NETWORK

Advertentie VNU

Page 55: SOFTWARE DEVELOPMENT NETWORK

magazine voor software development 55

DATABASES

point). Door BI-professionals wordt dit werk nog wel eens denigrerendafgedaan als werk van ‘Excel knutselaars’. In de praktijk zijn deze Office tools juist de tools waarmee het (top)management vertrouwdis, omdat zij er dagelijks mee werkt, in tegenstelling tot specifieke BI-tooling. Veruit de meeste bedrijven worden bestuurd aan de handvan op deze wijze verkregen informatie, en hier zit een grote discrepantie tussen de theorie en de praktijk.Dit laat echter niet onverlet dat met het toenemen van het aantal applicaties, vestigingen, managers en Excel spreadsheets en kruis tabellen, de complexiteit, schaalbaarheid en consistentie van BIeen overgang naar het volgende niveau noodzakelijk maken.

Niveau 2: Business intelligence met behulp van datawarehouseOp dit niveau ontstaat een kanteling in de beschikbaarheid van cijfers.Cijfers zijn niet langer direct afgeleid van de broncijfers. Er ontstaat eenmodel dat de som van de modellen van de bronsystemen representeert. Een compleet plaatje dus: een mix van cijfers uit verschillende interne- en externe systemen. BI loopt via een data staging area waar alle gegevens onbewerkt binnenkomen en vanuitdaar in de juiste vorm worden doorgezet naar het datawarehouse. DeBI in het datawarehouse wordt ontsloten via een eigen portaal, meteen eigen user interface en standaard rapportages of met Office tools.Bij grote organisaties ontstaat bij met name gespecialiseerde onderzoekers en beleidsmedewerkers behoefte aan verdergaandeanalysetools waarmee de overgang naar niveau 3 zich aandient.

Niveau 3: Business intelligence met behulp van datamartsNiet alleen kale data maar ook afgeleide data is op niveau 3 beschik-baar om naar wens gebruikt te worden als basis voor rapportages.De koppeling met de originele systemen is los door het gebruik vanstaging areas (tussenlaag voor het inlezen van gegevens). Op het datawarehouse zijn datamarts gebouwd waarop analyses kunnenworden losgelaten met behulp van BI tools, die verder gaan dan de

Liesbeth Smits

Business Intelligence:Theorie en PraktijkWeet u wie uw beste klanten en leveranciers zijn en hoe uw interne organisatie in dat kaderpresteert? Of u geïntegreerde ERP-systemen hebt of maatwerkapplicaties, ze bevatten door-gaans een schat aan gegevens die niet in uw rapportages verschijnen, laat staan dat ze benutworden in de besluitvorming. Dat vergroot de kans op foutieve beslissingen en belemmert uwsucces. Met welke informatie wilt u uw organisatie sturen? Een analyse van uw business processen en risico’s is nodig voor een goede definitie van uw informatiebehoefte. Daarna wiltu sturen op Key Performance Indicators (KPI’s), maar waar haalt u de informatie vandaan?Business Intelligence (BI), datawarehouse, datamining, het zijn toverwoorden. Theorie met veelmystiek omgeven. In de praktijk kosten BI-projecten veel en leveren een teleurstellend rendement omdat ze vaak te hoog worden ingestoken.Een confrontatie met de harde feiten is noodzakelijk om succesvol te besturen. Dit artikel pleitdaarnaast voor een ‘met beide voeten op de vloer’ benadering: pragmatisch instappen en pasverder investeren na gebleken succes, in nauwe aansluiting op de daadwerkelijke behoefte enrekening houdend met diverse belangengroepen in een organisatie.

BI van ‘eenvoudig en voor iedereen’ tot ‘geavanceerd en voorde specialist’Wij onderkennen 5 niveaus van BI. De meeste BI leveranciers zien niveau 4 als de ultieme situatie. In de praktijk blijken de meeste klanten op niveau 0 of 1 te zitten, niveaus die door leveranciers niet alsBI worden gezien. Succesvolle BI begint met de acceptatie dat BI opniveau 0 of 1 helemaal geen schande is. Een pragmatische vertaal-slag maken van informatiebehoefte naar informatievoorziening is hetuitgangspunt. Ontstaat vervolgens de behoefte aan gedetailleerdereinformatie, dan is dat het moment voor de stap naar het volgende niveau. Niet eerder en zeker niet ineens. PS: Een overzicht van de niveaus vind je aan het einde van het artikelin een aparte tabel.

Niveau 0: Er is een hot stand-by database beschikbaar voorrapportages en extra queriesOp basaal BI-niveau 0 maakt een organisatie een hot stand-by kopievan de OLTP productie-database. Dit kan goed gecombineerd wordenmet een failover backup- en recovery-strategie. Deze tweede database-server is de stand-by backup voor de organisatie en wordtgebruikt voor de rapportages. Met extra indexen en materialized viewsis deze database beter geschikt als rapportage-server dan het origineel. De hot stand-by is nauwelijks belastend voor de origineleOLTP productie-database, die nu zelfs ‘ge-offload’ is van de rapportage-workload. Ad-hoc queries ten behoeve van productie opde hot standby maken deze tot een prima BI-laboratorium.

Niveau 1: Business intelligence met behulp van OfficeNiveau 1 borduurt voort op niveau 0. Echter, de hot stand-by wordt(naast standaard rapportages en ad-hoc queries) nu ook gebruikt doorOffice tools. Vaak worden gekoppelde Excel spreadsheets gebruiktom cijfers en grafieken te produceren die weer (al dan niet gekoppeld)worden gebruikt in documenten (Word) en/of presentaties (Power-

Page 56: SOFTWARE DEVELOPMENT NETWORK

Office tools. Deze BI tools ontsluiten het datawarehouse met zogenaamde multi-dimensionele kubicals. In deze kubicals staat dedata als het ware klaar in elke gewenst vorm of doorsnijding. Ten behoeve van sales-reporting, marketing, budgeting, forecasting, etc.worden met typische On Line Analytical Processing (OLAP) techniekenals ‘slice & dice’ en ‘drillen’ analyses op maat uitgevoerd.

Niveau 4: DataminingDe definitie van datamining is: ‘Het geautomatiseerd ontdekken vanpatronen en/of trends in bestaande informatie uit databases’. Zoekt deonderzoeker op niveau 3 handmatig naar onderbouwing voor doorhem zelf geformuleerde trends, datamining doet dat op een geauto-matiseerde manier waarbij een eventueel ontdekt patroon of ontdektetrend niet van te voren bekend is.

Datamining is bekend vanuit marketing, maar kan op vele andere terreinen worden toegepast. Voorbeelden hiervan zijn de analyse vanproductieprocessen, de schatting van kredietwaardigheid van klantenop termijn en de detectie van fraude aan de hand van transactie-analyse. Een bekend voorbeeld van een grote supermarktketen is deonverwachte relatie tussen bier en luiers: ‘mensen die luiers kopen,kopen meestal ook bier.’

Niet ieder bedrijf heeft baat bij een niveau 4 business intelligence inrichting. Zo kan het voor een waterleidingbedrijf interessant zijn omte weten hoe het waterverbruik van particuliere huishoudens zich inde loop van de jaren ontwikkelt, maar is het niet interessant om teweten dat een hoekhuis 5% meer water verbruikt om de tuin tesproeien. Voor een credit risk afdeling is het echter wel erg interessantom te weten wanneer een bedrijfstak in de problemen komt. Als datvia datamining kan worden voorspeld, zijn dat de kosten van een niveau 4 BI inrichting in tienvoud waard. Het grote punt van BI op niveau 4 is het woordje ‘als’ in de vorige zin. Niveau 4 projecten zijnkostbaar en op voorhand staat een uitkomst niet vast en/of kan eentrend niet worden opgemerkt!

Fig. 1: BI niveaus

De overgang naar hogere niveausStel een bedrijf heeft nog geen BI, maar is wel ambitieus. Kan een bedrijf meteen naar een niveau 2 gaan? Of zelfs direct naar niveau 3of 4? Een korte toelichting …

Vanuit niets naar niveau 0 kan eenvoudig. Dit is vooral een technischestap. Wellicht is bij navraag een dergelijk systeem al draaiend.

Vanuit niets naar niveau 1, zonder de voorgaande stap, zal perfor-mance-problemen veroorzaken in de productie-applicatie. Vanuit niveau 0 naar niveau 1 kan heel goed; wel zullen managers inzake dekoppeling van Office applicaties wegwijs moeten worden gemaakt inhet datamodel.

Vanuit niets naar niveau 2 kan, maar heeft organisatorisch veel risico’s.Alle technische en organisatorisch issues uit voorgaande stappen dienen zich nu in een keer aan. Met name oudere managers zullenmoeten wennen aan de verschillende data bronnen en ontsluitings-applicaties.

De behoefte om in één keer naar niveau 2 te stappen ontstaat nietvan de ene dag op de andere. Vaak hebben zich andere behoeftes aleerder voorgedaan die met een niveau 0 of 1 oplossing zijn ingevuld.

Niveau 3 en 4 zijn pas aan te bevelen na enige ervaring met niveau 2.Het is erg moeilijk om vanuit een nulpunt te bepalen over welke datameer informatie interessant is. Technisch is het mogelijk, maar de kansop succes vanuit bedrijfsperspectief is veel kleiner dan na een paarjaar op niveau 2.Vandaar dat ik adviseer het BI terrein niet te ambitieus te betreden. Zo is bijvoorbeeld BI met Office tools (niveau 1) op een hot stand-bydatabase een technisch volwaardige stap met een hoge acceptatie-graad bij managers met beperkt invoeringsrisicoprofiel. Stappen naarhogere niveaus ontstaan daarna als vanzelf. Organisch, pragmatischen beheerst.

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK BEELDMERK

FULL-COLOUR

SOFTWARE DEVELOPMENT NETWORK DIVISIES

CONFERENCE

MAGAZINE

EVENTS

.NET

.NL

DELPHI

5 0 c y a a n1 0 0 g e e l

5 0 z w a r t1 5 c y a a n

SOFTWARE DEVELOPMENT NETWORK SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

Voorbeeld:Database bevat verkoopcijfers per product en locatie. Tot en met niveau 2zijn er rapporten met totalen, somma-ties en onderverdelingen beschikbaar.Vanaf niveau 3 kunnen deze totalen,sommaties en onderverdelingen ge-bruikt worden in verdere berekeningen.Dus kan bijvoorbeeld eenvoudig hetverschil in groei in verkoop per productsoort worden bepaald

De definitie van datamining is: ‘Het geautomatiseerd ontdekken vanpatronen en/of trends in bestaande informatie uit databases’ Vandaar dat ik adviseer het BI terrein

niet te ambitieus te betreden

DATABASES

56

Page 57: SOFTWARE DEVELOPMENT NETWORK

De drijvende kracht achter de opbouw van een BI systeemBusiness intelligence op niveau 0 en 1 is BI voor iedereen. Vanaf niveau2 gaat ‘ownership’ een rol spelen.Als een IT afdeling de BI kar trekt, ontstaat een systeem waarop andere afdelingen jaloers zullen zijn. Helaas is BI voor de gebruikerswel een ‘ivoren toren’ geworden; ze mogen er niet aankomen. Het wordt een technisch heel geavanceerd systeem dat iedere dagalle loads verwerkt en waarin alle data zit. Alle data? Nou ja, natuurlijkniet die data waar een gebruiker vorige week om vroeg. Daarvoor moeteerst de aanvraagprocedure doorlopen. En tegen de tijd dat dan allesbeheerst is gemaakt, is de gebruikersvraag achterhaald. Dus na eenkorte tijd houden gebruikers maar op met exact die informatie te vra-gen die ze graag willen hebben. Die slaan ze zelf wel weer op via Excel!De business haakt hier af, en we zijn weer terug bij niveau 1.Als de dagelijkse operatie de trekker is, dan ontstaat een systeem datveel gebruikt wordt en dagelijks wijzigt. Het is eigenlijk een niveau 1 oplossing met één specialist. Naast die expert kan niemand andershet onderhouden. Iedere afdeling regelt het voor zichzelf.Als de beleidsafdeling verantwoordelijk is, bevat het systeem informa-tie waaraan de dagelijkse operatie niets heeft. Als een organisatie alniet blijft hangen in planfase met torenhoge consultancy-kosten.

magazine voor software development 57

Liesbeth Smits

De auteur van dit artikel is LiesbethSmits (Oracle BI consultant) vanVX Company. Liesbeth Smits is af-gestudeerd aan de Technische Universiteit Delft op kennistechnolo-gie. Binnen de Oracle unit van VX-Company leidt ze de productgroepBusiness Intelligence en dataware-houses. Ze werkt aan het verbeteren van datawarehouses bijdiverse opdrachtgevers.

Niveau 43210Komt voor bij 50% 20% 5% 1% enkele (NL)bedrijven met meerdan 100 werknemersDe normaal grens 100 250 400 5.000 20.000(50%) ligt bijbedrijven met XwerknemersOptimaal voor Verzamelen, Idem niveau Veel of complexe Complexe data Eenvoudige

groeperen, 0 maar voor data vanuit met complexe maar véél data.rapporteren meerdere meerdere rapportages, Het vinden vanvan data tot

beschikbaar.systemensystemen een bruikbaar dwarsverbanden

een datawarehouse is moeilijk.beredeneerbaar is al langere tijd Dwarsverbandenniveau. aanwezig. leiden tot zeer

groteopbrengsten.

Vraagt van IT weinig weinig middel veel heel veelafdelingBenodigde kennis op SQL Excel Portaal OLAP Geavanceerdde IT afdeling OLAPOrganisatieonderdeel Team en Team en Afdeling en Beleid en Strategisch

afdeling afdeling middelmanagement hoger managementmanagement

BI tooling naast Rapportage Rapportage ETL* ETL Idem aanrapportage tooling Office Portaal Analyse en niveau 3

rapportage Datamining

beschikbaar.

* Extract Transform Load (ETL)

De beleidsafdeling heeft het budget en zal alleen informatie voor zichzelf willen opslaan.De kunst is de belangen van de drie stromen te combineren. De kansop succes is het grootste bij een BI-project dat vanuit alledrie de rich-tingen wordt aangestuurd. Er is een multidisciplinair projectteam nodig,waarin business en ICT samenwerken. •

SDN TIP:Wil je direct naar de magazines op de SDN-site, surf dan naarwww.sdn.nl/magazine.

Tabel 1: BI niveaus

SDN TIP:Meer SDN-informatie over architectuur vind je opwww.sdn.nl/architecture.

DATABASES

Page 58: SOFTWARE DEVELOPMENT NETWORK

DELPHI

Help & Manual descriptionHelp & Manual was written in Delphi 2007. (EC software is currentlyusing Delphi 2009 for upgrades to Help & Manual). The Standard version of Help & Manual allows for the creation of extensive help systems and documentation. There is also a Professional versionwhich allows you to also work with and save files in uncompressedxml, includes multi-user functionality which allows for concurrent multi-author editing, integrates with version control software, and providescapabilities for project help system translations and localization. Thereis also a Premium pack of 14 configurable skins for your help systemswhich is available as an optional add-on for purchase with both theStandard and Pro versions.

Help & Manual makes it easy to create self-contained help systemsthat include a multi-level table of contents, topic details, a navigatio-nal bar for moving forwards and backwards through topics, searchcapabilities, and indexes. You can start with one of the project templates, or you can create your own template. In addition, the skins

in the Premium pack allow you to easily try out a variety of professio-nal looks for your help system. You can import existing text into Help & Manual from a variety of formats including HTML and text files, RTF documents (saving Wordfiles as RTFs), compiled HTML help files (.CHM), compiled WinHelpfiles (.HLP), WinHelp source files (.HPI), and RoboHelp for HTML project files.

Help & Manual’s main screen is shown figure 1.

Fig. 1

In Help & Manual you work with projects, and these are displayed inthe Project Explorer. Help & Manual projects contain your individualtopic files and baggage files for files that are used repeatedly such asicons used in the help display, and the like. For images you use in yourhelp, you will most likely want to keep them organized in one or morefolders. You simply configure your project properties to include thepaths to search to let Help & Manual know where to find these files.

The topics displayed in the Project Explorer contain your text (shownin the Editor). Topics form your table of contents entries in your helpsystem. You can easily create, edit, rearrange, and delete topics within the Project Explorer.

The Ribbon toolbar contains the tools you use for working with projects, writing, working with tables, viewing and selecting other Help& Manual program options, and accessing Help for Help & Manual.

The wysiwyg Editor (a true wysiwyg xml editor) is where you do thebulk of your writing. The Editor has all of the word processing and formatting features that you want and need, plus all the help systemtools to add and define links, insert images, insert and define tables,and include other objects like movies, horizontal (sizable) lines, special

Loy Anderson

Creating Help Systems withHelp & ManualAbstractHelp & Manual is a help system author toolfrom EC Software. It’s actually more than just ahelp system tool. Help & Manual is a single-source help authoring and technical writingproduct that you can use to create online andoffline help, interactive and hardcopy docu-mentation, and many other types of written oronline material. In other words, write once, publish in multiple formats, and include someor all of your writing in the documentation.This article provides an overview of Help & Ma-nual features. It also describes using Help &Manual to create a rights-sensitive help systemfor an online application written in Delphi for.NET. What help screens are displayed by theonline help is controlled by the Delphi applica-tion, since the help varies depending on thecurrently logged on user’s assigned privileges.

Help & Manual makes it easy to create self-contained help systems

58SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK BEELDMERK

FULL-COLOUR

SOFTWARE DEVELOPMENT NETWORK DIVISIES

CONFERENCE

MAGAZINE

EVENTS

.NET

.NL

DELPHI

5 0 c y a a n1 0 0 g e e l

5 0 z w a r t1 5 c y a a n

SOFTWARE DEVELOPMENT NETWORK SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

Page 59: SOFTWARE DEVELOPMENT NETWORK

characters and symbols, hyphens, and page breaks for printed manuals. Your links can link to other topics in your help, anchors inyour help, images, files, movies, URLs, and the like.

From the Editor, you can add additional features to your help. Forexample, you can add expanding/collapsing text, insert topic anchors,insert HTML code objects, and insert or link snippets of text from othertopics or other files. Using snippets, you can build a library of reusa-ble content that updates automatically in your projects if you edit thesource snippets, provided you use linked snippets. You can also insertOLE objects, add and define image hotspots, insert WinHelp macros,and insert dynamic HTML or JavaScript code to extend the featuresneeded in your Help system, and add comments for future reference.

You can publish (compile) your documentation in a variety of differentformats including:• HTML help (.CHM)• WebHelp, a browser-independent HTML format for

a self-contained Web site• Adobe PDFs for creating pdfs with interactive

table of contents and hyperlinks• Adobe PDFs for printing documentation• WinHelp (.HLP)• Microsoft Word RTFs• A proprietary e-book .exe file with the content

and a viewer to display the help content• EPUB, a cross-platform e-book standard containing

XHTML and XML files

In addition, you can integrate your Help file into the Microsoft VisualStudio .NET Help documentation (MS Help 2.0) in order to documentthird-party programming components designed for integration intoVS.NET.

You can also create context-sensitive Help. For example, you can simply create a popup window that displays a small amount of information when a user clicks on a link or presses F1. More frequentlyin an application, you want your context-sensitive help to also includeaccess to the rest of the help system. In this case, you make a call fromyour application or a link from HTML to the particular help topic.

Help & Manual includes tools for creating context-sensitive help whenyou want to include your entire help system, since how you create thelinks varies depending on your programming language and the formatof your Help system. There are also online tutorials and references forhelp with integrating your help systems with applications written in Delphi, C++, Visual Basic 6, Visual Basic.NET (Visual Studio.NET), Microsoft Access, Visual Objects, Visual FoxPro, Clairon, APL, andREALbasic for Windows.

The 14 configurable skins available as an add-on for both the Standardand Pro versions are professionally designed layouts that make it veryeasy to test out different HTML designs to apply to your help projects.The skins work for Internet Explorer 6 & 7, Google Chrome, and otherstandards-compliant browsers. You can modify the JavaScript, CSSstyles, and HTML in these skins. However, if you do configure or create your own skins, you do need to test in all browsers. For instance, you need to use equivalent CSS styles and HTML in case theuser has JavaScript disabled on their browser.

magazine voor software development 59

Help & Manual's files are encoded in Unicode, making it possible topublish (compile) your projects in a variety of languages. Although Help& Manual makes creating help projects for Unicode languagesstraightforward, there are some additional setup issues that need to bedealt with for Microsoft help compilers that are not Unicode enabled.You will also need to be running the Windows-based version for thelanguage you are compiling to in order to test your help system's func-tionality like the table of contents, search features, and hyperlinks.

Other Help & Manual features of note:• Allows you to create very large help projects• Images in help can be expanded easily (i.e. view larger image type

feature)• Allows you to work directly with map files• Allows for conditional text and conditional variables in the help• Referral checks, allowing you to find incoming and outgoing

referrers to specific topics• A reporting tool for checking topic captions, topic IDs, help context

descriptions, build inclusions, and dates modified• A project synchronization tool to manage and update translated

versions of your projects

Help & Manual also comes with three very useful tools:1. Screen capture software;2. IMPICT Screenshot Editor, an easy-to-use, nice tool for adding

special elements, such as the callouts in figure 1;3. Print Manual Designer, which allows you to further customize pdfs

and printed pdf output.

And I guess we shouldn't be surprised that a company that createshelp system software has outstanding help documentation about theirproduct, both with the product and online. The Help & Manual help isextensive, and well-written. In addition, tips on good design practices,organization, and other such essential topics are included throughout.

An example of using Help & Manual to build a web-based help systemThe Help system described in this article is end-user Web-based helpfor one part of an access-controlled Internet application that was written in Delphi for .NET. This Help system used the WebHelp formatin Help & Manual, creating a self-contained HTML-based Help systemwith a table of contents, navigation capabilities, and a searchableindex.

The help system actually included several different online help systemssince the help information displayed differed depending on the employee’s individual access rights. For example, a supervisor needsto be able to see the same help that their employees are able to see,but also see more specific information about features of the

You can also insert OLE objects, add and define image hotspots, insert WinHelp macros, etc

Help & Manual's files are encoded inUnicode, making it possible to publish(compile) your projects in a variety oflanguages

The help system actually included several different online help systemssince the help information displayeddiffered depending on the employee’sindividual access rights

DELPHI

Page 60: SOFTWARE DEVELOPMENT NETWORK

application only available to supervisors.

Special considerations/requirements for this system included:• Text needs to be easy to read, with lower reading level assumed for

parts of target audience• Application code controls display of help because of different levels

of user access required:- Some topics, all users have access to- Some topics, a subset of users have access to- Some topics, different users see identical help but with some

variations, depending on their access level• Application code controls links to context-sensitive help• Help needs to display quickly, include a table of contents and index,

and be searchable• Help needs to be able to be downloaded to a local machine if the

user wanted• Parts of help need to be in a printed format for learning or desk re-

ference documentation

Creating the help projectI started by writing in Word, and then imported documents into Help& Manual. But after my initial writing, it soon became apparent thatHelp & Manual was up to the task and became my primary help writing tool. The wsywig editor, along with the breath of word-proces-sing and formatting tools, made writing in Help & Manual as easy as writing in Word. Another reason why I preferred writing in Help & Manual is becausesome tasks can only be done with Help & Manual. These tasks include setting up global properties for the help project, defining topics,assigning unique topic IDs used to link to a page directly from anotherpage or from a link in the application, organize topic structure, definingindex items, defining links between items and topics, defining conditional variables, and defining links to external files.

As you can see in figure 2, you are able to have multiple levels withinyour table of contents. You right-click on an entry in your table of contents to add or delete topics, and define properties such as including or excluding topics in various builds (output formats).You use the Topic Options tab to define unique topic IDs and definekeywords that will appear in a help index and link to this topic. Youcan also insert HTML topic variables like <%DATE%> as well as define your own conditional variables. You can redefine variables on aper-topic basis. This is especially useful for HTML code variables, allowing you to vary the code in the template part of your topic page(i.e. outside the <BODY> section generated by the topic in the editor)on a per-topic basis, for example, for fine-tuned search engine optimization. You click the XML Source tab to directly edit the xml.

Fig. 2

Modular help projects with master/child relationshipsWe needed to account for five different levels of user access for oursubset of applications, and we didn’t want to have to repeat some of the same help information over and over again in the Help documentation for every user access level. With Help & Manual, you can set up a modular help system, usingmaster/child relationships so you can keep your unique help documentation in separate files for easy reuse and more accurate helpinformation. This way, you only need to edit or update particular helptopics once. You can then set up master help files and include entriesfor the child projects files where they should appear in your table ofcontents. Furthermore, you can nest modules so that these child projects also contain their own child project entries.Figure 3 shows an example of modular help, including two differentmaster projects, MasterHelpSC.hmxz and MasterHelpE.hmxz, andone child project ToolHelp.hmxz. This child project contains help information common to all users of the application, and was includedin each of the master files as the first item, Table of Contents in (Tool-Help). Besides using master projects to organize the child projects,you can also include topics directly in these files, and child projectscan be included anywhere within the master project’s table of contents.

Fig. 3

You can then publish (compile) your master help file, which merges allthe module files it contains in the order shown into one complete Helpsystem. Publishing also converts and references your image files forthe help system. You can test your help system in a browser locally.Once you are satisfied, you upload all the help system files, including

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK BEELDMERK

FULL-COLOUR

SOFTWARE DEVELOPMENT NETWORK DIVISIES

CONFERENCE

MAGAZINE

EVENTS

.NET

.NL

DELPHI

5 0 c y a a n1 0 0 g e e l

5 0 z w a r t1 5 c y a a n

SOFTWARE DEVELOPMENT NETWORK SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

60

Fig. 4

DELPHI

Page 61: SOFTWARE DEVELOPMENT NETWORK

images and other files, to the server from which the online help will beserved. An example of testing the published online help (Webhelp format, using the default skin) in Internet Explorer is shown in figure 4.

Figure 5 shows the same help using a different skin. The Index tab isselected here, showing the keywords we set up to link to particulartopics. Users can also click the Search tab and search for text, and aregiven information on the number of matches and scores on relevancy.

Fig. 5

Usability Side Note: You may notice “The Tool Help” name in thehelp title and the Internet Explorer title bar. Despite whatever the application developers or management named the application(s), theend-users referred to the application simply as “The Tool,” as in, “I booked the vehicle in The Tool.” So, the name stuck as the wholepoint of the application was to make sure the users used, and tookownership of, the application.

As mentioned earlier, Help & Manual allows you to define conditions forpublishing output for different formats. You can specify whether to include or exclude child projects, and include or exclude topics on atopic-by-topic basis. For example, you can include all information foronline help, but exclude some topics for a printed pdf version. In addition, you can set up either compile time merging of modules (asshown here) or runtime merging which maintains separate help filesthat are merged, if present, at runtime.

Using Delphi and a database to control which help screens aredisplayedWe controlled user access to the help display from a Delphi for .NETASP.NET Web application. The application itself employs access control on a number of levels. Each time a user requests a page ofthe application, a special class confirms that the user has already logged into the system, and that their session has not timed out. If theuser has not yet logged into the system, or they have been idle toolong, the application redirected them to a login page where they canenter their username and password.Following this initial validation, a special class, called UserSession,reads a list of privileges specific to the logged in user. These privilegesare then used to configure any ASP.NET Hyperlink controls that appearon the requested page. Zero or more Hyperlink controls may appearon a given page, and each of these may be associated with a differentpage or bookmark on a page.

The association between a Web page of an application, the help linksthat appear on that page, and a users privileges are table driven, permitting links targets to be updated by editing the database.

The two tables in the underlying database that are used to associatehelp system links on specific pages of the application with a collectionof user privileges are shown in figure 6. The top table shown in figure 6 depicts the HelpBaseLinks table. Thistable contains the base URL of the help system for each of the available applications, based on user privileges. These entries are sequenced in order to provide the particular user with the help systemassociated with the highest-level privilege that the logged in user possesses. A single user may have many privilege levels. (Note that thethe URLs shown in the BaseHelpURL field are not valid URLs, and areincluded here for descriptive purposes only.)

Here is how the process works. Once a user is validated for a page,a method named LinkHelpControls is called, passing it a single parameter containing a pointer to the current Web Page. LinkHelp-Controls queries the HelpBaseLinks for the application name (which isdetermined from the SCRIPT_NAME cgi variable) for the base helpsystem reference associated with the user’s highest privilege. If thereis no base help system defined, all Hyperlink controls configured on thecurrent page have their visibility property set to False, and the processis over.If a help system reference is found for the particular application/privilege combination, the HelpLinks table is queried for all of thenamed links expected on the current page, using the applicationname/page name as a key. This query returns not only the link name,but also the specific page or page/bookmark that each Hyperlinkshould link to. This result set is then scanned, using each link name tocall the FindControl method of the Web page. If FindControl does notreturn nil, the Hyperlink control is configured to reference the baseHelp URL plus the specific page or page/bookmark resource.If the HelpLinks table contains an entry for a Hyperlink, but does notsupply an associated page or page/bookmark value, it is assumedthat this link should be suppressed on this page for this type of user.Under these circumstances, again the Hyperlink’s Visible property isset to False.

Fig. 6

magazine voor software development 61

DELPHI

The association between a Web pageof an application, the help links thatappear on that page, and a users privileges are table driven, permittinglinks targets to be updated by editingthe database

Page 62: SOFTWARE DEVELOPMENT NETWORK

The code for LinkHelpControls is shown below.

procedure TUserSession.LinkHelpControls(WebPage: System.Web.UI.Page);

varConnection: AdsConnection;Command: AdsCommand;DataReader: AdsDataReader;AppName: String;PageName: String;PrivilegeString: String;BaseURL: String;sa: array of String;LinkName: String;LinkTarget: String;LinkObject: HyperLink;

begin//Note: GetConnection, ReleaseConnection,// and GetStringField// are utility methods, // and are not part of the .NET framework

//Parse the application name and Web page nameAppName := WebPage.Request.ServerVariables.

Item['SCRIPT_NAME'];sa := AppName.Split(['/']);PageName := sa[2];PageName := PageName.SubString(0,Length(PageName)-5);AppName := sa[1];Connection := GetConnection;try

//Determine the Help system BaseURL// for this user’s privilege levelCommand := Connection.CreateCommand;Command.CommandText :=

'SELECT PrivilegeStringList, BaseHelpURL ' +'FROM HELPBASELINKS WHERE ApplicationName = ''' +AppName + ''' ORDER BY SEQUENCE';

DataReader := Command.ExecuteReader;while DataReader.Read do

if Self.HasAtLeastOnePrivilege(GetStringField('PrivilegeStringList', DataReader)) then

begin//The BaseURL for the highest privilegeBaseURL := GetStringField('BaseHelpURL',

DataReader);Break;

end;DataReader.Close;

if BaseURL= '' then //Bad news. No helpbegin//Make all help controls not visibleCommand.CommandText :=

'SELECT LinkName, LinkURL FROM HELPLINKS '+'WHERE PageName = ''' + AppName + PageName + '''';DataReader := Command.ExecuteReader;try

while DataReader.Read dobegin

LinkName := GetStringField('LinkName', DataReader);

if WebPage.FindControl(LinkName) <> nil thenbegin

HyperLink(WebPage.FindControl(LinkName)).Visible := False;

end;end;

finallyDataReader.Close;

end;Exit;

end;

62SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK BEELDMERK

FULL-COLOUR

SOFTWARE DEVELOPMENT NETWORK DIVISIES

CONFERENCE

MAGAZINE

EVENTS

.NET

.NL

DELPHI

5 0 c y a a n1 0 0 g e e l

5 0 z w a r t1 5 c y a a n

SOFTWARE DEVELOPMENT NETWORK SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

//Get names of Hyperlink controls configured// for this pageCommand.CommandText :=

'SELECT LinkName, LinkURL FROM HELPLINKS '+'WHERE PageName = ''' + AppName + PageName + '''';

DataReader := Command.ExecuteReader;try

//For each Hyperlink controlwhile DataReader.Read dobeginLinkName := GetStringField('LinkName',DataReader);//Find the associated controlif WebPage.FindControl(LinkName) <> nil thenbegin

//Got it. Configure this controlLinkObject := HyperLink(WebPage.

FindControl(LinkName));LinkTarget := GetStringField('LinkURL',

DataReader);if LinkTarget <> '' thenbeginLinkObject.NavigateURL := BaseURL + '?' +

LinkTarget;LinkObject.Target := '_blank';LinkObject.ToolTip := 'Click for help';endelsebegin

//Oops. No Help. Make Hyperlink not visibleLinkObject.Visible := False;

end;end;

end;finally

DataReader.Close;end;

finallyReleaseConnection;

end;end;

ConclusionHelp & Manual makes it easy to create full-featured help systems andother documentation for all current types of help systems. With Helpand Manual, you can create a single source of material, and then cus-tomize the output for various formats from that same source as well asuse conditional output. In addition, Help and Manual allows you tocontrol your help documents programmatically, inserting your ownHTML code, or working with the XML source directly to extend yourhelp systems and documentation to get the exact results you need. •

Loy Anderson

Loy Anderson is Vice President ofJensen Data Systems, Inc. a Texasbased company that specializes inDelphi training, development, andconsulting, and on the AdvantageDatabase Server. Loy is a best-selling, award winning co-author oftwenty books with Cary Jensen including their latest book, Advan-

tage Database Server: A Developer’s Guide. Loy provides techni-cal writing services including Help systems. She has a Ph.D. fromRice University in Human Factors Psychology, specializing inhuman-computer interaction. You can reach Loy through her com-pany Web site at: http://www.JensenDataSystems.com or byemailing [email protected]

DELPHI

Page 63: SOFTWARE DEVELOPMENT NETWORK

GENERAL

But enough laughter. One of the characteristics of agile software development projects is the flexibility and adaptability to only do whatis necessary in the project. No matter which agile process we apply –be it Scrum, Smart, XP, FDD, or OpenUP – we try to delay the actualwork to the latest possible moment in time that we actual need to dothe work. And we delay decisions in the same manner. In both caseswe do this so we have maximum knowledge over what we should andshould not do. Thus, for example the design for a particular piece offunctionality is done just before building the software.

We know betterThese two approaches appear to be totally different or even orthogonal, and yes, they are. Still, a lot of organizations cling to the rigidness of their waterfall processes. In most cases this is becausethey think it will make their projects more predictable and repeatable.Or sometimes just because they just don’t have a clue. In most ofthese poor organizations, we agile people laugh at this rigidness, because we think we know better. But do we?

I would say there’s also a dark side to our laughter. In fact, with the increasing popularity of agile software development and a lot of newbieagilists entering our projects I predict that the freedom and flexibility wepreach will slowly shift towards more rigidity and ceremony. And I don’tmean waterfall rigidity, but agile rigidity. Again, a lot of people will thinkthat whoever invented or wrote down their software development process knew exactly what he or she was doing. A lot of people onlyhave a vague clue to why he or she wrote down the process.

No modelingThis agile rigidity anti-pattern is easily recognizable in projects – oreven better still: in blog discussions. These days there seem to bemore blog and Twitter posts on agile than there are user stories in agileprojects. Let me present you with a few examples of this new agile rigidity. In the agile process Smart (see www.smartusecase.com) it issuggested to add a number of work items right from the start of theproject to the project backlog that deal with determining project scope,modeling requirements (in smart use cases), creating a sound estimate for the project’s complexity, and maybe also deliver a projectproposal. Having a project proposal is not a bad thing if you want to(sell and) run the project. In my day to day life this short list of suggested work items works quite well, and moreover, is totally compatible with processes such as Scrum and FDD. We have beenusing this approach in agile projects for about ten years successfully.

However, much to my surprise, when I recently elaborated on this approach – in a blog post – people commented on this post and accused me of actually promoted doing waterfall disguised as agile –just because I advised a few neat deliverables other than writing codeduring the first iterations or sprints of my projects. Come again? Since when does being agile mean not capturing requirements. I’m not promoting the big upfront design here. Who says I have to deliver code anyway? I’ve used agile principles, techniques and bestpractices in numerous projects, including projects that didn’t deliverany code at all (like code audits). A backlog contains work to be done,whether that’s “check software architecture”, “investigate namespacedependencies” or “write login screen”. My burn down is still valid, andso are my estimates.

Another example? I love to have my requirements modeled out in whatwe call smart use cases – small use cases of similar complexity andgranularity that work pretty well in filling the project backlog and determine sprint backlogs (just to use the currently most popular terminology). But, standing at a coffee machine at a customer’s officea Java developer came up to me, claiming that I should write user stories on post-its instead of modeling smart use cases in a UML modeling tool. And why? “Because that’s what Scrum dictates.” Eh..“We do not do use use cases in agile projects,” said my developer,long hair, goatee and all. “And besides, we do not promote modelingtools.” Come again?

TrojanThat’s agile rigidity for you. In my honest opinion, with a huge crowdof people migrating into agile software development, agile rigidity willplay an increasing role in our life. And it will definitely contribute to failure in near future agile projects. You should note that this anti-pat-tern is not a threat coming from the ever dangerous outside world.This threat will be coming at you from within your own project. It’s Trojan rigidity. But there’s hope for you: just follow the correct procedures.

Sander Hoogendoornblog.sanderhoogendoorn.org •

Interesting things:

Trojan RigidityOne of the characteristics of most traditional – linear, waterfall – styled organizationsis the extremely rigid execution of their software development projects . “Our hand-book says we need to fill in this form, so that’s what we do, guys.” People in theseprojects live by the blind assumption that whoever invented or wrote down their soft-ware development process knew what he or she was doing. So we’ll just fill in theform, even though we’re not quite sure what it is for. And even better, all projects greatand small live under the same regime. This is where six weeks, three developer projects get stuck with a steering committee, an architecture board and a quality assurance work group. We need predictability in our projects more than anything else!

magazine voor software development 63

Page 64: SOFTWARE DEVELOPMENT NETWORK

DOTNETNUKE

Using jQuery UI inDotNetNuke ModulesWeb applications have made many advances over the years, especially in the area of user interface design. Interactive interfaces, complex windows style GUI, seamless flow and a great user experience are some of the requirements that developers are faced with. As developers we look to frameworks and libraries for easier, fasterdevelopment. In this article we’ll focus on adding jQuery UI, a library of rich client side components, to a DotNet-Nuke Module.

Sarah Darkis

What is DotNetNuke?DotNetNuke is an open source web application framework and a con-tent management system (CMS). DotNetNuke is the most successfulopen source project on the Microsoft .Net Platform. Developers caneasily extend the framework by building custom modules. Skins canbe applied to a DotNetNuke site to customize the graphic appearance. It’s impossible to cover all the features and extensibility ofDotNetNuke in this paragraph. If you are not familar with DotNetNuke,visit www.dotnetnuke.com.

jQuery is tested against all majorbrowsers and is CSS compliantWhat is jQuery?jQuery is an open source, fast, easy to use, JavaScript library. jQueryis a must have library for client side developers. What were once cumbersome JavaScript tasks that took many lines of code, can nowbe done quickly, efficiently, with very little code. It handles DOM manipulation, CSS, AJAX, events and animation. jQuery is testedagainst all major browsers and is CSS compliant. jQuery is easy to learn, with detailed documentation on jquery.com,cheat sheets and code samples readily available on the internet. ForVisual Studio developers, Microsoft has announced inclusion of jQueryin the next version of Visual Studio. You can download the intellisensefile (vsdoc.js) from jQuery.com and begin using jQuery with intellisensein your Visual Studio 2008 projects.

What is jQuery UI?jQuery UI is an open source library of client side components based onjQuery. jQuery UI provides components like accordion, tabs, drag &drop and many others. With jQuery UI you now have reusable components that give you consistency across your site. One of the most exciting tools jQuery UI offers is an online GUI calledTheme Builder. With the Theme Builder, you can select from an existing collection of pre-defined themes or create your own theme.The Theme Builder will generate the css styles and icons for you. UsingjQuery UI components and Theme Builder, you can quickly customizeyour module to match your DotNetNuke Skin.

Building the ModuleWe will assume that you already know how to build a DotNetNukeModule. If you are not familiar with module development, the moduledeveloper guide is included in the documentation download for the

version of DotNetNuke you are running. For this example, visit theDownloads page on www.DotNetNuke.com and download ‘DotNet-Nuke 4.9.2 Docs’.

This example is built using DotNetNuke Community Edition 4.9.2,jQuery 1.3.2 and jQuery UI 1.7.1. The module contains one ascx file,Demo.ascx and a folder named jQuery UI to hold the jQuery UI files.Create a jQuery UI Theme. We’ll use the jQuery UI Theme Roller tochoose a theme and to download the accordion component.• Go to http://www.jqueryui.com/themeroller/• Choose the Gallery option, for a list of predefined themes.• Choose the Redmond theme (a good match for the default

DotNetNuke skin)

Fig. 1: jQuery UI ThemeRoller - Gallery

The next page will allow you to select the components you wish todownload. The default option is ‘select all components’. Although inthis article we only need the Accordion, we will download all components so they are available for later use. After the download iscomplete, unzip the package. The contents will look like:

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK BEELDMERK

FULL-COLOUR

SOFTWARE DEVELOPMENT NETWORK DIVISIES

CONFERENCE

MAGAZINE

EVENTS

.NET

.NL

DELPHI

5 0 c y a a n1 0 0 g e e l

5 0 z w a r t1 5 c y a a n

SOFTWARE DEVELOPMENT NETWORK SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

64

Page 65: SOFTWARE DEVELOPMENT NETWORK

Fig. 2: Contents of jQuery Download

Adding jQuery UI to the ModuleWe only need to include the css and js folders in our module. The development-bundle folder contains demos. In our module we haveadded a jqueryui folder to hold our jquery files.Now copy the css and js folders from the jQuery UI download to thejqueryui folder in the module.

Fig. 3: jQuery UIDemo Project

In the code behind, register the css and script files and add thejQuery.noConflict(). jQuery.noConflict() is added immediately after including jquery-1.3.2-min.js. It is used to avoid conflicting with otherlibraries that use the $ variable. It will assign jQuery to the “jQuery” variable, but will not assign jQuery to the $ variable.

{

string basePath =

"~/DesktopModules/jQuery UIDemo/jQuery UI/";

string cssPath =

"css/redmond/jquery-ui-1.7.1.custom.css";

string jQueryPath = "js/jquery-1.3.2.min.js";

string jQuery UIPath =

"js/jquery-ui-1.7.1.custom.min.js";

// Add CSS Link

string jQueryCss = string.Format(

"<link type=\"text/css\" href=\"{0}\"

rel=\"Stylesheet\" />"

, ResolveUrl(basePath + cssPath)

);

Page.Header.Controls.Add(

new LiteralControl(jQueryCss)

);

// Register jQuery Script

Page.ClientScript.RegisterClientScriptInclude(

jQueryPath

, ResolveUrl(basePath + jQueryPath)

);

// Add jQuery.noConflict()

// jQuery will not be assigned to the $ variable

Page.ClientScript.RegisterClientScriptBlock(

this.GetType()

, "jQuery.noConflict"

, "jQuery.noConflict();"

, true

);

// Register jQuery UI Script

Page.ClientScript.RegisterClientScriptInclude(

jQuery UIPath

, ResolveUrl(basePath + jQuery UIPath)

);

}

There is some specific HTML required for the jQuery accordion widgetto work correctly. The title must be a <h3> tag followed by the contentplaced in a <div> tag. Add the following HTML to the Demo.ascxpage:

<div id="Accordion" runat="server">

<h3><a href="#">Section 1</a></h3>

<div>

...

</div>

<h3><a href="#">Section 2</a></h3>

<div>

...

</div>

<h3><a href="#">Section 3</a></h3>

<div>

...

</div>

</div>

Next add the JavaScript to create the accordion.

<script type="text/javascript">

jQuery(document).ready(function($) {

$("#<%=Accordion.ClientID%>").accordion();

});

</script>

The resulting page is

Fig. 4: DotNetNuke Page with jQuery UI’s Accordion Widget

magazine voor software development 65

DOTNETNUKE

Page 66: SOFTWARE DEVELOPMENT NETWORK

jQuery Integration in DotNetNuke 5In this module, we’ve registered the client script jquery1.3.2.min.js inour ascx control. JQuery is included in DotNetNuke 5 by default. Thereare two options for loading the jquery script file: from the Resourcesdirectory of the DotNetNuke website or from a url where the script ishosted remotely. Let’s look at including jQuery 1.3.2 from Google’sAJAX APIs.

DotNetNuke includes configuration options for jQuery in Host Settings> Advanced Settings > JQuery Settings.• Check the ‘Use Hosted jQuery Version?’ option• Update the ‘Hosted jQuery URL’

http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js

In our module, we can now remove the code required to register thejquery script file and ask DotNetNuke to register the jQuery script. OurPage_Init now looks like this:

protected void Page_Init(object sender, EventArgs e)

{

// Register the jQuery Script

DotNetNuke.Framework.jQuery.RequestRegistration();

string basePath =

"~/DesktopModules/jQuery UIDemo/jQuery UI/";

string cssPath =

"css/redmond/jquery-ui-1.7.1.custom.css";

string jQuery UIPath =

"js/jquery-ui-1.7.1.custom.min.js";

// Add CSS Link

string jQueryCss = string.Format(

"<link type=\"text/css\" href=\"{0}\"

rel=\"Stylesheet\" />"

, ResolveUrl(basePath + cssPath)

);

Page.Header.Controls.Add(

new LiteralControl(jQueryCss)

);

// Register jQuery UI Script

Page.ClientScript.RegisterClientScriptInclude(

jQuery UIPath

, ResolveUrl(basePath + jQuery UIPath)

);

}

ConclusionA little plumbing code, 2 lines of JavaScript and we have convertedsimple HTML into a fully functional accordion that is themed to matchour DotNetNuke skin. DotNetNuke Modules & jQuery UI combinedoffer an excellent combination of framework and library to make yourweb application development, quicker, easier and more cost effective.

Resources• www.dotnetnuke.com - Official DotNetNuke site• www.jquery.com - Official jQuery Site• www.jqueryui.com - Official jQuery UI SiteAt the time of writing, the jQuery UI is in the early stages of develop-ment. Check out their planning wiki for a list of future planned UI com-ponents: http://jqueryui.pbwiki.com/• Instructions on how to add jQuery Intellisense in Visual Studio 2008http://weblogs.asp.net/scottgu/archive/2008/11/21/jquery-intelli-sense-in-vs-2008.aspx •

66SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK BEELDMERK

FULL-COLOUR

SOFTWARE DEVELOPMENT NETWORK DIVISIES

CONFERENCE

MAGAZINE

EVENTS

.NET

.NL

DELPHI

5 0 c y a a n1 0 0 g e e l

5 0 z w a r t1 5 c y a a n

SOFTWARE DEVELOPMENT NETWORK SOFTWARE DEVELOPMENT NETWORK

SOFTWARE DEVELOPMENT NETWORK

Sarah Darkis

Sarah Darkis has been a professio-nal software developer for 10 years.Included in her background is 7years experience in C# / ASP.NetWeb Application Development and4 years of custom module develop-ment using DotNetNuke. She hasrecently taken a position as Senior Developer for DotNetNuke Corporation.

Delphi TIP:Aantal UTF-16 printbare tekensAls je een UTF-16 string S hebt, weet je wel dat die uit Length(S)WideChars bestaat, maar omdat sommige van deze WideCharzgn. surrogate pairs kunnen zijn (twee WideChars die samenéén printbaar teken opleveren) weet je niet altijd van te vorenexact hoeveel printbare tekens er in de UTF-16 string zitten.Om het aantal printbare tekens te vinden moeten we door dehele string lopen en het aantal surrogate pairs bijhouden (tweesurrogate pairs zijn één teken), als volgt:

function UTF16Length(const S: String): Integer;

var

i: Integer;

begin

Result := 0;

for i:=1 to Length(S) do

if not IsSurrogate(S[i]) then Result := Result + 1

else // Surrogate

if (i > 1) and IsSurrogatePair(S[i-1],S[i]) then

Result := Result + 1

end;

DOTNETNUKE

Page 67: SOFTWARE DEVELOPMENT NETWORK

Advertentie Sogeti

Page 68: SOFTWARE DEVELOPMENT NETWORK

Advertentie Bridge Incubation group