Top Banner
Nummer 108 februari 2011 SDN Magazine verschijnt elk kwartaal en is een uitgave van Software Development Network www.sdn.nl IN DIT NUMMER O.A.: Introduction to Razor Syntax < Duet Enterprise < Building a Custom Health Rule < Best practices bij het vervangen van een SCOM Gateway Server < SOFTWARE DEVELOPMENT NETWORK MAGAZINE 108
52

SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

Jun 04, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

Nummer 108 februari 2011 SDN Magazine verschijnt elk kwartaal en is een uitgave van Software Development Network

www.sdn.nl

IN DIT NUMMER O.A.:

Introduction to Razor Syntax <

Duet Enterprise <

Building a Custom Health Rule <

Best practices bij het vervangen van een SCOM Gateway Server <

SOFTWARE DEVELOPMENT NETWORK

MAGAZINE

108

Page 2: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

Afgelopen zomer was Achmea’s Alex Thissen een week lang te gast bij het Windows Communication Foundation team op Microsofts hoofdkantoor in het Amerikaanse Redmond. “Er zijn op de hele wereld maar zes bedrijven die daarvoor werden uitgenodigd, dus ik beschouw het wel als een eer dat Achmea deel uitmaakt van dit selecte groepje. Microsoft luistert echt naar Achmea, ze beschouwen ons als een bedrijf dat voorop wil lopen. We spraken bijvoorbeeld over Microsofts onder-steuning van IBM Websphere MQ, waarvoor wij andere communicatie-patronen mogelijk wilden maken. Maar ook de koppeling tussen Sharepoint en SAP was onderwerp van gesprek.”Microsoft-topman Scott Guthrie, alias ‘Scott Gu’, was onlangs te gast op de Achmea-burelen. Thissen: “Ja, dat zijn inspirerende sessies. In mijn vakgebied heeft hij de status van een popster, dus je begrijpt dat het geweldig sparren is met zo’n man.”

Mep je fitBij de ontwikkeling van Visual Studio Team System (bestaande uit ontwikkelomgeving Visual Studio

2010 en de ‘Application Lifecycle Management omgeving’ Team Foundation Server 2010) was Achmea in een vroeg stadium betrokken, vertelt Thissen. “We hebben ideeën en suggesties aan-geleverd en Microsoft gewezen op bugs en verbeterpunten, zoals bijvoorbeeld bij het berekenen van de burnrate van code. Dat is nuttig voor ons én nuttig voor Microsoft.”Voor Achmea is Visual Studio Team System belangrijk bij het ontwik kelingen van software aan de voorkant, zoals webappli-caties en mobiele applicaties, en voor integratie-oplossingen met behulp van webservices. “Voor Achmea wordt het internet steeds belangrijker, niet alleen om schades te melden of verzekeringen af te sluiten, maar ook voor allerlei zaken op het gebied van preventie. Zo hebben we in opdracht van Zilveren Kruis Achmea de game ‘Mep je fit’ ontwikkeld voor Micro-softs ‘computertafel’ Surface. Ook tijdens de Olympische Winter-spelen hadden we in het Holland Heineken House een gezondheids-installatie staan; bezoekers konden

daarop onder andere hun bloeddruk en body mass index meten en sportieve prestaties vergelijken met die van topsporters.”

AgileDaarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server houdt alle stappen in het ontwikkelproces bij, vast-gelegd in hiërarchische workitems. Zo bieden wij onze klanten – de mensen in de business van Achmea – optimaal inzicht in het proces.”Last but not least is Thissen tevreden met MSF Agile, het processjabloon dat Visual Studio Team System voert. “Dat betekent dat we snel en flexibel kunnen bouwen, in korte iteraties met de klant. Dat is precies wat we nodig hebben, want Achmea wil razendsnel kunnen inspelen op nieuwe ontwikkelingen die zich voordoen in de markt.”

Alex Thissen: “Microsoft luistert echt naar Achmea.”

Foto

: Han

s B

arte

n

Page 3: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

magazine voor software development 3

ColofonUitgave:Software Development NetworkNegentiende jaargangNo. 108 • februari 2011

Bestuur van SDN:Remi Caron, voorzitterRob Suurland, penningmeesterMarcel Meijer, secretaris

Redactie:Remi Caron en Marcel Meijer([email protected])

Aan dit magazine werd meegewerkt door:Aan dit magazine werd meegewerkt door:Roel Hans Bethlehem, Christiaan Heidema,Bob Swart, Stefan Kamphuis, Peter Donker,Maarten van Stam, Alexander Meijers, RemiCaron, Marcel Meijer en natuurlijk alle auteurs!

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

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

©2011 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.

AdverteerdersAchmea 24DotNet 6Sogeti 8Bergler 18Triple A 23Uniface 29Barnsten/Embarcadero 34Microsoft 51Macaw 52

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

voorwoordBeste SDN magazine lezer,

Het jaar is al weer een tijdje bezig. Inmiddels hebben we het eerst event EngineerWorld

(georganiseerd samen met Sogeti) alweer achter de rug. Het volgende reguliere SDN event

staat gepland vrijdag 18 maart. Dit event staat weer bol van de content. Sessies over

AppFabric, ALM voor Azure projecten, SharePoint Document management, Blend for

Developers, Claimbased security, Delphi XE, Intraweb, Razor, DNN RadEditor en DNN in

combinatie met Entity Framework. Traditioneel zal er tijdens dit event ook de Algemene Leden

vergadering. Dit is nog maar een kleine greep. Kijk op de website voor meer informatie.

Let op, ons tijdschema is veranderd. We beginnen om 9:30 en eindigen rond half vijf.

Met het nieuwe jaar zijn er ook een aantal wijzigingen in de organisatie. Sandra de Ridder van

de UX track heeft ons verlaten. Ze kon de werkzaamheden voor de SDN niet meer goed

combineren met haar werk en prive leven. Marcel van Kalken van de Delphi track heeft ook

zijn taken neergelegd. Beide danken wij hartelijk voor hun inzet de afgelopen jaren en

wensen ze succes voor de toekomst. De organisatie is daarentegen ook uitgebreid met

Alexander Meijers voor de Information Worker track en Roel Hans Bethlehem voor de

Architecture track. Alexander en Roel Hans welkom bij de club, we gaan er een mooie tijd van

maken. Ook hebben we dit jaar twee nieuwe corporate sponsoren IBM en Compuware. Daar

zullen we de komende tijd veel meer over horen en van zien.

Dit magazine staat bol van de artikelen. Van het Nieuwe werken tot SCOM en twee artikelen

over Razor. Kortom wederom een magazine waar je je kennis mee kan verbreden. De

volgende magazines gaan we meer richten op 4 standaard categorieen (Cloud, Mobile, Client

apps en Web apps), natuurlijk blijven Delphi en DotNetNuke het hele palet compleet maken.

We zijn altijd op zoek naar leuke artikelen van een tot twee pagina’s. Mocht je interesse

hebben, meldt je dan bij [email protected]. Wij kunnen je ook helpen met schrijven.

Veel leesplezier!

Groeten

Marcel Meijer

Page 4: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

Inhoud03 VoorwoordMarcel Meijer

04 Inhoudsopgave

04 Agenda

05 Leer Het Nieuwe Werken van een ZZP’er!Anky Persoons

07 Azure VM RoleMarcel Meijer

09 Introduction to Razor SyntaxAndrew Nurse

12 Introduction to the Delphi Open Tools APICary Jensen

16 Wat is er zo moeilijk aan een mobiele applicatie?

Jaap van Ekris

19 Drag and Drop deel 2: Bestanden slepen naar de Windows Explorer

Eric Roosendaal

20 Mixing Scrum and SmartSander Hoogendoorn

24 Introduction to the code coverage tooling in Rational Application Developer

Paul Klicnik

30 Duet EnterpriseChristian Siegers en Mark IJsselstein

32 Historie en toekomst van Database Change Management

Ben Suurmeijer

36 Webservices en transactiesMichiel van Otegem

38 Building a custom Health RuleAnita Boerboom

42 “Nieuw” in Nederland: NLDeveloperRobert Blom

43 Best practices bij het vervangen van een SCOM Gateway Server

Mark Wolzak

46 De uiterste houdbaarheidsdatum van requirements

Sander Hoogendoorn

47 DotNetNuke supports Razor Charles Nurse

50 Reflection loops of Agile Joachim Nilsson

Tech-Ed Middle East 2011 . . . . . .8 maart

Tweede WAZUG meeting . . . . . .17 maart

SDN Event maart + ALV . . . . . . .18 maart

CodeCamp / . . . . . . . . . . . . . . . . . . . . . .

SharePoint Saturday . . . . . . . . .26 maart

DevDays 2011 . . . . . . . . . . . . . . .28 april

SDN Magazine 109 . . . . . . . . . . . .20 mei

SDN Event juni 2011 . . . . . . . . . . .17 juni

SharePoint Conference 2011 . .3 oktober

SDN Event December 2011 .9 december

Agenda 2011

Page 5: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

IW Anky Persoons

Méér dan leuke ICT-tooltjesEr is veel te doen over Het Nieuwe Werken (HNW). Eind 2010 was erzelfs “De Week van Het Nieuwe Werken” en in 2011 zullen we er alleen maar meer over horen. Iedereen heeft het erover, wil het graag(of juist niet), moet het van zijn baas, vindt er iets van, of vindt het niks.In de pers worden steeds weer dezelfde praktijkvoorbeelden aan -gehaald: Microsoft, Interpolis.

Is HNW een hype of het begin van een tijdperk waarin mensen andersomgaan met hun werk, hun tijd, het samenwerken met anderen enhun werk-privébalans? Worden we beter presterende, meer tevredenwerkers of is het vooral een marketingterm waarmee ICT-bedrijvenhun oplossingen verkopen, HRM-adviseurs hun uren en interieur -architecten hun adviezen?

Verantwoordelijkheid nemenVeel mensen denken dat Het Nieuwe Werken betekent dat je hetzelfdewerk blijft doen, maar dat je zelf bepaalt wanneer en waar je dat doet.In de praktijk is het echter niet zo eenvoudig. Het is meer dan thuis-werken, communiceren met nieuwe slimme ICT-middelen, geen vastewerkplek meer hebben op kantoor en zelf je tijd kunnen indelen. Datzijn eigenlijk maar bijkomende verschijnselen, die echter vaak de aan-dacht trekken en het zicht vertroebelen op waar HNW echt over gaat.

In de kern gaat HNW over zelf verantwoordelijk zijn voor je werk. Datwerk bestaat uit opdrachten met een duidelijk omschreven eindresul-taat, een deadline en tussentijdse evaluaties. Een medewerker heeftgeen inspanningsverplichting meer, maar een resultaatverplichting. Ditheeft nogal wat gevolgen voor de werknemer en voor de manierwaarop hij samenwerkt met managers, collega’s en ondergeschikten.En voor de balans tussen werk en privé. Want die zakelijke telefoon-tjes komen ook gewoon binnen als je net je kind uit school hebt gehaald. Werknemers hebben dus nieuwe vaardigheden nodig: zelfsturing, ondernemendheid, planning, grenzen bewaken.

Het nieuwe managenOok de rol van de manager verandert. Als niemand nog een 40-urigewerkweek heeft, hoe stuur je dan je team aan? Je moet leren om tebeoordelen op resultaat, niet meer op aanwezigheid. Vertrouwen

neemt de plaats in van controle. Je zult meer aandacht moeten besteden aan de synergie in het team en aan de onderlinge communicatie en uitwisseling van informatie.

Kortom, HNW vraagt om een cultuuromslag. Een omslag van eenrichtingsverkeer naar een dialoog, van delegeren naar coachen,en van werk of privé naar werk én privé. Dan krijgen medewerkers deruimte om mee te denken, beslissingen te nemen en productieverte zijn.

ZZP’ers werken al heel lang “Nieuw”Terwijl bedrijven en hun medewerkers hun best doen om HNW onderde knie te krijgen, vergeten we met zijn allen dat er een grote groepwerkers is die al veel langer met dit bijltje hakt. HNW is eigenlijk nietsnieuws onder de zon. Dat is het wel voor mensen die in loondienstwerken en gewend zijn om 9 uur te starten en om 5 uur weer uit teklokken, om vervolgens op dezelfde snelweg weer in dezelfde file tegaan staan, net als hun collega’s. Maar niet voor de Vrije Werkers,Zelfstandige Professionals of - zoals ze meestal genoemd worden -ZZP’ers. Voor velen van hen was de wens om op deze manier te kunnen werken zelfs een belangrijke reden om uit loondienst te gaanen “voor eigen rekening en risico” aan de slag te gaan. Misschien hebben de ZZP’ers HNW wel uitgevonden.

Ga maar na: veel zelfstandige professionals wisselen het werken inhun thuiskantoor af met werken bij de klant en met besprekingen opverschillende locaties met mede-ZZP’ers en andere samenwerkings-partners. Ze doen overdag een boodschap, gaan sporten of halen dekinderen uit school, en werken dan ’s avonds of in het weekend nogeen paar uur. In drukke tijden maken ze wat meer uren, in rustige tijden kan het even een tandje lager. Er is vaak één PC voor zakelijkeen privéaangelegenheden. Ze doen hun eigen acquisitie en voerenvoor hun klanten vaak projectmatige werkzaamheden uit, waarbij eenvooraf afgesproken resultaat op een bepaalde datum moet wordenopgeleverd. Deze professionals hebben de strijd om de werk-privé balans al gestreden. En vaak niet zonder moeite: zeker ondernemerszijn (in het begin) geneigd meer te werken dan goed is voor henzelf ende privésituatie. En ze vormen dus uitstekende rolmodellen en vraag-baken voor medewerkers die HNW onder de knie moeten krijgen.

magazine voor software development 5

Leer Het Nieuwe Werkenvan een ZZP’er!Steeds meer bedrijven stappen over op Het Nieuwe Werken. Vaak richten ze zich bij de invoering ervan sterk op de praktische aspecten (ICT, HR, facilitair). Wat ze vaak uit het oogverliezen is de cultuuromslag die nodig is om deze verandering succesvol te laten verlopen. Op dat vlak kunnen ze veel leren van ZZP’ers, die bij het werken als ondernemer hebben moeten leren omgaan met vrijheid, verantwoordelijkheid en het zoeken naar balans.

In de kern gaat HNW over zelf verantwoordelijk zijn voor je werk

Misschien hebben de ZZP’ers HNW wel uitgevonden

Page 6: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

IW

MAGAZINE

6

De ZZP’er als voorbeeld van ondernemerschapToch hebben managers in HNW-bedrijven juist vaak moeite om de ingehuurde ZZP’ers het vertrouwen te geven dat bij HNW hoort. Ze hebben ze het liefst zichtbaar om zich heen, en niet thuiswerkend.Ze zijn immers per uur ingehuurd en dan wil je ook zien dat die urenallemaal gemaakt worden.

Wat een gemiste kans! Want is HNW eigenlijk niet gewoon: onderne-merschap onder de vleugels van de werkgever? Het is werken metmeer vrijheid en verantwoordelijkheid, zonder de risico's van het echteondernemen te dragen. Wie kan er dan beter kennis en ervaring hier-over delen dan een ZZP-‘er?

Een ZZP’er die ervaring heeft opgedaan met HNW bij opdrachtgeversis Gary Wenneker. Hij werkt als zelfstandig SharePoint specialist enkomt al jarenlang “bij de klanten thuis”. Hij vertelt: “Sinds een paar jaarzie ik in steeds meer bedrijven Het Nieuwe Werken opkomen. Demeeste medewerkers vinden die nieuwe vrijheid prettig, maar hetmaakt mensen ook onzeker. Hoe bereikbaar moet je zijn? Moet je nietvaker je gezicht laten zien op kantoor? Wanneer kun je je collega’swel, of juist niet, bellen?”

Daarnaast ervaart Gary ook dat managers worstelen met HNW. “Zekerals het gaat over tijdelijk ingehuurde krachten. Die moeten toch eigenlijk wel gewoon op kantoor werken. Dat betekent dan voor diemanager dat hij zelf ook veel op kantoor aanwezig is om de voortgangin het oog te houden. Zodat hij niet een goed voorbeeld is voor zijn

medewerkers, die dan ook niet goed de stap durven maken naar locatie-onafhankelijk werken.”

Terwijl het voor Gary heel gewoon is om resultaatgestuurd te werken.Als ZZP’er werkt hij immers zowel op uurbasis als op projectbasis. “Ikben gewend om zelf mijn tijd in te delen en flexibel samen te werkenmet andere teamleden, of dat nu vaste of tijdelijk ingehuurde mede-werkers zijn, of medewerkers van een externe leverancier. Als teamlidmet HNW-ervaring kan ik de andere teamleden tussen de bedrijvendoor begeleiden bij het wennen aan HNW en ze suggesties gevenover beschikbaarheid, balans, communicatie met collega’s en omgaanmet vrijheid en verantwoordelijkheid.”

Veel ZZP’ers delen Gary’s ervaringen. Wanneer zij de ruimte krijgenzodat ook zij optimaal kunnen functioneren kunnen zij op een natuur-lijke manier in de dagelijkse werksituatie optreden als “rolmodel” ende andere teamleden laten zien hoeveel winst Het Nieuwe Werken kanopleveren. Voor het bedrijf, maar zeker ook voor de medewerkers.•

Als ZZP’er kan ik medewerkers coachen in het wennen aan HNW

Ankie Persoons

Ankie Persoons is directeur van ICT-

Professionals, een maatschap van

zelfstandige ICT-ers die de afstand

tussen werken in loondienst en zelf-

standig werken verkleint. Ze heeft

brede communicatie-ervaring in de

ICT-branche en is Social Media-

consultant en trainer.

TEST CENTER

4DotNet bv Paradijsweg 2 7942 HB Meppel t. 0522-24 14 48 [email protected] www.4dotnet.nl

The one-stop company for .NET development

TEST CENTER

The one-stop company for .NET development

Een keer rijden in een Ferrari of zweefvliegen.

Wie droomt daar nou niet van? Boekt u voor 31 maart een training bij 4DotNet dan krijgt u van ons een unieke belevenis cadeau!

4DotNet bv Paradijsweg 2 7942 HB Meppel t. 0522-24 14 48 [email protected] www.4dotnet.nlTEST CENTER

ons een unieke belevenis cadeau!

Kijk voor alle belevenissen op www.4dotnet.nlMaak uw dromen waar!Maak uw dromen waar!Boek dit voorjaar een training bij 4DotNet en krijg een unieke belevenis van ons cadeau!

Lees alles over deze droomactie op www.4dotnet.nl

Heeft u altijd al willen rijden in een Ferrari of een keer zweefvliegen?

actie is geldig t/m 30 juni 2011

Page 7: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

CLOUD Marcel Meijer

Veel standaard ASP.NET webapplicaties kunnen in principe redelijkeenvoudig naar de Azure Cloud gebracht worden. Uiteindelijk is deAzure Cloud een Microsoft .NET platform met nagenoeg dezelfde om-gelijkheden1. Maar als je applicatie heb die niet is op het Microsoft.NET platform, dan is de Azure VM Role een goede mogelijkheid. Jelegacy applicatie moet dan wel te gebruiken zijn op Windows 2008server. Op dit moment het enige mogelijke Operating system voor deVM Role.

Een VM voor de VM Role moet natuurlijk op een bepaalde manier op-gebouwd zijn. Op deze site wordt dat keurig stap-voor-stap uitgelegd.http://msdn.microsoft.com/en-us/library/gg433125.aspx. Een derge-lijke VM kan gemaakt worden op een Windows 2008 R2 server metHyper-V. Tijdens de installatie van deze VM kun je dan je “legacy” applicatie installeren.In een van de stappen moet je Windows AzureVM Role Integration Components installeren. Deze software installeertook iets om te connecten met de storage.Nadat je de VM dan gesysprepd hebt, dan kun je deze uploaden naarAzure. Ook deze stappen staan op bovenstaande site uitgelegd. Inhet kort komt het erop neer, dat je een Windows Azure SDK com-mand prompt in Administrator mode starten. Dan moet je met hetCSUPLOAD tool de connectionstring vast leggen, dat zie je in het eer-ste deel. Daarna begint de daadwerkelijke upload.

Zoals uit het figuur blijkt, begon het tool CSUPLOAD gewoon met hetvoorbereiden van de upload. Maar toen het feitelijk uploaden moestbeginnen, kwam onderstaande foutmelding. In de cirkel zie je dat ik in-derdaad “Anywhere Europe” gekozen had, dat is per definitie geensingle location .

Gelukkig is het tool wel handig opgezet. Het hele preparing gedeeltehoeft niet nog een keer te gebeuren, hij begint nu met het feitelijk uplo-aden. Dit duurt wel een tijdje.

Bij het preparen worden er twee tijdelijke bestanden aangemaakt. Eentje met de extensie .PREPED en eentje met de extensie .DIGEST.Tijdens deze upload actie zie je dan op het Windows Azure portaal destatus PENDING. Als de upload klaar is, dan zie je op de commandline en op het Windows Azure portaal het volgende.

Als je de VM dan geupload hebt, dan is er geen mogelijkheid om deVM te starten. In Visual Studio moet je een Virtual Machine role toe-voegen aan je project. Daarbij kies je dan de geuploade VHD. Dit kanpas als de upload daadwerkelijk klaar is

Dit moment moet de VM en de applicatie nog in hetzelfde zone staan.Dit zal wel te maken hebben met de beta fase waarin de VM role ver-keerd. Je krijgt een foutmelding tijdens het deployen als dit niet klopt.•

Azure VM Role

Marcel Meijer

Marcel Meijer werkt als SoftwareDeveloper / Solution Architect bijVX Company. Hij is .NET trackowner en bestuurslid bij de SDNen MVP.

1 Uiteraard is dit niet altijd zomaar waar en zitten hier soms nog een paarhaken en ogen aan.

magazine voor software development 7

Page 8: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

Microsoft-specialistenStel, je hebt een passie voor Microsoft. Je bent een

kei in applicatieontwikkeling en -architectuur. En je

wilt verder in je vakgebied. Dan is Sogeti het bedrijf

voor jou. Met 700 Microsoft-professionals behoren

we tot de grootste Microsoft-communities van

Nederland. Bovendien verwachten onze klanten

innovatie, zodat je echt al je kennis inzet. Wat ons

betreft wordt die kennis steeds breder en dieper;

we dagen je uit om het maximale uit jezelf te halen.

Bijvoorbeeld door je cursussen en opleidingen

aan te bieden. We zijn niet voor niets een van de

meest gecerti� ceerde organisaties in de branche.

Qua omgeving kun je denken aan ALM, VSTS 2010,

.NET4.0, O� ce 2010, SharePoint 2010, Azure en

BPOS. Terwijl de projecten enorm gevarieerd zijn.

Van BizTalk-implementaties en end-user BI-oplos-

singen tot de omvangrijkste integratie ooit van

SharePoint in Dynamics CRM.

JAVA-specialistenAls je passie hebt voor het Java vakgebied, dan

wil je natuurlijk ook werken bij het bedrijf met de

beste Java Community van Nederland. Bij Sogeti

ben je dan aan het juiste adres. Ruim 100 ervaren

Javanen werken bij Sogeti aan het realiseren van

complexe en innovatieve oplossingen voor haar

klanten. Aangezien vakmanschap bij Sogeti hoog

in het vaandel staat, wordt er veel tijd geïnvesteerd

in het vergroten van kennis en de persoonlijke

ontwikkeling van de Java professionals. Het behalen

van Java certi�ceringen is daar onlosmakelijk mee

verbonden. Sogeti heeft dan ook niet voor niets de

best gecerti�ceerde Java Community van Nederland.

Wil jij met jouw kennis en ervaring onze Microsoft

Community of Java Community versterken?

Neem dan gerust contact met ons op of kijk op

werkenbijsogeti.nl.

Wat kun je? Die vraag stelt ieder bedrijf met een vacature. Wie ben je? Die vraag stelt Sogeti

meteen daarna. We vinden het belangrijk dat je bij ons past. Want een ICT-er van Sogeti is

geen gemiddelde ICT-er. Het is er een met uitgesproken eigenschappen.

Gedreven. Resultaatgericht. En niet snel tevreden. Natuurlijk: plezier hoort erbij. Maar we

gaan op de eerste plaats voor de inhoud. Zo kennen klanten ons. Zo kennen we elkaar.

Als het een ICT-er is, zit hij bij Sogeti.

Page 9: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

Andrew Nurse

What is Razor?When we started designing Razor, we took a simple snippet ofpseudo-code as an example:

<ul>

foreach(var product in Products) {

<li><a href=”/Products/product.Id”>product.Name</a></li>

}

</ul>

Listing 1: What the developer means

This is what the developer means; what they want their code to do.However, in most web languages, like the traditional ASP.Net syntax,you have to write something like this:

<ul>

<% foreach(var product in Products) { %>

<li><a

href=”/Products/<%=product.Id%>”><%=product.Name%></a></li>

<% } %>

</ul>

Listing 2: What the developer has to write, in WebForms syntax.

So, we stripped all the extra control characters out and started again,back to the first example. We wanted to find a way to blend server-sidecode and client-side markup with as few characters as possible. Theanswer was a single character.

What makes Razor so different from other languages is that it only hasone major control character, the at-sign (@). Going back to the earlierexample, writing it in Razor would require only 3 control characters instead of 18 control characters:

<ul>

@foreach(var product in Products) {

<li><a

href=”/Products/@product.Id”>@product.Name</a></li>

}

</ul>

Listing 3: The @ at work.

However, Razor does more than just cut down on extra characters.The magic of Razor lies in how it unifies two languages, the server-side code and the client-side markup. Razor has a fairly deep under-standing of C#, VB and HTML and it uses that understanding to cutback on the extra syntax users need to write. For example, in Listing3, you’ll notice that there are @ characters indicating where we switchto code, but nothing to indicate that we’ve gone back to markup. TheRazor parser understands that immediately after the first @, there’s aforeach statement, so it assumes that when that statement is finished,you’re ready to go back to markup. Similarly, the parser is able to detect the <li> tag and treat it’s contents as markup. Razor also allowscontinued nesting of markup within code and vice-versa.

Getting Started with RazorTo get started with Razor, you can download Microsoft WebMatrixfrom http://www.microsoft.com/web/webmatrix/. Everything you needis installed as part of that package.

Razor files have one of two extensions, indicating which language theserver-side code is written in. If you are using C#, the file extension isCSHTML. If you are using VB.Net, the file extension is VBHTML. Forthe most part, the server-side languages work the same way in Razor,but there are a few cases where one language works a little differentlythan the other. I’ll highlight those cases when we get to them.

A Razor DocumentA Razor document starts with HTML. Until you need to start insertingsome server-side code, a Razor file is just like a plain HTML file. Whenyou’re ready to go in to code, you start a code block.

Code BlocksCode Blocks in Razor are started with a single @, followed immedia-tely by a C# or VB block construct (like foreach, or If). If you want codethat isn’t within the body of a block statement (for example, you wantto declare some variables or calculate some values), you can create ageneric code block using @{ in CSHTML, or @Code in VBHTML.

Introduction to Razor SyntaxSince about 1996, writing websites on the ASP.Net platform has involved working with the“angle-bracket percent” (<%) syntax (sometimes called “WebForms syntax”) I’m sure we’re allfamiliar with. From Classic ASP right up to ASP.Net 4.0, if you worked with the Microsoft WebPlatform, you probably worked with this syntax. However, with the release of the MVC frame-work in 2009 (more than 13 years after Classic ASP 1.0), the community started to explore newlanguages and new ways of writing web pages. Last year, we started investigating ways inwhich we could revamp the ASP.Net syntax, and the result of that process is Razor. In this article, I will describe the motivations behind developing Razor, and give an overview ofthe syntax.

magazine voor software development 9

.NET

The answer was a single character

Page 10: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

.NET

@{ var foo = GetFoo(); }

<p>This is just regular markup!</p>

@if(foo != null) { foo.Bar(); }

Listing 4a: C# - Code Blocks

@Code

Dim foo = GetFoo()

End Code

<p>This is just regular markup!</p>

@If foo IsNot Nothing

foo.Bar()

End If

Listing 4b: VB - Code Blocks

Notice that there are no Razor constructs necessary in order to markthe end of a code block, the code block ends when it would naturallybe expected to end.

Mixing Code and MarkupOn the web, code isn’t very useful unless it can be used to control theoutput of client-side markup. In Razor, any code block can containmarkup blocks within it. In fact, those markup blocks can then containfurther code block which can contain further markup blocks. You cannest them as deeply as you need!

In CSHTML, mixing markup in to your code is as easy as just typingsome HTML! However, there are two rules to keep in mind. First, mar-kup is only allowed at the start of a C# statement, you can’t placemarkup in the middle of a statement. Second, you must start yourmarkup with a tag and all the tags must have a matching closing tag(or be self closed, like <br/>). For those cases where you don’t wantto have an outer tag (like <p>) rendered around your text, you can usea special tag called <text>. The <text> tag is only used to define theboundaries of your markup, and it will not actually be rendered.

Once inside the tag, everything until the matching close tag is considered HTML, including additional tags. You can also use the @character to start another code block. This is why it’s so essential toclose your tags. If you don’t, the parser can’t determine where themarkup block ends, so it doesn’t know when to switch back to code.

Unfortunately, this is also one place where CSHTML and VBHTML differ. Due to the complexity of the VB language, and the XML literalsfeature, we aren’t able to be quite as smart when parsing VB. So inVBHTML, when you want to switch from Code back to markup, you must use the @ character again. You can still use the <text> tag as before and

The following example shows some valid and invalid ways of puttingmarkup inside C# and VB code:

@if(foo) {

<p>This is valid</p>

<text>This is also valid, and it won’t have any tags around

it!</text>

string p = <p>This is NOT valid!</p>;

string p = <text>Nor is this!</text>;

}

Listing 5a: C# - Mixing Markup and Code

@If Foo

@<p>This is valid</p>

<p>This is NOT valid</p>

@<text>This is also valid, and it won’t have any tags

around it!</text>

<text>This is still NOT valid!</text>

Dim p = <p>This is actually an XML Literal, and not

considered markup!</p>

Dim p = <text>Same for this!</text>

}

Listing 5b: VB - Mixing Markup and Code

Partials, Layouts and SectionsOften, when writing a web application, you will find it necessary to extract out common view logic into a component. In ASP.Net WebForms, these are called UserControls and in ASP.Net MVC andWebPages, we call them Partials. Razor supports rendering partialsusing the RenderPage method. For example, consider a partial likethe following (shown only in C#, but the VB code is similar):

The current time is @PageData[0]

Listing 6: _Time.cshtml Partial Page

Let’s note a few things about this file. First, the file-name starts with an“_”. In both ASP.Net WebPages and MVC, this indicates to the Razorengine that the file cannot be served on it’s own. With traditionalASP.Net syntax, UserControl have a different file extension (ascx) whichprevents them from being served. However, all Razor pages written inthe same language have the same extension, so we use the “_” to de-note pages which are not to be served on their own. Second, is thePageData collection. When rendering a partial page, this collection willcontain all of the extra arguments that were provided to the Render-Page method. So to use this partial, we would write code like this:

<p>@RenderPage(“_Time.cshtml”, DateTime.Now)</p>

Listing 7: Using the Time Partial

The first argument to RenderPage is the virtual path to the page wewant to render, and the remaining arguments are passed on to thatpage.

One of the most popular features of ASP.Net is master pages. Razorhas a concept similar to master pages, called layout pages. A layoutpage is a template, much like a master page, which has placeholderswhere each specific page’s content will be rendered. As with partialpages, layout pages are not directly requested, they are linked to acontent page. When the user requests the content page, the Razorengine runs the page and collects up all the content to be rendered.It then checks to see if the page defines a layout page and if so, passes the content to that page and renders it.

Here’s a simple example of a content page:

@{

Layout = “_Layout.cshtml”;

}

@section Header {

This is the header

}

@section Footer {

This is the footer

}

This is the body

Listing 8: Content Page – Content.cshtml

MAGAZINE

10

Page 11: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

.NET

Let’s review this code from the top. First, we need to attach a layoutpage to our content page. We do this by simply setting the Layoutproperty in a code block. You can use any code you want to set thisproperty, even load it from config files or a database. Next, we definea Header section. Just like master pages allow for multiple contentplaceholders, Razor content pages can define multiple sections, aswell as a special “body” section. Each named section is defined usingthe @section keyword (in both C# and VB). In C#, we use “{“ and “}”to delimit the boundaries of the section. In VB, the “End Section” key-word is used, much like existing VB constructs like “If”. Any contentwhich is not contained in a section is considered part of the “body”,which is a special unnamed section. Then, after our header section,we define some body content and then a footer section.There are also some cases where it doesn’t make sense to have abody. For example, if you have a three column layout, you may wantto have three sections “Col1”, “Col2” and “Col3” and no body. InRazor, as long as you have at least one @section block, you can omitthe body completely.

Now that we have a content page, let see what the layout page wouldlook like:

<html>

...

<body>

<div id=”header”>@RenderSection(“Header”)</div>

<div id=”body”>@RenderBody()</div>

<div id=”footer”>@RenderSection(“Footer”, required:

false)</div>

</body>

</html>

Listing 9: Layout Page - _Layout.cshtml

The layout page contains all the outer HTML markup we need to define our page, then it uses the RenderSection and RenderBody methods to render the sections defined by our content page. The RenderSection method injects the section with the specified name,and the RenderBody method injects the content which was not partof a section. Here, we’ve also specified that the footer section is notrequired. Normally, if we try to render a section the content page doesnot define, we get an run-time error, but by setting the “required” pa-rameter to false, we tell the run-time that this section is optional. Layout pages can also be nested, so our _Layout.cshtml file abovecould have specified a further layout page simply by setting the Layout property.

Other Bits of SyntaxSometimes it is necessary to define common functions that will beused throughout the page. For this purpose, Razor has a “functions”keyword which allows you to insert C# or VB function declarations.For example:

@functions {

public DateTime CurrentTime() {

return DateTime.Now;

}

}

The time is: @CurrentTime()

Listing 9a: C# - Functions Block

@Functions

Public Function CurrentTime() as DateTime

Return DateTime.Now

End Function

End Functions

The time is: @CurrentTime()

Listing 9b: VB - Functions Block

It is also often necessary to import classes and types from other namespaces into your Razor pages, and for this we provide the@using/@Imports keyword:

@using System.IO

@{

// Now I can use FileStream!

Stream s = new FileStream();

}

Listing 10a: C# - Using Statement

@Imports System.IO

@Code

‘ Now I can use FileStream!

Dim s as Stream = New FileStream()

End Code

Listing 10b: VB – Imports Statement

Finally, Razor also includes its own server-side commenting feature.This allows you to write comments in both code and markup block, aswell as comment out chunks of Razor code. This syntax is the samein both languages:

This will be rendered!

@* But this will not, because it is a comment *@

Listing 11: Razor Comments

ConclusionThis is by no means a complete review of the features of Razor, thereare a few more cool features to check out, so I recommend you checkout the http://www.microsoft.com/web/webmatrix site and click theLearn tab to learn more about Razor, ASP.Net WebPages and WebMatrix. I hope you’re as excited to use Razor as we were to writeit. We really believe this is a revolutionary new syntax and hope thatyou find it useful! •

magazine voor software development 11

Andrew Nurse

Andrew is a developer on the

ASP.Net team at Microsoft and

works on the Razor parser.

Page 12: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

DELPHI Cary Jensen

deprecated, and the OTA is now entirely based on interfaces. And,with the release of the Galileo IDE (initially available in the now defunctC#Builder), the reliance of the OTA on pure interface definitions is complete.

A Brief Overview of InterfacesBecause they are so central to Delphi's open tools API, let's take abrief look at interfaces and their implementation. To begin with, an interface is a definition of public methods and properties. Interfacesserve as a sort of template for classes, defining the methods and properties that a class which implements the interface must support.In that sence, an interface defines a contract that a class must observe, without defining how that contract must be implemented.

One of the crucial features of an interface is that it provides for polymorphism without relying on common class ancestors. In otherwords, two classes that implement the same interface are assignmentcompatible with respect to that interface, regardless of what classesthey descend from.

As far as the open tools API is concerned, these interfaces play twodistinct roles. On the one hand, these interfaces define the collectionof methods and properties that must be implemented in the classesthat you create to implement your OTA features. (Well, that's not entirely accurate. The OTA also includes several interfaces, such asIOTAProjectWizard, that define no methods or properties. These interfaces are identifiers, and are used to signal to Delphi somethingabout what roles the implementing object plays.)

The second role of these interfaces is to define the methods and properties that are available for your use in objects that the OTA sup-plies for you. Specifically, there are numerous objects that you can useto do such things as manipulate Delphi's menus, toolbars, and glyphs.Similarly, there are objects that the OTA provides so that you can in-teract with the debugger, the code editor, the Object Repository, theMessage pane, code completion, and much more.

These interfaces are actually divided into two groups, the native toolsAPI (NTA) and the open tools API (OTA). The NTA is used to access theDelphi IDE objects, such as the menus and toobars. The NTA is defined by a single interface, INTAServices.By comparison, the OTA is a collection of interfaces that represent various facilities that the OTA makes available to you.

Introduction to the DelphiOpen Tools APIIn a recent article in this magazine I wrote about how you can add custom key bindings to Delphi's editor. In response, I received a number of questions about the mechanisms that permit Delphi developers to access something as internal as the code editor. This mechanismis called the open tools API, or OTA for short. It's been around since the very earliest days ofDelphi, and it’s one of the more powerful, and least exploited areas of Delphi development.

This is the first in a two part series on Delphi's open tools API. In thisarticle I provide you with an overview of the OTA, and provide an example of a project that adds menu items to Delphi's menu. In thenext article in this series, I will discuss a more complicated OTA implementation. Specifially, I will show you how to write a wizard thatyou can install into the Object Repository.

Overview of the Delphi Open Tools APISince Delphi 1, the Delphi IDE has provided developers with accessto some of its most internal features. It is through this mechanism thattools such as CodeSite, CodeRush, and GXperts, and the like, havebeen able to extend the capabilities of Delphi beyond those implemented by the Delphi team.

In the early days of Delphi, the open tools API was based on virtual,abstract base classes that provided templates for the features exposed through the OTA. In those days, you descended a customclass from one of these abstract classes, or one of their partially concrete descendants.

It was a little clumsy in the early days. Even adding a single new com-ponent to the component palette required a complete re-compilationof the installed visual component library (VCL). Nonetheless, it was agroundbreaking capability.

There have been many changes to the Delphi language over the years,and the open tools API has evolved along with it. Two of the major en-hancements to Delphi that have had a profound influence on the opentools API was the introduction in Delphi 3 of packages and interfaces.

With design-time packages, it became possible to easily install OTAextensions without re-compiling the entire VCL. On the other hand,some of the OTA extensions didn't actually require additions to theVCL. Instead, some of them, such as Object Repository wizards, wereadded to Delphi by compiling your Wizard class in a DLL. Delphi loa-ded that DLL based on entries that you made to the Windows registry.

While packages made the installation of OTA classes easier, the introduction of interface support in the Delphi language had a muchmore profound influence on the architecture of the OTA. While interfaces were used sparingly when first introduced, they have grownexponentially more important in defining the application programminginterface of the OTA. Indeed, the abstract classes of old are long

MAGAZINE

12

Page 13: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

DELPHI

These include IOTACodeCompletionServices, IOTADebuggerServices,and IOTAKey BindingServices, to name just a few.

The objects provided you by the NTA and OTA are accessed througha single interface, IBorlandIDEServices. The object that implementsthis interface is assigned to a global variable named BorlandIDEServices that is declared in the ToolsAPI unit.

To access a service of the NTA or OTA you cast BorlandIDEServicesto the appropriate interface. Actually, a better way to put this is that youshould first ask whether or not BorlandIDEServices implements an object that implements the service you are interested in, and if so, thenperform the cast.

The Supports function, defined in the SysUtils unit, is the preferredtechnique for performing this task. For example, consider the following code

var

MessageService: IOTAMessageServices;

begin

if Supports(

BorlandIDEServices,

IOTAMessageServices,

MessageService) then

begin

//CustMessage is a class that

//implements IOTACustomMessage

MessServ.AddCustomMessage(CustMessage.Create);

end;

Actually, this little code sample is a good representation of just how youapproach the open tools API. Specifically, you use the Delphi providedobject that implements the IOTAMessageServices interface to add amessage to the Message pane (in this particular example). However,the method, AddCustomMessage, takes a single argument of the typeIOTACustomMessage. That interfaces is one that you must implementin an object that you define.

In other words, Delphi provides some of the implementations of OTA(and NTA) interfaces, while you will supply additional objects that implement OTA interfaces, when necessary.

A Simple OTA DemonstrationIn the following project I am going to show you how to add your ownmenu items to Dephi's main menu using both the OTA and NTA. Oneof these menu items is added by implementing the IOTAMenuWizardinterface, which you can use to add a single menu item to Delphi'sHelp menu.

The second technique is more general, in that you can add one ormore menu items to any of Delphi's menus. This second techniquemakes use of the NTA (and also requires greater care on your part, asyou can seriously damage the Delphi IDE if you make mistakes).

To begin with, you start with a design time package. Use the followingsteps to begin the project

1. From Delphi's main menu, select File | New| Package.2. Right click the newly created package in the Project Manager and select Options.

3. From the Description page of the Project Options dialog box, set Usage options to Designtime only.

4. Right-click the project in the Project Manager and select Add Reference. Add the designide.dcp package to the project. In Delphi XE, this project is located by default in C:\Program Files

(x86)\Embarcadero\RAD Studio\8.0\lib\win32\release (omit the(x86) if you are using a 32-bit operating system).

Fig 1: Configuring the package to be a design time package

Next, we will add a unit in which we will define a class that implementsthe IOTAMenuWizard interface. To do this, use the following steps:1. Select File | New | Unit.2. Add the following units to the interface section uses clause: ToolsAPI, SysUtils, Menus, Dialogs.

3. Add a class that descends from TNotifierObject and implements the IOTAWizard and IOTAMenuWizard interfaces. In addition, add a declaration of a no-parameter procedure named Register. The interface section of this unit should now look like the code that appears in Listing 1.

4. Next, implement the methods of the TMenuDemo class and the Register procedure as shown in Listing 2.

interface

uses ToolsAPI, SysUtils, Menus, Dialogs

type

TMenuDemo = class(

TNotifierObject, IOTAWizard, IOTAMenuWizard

)

procedure MenuClick(Sender: TObject);

constructor Create;

{ IOTAWizard }

//Basic information about the wizard

function GetIDString: string;

function GetName: string;

function GetState: TWizardState;

procedure Execute;

{ IOTAMenuWizard }

//Implement this interface to add an item

//to the Help menu

function GetMenuText: string;

end;

procedure Register;

Listing 1

implementation

procedure Register;

begin

magazine voor software development 13

Page 14: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

DELPHI

RegisterPackageWizard(TMenuDemo.Create);

end;

{ TMenuDemo }

constructor TMenuDemo.Create;

var

NTAServices: INTAServices;

MainMenu: TMainMenu;

Menu1, NewMenu: TMenuItem;

begin

if Supports(

BorlandIDEServices,

INTAServices,

NTAServices) then

begin

MainMenu := NTAServices.MainMenu;

Menu1 := MainMenu.Items.Find('Project');

if Menu1 <> nil then

begin

NewMenu := TMenuItem.Create(MainMenu);

NewMenu.Caption := 'Custom Menu Item;

NewMenu.OnClick := MenuClick;

Menu1.Add(NewMenu);

end

end;end;

procedure TMenuDemo.Execute;

begin

ShowMessage('Your OTA object is executing');

end;

function TMenuDemo.GetIDString: string;

begin

Result := 'JDSI.MenuDemo';

end;

function TMenuDemo.GetMenuText: string;

begin

Result := 'Select Me';

end;

function TMenuDemo.GetName: string;

begin

Result := 'Simple Menu Demo';

end;

function TMenuDemo.GetState: TWizardState;

begin

Result := [ToolsAPI.wsEnabled];

end;

procedure TMenuDemo.MenuClick(Sender: TObject);

begin

ShowMessage('This is where your new menu ' +

'item will do something cool');

end;

Listing 2

The final step is to save your project and then install it. After saving yourproject, right-click the project in the Project Manager and select Install.

Once it has been installed, you will find two new menu items added toDelphi's menu. On the Help menu you will find the Select Me menu

item created by the implementation of IOTAMenuWizard. Similarly, youwill find the Custom Menu Item menu item at the bottom of Delphi'sProject menu, as shown in Figure 2.

Fig. 2: A custom menu item appears in Delphi's Project menu

ConclusionThis article has given you a basic introduction to using Delphi's opentools API as well as its native tools API. In the next article in this series,we will take a look at a more complicated OTA project, one that addsa new custom wizard to Delphi's Object Repository. •

Cary Jensen

Cary Jensen is President of Jensen

Data Systems, Inc., a training and

consulting company that won the

2002 and 2003 Delphi Informant

Readers Choice Awards for Best

Training. He is an award-winning

author of 20 books, including

Advantage Database Server: A Developers Guide (2007, Sybase),

Building Kylix Applications (2001, Osborne/McGraw-Hill), JBuilder

Essentials (1998, Osborne/ McGraw-Hill), and Delphi in Depth

(1996, Osborne/McGraw-Hill).

For information about onsite training or consulting services, you

can contact Cary at [email protected] or visit

his web site at www.JensenDataSystems.com.

MAGAZINE

14

DELPHI TIP:IntraWeb XI in Delphi XEDe "bundled" versie van IntraWeb bevat niet langer alle featu-res en mogelijkheden. Zo is o.a. ISAPI Deployment tegen-woordig uitgesloten van de gratis bundled features.Zie http://www.atozed.com/intraweb/featurematrix.aspx vooreen overzicht van de versies en wat het kost om naar IntraWebXE Ultimate over te stappen met daarin alle features.

Page 15: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

De bekende quote Premature Optimization isthe root of all evil van Donald Knuth uit 1974(http://pplab.snu.ac.kr/courses/adv_pl05/papers/p261-knuth.pdf) is ook vandaag nogeen bekend anti-pattern.

Als programmeur probeer je van te voren al ingedachten je programma te optimaliseren. In 97% van de gevallen is de bedachte optimali-satie zo klein dat het (bijna) niets oplevert. Vandaar dat vaak wordt aangeraden om het programma eerst laten werken, leesbare codeproduceren, tests schrijven en dan als je ervaringscijfers hebt, dan te optimaliseren.

Zet een club van software architecten bij elkaaren iedereen optimaliseert vanuit zijn invalshoek.Geeft regels mee voor de bouw vanuit zijn gedachtenwereld. Hoe groter de organisatie, hoe meer acrchitectuur regels, design authori-ties, wijzigings advies commissies en andere ballotages je door moet. Zelf heb ik al een paar

projecten meegemaakt waar het budget op ging in de architectuur fase door de

constante drang naar optimalisaties vanuit verschillende hoeken. Erger nog het kan leiden tot een verlamming als je je hetdoel uit het oog verliest. Samen denken we na over academischeoplossingen voor een praktischprobleem van de klant zonderaandacht voor het probleem vande klant zelf.

Ik heb zelf gevoetbald en was noch een Sneijder noch een Robben.Wou altijd mooi scoren maar miste net doel. In ons collectieve geheugen staat Nederland - Spanje, Robben dribbel op Casillas gegrift. Ik zag die bal er al in gaan en droomde van een weeklang feest.Die teen van Casillas stond echt niet in het design, effectief was hetzeker want het Spaanse doel bleef leeg.

Nu vraag je je vast af hoe Robben en Casillas in premature optimiza-tion passen. Soms moet je gewoon springen en kijken hoe ver je komt,tegen het gras of de bal wat meer hoogte geven, niet nadenken gewoon doen. Die terrabytes in je hoofd en de ervaring die je hebtlaten de software wel werken. Schrijf het duidelijk op en maak het testbaar. De optimalisatie komt dan vanzelf want de code is test- enleesbaar en toegankelijk voor je collega’s die je bij de optimalisatiekunnen helpen. In 2012 worden we kampioen!

Roel Hans Bethlehem •

SDN > Update

magazine voor software development 15

prematureoptimization is the root of all evil

Page 16: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

MOBILE Jaap van Ekris

Technisch is het ook niet zo moeilijk: er zijn voor Apples iOS, GooglesAndroid en Microsofts Windows Phone zeer goede ontwikkelstudio’sbeschikbaar. Het is geen drag-and-drop ontwikkelwerk, maar hetscheelt erg weinig. De applicaties zijn functioneel vaak geen rocket-science. Feit is dat als je voor de desktop kunt ontwikkelen je ook voorde telefoon kunt ontwikkelen.

Toch zit er wel een voetangel. Een groot deel van de gedownloadeapplicaties blijft ongebruikt. Slechts 25% van de gebruikers koopt ooiteen applicatie. Dus er zijn wel degelijk een hoop applicaties die bijnader inzien gewoon “rommel” zijn in de ogen van de gebruiker.In dit artikel gaan we in op wat de rommel van de top-applicaties onderscheidt. We beginnen met het uitleggen van het meest fundamentele verschil tussen desktop en mobiele applicaties: de gebruikerscontext. Daarna kijken we naar de impact hiervan op deuser-interface en gebruikte techniek.

GebruikerscontextDe gebruiker en zijn context is zonder twijfel het grootste verschil tussen desktop en mobiele applicaties. De desktop gebruiker zit inhet algemeen relaxed op een vertrouwd plekje zijn werk met zijn computer te doen. Kern hiervan is dat hij de omgeving vertrouwt endat hij bezig is met zijn werk op de computer. De mobiele gebruiker isbezig in een onvertrouwde omgeving en heeft zijn telefoon nodig omhem te helpen beslissingen te nemen in die omgeving. Kern hiervan isdat de gebruiker in een onvertrouwde (wellicht zelfs onbetrouwbare ofpotentieel vijandige) omgeving bezig is beslissingen te nemen waarbijzijn telefoon hem moet helpen. De mobiele gebruiker moet, in tegenstelling tot de desktop gebruiker, real-life beslissingen nemen enwil eigenlijk helemaal niet bezig zijn met die applicatie. De mobiele applicatie is voor de gebruiker is slechts een noodzakelijk kwaad omzijn omgeving beter te begrijpen.

Doordat de mobiele applicatie slechts een middel is tot een hoger gebruikersdoel, ontstaat er een soort ongeduld bij de gebruiker. Als de applicatie te traag is of teveel aandacht opeist zal hij de applicatie terzijde schuiven en gewoon “blind” beslissingen gaannemen zoals hij vroeger ook deed: op een gegeven moment moet jeals gebruiker gewoon die trein gaan pakken, in plaats van uitzoekenwelke van de vele opties de meest optimale is. De wereld om de applicatie gaat door en de gebruiker dus ook, met of zonder applicatie.Gek genoeg is de benaderingswijze van veel software ontwikkelaarser een van het laten krimpen van een desktop-applicatie. Men heeft te veel informatie in de applicatie, de user interface is te complex en er wordt vaak geen rekening gehouden met technischebeperkingen van mobiele toestellen.

Wat is er zo moeilijk aan een mobiele applicatie?

Keep it simpleEen van de belangrijkste basisprincipes is “hou het simpel”. Dat klinktmakkelijk, maar de praktijk wijst uit dat het ontzettend moeilijk is eenapplicatie eenvoudig te maken voor de gebruiker: het vereist de moedom keuzes te maken.

Een van de belangrijkste keuzes is het beperken van de applicatie totéén heel specifieke taak van de gebruiker. Een mobiele applicatie dienteen bepaald doel en daar moet dus niet teveel franje in komen, omdatdat domweg in de weg gaat zitten bij gebruik. Een interessant voor-beeld hiervan is bijvoorbeeld de NS Reisplanner Xtra, die geen enkeleinformatie bevat over de prijs van een reis. Hij is puur bedoeld ommensen treinreizen efficient te laten plannen. Overigens moet ook bijdeze applicatie wel een kritische kanttekening worden gezet: er is eendeel in de applicatie gereserveerd voor marketing-acties, wat kost-bare ruimte in de navigatiebalk kost. Als men dergelijke informatie zouwillen bieden, zou je eigenlijk moeten overwegen een tweede applicatie te bouwen. SPB Traveller doet dit structureel: alle onderdelen (vluchtplanning, currency-converter, woordenboek, etc.)worden ook als losse applicatie geinstalleerd, zodat er vlot genavi-geerd kan worden.

User interfaceEen belangrijk onderdeel van de applicatie is de user interface. Belangrijk is om te onthouden dat de niet de tijd, zin of aandacht heeft om precieze handelingen uit te voeren. Ook moet informatie zeer overzichtelijk zijn om snel te kunnen analyseren. Dit betekent dat de applicatie hier ook op ingericht zijn. Dit uit zich op verschillende vlakken: het visuele deel van de de user interface maarook de page-flow en de informatie die ingevuld moet worden in de interacties.

Een belangrijke wake-up call voor GUI ontwerpers is dat mensen hunapplicatie ook gebruiken, maar dan ook echt overal. Onderzoek laatzien dat veel mensen hun telefoon gebruiken als ze in bed liggen of opde WC zitten. Maar ook treinstations en bushaltes zijn vaak favorieteplekken om even wat te gaan doen. Dit laatste brengt nogal wat uit-dagingen, zeker in Nederland en noord Europa. Mensen hebben ’s winters handschoenen aan of zijn onnauwkeurig door de koude.Kleine controls op zo’n telefoonscherm zijn dan ook volstrekt uit denboze, gewoon omdat het niet te bedienen is. Een scherm moet goedte bedienen zijn met een dikke handschoen aan of koude handen.Ook mensen die meer bezig zijn met hun omgeving zitten nog weleens een paar milimeter mis. Grote knoppen met duidelijke gevolgenzijn dan ook essentieel. Daar faalt eigenlijk de iPhone GUI al een beetje:daar staan eigelijk al te kleine knoppen op.

Mobiele applicaties zijn helemaal hot. Eigenlijk tel je als bedrijf niet mee als je geen mobiele applevert aan je klanten. Niet alleen de usual suspects als Nederlandse Spoorwegen en OV9292maar ook Albert Heijn, TNT Post, QPark en Rabobank proberen actief een plekje te verwervenop het meest private stukje electronica wat we kennen: onze telefoon.

MAGAZINE

16

Page 17: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

SDN Event18 maart 2011aanmelden viawww.sdn.nl/sde

MOBILE

Bedenk ook dat een gebruiker veelal informatie in een oog-opslagmoet kunnen interpreteren, zonder al teveel analyse van zijn kant. In de desktop wereld kun je probleemloos informatie op een visueelaantrekkelijke, maar onoverzichtelijke, manier presenteren: de gebrui-ker moet er toch nog zijn eigen analyse op los laten. Een mobiele gebruiker wil graag snel hapklare informatie hebben die zijn beslissingin de wereld zal gaan beinvloeden. Je eindigt dan al snel in tabel-georienteerde vormgeving. Visueel wellicht niet de mooiste oplossing,maar vaak wel de meest effectieve. Soms moet je een hele andereaanpak kiezen: file-informatie moet je wellicht niet als lijst van filesweergeven (wat een behoorlijke wissel trekt op de topografische kennis van de gebruiker), maar meer als kaart van Nederland met roodsnelwegen of gekleurde gebieden.Denk ook aan het minimaliseren van “vereisten” van een huisstijl. Bijvoorbeeld de NS heeft in haar NS Reisplanner Xtra een plaatje zitten die bijzonder veel ruimte inneemt. Ruimte die anders door nuttige informatie gebruikt zou kunnen worden. Maar ook zaken als logo’s, beeldelementen en standaard icoontjes kunnen op een kleinscherm wel eens zeer veel ruimte kosten of erg onduidelijk overkomen. Het is verstandiger om te kijken hoe de applicatie hetbeste uit de verf komt, en dan pas een huisstijl hier passend in te krijgen, dan de huisstijl leidend te laten zijn.

Page-flow is een volgend punt van aandacht. Die moet niet te complex zijn, maar zeker ook niet te lang. Een gebruiker raakt snel afgeleid, en de vraag “waar was ik ook al weer” is foutgevoelig en helptniet bij het vlot uitvoeren van de dingen die hij snel wilde doen. Idealiter bestaat een handeling uit maximaal 3 tot 4 verschillendeschermen die erg duidelijk maken waarmee de gebruiker bezig is.

Denk ook over de gevolgen van de pageflow na: de gebruiker is bijzonder doelgericht en zal alles doen om die taak te volbrengen. Het beste voorbeeld hiervan is het navigatiepakket van de ANWB, watniet toeliet dat de gebruiker de bestemming invoerde of wijzigde als deauto bewoog. Doel van de ANWB was om veiliger weggedrag te stimuleren. Gevolg was echter dat de gebruiker met enige vorm vancreativiteit de GPS deactiveert en vervolgens alsnog zijn bestemmingingeeft/wijzigt. Gevolg is dus een agressievere en veel meer afgeleidebestuurder dan de bedoeling van de ANWB was. Ongemerkt zittendit soort zaken in elke applicatie: een tunnelvisie van hoe het gebruiksscenario verloopt is handig, maar zeker niet altijd de realiteit.

Ingevoerde informatie is een verhaal apart. Veel devices kennen eenon-screen toetsenbord of zelfs een (klein) fysiek toetsenbord. Veel ontwikkelaars zien dit als een excuus om dit ook te gebruiken. Het gebruik van zo’n toetsenbord is alles behalve comfortabel: er zijn zelfsspecifieke RSI-varianten voor dit soort gebruik ontdekt. Een paar tekens is vaak nog te doen, maar grotere stukken tekst zijn voor gebruikers vaak erg vervelend. Soms is het een bruikbaar scenarioom complexe informatie via een website in te voeren en dan naar hettoestel te syncen. Zo werken de reisschema’s van TripIT bijvoorbeeld.Voorkomen dat een gebruiker veel informatie moet invoeren is belangrijk omdat het afleid van het primaire doel van de gebruiker: zijnomgeving managen.

Technische mogelijkheden en beperkingenOok technische mogelijkheden en beperkingen spelen een sterke rolbij de kwaliteit van een mobiele applicatie. Het is voor een gebruikerzeer vreemd als technische mogelijkheden onbenut blijven of als je ingaat tegen technische beperkingen.

Een smartphone heeft zeer veel technische mogelijkheden. Technischgezien zijn ze bijna gelijk aan laptops van 3 jaar terug met office volledig geinstalleerd. Maar een smartphone weet tegenwoordig ookzijn eigen locatie en heeft een camera. Het is voor gebruikers dan ookzeer vreemd als je als applicatiebouwer daar geen gebruik van maakt.

Het zou bijvoorbeeld bijzonder vreemd zijn als je bij de NS Reisplan-ner de startlocatie handmatig zou moeten ingeven. Hoogstwaar-schijnlijk is dat het dichtsbijzijnde station. Maar ook verwacht degebruiker bijvoorbeeld dat Appie, de Albert Heijn boodschappenlijst,gewoon automatisch het juiste filiaal selecteert. Maar de gebruiker verwacht ook integratie met de agenda en contactpersonen. Gewoonomdat het technisch mogelijk is en hem veel complex werkt bespaart.

Maar de smartphone kent ook zijn technische beperkingen: met namede accu is een van de belangrijkste. Als je als applicatie de accuduursignificant verkort, door veel van de GPS, CPU of internet-verbindingte vragen, dan pak je figuurlijk de telefoon van de gebruiker af. Je verkort de bruikbare tijd van een telefoon voor de gebruiker. Dus veelenergie gebruiken door intensief energie-slurpende hardware te gebruiken is niet verstandig. Dat is de manier om slechte reviews tekrijgen met de opmerking “battery drain”.

Een ander punt is de internetverbinding. De telecom-operators willenons erg graag laten geloven dat hun netwerk overal aanwezig is metvoldoende bandbreedte. Dit is niet het geval: de dekking door hunnetwerken valt in de praktijk gewoon erg tegen. Zelfs al zou je goededekking hebben, valt de kwaliteit daarvan vaak tegen door verstorin-gen door gebouwen of warmtewerende beglazing. Bovendien rakennetwerken erg snel overbelast: een grote storing op Utrecht Centraalen je krijgt in de wijde omtrek geen data-verbinding meer. Een volle-dige afhankelijkheid van internet is dus iets wat je als ontwikkelaarmoet zien te vermijden als het mogelijk is.

Conclusie is dus dat het bij mobiele applicaties veel minder over deharde techniek van API-calls en code gaat, maar veel meer nadenkenover hoe de applicatie gaat functioneren in de context van een gebruiker die iets wil realiseren. Bij mobiele applicaties gaat het veelmeer om hoe de gebruiker snel zijn beoogde taak kan realiseren, endat vergt speciale aandacht voor wat de functionaliteit is, hoe de GUIer uit ziet en de oplossing technisch wordt opgezet. •

Jaap van Ekris

Jaap van Ekris (Det Norske Veritas)

is een Microsoft Most Valuable Pro-

fessional, gespecialiseerd in Mobiele

applicaties, hoe ze passen in het

levensritme van hun gebruikers

en de business modellen achter

applicaties.

magazine voor software development 17

Page 19: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

Eric Roosendaal

Laten we om te beginnen aannemen dat u een ListBox hebt, gevuldmet filenamen, zoals hieronder.

Hoe kunt u nu een aantal van deze bestanden verslepen naar deWindows Explorer? Omdat het handiger is om meer bestanden tege-lijk te kunnen slepen stellen we de SelectionMode van de ListBox in opMultiExtended.

De code voor het starten van een Dragactie via het MouseMove Eventis al in deel 1 aan de orde geweest. De code luidde als volgt (voor hetwaarom precies verwijzen we gaarne naar deel 1):

if ( isdragstart )

{

if( Math.Abs(e.Location.X - dragstartposition.X) >

SystemInformation.DragSize.Width / 2

|| Math.Abs(e.Location.Y - dragstartposition.Y) >

SystemInformation.DragSize.Height / 2)

{

isdragstart = false;

// perform the drag

}

}

Nu moet het Draggedeelte nog daadwerkelijk worden ingevuld. Heteerste gedeelte is eenvoudig: de ListBox heeft een property SelectedItems die alle geselecteerde items bevat. Doorloop deze collectie enverzamel alle geselecteerde items in een generic List van strings.

List<string> list = new List<string>();

foreach (var x in listBox1.SelectedItems)

{

list.Add(x.ToString());

}

Maar dan moet de data nog meegegeven worden bij DoDragDrop, endaarvoor is een speciaal object nodig. Zo’n object heet een DataObject. Dit moet nieuw worden gemaakt en bovendien moet er bij worden aangegeven, dat het een object moet worden voor het verslepen van bestanden. Daarvoor is een speciaal formaat nodig endat heet DataFormats.FileDrop. Tenslotte wordt het object gevuld metde inhoud van de List die dan eerst moet worden omgezet in eenstring-array. De code ziet er dan zo uit:

DataObject data =

new DataObject(DataFormats.FileDrop, list.ToArray());

listBox1.DoDragDrop(data, DragDropEffects.Copy);

U zult nu merken dat u bestanden van de ListBox naar een folder kuntslepen. •

magazine voor software development 19

Drag and Drop deel 2:

Bestanden slepen naar de Windows Explorer

Eric Roosendaal

Eric Roosendaal is trainer bij

Compu'Train. Hij is afgestudeerd in

Scheikunde, maar eind jaren '80

geswitcht naar IT, met name naar

Development. Sinds medio jaren '90

in dienst van Compu'Train als spe-

cialist voor alle programmeertalen,

de laatste jaren met name .NET (VB

en C#). Hij is Microsoft Certified

Trainer, gecertificeerd sinds 1995. Eric is te bereiken via

[email protected].

Het implementeren van bestandenslepen is redelijk straightforward

.NET

Page 20: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

ARCHITECTURE

• Many different stakeholdersProjects have many different parties in the organization that are involved. Often such projects realize goals for different departmentsor divisions in the organization. As an example I once coached aproject that served 22 different departments. Quite often these departments or division try to achieve overlapping or even contradicting goals.

• Business processesIn general enterprise projects (re-)implement (parts of) businessprocesses that are key to the organizations success, rather thanbuilding a straightforward web application.

• Complex software architecturesMost likely, enterprise projects implement business processes in acomplex IT landscape or architectures. Think of landscapes thathost many different applications all tied together.

• Many external dependenciesOften, such complex IT landscapes contain components that are

outside of the organization. Services that run outside the corporatefirewall, with other parties. A well-known issue to agile projects isthat of availability. We need the new version of the service in thisiteration, but the other party runs a waterfall project that will not deliver this year.

• Changing requirementsIn enterprise projects, requirements change continuously. Either bychanging insights during the project, but more often due to changing legislation or regulations.

• Many different types of deliverablesTraditionally these projects count many different types of deliverables. Think of service description, user interface, processmodels, non-functional requirements, workflow, project plans, testplans and many, many others.

• Multiple rolesLarge organizations have many different roles that are involved inprojects. There are business analysts, enterprise architects, information analysts, testers, release managers, SAP developers,web developers, SAP functional consultants,

Thus these projects often become a mission impossible, and fail inlarge numbers. Such projects are difficult to estimate, therefore hardto plan. For developers it’s tough to build the software, often with manynew techniques and technologies, and even worse for testers, theseprojects are sheer impossible to test well. This is where a structuredagile approach should come to the rescue.

Being agile in enterprise projectsIndependent of the approach that is applied, or the agile process thatis followed, being successful in agile projects follows a number of keyprinciples:• Multi-disciplinary teamsInstead of different roles such as analysts, designers, developer andtesters working in consecutive stages in a project, all roles collabo-rate in implementation individual work items from heads to tails.

• Short iterationsProject work in short time boxes, in most cases 2, 3 or 4 weeks. During such an iteration, a number of work items is planned, completed and evaluated – with different terminology in use withdifferent agile processes.

• A small standardized unit of workProjects require a small unit of work, to be able to deliver a numberof them in a single iteration. Large work items such as traditionaluse cases therefore do not apply well.

• Testing from day oneTesting is an important discipline during agile projects. Testers areinvolved from the very first iteration, when the first work items arerealized. Note that testing in most projects goes way beyond theobvious unit testing – which is actually a developer technique.

To cut to the chase, those of you who have worked on enterprise or service oriented projects before already know this. These types of projects are characterized by a large number of organizational, functional and technically complicating factors. Enterprise software development projects are surrounded by a large number of complicating characteristics and challenges:

A recipe for enterprise agile.Mixing Scrum and Smart

Sander Hoogendoorn

MAGAZINE

20

Page 21: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

ARCHITECTURE

• Continuous measurementSuccessful agile projects continuously measure their progress.Since they are always delivering individual work items, measure-ment in agile projects is easy.

• Continuous (process) improvementAt the end of each iteration not only the realized work items are evaluated, but also the project approach itself is evaluated, leadingto highly effective project approaches.

Scrum in a nutshellWhen organizations first start with agile projects Scrum is often theprocess of choice. At this point in time, Scrum is by far the most popular and best known agile approach. Scrum is a straightforwardlightweight agile process that offers a collection of highly applicableprinciples and techniques for short iterative projects and is easy to understand. It also specifies a remarkable terminology with scrums,sprints and user stories.

In a nutshell, Scrum is characterized as follows:• SprintsProjects are divided into iterations, called sprints. In general theseare 2 to 4 weeks.

• BacklogsWork items still to be done during a project reside in a so calledproject backlog. At the start of each sprint items from the backlogare placed in the sprint backlog. These are the worked items to berealized.

• Sprint cycleAll iterations follow the same simple process, with an iteration kick-off, actual work and a retrospective workshop for evaluation.

• User storiesThe main unit of work is usually the user story, although this is notmandatory. This rather informal requirements technique is sharedwith the agile process extreme programming.

• PlanningIn general the project and sprint planning is visualized in taskboards, which usually are put up on a wall using post-its. Progressis monitored by using burn down charts, a straightforward diagramthat on a daily basis displays the number of points still to realize. A trend line in the burn down chart extrapolated from the pointsidentifies the likely project end date. Again this technique is sharedwith a number of other agile processes, including Smart and extreme programming.

• DeliveryEvery iteration or sprint results in fully delivered products, softwareor otherwise.

Scrum has proven to be a successful approach in many (smaller scale)web projects. In larger, more complex, service or cloud oriented andenterprise projects, I think Scrum needs to be augmented to fit theproject and its environment. Let me explain.

Beyond lightweight agileWhen applying Scrum or other lightweight agile processes such asCrystal Clear or the set of lean principles (applied to software development that is) to more complex projects of all sorts, you mightrecognize a number of shortcomings:• Business goalsIt is often unclear how the work items in such projects (in mostcases user stories) link back to business goals, stakeholders andbusiness processes to implement.

• Analysis and design. Although many people in the so-called agile community will nowthink I’m promoting a waterfall approach, in most agile approachesthere are hardly any analysis or design activities or deliverables defined. For instance, it is undefined how the backlog in a Scrumproject is assembled. Let me assure you, in more complex projectssome analysis and design is required, albeit not in big-upfront-design mode.

• ArchitectureThe same argument goes for software architecture. Most agile approaches lack decent software architectural activities and deliverables. Architecture is often assumed as-is. If you’re implementing business processes that run through a systems landscape of over 40 collaborating systems, you will definitivelyneed to design your architectures, but again this need not be in big-upfront-architecture mode.

• RolesScrum and extreme programming describe a very limited set of rolesthat, although looking slick, in most projects does not adhere to thestanding organization. There’s often enterprise architects, information analysts, business analysts, middleware developers, application management, testers, release manager. How will a project work with all those roles? There’s a bit more to it than justsaying they are allowed to participate in the daily scrum.

• TestingApart from the obvious (developer) techniques such as unit testing,the role of testing more specifically – which is essential in larger agileprojects – is not very well described in lightweight agile approaches.

• User storiesAlthough very flexible, user stories are a highly unstructured unit ofwork, despite efforts in epics or story maps. Applying such an unstructured unit of work may result in low re-use, non-repeatableestimation, difficult to standardize development, testing and measurement beyond the individual projects. In a multi-project environment user stories will block progress and reuse (of for instance metrics and code).

• Delivery cycleScrum does not specify the organization of delivery of the productsto different environments such as test, acceptance and (pre)pro-duction (so called OTAP). When executing large, more complex, service oriented or enterpriseprojects, I therefore strongly recommend to overcome these limitations by augmenting Scrum and the likes with additional techniques.

Smart acceleratorsIn my personal experience in enterprise projects I have had very goodexperiences with mixing the agile process Scrum with the best

magazine voor software development 21

Page 22: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

ARCHITECTURE

practices from another agile process called Smart to overcome thedrawbacks of the aforementioned approach. Smart originated from the Netherlands in 1998 and was originally designed to implement best practices for DSDM, an iterative approach that was popular in those days. Later Smart grew out to astand-alone agile approach that particularly combines well with othermore basis agile approaches such as Scrum and extreme program-ming, but also aligns well with PRINCE2.

More specifically Smart puts accents on aspects in project that areonly marginally highlighted in other agile approaches. As an exampleSmart adds the following accelerators to projects:• Preliminary iterationsPreliminary iteration types Propose and Scope is where work itemsare added to the backlog such as a modeling business processes,modeling smart use cases, creating an estimate, creating a cost-benefit analysis, writing a project plan (not that obvious it seems),first-cut software architecture set-up, development environment set-up, project kick-off, team education and first-cut user interfaceguidelines.

• Smart use casesNext to the more “non-functional” work items mentioned above,Smart introduces the well-known smart use cases requirementstechnique. Smart use cases not only model the needs of the user,but also identify workflow and reusable back-end services. Thistechnique allows for identifying re-use, repeatable and reliable estimation, and very good traceability between requirements, architecture and code, great functional testing capabilities. An absolute must in enterprise projects.

• EstimatesEstimation of size and complexity of a project is estimated and measured in smart use case points, defined on a scale from 1 to 10.Smart use case points of course come from estimating the size orcomplexity of smart use cases, and is a highly pragmatic and repeatable technique..

• Work item life cycleWhere Scrum’s work item life cycle contains to-do, working anddone, in Smart, work items are delivered through a slightly morestructured life cycle, that allows for all roles in enterprise projects tobe maximally involved in a collaborative manner. Due to the lifecycle, work items need not be broken down in tasks, a cumber-some and highly unstructured element of Scrum. In Smart workitems simply move through the stages of the life cycle (in most casesin one or two days), the progress of which can be shown easily ona dashboard.

• DesigningDuring the daily stand-up meeting, it is decided whether or not a design session is required. This time-boxed design session addresses the design or a single smart use case. Most project will

organize this design session directly after the daily stand-up. On atypical time scale, if the stand-up runs from 10:00 to 10:15, the design session runs from 10:15-11:00. During such sessions allroles that need to deliver input to this particular use case partici-pate. Of course also the developer and tester are present, so allroles create a homogeneous view of the smart use case at hand.

• Smart testingWorking with user stories will normally not result in a very efficienttest approach, as user stories do not add structure to the project.Smart describes a standardized approach on functional testing inagile projects of course based on smart use cases.

• Stabilizing iteration Usually the last iteration of a Smart project or the last one to an upcoming release is used to round off remaining work items, buildissues, bugs, and remaining features. This iteration is merely usedto stabilize the solution. In Smart this iteration type if referred to asFinalize.

Blending Scrum and SmartBesides defining an obvious project life cycle, these best practicesfrom Smart blend in really well with the more lightweight approach ofScrum and extreme programming. This leads to the following bestpractices:• Initial backlogThe initial backlog of the project is filled with the work items Smartrecommends, rather than assuming a user story filled backlog.When prioritizing work items for the first sprint in a mixed Scrumand Smart project, it is very likely that these are picked. As a result,after one or two iterations, a project plan for the remainder of theproject is produced, containing at least an estimate, based on thesmart use cases that are also defined during these iterations (ofcourse without any analysis or design, just the diagrams, the ovalsand the actors).

• Iteration kick-offAfter the initial work-items are cleared from the backlog, the smartuse cases become the primary work item type in the project. Duringsprint kick-off a number of smart use cases is picked to implementin the next sprint.

• DashboardThe traditional Scrum task board is replaced by Smart’s agile dash-board, containing columns for the stages in the work item life cycle– In Iteration, Designing, Working, Testing, Rework, Accepted. If appropriate additional columns can be added, e.g. when testing issplit up in Developer Testing and Customer Testing.

• PointsThe progress in the project is not measured in story points, but rather in smart use case points.

MAGAZINE

22

Page 23: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

ARCHITECTURE

• Scrum meetingThe focus of the daily scrum meeting shifts a bit as it is also usedto answer the question: what still needs to be done on the smartuse case(s) we’re currently working on to get them accepted?

• DesignHost the design sessions as Smart recommends, preferably rightafter the daily scrum meeting.

• TestingAs the work item life cycle clearly stipulates, functional testing, oftendone manual is all in a days work. The role of the testers here be-comes imminent in the project.

• FinalizeProjects have to decide when to apply a Finalize iteration to stabi-lize the solution and round up loose ends. Depending on the typeof project, these iteration can be the very last sprint, but also can be

very well aligned with the organizations release calendar.

This approach of mixing best practices, techniques and tools fromScrum, Smart over the past 12 years has proven to be very succes-sful in a variety of projects and project types, including larger Java and.NET projects. service oriented projects, business intelligence projects,and even packaged implementations. Moreover, when augmented with more technical best practices fromextreme programming, such as refactoring, continuous integration,pair programming, and test driven development (smart use cases area very good unit for unit testing code) projects are aligned to deliver on-time, on-budget, and with just-enough documentation and fitting (reusable) features.

As former US president Bush used to say: failure is not an option. •

Sander Hoogendoorn

Principal Technology Officer and

Agile thought leader Capgemini

www.smartusecase.com

www.sanderhoogendoorn.com

The Triple A Company = SharePoint. Ruim 11 jaar verzorgen wij de implementatie van Microsoft SharePoint voor organisaties uit diverse markten. Daar zijn we trots op en we willen graag dat je in die trots gaat meedelen. Ter uitbreiding van het team zijn wij per direct op zoek naar een:

SharePoint Managing Consultant M/V Als Managing Consultant kun je jouw team van SharePoint Consultants stimuleren en richting geven. Je zorgt er voor dat planningen gemaakt en gehaald worden. Je begeleidt projecten en springt in als het moeilijk wordt.

Functie-eisen:

Universitair/HBO werk- en denkniveau. Minimaal vier jaar ervaring met SharePoint implementaties en managementprojecten. Hoge mate van zelfstandigheid. Projectmanagement en coaching is een tweede natuur.

Over The Triple A Company: The Triple A Company is informeel, kenmerkt zich door hiërarchie. We zijn een flexibel, innovatief en een vooruitstrevend bedrijf met een sterk concurrerend en onderscheidend vermogen in de markt, experts. Interesse? Herken je jezelf in het profiel en wil je deze uitdaging aangaan? We ontvangen je Curriculum Vitae samen met je motivatie graag voor 31 maart 2011 op [email protected] of per post t.a.v. Dhr. A.M.C. Deibel, 5301 LJ, Zaltbommel. Voor meer informatie verwijzen wij u naar onze website www.triplea.net. Voor aanvullende informatie kunt u contact opnemen met Dhr. A.M.C. Deibel op: 0418 -510 570.

Page 24: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

Paul Klicnik

The IBM® Rational® Code Coverage feature is a tool that integrateswith IBM® Rational® Application Developer. You can use it to generate and analyze coverage statistics for your Java applications.The tooling generates statement coverage statistics for the applicationunder test (that is, the number or percentage of lines in your application that have been executed).

InstrumentationIn order to properly analyze the coverage statistics in the RationalCode Coverage feature, it is important to understand the technologyused behind the scenes.

Rational Code Coverage uses an instrumentation engine to manipulate the bytecode of a class and inject custom calls to the coverage data collection engine. Figure 1 provides a high-level overview of the process:

Fig. 1: Overview of the Rational Code Coverage execution environment

Basic blocks versus executable unitsThe instrumentation engine operates on units of bytecode called executable units. The definition of executable unit is slightly differentthan the traditional definition of basic block, but the differences are important to take into account when the results are analyzed.

By definition, a basic block is a set of instructions that cannot be branched into or out of. The key idea here is that when the first instruction runs, all of the subsequent instructions in that block areguaranteed to be executed without interruption. It follows that a basicblock can be conceptually considered a single group or block of instructions. In general, basic blocks end on branch, call, throw or return statements.

An executable unit begins at the start of every basic block and at anyinstruction that corresponds to a line of source code that is differentthan the previous instruction. What differentiates an executable unitfrom a basic block is the condition that triggers the end of the executable unit. For example, the divide instruction is not consideredto be the end of an executable unit despite the fact that it can throwan exception.

The instrumentation engine in Rational Code Coverage is used to inject custom code at the start of every executable unit. Consequently,you can customize the Rational Code Coverage feature to report statistics down to the executable unit level of granularity (in otherwords, block coverage). Figure 2 provides an overview of how the instrumentation engine modifies the bytecode to support code coverage.

Fig. 2: Overview of the bytecode instrumentation

Generating coverage statistics in RADOne of the major advantages of the Rational Code Coverage featureis that you can enable it on any Java project in RAD by navigating to theCode Coverage panel in the project Properties, as shown in Figure 3.

Code coverage is an important aspect of software testing, and can be considered fundamen-tal to the overall system testing of a component. The motivation behind coverage tooling is simply to give you (as a developer or tester) more insight into the areas of code that are beingexercised by a set of test cases. This information is useful because you can then use it to devise new test cases to achieve adequate coverage.

Introduction to the code coverage tooling in

Rational Application Developer

CORESYSTEMS

MAGAZINE

24

Page 25: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

CORESYSTEMS

Fig. 3: Code Coverage panel in the project Properties

Select the Enable code coverage check box in Figure 3 to enablecode coverage for the project, and to instrument the classes in yourproject under the covers. You can also use this panel to customizeacceptable coverage levels for each step of granularity. The suppor-ted levels of granularity are described following:• Type coverage: the percentage of types covered in a class• Method coverage: the percentage of methods covered in a class• Line coverage: the percentage of lines covered in the class file• Block coverage: the percentage of blocks covered in a class file.Note that a block refers to an executable unit (as described previously)

You can also specify custom filters, and they are used to control whatgets instrumented in your project. By default, all of the classes in yourproject are instrumented, but you can create custom filters to excludetarget packages or specific types, if there is a need to restrict the results.

Package ExplorerAfter you enable code coverage on a project, coverage statistics willbe generated the next time that the application is launched. Note thatstatistics will not be generated for all types of launch configurationsautomatically. Table 1 displays the launch types that are supportedfrom within RAD.

Launch Type Java AppletOSGi FrameworkJUnitJUnit Plug-in TestJava ApplicationEclipse ApplicationStandard Widget Toolkit (SWT) Application

Table 1. Supported launch configurations

A sample application has been provided (see link at the bottom of thisarticle) and will be used throughout this article. The application is asimple representation of different vehicles (car, van, motorcycle, and soon) and the various parts associated with each vehicle. The UML dia-gram outlining the structure of this application is displayed in Figure 4.

There are two JUnit tests already defined in the project: TestCar.javaand TestCarImproved.java. As the names suggest, these tests targetthe Car.java class.

Fig. 4: UML diagram for the sample application

While in the Java perspective in RAD, you can start the TestCar.javatest by right-clicking TestCar.java and selecting Run As > JUnit test.The results of the JUnit test will appear in the JUnit view as normal. Thecoverage results are integrated into the RAD UI, and you can analyzethem by switching back to the Package Explorer. Figure 5 displays asample result set for the TestCar.java test.

Fig. 5: Coverage results for TestCar.java displayed in the PackageExplorer

By default, the UI is annotated with only the line coverage information;however, you can change this in the workbench Preferences, and optionally choose to include coverage for packages, types, andblocks. The percentage beside each Java item is a breakdown of theline coverage for the last execution. You can drill down into the various Java artifacts (for example, classes, types, and methods) inthe Package Explorer to get coverage statistics at a lower level of granularity.

The results are color-coded depending on the success rate: by default, red indicates that the acceptable coverage level has not beenmet while green indicates that the appropriate coverage level wasachieved. Naturally, the goal of the test is to reach an acceptable coverage level on the classes of interest.

magazine voor software development 25

Page 26: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

CORESYSTEMS

Based on the results shown in Figure 5, the first test was inadequate:the Car class (and abstract parents AbstractFourWheelVehicle andVehicle) did not reach appropriate coverage level. Luckily, you have asecond attempt to execute: TestCarImproved.java. Again, you canexecute the test as a normal JUnit and the results are automatically up-dated in the Package Explorer (Figure 6).

Fig. 6: Code coverage results for TestCarImproved.java displayed inthe Package Explorer

Java editorLine coverage results are also displayed and marked in the Java editor, and you can use it to give a more precise indication of whichlines are covered in each class. After coverage statistics have beengenerated, you can open any class in your project with the Java editor, and the left ruler bar in the editor shows the coverage information. Figure 7 displays the results for Vehicle.java:

Fig. 7: Coverage results displayed in the Java editor

The color indicators are the same as they are in the Package Explorer. That is, by default a green line was covered and a red line

was not covered. There is a slight advantage in viewing the results inthe Java Editor because it also indicates the partially covered lines.Partially covered lines can occur when there is more than one executable unit on a line of source code, but only one of them hasbeen executed. As an example, look at the first line of code in the setTargetSpeed(int speed) method shown in Figure 7: the first executable unit is the if statement, and the second executable unit isthe return statement. By default, a partial line is colored in yellow.

Generating reportsYou can compile the code coverage results into reports and view themin RAD, or save them to the file system for future analysis. You cangenerate two different types of reports: Workbench reports (Eclipse-based) and HTML reports. To generate a report, select Run > CodeCoverage > Generate Report. Figure 8 shows the report generationdialog.

Fig. 8: Report generation dialog

You can create and view a report in RAD using the Quick View optionon the dialog, or save it to the file system using the Save Report option.

Workbench reportsThe workbench reports (also known as Eclipse-based reports) provide a consolidated view of all of the coverage statistics for yourproject, and contain coverage information for all of the classes in yourproject at execution time. Figure 9 shows a populated Eclipse-basedreport. Workbench reports have the added advantage of being integrated in RAD, so you can use them as a quick tool to provide insight into the parts of your code that require improved test coverage.As Figure 9 shows, the statistics in a workbench report contain coverage information for all levels of granularity: from a package to amethod. Right-clicking any of the Java artifacts displays a pop-upmenu with two additional actions: Show in Package Explorer andOpen in Java Editor. These are useful tools for identifying and inves-tigating areas of code with low coverage, because they highlight the elected area of code by opening it in the appropriate viewer or editor.

MAGAZINE

26

Page 27: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

Fig. 9: Coverage results in an Eclipse-based report

HTML reportsHTML reports display the same type of information provided in theEclipse-based report, but in HTML format. These reports are particu-larly useful when saved to the file system, because they provide a wayfor the coverage results to be analyzed independently of RAD, sharedwith team mates, or published to a Web site for viewing.

Generating statistics outside of the workbenchOne of the major features of the Rational Code Coverage tool is itsability to generate statistics outside of RAD. This provides extra flexibility and enables you to customize your environment to take advantage of the Rational Code Coverage feature in your systems.For example, one natural combination would be to set up a nightlybuild environment and generate statistics with JUnit tests on the nightlydriver. You can integrate the Rational Code Coverage feature into yourenvironment by performing the following three steps: instrumentation,execution, and report generation.

Step 1. InstrumentationThere are two different approaches that you can use to instrumentyour application. The first is to use the instrument.bat/sh script provided in the <RAD_HOME>/plugins/com.ibm.rational.llc. engine_<date>/scripts directory. This article does not focus on this script, butyou can reference the RAD documentation for more information if necessary. The second approach is to use the instrumentation Anttask provided by the Rational Code Coverage feature. Listing 1 showsan example usage of the instrument task configured to target the sample application in this article.

<target name="instrument">

<taskdef name="instrument"

classname="com.ibm.rational.llc.engine.instrumentation.

anttask.InstrumentationTask"

classpath="{path to com.ibm.rational.llc.engine plugin}"/>

<instrument saveBackups="true"

baseLineFile="project.baseline"

buildPath="VehicleProject"

outputDir="VehicleProjectInstr"/>

</target>

Listing 1: Example usage of instrument Ant tasks on the sample application in this article

CORESYSTEMS

A quick overview of the expected parameters is outlined in Table 2. Bothapproaches to instrumentation will out-put a baseline file. A baseline file is a no-tion specific to the Rational CodeCoverage feature. The baseline file con-tains an index of all of the classes in yourproject, and maintains additional meta-data about each class.

This file is used at the reporting step(Step 3) to determine which classes inyour application were not covered. Thisstep is necessary because the RationalCode Coverage data collection engine isonly notified of a class when it is loadedby Java™ Virtual Machine (JVM), and soa list of the classes that were not execu-ted cannot be determined without addi-tional metadata. If the baseline file is not

present at reporting time, the classes that were not loaded will be ab-sent from the report.

Table 2: Input parameters for instrumentation tasks

Step 2. ExecutionIn order to execute the instrumented classes, the Java environmentmust be configured correctly at launch. The two specific parametersneeded for execution are explained below:• -Dcoverage.out.file=<absolute path to output file>: the filespecified by this JVM argument is the output location of the coveragestatistics• Add the <Rational Application Developer HOME>/plugins/

com.ibm.rational.llc.engine_<date>/RLC.jar to the classpath: because the code has been instrumented with callbacks to the theRational Code Coverage data collection engine, the RLC.jar file needsto be on the classpath at runtime.

These parameters can be supplied to a JUnit Ant task. Listing 2 provides example usage.

<target name="run">

<junit showoutput="true" fork="yes">

<jvmarg value="-Dcoverage.out.file={absolute path to the

output file}"/>

<classpath>

<pathelement location="{absolute path to the

<Rational Application Developer

HOME>/plugins/com.ibm.rational.llc.engine_<date>

/RLC.jar file}"/>

<pathelement location="{path to the project classes}"/>

<pathelement path="{absolute path to the junit.jar}" />

</classpath>

Parameter Description buildPath The path to the project on the file systemoutputDir (Optional) The output directory of the instrumented project.

If not specified, the classes in the buildPath will be instrumented in place.

baseLineFile (Optional) The output location of the baseline project index file. See the following paragraph for more information on this file.

saveBackups (Optional) Set to true if the original class files should be backed up before instrumenting.

magazine voor software development 27

Page 28: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

CORESYSTEMS

<test name="com.ibm.vehicles.tests.TestCar"

outfile="TestCar" />

</junit>

</target>

Listing 2: Example of how to specify the the Rational Code Coverage feature arguments in an Ant launch

Step 3. Report generationYou can generate reports using another Ant task provided by the Rational Code Coverage feature. This task uses the reporting functionality provided by the BIRT Eclipse.org project, and thus requi-res that you download the BIRT V2.3.2 Reporting Engine standaloneoffering. This can be done by navigating to http://www.eclipse.org/birt/download, select the V2.3.2 release and downloading the Report Engine offering. Note that this Ant task can only produce HTML reports. Listing 3 provides sample usage of the reporting Ant task. Note that,as input, it requires the coveragedata file generated in Step 2 and (optionally) the baseline file generated in Step 1.

<target name="generate-report">

<path id="lib.path">

<pathelement location="{absolute path to the

<Rational Application Developer HOME>/plugins/

com.ibm.rational.llc.common_<date>.jar plugin}"/>

<pathelement location="{absolute path to the

<Rational Application Developer HOME>/plugins/

com.ibm.rational.llc.report_<date> plugin}"/>

<pathelement location="{absolute path to the

<Rational Application Developer HOME>/plugins/

org.eclipse.equinox.common_<date>.jar plugin}"/>

<fileset dir="{absolute path to the BIRT ReportEngine

directory}\lib" includes="*.jar"/>

</path>

<taskdef name="code-coverage-report"

classname="com.ibm.rational.llc.report.birt.adapters.ant.

ReportGenerationTask"

classpathref="lib.path"/>

<code-coverage-report

outputDir="{absolute path to the report output directory}"

coverageDataFile="{absolute path to the coveragedata file

generated in step 1}"

baseLineFiles="{absolute path to the baseline file

generated in step 1}"/>

</target>

Listing 3: Example usage of the report generation Ant task on thesample application in this article

An example HTML report is displayed in Figure 10. Generating HTMLreports using the Ant task provides a means by which users can viewthe statistics generated in an Ant environment independently of RAD.

Try it out!The downloads section of this article at http://www.ibm.com/develo-perworks/rational/library/10/introtocodecoveragetoolinrationalappli-cationdeveloper/ provides sample scripts and build files for an Antenvironment that can be used to instrument, execute, and generate reports on the sample application. If you're interested in testing this environment out, refer to the README file in the Standalone.zip file.

Fig. 10: Coverage results in an HTML report •

Paul Klicnik

Paul Klicnik is a Software Developer

at IBM Toronto lab in Markham

Ontario. He has worked on Code

Coverage since 2008, and worked

in the general area of performance

and testing tools since 2006. Paul

has worked on several key IBM

products, including IBM Rational

Performance Tester and IBM

Rational Application Developer, as well as the Eclipse Test and

Performance Tools Project (TPTP) project.

MAGAZINE

28

TIP:Windows Azure gebruikAzure kost geld voor het verbruik van Rekenkracht (CPU), Sto-rage en Netwerk verkeer. Bij een MSDN account kun je Azure sub-scription instellen. Deze subscription heeft een aantal serviceszonder kosten, zoals 750 Small compute uren per maand, 10 GbStorage, 3 SQL Azure web databases en nog een paar. Ruimevoldoende voor wat development en probeersels. Als je over jebudget heen gaat, dan moet je als nog betalen. Tegenwoordigkrijg je een mail Microsoft Online Services als boven een bepaaldpercentage van je basis eenheden zit. Erg handig, zo hou je deextra kosten een beetje in de hand.Microsoft heeft daar iets aan veranderd. Vorige week kreeg ik eenmail van de Microsoft Online Services met de mededeling ik datik 75% van mijn basis eenheden zat.

Page 30: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

ARCHITECTURE Christian Siegers en Mark IJsselstein

SAP en Microsoft komennu met een nieuwe versie,namelijk Duet EnterpriseNiet zozeer een nieuwe ver-sie van Duet maar eencompleet nieuw ontwikkel-platform. Duet Enterprisebiedt out-of-the-box eentoolset waarmee je zelfbusiness scenario’s kuntrealiseren. Er is gekozenom zoveel mogelijk gebruikte maken van de bestaande producten vanbeide leveranciers en duszo min mogelijk nieuwetools en componenten teintroduceren. Duet Enter-prise draait als add-ons op SharePoint 2010 en SAP, waardoor de technische omgeving vele malen simpeler is geworden.

Wat biedt Duet Enterprise aan functionaliteit In bovenstaande komt nog geen Duet Enterprise functionaliteit voor,deze integratie kan ook met SAP en SharePoint (dus zonder Duet Enterprise) worden gerealiseerd. De toegevoegde waarde is redelijksubtiel, maar zeker op de lange termijn (volgende versies) erg belang-rijk. Duet Enterprise levert op hoofdlijnen de volgende functionaliteit:• Gateway aan de SAP zijde (IWF)• Workflow integratie• Technische integratie• Platform capabilities

Gateway aan de SAP zijdeBedrijven hebben een divers SAP landschap, waarin meerdere SAPproducten zitten en waarin meerdere versies van SAP tegelijk in gebruik zijn. Om te zorgen dat vanuit SharePoint geen rekening hoeftte worden gehouden met welk product, versie of technologie gebruiktwordt voor de verschillende SAP entiteiten, is gekozen om aan de SAPzijde een gateway te implementeren. Deze wordt de Information Worker Framework (IWF) genoemd. Hierin kun je entiteiten definië-ren/samenstellen die je vanuit SAP beschikbaar wil maken voor

SharePoint. Tevens geef je aan hoe deze entiteiten zich verhouden tot de verschillende bestaande SAP entiteiten uit het SAP landschap. Dusconcreet welk SAP product, welke versie en welke technologie wordtgebruikt om de data te lezen en schrijven. Vervolgens wordt die entiteit op uniforme wijze aan SharePoint gepresenteerd middels webservices. Alle webservices die SharePoint nodig heeft om de entiteit te onderhouden worden beschikbaar gemaakt. Denk hierbijaan ‘selecteer één object’, ‘selecteer alle objecten’, ‘voeg object toe’,etc. Als een nieuwe versie van een SAP product in gebruik wordt genomen, dan hoeft alleen de definitie van de entiteiten in de IWF teworden aangepast en blijft de interface naar SharePoint gelijk.

Workflow integratieEen andere feature die Duet Enterprise levert is workflow integratie. In SAP is het mogelijk meerdere soorten workflows te definiëren. De focus van Duet Enterprise ligt op goedkeuringsprocessen. Een voorbeeld is als iemand vakantie aanvraagt, dan moet de verantwoordelijke manager dit goedkeuren. Duet Enterprise levert demogelijkheid om de goedkeuringsstappen te integreren met Share-Point en Outlook. Als een stap in SAP actief wordt, dan wordt voordeze stap een gelijkwaardige workflowstap in SharePoint gegenereerd.Per stap heeft de beslisser dan de keuze of hij de goedkeuring doetin SAP, SharePoint, Outlook of op z’n smartphone. Nadat een beslis-sing is genomen, worden de workflow in SAP en SharePoint automa-tisch met elkaar gesynchroniseerd.

Voordeel is dat je hiermee alle collaboration features van SharePointkan gebruiken. Je kan dan andere mensen om advies vragen, je goed-keuring aan een ander delegeren, je kan discussies voeren en docu-menten delen.

Technische integratieDe technische integratie wordt gerealiseerd door in SAP webservicesbeschikbaar voor SharePoint te maken. SharePoint gebruikt BCS(Business Connectivity Services) en BDC (Business Data Catalog) omde SAP webservices te consumeren. Hiermee kunnen SAP entiteitenin een ‘external list’ worden geladen. Een external list is een lijst inSharePoint met data die niet in SharePoint zelf is opgeslagen. Dezedata kan vanuit de external list in een SharePoint site worden getoonden gewijzigd.

Duet EnterpriseDuet is het product dat door SAP en Microsoft samen is ontwikkeld om business oplossingente bieden die gebruik maken van software van beide leveranciers. Vaak hebben bedrijven SAPproducten voor backend processen en Microsoft producten voor werkplekken (Windows, Office, eventueel SharePoint). Duet is een oplossing om de sterke punten van beide platformsmet elkaar te combineren. In de huidige versies van Duet wordt een aantal standaard scenario’s geleverd, die met geringeconfiguratiemogelijkheden enigszins aangepast kunnen worden aan de klant. Duet biedt geenondersteuning om nieuwe scenario’s te ontwikkelen, dus als de benodigde functionaliteit nietaanwezig is zal een andere oplossing gekozen moeten worden.

MAGAZINE

30

Page 31: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

ARCHITECTURE

Platform capabilitiesDuet Enterprise zorgt voor onderliggende ontwikkelplatform functio-naliteit, met name Single SignOn (SSO), traceability in de logging enerror handling.

Single SignOnSSO tussen SAP en SharePoint was tot nu toe technisch ingewikkeld.Duet Enterprise maakt gebruik van de SharePoint 2010 feature Security Token Service (STS) STS maakt gebruik van claims basedauthentication. STS maakt het mogelijk om op basis van een Windowslogin toegang te krijgen tot andere systemen door credentials van andere systemen te koppelen aan een Windows login. Met Duet Enterprise wordt binnen STS de Windows login van de gebruiker vertaald naar de SAP ID van die gebruiker. Gevolg is dat van alle acties die een gebruiker doet, wordt gevalideerd door SAP of die gebruiker daar de benodigde rechten toe heeft. Het enige wat nogmoet gebeuren is de mappingtabel tussen Windows en SAP identiteitte vullen in SAP.

TraceabilityHet is belangrijk om processen integraal te kunnen volgen voor auditing doeleinden en wanneer een fout optreedt. Auditing wordt bij-voorbeeld gebruikt om te kunnen achterhalen welke gebruiker bepaalde data heeft benaderd of aangepast of een beslissingstapheeft uitgevoerd. Als processen van SAP naar SharePoint lopen enweer terug, dan moeten de processtappen in SAP gerelateerd kunnenworden aan die in SharePoint. Duet Enterprise zorgt ervoor dat in delogging op basis van IDs terug is te vinden bij welk SAP proces eenSharePoint proces hoort (en andersom).

Error HandlingDuet Enterprise zorgt ervoor dat fouten die optreden in SAP netjes enuniform worden teruggegeven aan SharePoint. Ontwikkelaars hoevendus niet allerlei verschillende soorten foutafhandelingen te implemen-teren.

Voordelen van het platformHet SAP-SharePoint en Duet Enterprise platform biedt de volgendevoordelen. • Collaboration mogelijkheden rondom ‘SAP beslissingen’. Processen die voorheen binnen SAP plaatsvonden en waaroverwerd gecommuniceerd via email, losse documenten en ander communicatiemiddelen, worden nu ondersteund door een geïntegreerde omgeving.

• Geïntegreerde zoekfunctionaliteit. Op basis van SharePoint Federated Search kun je tegelijk in SharePoint, SAP en eventuele andere systemen zoeken. Hierbijwordt rekening gehouden met de SAP rechten die de zoekende gebruiker heeft.

• Outlook offline functionaliteit. In de 2010 versie van Outlook kun je data uitSharePoint lijsten offline beschikbaar maken.Hierbij wordt de gehele inhoud van de lijst lo-kaal in een database opgeslagen. Deze datakan worden gelezen en gewijzigd. Als je weerconnectie hebt, worden de wijzigingen naar deserver gepubliceerd. Deze functionaliteit werktout-of-the-box en kan ook gebruikt wordenvoor lijsten met externe data zoals data uit eenSAP systeem. De lokale data is ook door andere Office onderdelen te gebruiken, dus bijhet maken van een offerte in Word kunnen deklantgegevens automatisch worden ingevulddoor het selecteren van een klant uit het SAP systeem, ook als je offline bent.

• No-code customization. Er is veel effort gestopt om te zorgen dat de scenario’s kunnen worden gemaakt zonder dat hiervoor gecodeerd hoeft te worden.Bijna alles kan door configuratie worden gerealiseerd.

ConclusieDuet Enterprise is een oplossing om Microsoft SharePoint en daarmee Office te integreren met SAP systemen. Het bouwt voort opde reeds aanwezige functionaliteit van deze producten. Hierdoor ishet voor zowel eindgebruikers, ontwikkelaars en beheerders vertrouwdterrein. Duet Enterprise is niet nodig voor het realiseren van één enkeletechnische interface tussen SharePoint en SAP. Als een bedrijf kiestom bedrijfsprocessen met SAP te ondersteunen en het Share-Point/Office platform kiest voor de gebruikersinterface, dan moetende technische beginselen als SSO en auditing goed geregeld zijn. In dat geval is Duet Enterprise de enige logische keuze voor de toekomst. •

magazine voor software development 31

Christian Siegers

Christian Siegers is werkzaam bij

Capgemini als Managing Consul-

tant. In projecten wordt Christian in-

gezet als Solution Architect.

Christian richt zich voornamelijk op

de Microsoft technologie en heeft

zijn roots in de integratie liggen. Het

integreren van Microsoft technolo-

gieën met de cloud als het integre-

ren van een Microsoft platform met een SAP platform hoort tot

Christian’s specialiteiten.

Mark IJsselstijn

Mark is an architect with 11 years of

experience working mostly with

Microsoft-related technology.

Page 32: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

DATABASES Ben Suurmeijer

macode omvat dit proces weinig meer dat het simpelweg kopiëren enregistreren van individuele bestanden. Echter, het verplaatsten van database objecten is niet zo eenvoudig. Het is niet zonder meer mogelijk een gewijzigde tabel vanuit ontwikkeling in productie wantdan gaat alle productiedata verloren.

In tegenstelling tot een software ontwikkelaar, die gebruik maakt vaneen SCM oplossing, waarbij een gedetailleerde registratie van alle ver-anderingen wordt bijgehouden, moeten database ontwikkelaars vaakhandmatig een lijst bijhouden met alle database wijzigingen. Geloofhet of niet maar, maar ik heb wel eens een database ontwikkelaar ge-zien die alle modificaties bijhield op gele Post-It briefjes die verspreidwaren over zijn bureau en beeldscherm. Met andere woorden, database ontwikkeling is een totaal andere takvan sport dan traditionele programmacode ontwikkeling. Als gevolge van de enorme verschillen tussen software ontwikkeling endatabase ontwikkeling, is een geautomatiseerd proces voor DatabaseChange management (DCM) á la SCM nooit echt van de grond gekomen, en wordt er noodgedwongen gebruik gemaakt van eenbreed scala van handmatige processen en work-arounds.

Historie en toekomst van Database Change ManagementSinds tientallen jaren halen veel organisaties voordeel uit het gebruik van geaccepteerde en bewezen Software Change Management (SCM) principes. Processen zoals “file locking”, “checkin / check out”, “compare and merge” en “rollbacks” stellen organisaties in staat om op een productieve en gecontroleerde manier wijzigingen aan te brengen in hun applicaties.

Echter, binnen de database wereld werkt het hele principe van SCM niet bijzonder goed. De belangrijkste reden is dat databases totaal anders zijn gestructureerd dan traditionele programma code (zoals Java en .NET), en om die reden kunnen de traditionele SCM produc-ten, zoals bijvoorbeeld IBM Rational of Subversion, niet gebuikt worden in de databasewereld.Het gevolg is een enorme kloof tussen SCM en database ontwikkelactiviteiten.

De problematiek van database veranderingenEen database is, in tegenstelling tot een softwareprogramma bijvoor-beeld, geen verzameling bestanden, en door het filesysteem wordteen database meestal gezien als één groot bestand. Bij veranderingenin het programma code, wordt er een kopie van het programmabe-stand gemaakt en vindt de ontwikkeling van code plaats op deze lokale kopie.

Een database is echter geen verzameling bestanden, maar een centraal middel waar iedereen toegang tot heeft en waar ontwikke-laars tegelijkertijd wijzigen in aan kunnen brengen. Er worden zeldenkopieën gemaakt voor elke individuele ontwikkelaar. In situaties waardit wel gebeurt, moet er nagedacht worden over hoe deze verschil-lende kopieën van de database voordurend gesynchroniseerd kunnen worden om databaseconsistentie te garanderen. Een lastigprobleem. Verder moet er rekening gehouden worden met versie-beheer, en bestaat er geen zogenaamde “debug” omgeving.

Ook een gestructureerd proces van ontwikkeling, waarbij aanpassin-gen door van de ontwikkelafdeling door worden gegeven aan QA(Quality Assurance), integratie en vervolgens productie, stuit bij data-base ontwikkeling op problemen. Bij de ontwikkeling van program-

MAGAZINE

32

Page 33: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

DATABASES

Een work-around: DDL exportDe meest bekende work-around is de database definition language(DDL) te exporteren om een databasestructuur te definiëren, en dezevervolgens als bestanden veilig te stellen binnen een traditionele SCMoplossing (zie diagram). Echter, dit proces is verre van waterdicht. Niemand kan namelijk verwachten dat ontwikkelaars daadwerkelijkconsequent dit proces volgen voor iedere veranderingen die ze aanbrengen in een database. En wat gebeurt er als iemand alleenmaar de database aanpast, en niet de bijbehoorde SCM bestanden?Hoe wordt er omgegaan met deze inhoudelijke veranderingen? Eenveranderde waarde van een parameter (in bijvoorbeeld een lookup ofmetadata tabel), kan invloed hebben op het gedrag van een applica-tie programma en moet goed beheerd worden. De vraag is alleen hoe?In dat geval moet er handmatig code geschreven worden om de wijzigingen in de databasestructuur mogelijk te maken zonder verliesvan data. Dit is niet alleen erg tijdrovend, maar ook er foutgevoelig.Bovendien is deze handmatige code geen deel van een zogenaamdapplication lifecycle management (ALM) proces, en volgt hierdoor nietde zelfde regels en voorwaarden als bij normale programmacode.

De eerste generatie database change managementDe eerste generatie database change management producten zijn inprincipe geautomatiseerde “vergelijk en synchroniseer” oplossingendie het mogelijk maken verschillende databaseomgevingen met elkaarte vergelijken. Dit type oplossingen genereert rapporten die de verschillen aangeven, waarna er automatisch code gegenereerd kanworden om de verschillen te compenseren. Dit type oplossingen biedteen belangrijke verbetering in het database change management proces. Door het geautomatiseerde karakter wordt het aantal foutenals gevolg van handmatig handelen in belangrijke mate gereduceerd.

Echter, veel change management problemen worden met de eerstegeneratie van database change management producten nog steedsniet geadresseerd: • Wat gebeurt er bijvoorbeeld als er veranderingen in de test-omgeving worden aangebracht? Dan kan het gebeuren dat de referentieomgeving niet langer identiek is, en wijzigingen kunnenverloren gaan.

• Een andere vraag is wat er precies gebeurt tijdens een ontwikkelcyclus? Welke stappen zijn in deze cyclus genomen. Er was geen informatie beschikbaar over hoe het uiteindelijke resultaat is bereikt.

• Kan iedereen die toegang heeft tot een database wijzigingen aanbrengt in de database?

• Welke veranderingen zijn door wie, wanneer gemaakt? • Is database ontwikkeling effectief gesynchroniseerd met de software ontwikkeling?

• Hoe te handelen bij gedeeltelijke distributie van de veranderingen?Bijvoorbeeld de noodzaak een applicatie aanpassing te distribuerenzonder een andere, minder stabiele aanpassing?

In vergelijk tot moderne SCM oplossingen, biedt de eerste generatiedatabase change management producten weinig meer dan “vergelijken synchroniseer”. Ze bieden zeker niet de complete functionaliteitvan moderne SCM oplossingen, zoals bijvoorbeeld de mogelijkheidveranderingen terug te draaien (rollback), check in / check out, file locking, baseline settings, code merging en veranderingsrapportenvoor auditing en regelgeving. Omdat deze eerste generatie databasechange management producten nog steeds niet in staat is naar tevredenheid veranderingen te managen, is het wellicht beter dezeproducten te categoriseren als database development management inplaats van database change management producten.

De nieuwe generatie database change management Vandaag de dag zijn database ontwikkelaars meer en meer op zoeknaar een oplossing die hen in staat stelt het volledige proces van

database veranderingen te beheren, in principe een oplossing die dezelfde functionaliteit kan bieden als traditionele SCM oplossingen:

1. Het afdwingen van formele, gedisciplineerde database change management processen en workflows

2. Het werk van verschillende database ontwikkelteams synchro-niseren en coördineren

3. Het ondersteunen van de volledige database ontwikkelcyclus, vanafontwikkeling via Q&A, naar integratie en tenslotte productie.

4. Beheren en volgen van veranderingen5. Het bieden van een goede, stabiele centrale opslag (repository) voorhet opslaan van een veranderingshistorie voor auditing doeleinden

6. Het koppelen van database veranderingen met traditionele SCM projecten

7. Database veranderingen distribueren door middel van SCM taken

Om dit te realiseren, moeten de nieuwe generatie database changemanagement oplossingen het complete palet van software changemanagement functionaliteit in een database wereld gaan ondersteu-nen. In tegenstelling tot de eerste generatie oplossingen, welke zoalswe hebben gezien niet meer biedt dan een “vergelijk en synchroni-seer” product, moeten moderne database change management op-lossingen vandaag de dag een uitgebreid scala aan functionaliteitenkunnen bieden waaronder object locking, check in / check out, baseline setting, samenvoegen van code en een rollback van veranderingen.

In plaats van het foutgevoelige en handmatige proces waar databaseontwikkelaars vandaag de dag noodgedwongen gebruik van makenom aanpassingen in de database te maken, hebben ontwikkelaarseen dwingende behoefte aan een manier wijzigingen direct en effectief aan te kunnen brengen in de structuur van de database.

Maar, ook de nieuwe generatie database change management op-lossingen is niet geheel zonder uitdagingen. Een moet bijvoorbeeldeen nieuw type centrale opslag (repository) worden gecreëerd diezowel speciale attributen, database objecten als ook database inhoudkan opslaan. Verder is er het probleem van het beheren en coördine-ren van de centrale resources en de gekopieerde resources. Een veranderingsproces moet worden gedefinieerd en worden afgedwongen, en de activiteiten van de diverse ontwikkelteams moetworden gesynchroniseerd. Database ontwikkeling moet worden gekoppeld met traditionele SCM componenten zoals versiebeheer,verandering sets (change sets) of activiteiten.

Maar ondanks deze uitdagingen, biedt een succesvolle implementa-tie van de nieuwe generatie database change management oplossin-gen enorme voordelen. De crux is de juiste database changemanagement oplossing te vinden, en de focus te houden op risico beheersing. Een goede database change management oplossing vande nieuwe generatie moet aan de volgende eisen voldoen:

• Procedures moeten worden afgedwongen zodat wijzigingen alleen via een SCM workflow doorgevoerd kunnen worden.

• Database ontwikkeling moet zodanig worden gedaan dat botsingen en conflicten voorkomen kunnen worden.

• Standaarden moeten gedefinieerd kunnen worden en worden afgedwongen via check in / check out en labels.

• Een compleet audit trail van alle veranderingen moet kunnen worden vastgelegd.

• Een automatische rollback van veranderingen, zowel in ontwikkel- als ook in productieomgevingen moet mogelijk zijn.

• De uitrol van verschillende databases moet volledige geautomatiseerd plaats kunnen vinden, met three-way comparison en analyse met gebruik maken van het samen-voegen van database code.

magazine voor software development 33

Page 34: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

DATABASES

www.barnsten.com Voor al je development & database tools. 023 - 542 22 27

Tot 31 maart 2011 extreem voordelig! Ga naar: www.barnsten.com

RapidSQLSQL Scripting,

Query Building,Versiebeheer,

ObjectManagement+

DB PowerStudio voor SQL Server

Change Manager

Beheer alle veranderingen

op alle databases (data, schema, con�g)

+SQL

OptimizerOntdek,

diagnosticeer en optimaliseer slechte code

+DBArtisan

Alle beheertaken vanuit 1 scherm,

DB migraties, user management

Nieuw!

MAGAZINE

34

dbMaestro TeamWorkTeamwork van dbMaestro maakt het mogelijk om database ontwik-keling een integraal onderdeel van een gedisciplineerd SCM proceste maken in plaats van een handmatig proces of, op zijn best, semigeautomatiseerd proces. TeamWork voldoet in alle opzichten aande eisen voor een nieuwe generatie database change managementoplossingen, en vergroot in belangrijke mate de voordelen voor organisaties die een SCM proces volgen voor zowel software ontwikkeling als ook database ontwikkeling.

Veranderingen in databases kunnen nu op eenzelfde manier gevolgdworden als veranderingen in de software code, waardoor het complete ontwikkel project, inclusief database veranderingen, op eengecontroleerde, geregistreerde en gestandaardiseerde wijze uitgeroldkan worden. Teamwork integreert met oplossing als IBM Rational.

ConclusieProgramma code ontwikkelaars hebben meer dan 20 jaar de voor-delen ervaren van het gebruik van SCM oplossingen. Het is nu tijd omeen database change management proces naar hetzelfde niveau te tillen als een SCM proces, en database ontwikkelaars en DBAs dezelfde mate van eenvoud en procesmatige beveiliging te bieden bijdatabase ontwikkeling. Integratie met bestaande, traditionele SCMproducten biedt een homogeen ontwikkelproces, identiek voor programmacode ontwikkeling als ook voor de ontwikkeling van database objecten.

De database developer community heeft behoefte aan oplossingenmet voordelen als object-locking en auditing, die een nauwere controlebiedt van de ontwikkelprocessen binnen een team. Deze benaderingbiedt tevens de mogelijkheid tot het distribueren van veranderingenen versie beheer van database objecten en schema’s.

Innovatieve volgende generatie database change management oplossingen, zoals dbMaestro TeamWork™, bieden al de hiervoor beschreven mogelijkheden, plus heel veel meer. •

Ben Suurmeijer

Ben Suurmeijer is ruim 17 jaar actief

in de IT. Eerst als Unix systeem -

beheerder en Oracle DBA, later als

pre sales bij onder andere Ameri-

kaanse en Israëlische bedrijven,

maar altijd op het gebied van IT

Beheer. www.go-esi.com/blog /

blog.dbmaestro.com

Page 35: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

De afgelopen maanden zijn er verschillende ontwik-kelingen en technische publicaties op het gebied vanDelphi geweest. Hierbij een overzicht van het meestin het oog springende en interessante nieuws.

SDN > Update

Het duurt nog even, maar over een paarweken staat de december SDE weervoor de deur. Het Delphi DevelopmentNetwork heeft een drietal sprekers gevonden die samen weer vier sessieszullen verzorgen.

Pawel GlowackiPawel Glowacki, de Embarcadero TechnicalLead voor Delphi in EMEA, zal laten zien“What’s Cooking” in de labs voor de ko-mende “Pulsar” release van Delphi, en zaldaarbij ook het laatste nieuws delen m.b.t.Delphi en de ontwikkelingen voor en met Del-phi. Voor eventueel nieuws over 64-bits en/ofMac is dit de sessie om niet te missen…

Bob SwartBob Swart zal de nieuwe mogelijkheden vanIntraWeb XI in Delphi XE laten zien, en daar-

mee een introductie geven voordat Bruno Fierens er in zijn sessie dieper op in kan gaanmet onder andere de IntraWeb iPhone con-trols. In deze sessie komen de verschillendeedities van IntraWeb XI (personal, standard enultimate) aan de orde – zowel de bestaandeals nieuwe features. Deployment als stand-alone toepassing of ISAPI DLL zal gedemon-streerd worden, net als URL Mapping, denieuwe Authentication en AJAX support voorsnelle en interactieve web Applications.

Bruno FierensBruno Fierens van TMS Software uit Belgiëzal een tweetal sessies voor ons verzorgen:Extending the Delphi IDE en Getting the mostout of IntraWeb. In de eerste sessie zullen ver-schillende types van IDE extensies uitgelegdworden gerealiseerd aan de hand van deopen tools API (OTAPI) Dit gaat van exten-sies op de Delphi repository, access van deproject manager, custom toolpanels in theIDE toevoegen en access tot de Delphi codeeditor. De extensies worden geillustreerddoor kleine voorbeelden en daarnaast wor-den ook een aantal gratis extensies gepubli-

ceerd door TMS software gedemonstreerd.Voor performante en gebruiksvriendelijke web applicaties staan in IntraWeb client-events,asynchrone events en updates ter beschik-king. In de sessie wordt gedemonstreerd hoedeze technieken aangewend worden in theTMS IntraWeb grids. Verschillende asyn-chrone en client-side features van de gridskomen aan bod. Daarnaast komen ook deTMS IntraWeb iPhone controls aan bod dieeveneens via veel async functionaliteit toela-ten iPhone, iPad web applicaties te ontwik-kelen met Delphi en IntraWeb.

Erik van de WeteringErik van de Wetering van Marik Computerszal een sessie doen over een Applicatie Fra-mework met o.a. Datasnap in XE. De sessiestart met een korte intro van het project Ap-plicatie Framework, en laat o.a. zien hoe dedataset structuur opgebouwd wordt via da-tasnap tijdens runtime (server-side en client-side). Ook zien we een ClassForName functievan Java in Delphi, Firebird sql en views, en Delphi programma’s via Remote Applicationsvan Win2008.

REST Servers in DelphiXE Using DataSnapEmbarcadero is weer begonnen met een aantal RAD in Action whitepapers. De eerste is half januari gepubliceerd op de website van Em-barcadero, en er zullen er meerdere volgen. REST Servers in Delphi XEusing DataSnap geschreven door Marco Cantù kan gelezen wordente http://www.embarcadero.com/rad-in-action/datasnap-rest waarook videos en voorbeeld code te vinden is.

Andere RAD in Action white papers die zullen volgen zijn o.a. DelphiPrism XE for iPhone Development door Brian Long, en een Delphi XEDataSnap XE Case Study geschreven door Bob Swart (met een webinar gepland op woensdag 2 maart 2011).

Delphi XE Starter Edition

Op 1 februari 2011 heeft Embarcadero een goedkoper Starter Edition uitgebracht van Delphi XE. Met een New Userprijs van 199 Euro (ex.BTW) maar een “Upgrade van elke an-dere IDE (inclusief Notepad++)” prijs van 149 Euro (ex.BTW)is deze versie gericht op de hobbyist of de starter die met wei-nig budget toch met Delphi XE aan de slag wil. Er zitten welenkele beperkingen in Delphi XE: zo is database toegang beperkt tot de BDE (dat wil je niet) of InterBase met IBX, en zitten er geen web, cloud of multi-tier zaken in (maar daarmoet je dan ook de Professional of Enterprise versie voorkopen). Iedereen die Delphi XE Starter Editie koopt kan dePDF Delphi XE Starter Essentials gratis downloaden van de Registered Users pagina, of in paperback formaat kopen vanLulu.com via http://www.lulu.com/product/14723094 Ook zijn speciale upgrade prijzen naar Delphi XE Enterpriseen RAD Studio XE Enterprise aangekondigd, geldig tot heteinde van dit kwartaal. Zie http://www.delphixe.nl voor meerdetails.

SDE18 maart 2011

Delphi Nieuws

magazine voor software development 35

Page 36: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

.NETASP

Juval Löwy, verantwoordelijk voor de C# coding standards van IDesignen schrijver van onder andere Programming .NET Components enProgramming WCF Services (beide uitgegeven door O’Reilly), heeftwel eens gezegd dat iedere applicatie die geen gebruik van transac-ties maakt speelgoed is (“Any application not using transactions is atoy”). Dit is natuurlijk wat gechargeerd, maar het is niettemin belang-rijk om op z’n minst na te gaan of je applicaties transacties nodig heeft.Daarbij moet je bedenken hoe je het systeem consistent wilt houden.Een inconsistent systeem doet immers niet wat het moet doen, omdathet gegevens bevat die elkaar tegenspreken. Dit zelf oplossen is overhet algemeen een heidens karwei, omdat de complexiteit snel oploopt.Bij vijf operaties in een transactie is het aantal permutaties 5! (=12), bijtien operaties 10! (=3.600.000). Transacties zijn daardoor vaak debeste oplossing. Het is niet voor niets dat .NET vanaf 2.0 uitstekendeondersteuning biedt voor transacties middels de TransactionScope(daarvoor al via System.EnterpriseServices), en dat technologieën alsLINQ-to-SQL en het Entity Framework alle wijzigingen met Save-Changes automatisch in een transactie verpakken. Ook in WindowsCommunication Foundation is het eenvoudig om services te makendie transacties ondersteunen (of vereisen). Om te beginnen moet je inhet operation contract aangegeven dat de betreffende service opera-tion transacties ondersteunt. Dit doe je met het TransactionFlow attribuut, zoals in Listing 1.

[OperationContract]

[TransactionFlow(TransactionFlowOption.Allowed)]

void MyServiceMethod(string someParam);

Listing 1: Operation Contract met ondersteuning voor transacties.

Andere waardes voor TransactionFlowOption zijn Mandatory (verplicht)en NotAllowed (niet toegestaan). Met de instelling Allowed zijn trans-acties toegestaan, maar kan een client de service ook aanroepen zon-der een transactie te gebruiken. Uiteraard kan een service intern dannog steeds wel een transactie gebruiken. Andere services die door declient aangeroepen worden zullen daarin echter niet meedraaien.

Met de TransactionFlow goed ingesteld, moet je nog wel zorgen datde operaties die je maakt aangeven of wat hun betreft de transactiegeslaagd is. Dit kun je declaratie doen met een Operation Behavior ofin code door expliciet OperationContext.Current.SetTransactionComplete() aan te roepen voordat de functie retourneert. Wanneer je

ervoor kiest een Operation Behavior te gebruiken, zoals in Listing 2, zaleen exception de transactie automatisch afbreken. Zonder exceptionwordt aangenomen dat de operatie geslaagd is.

[OperationBehavior(TransactionScopeRequired=true,

TransactionAutoComplete=true)]

public void MyServiceMethod()

{

// Implementatie hier

}

Listing 2: Operation Behavior voor automatisch transactiebeheer.

Om transacties mogelijk te maken, moet je wel een binding kiezen dietransacties ondersteunt. De belangrijkste binding die dat niet doet isBasicHttp, maar voor de meeste andere bindings is dit geen probleem.Je moet deze binding daarnaast ook configureren om transacties teondersteunen en dat doe je als volgt:

<binding name="MyBinding" transactionFlow="true" />

In .NET is het kinderspel om een client te maken die een transactie gebruikt bij het aanroepen van een service die dit ondersteunt. De bindingconfiguratie wordt automatisch overgenomen uit de metadataen daardoor wordt een aanroep binnen een TransactionScope auto-matisch gedaan met een transactie. WCF kiest hierbij automatisch hetmeest optimale protocol voor de transactie, waarbij het kan kiezen uitOleTx en WS-AtomicTransaction (WSAT). OleTx is een Windows-onlyprotocol dat uitstekend werkt binnen een lokaal netwerk. Zodra hetechter nodig is om ook andere services te betrekken, zoals servicesgemaakt met Java’s WCF tegenhanger Web Services InteroperabilityTechnology (WSIT), zal WCF automatisch schakelen naar WSAT. Ditkan ook als de transacties oorspronkelijk in OleTx gestart is. Dit is volledig transparant en je hoeft je hier dus niet om te bekommeren.Met WS-AtomicTransaction is het in principe mogelijk om webservicesdie over de hele wereld verspreid zijn te betrekken in een enkele trans-actie. Dat we dat kunnen betekent echter niet meteen dat we dat ookmoeten doen. WS-AtomicTransaction werkt op basis van 2-phasecommit. Dit betekent dat de zogenaamde Transaction Co-ordinator(TC), de regisseur van de transactie, eerst aan alle deelnemers in een

Transacties zijn bedacht om systemen consistent te houden en worden daarom ook al decennia gebruikt.De ondersteuning voor transacties is om die reden ook bedacht voor webservices in de vorm van de WS-AtomicTransaction standaard. Maar is dat wel een goed idee?

Michiel van Otegem

Webservices en transacties

De complexiteit loopt bij transacties alsnel op. Een transactie met 10 opera-ties kent 3.600.000 permutaties

Dat we webserivces die over de helewereld verspreid zijn in een enkeletransactie kunnen betrekken betekentniet dat we dit ook moeten doen

36

MAGAZINE

Page 37: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

.NETASP

magazine voor software development 37

transactie vraagt of de transactie doorgang kan vinden. Wanneer alledeelnemers daarop bevestigend antwoorden, laat de TC de transac-tie doorgaan en moeten de wijzigingen definitief gemaakt worden dooralle deelnemers. Deelnemers die in de eerste fase een OK gegevenhebben, kunnen hier niet op terugkomen. Dit systeem werkt uitste-kend, maar geeft wel een nadeel: locking. Zolang de TC nog niet aan-gegeven heeft dat de transactie door mag gaan, houdt de transactiein principe een lock op resources die betrokken zijn bij de transactie.Deze resource, zoals een database record of een bestand, mogen inde tussentijd niet door andere operaties gewijzigd worden en (afhan-kelijk van het Isolation Level) mogen de wijzigingen ook nog niet zicht-baar zijn voor andere operaties. Dit geldt bijvoorbeeld ook als de TCna de eerste fase, maar voor de tweede crasht en een tijd uit de luchtis. In zulk soort situaties zijn resources zo lang geblokkeerd dat ditenorme problemen voor een systeem op kan leveren. Maar zelfs alsalles goed gaat is het nog zo dat locks niet erg lang mogen duren.Meer dan een seconde kan al geweldige gevolgen hebben voor eensysteem waar een hoop wijzigingen op gedaan worden.

Afbeelding 1, Voorbeeld transactiesrichtlijnen

Binnen een applicatie en zelf binnen een lokaal netwerk is dit nog welte realiseren, maar is een van de deelnemers bijvoorbeeld een web-service in Singapore, dan kan een enkele request-response al 10 seconden duren. Dan duurt een 2-phase commit in vergelijking eeneeuwigheid. Afgezien van de technische implicaties is er ook nog eenander vraagstuk. Door een webservice aan te bieden aan een derdemet ondersteuning voor transacties, geef je eigenlijk een deel van decontrole over je eigen systeem uit handen. De gemiddelde systeem-beheerder zal hier van gruwen, en terecht!

Had er dan nooit een standaard als WS-AtomicTransactions moetenkomen? Of had deze nooit in WCF en WSIT geïmplementeerd moe-ten worden? Dat is ook wel weer een brug te ver. Transacties hebbenook in de wereld van webservices hun waarde. Je moet alleen goednadenken over wanneer je ze wel of niet moet gebruiken. Het beste isom hier binnen een organisatie richtlijnen voor op te stellen. Je kunthierbij services bijvoorbeeld verdelen in categorieën op basis van hunfunctie en plek in een proces. Zo kun je bijvoorbeeld services onder-scheiden die een bepaalde basisfunctie bieden, zoals het versturenvan een email.

Dergelijke “basisservices” worden altijd in de context van bedrijfslo-gica uitgevoerd en zijn dus een goede kandidaat om in een transac-tie mee te draaien. Services die deze services aanroepen zitten opeen hoger niveau en daarvan zou je bijvoorbeeld kunnen bepalen datze niet deel mogen nemen in een transactie, maar er wel een mogeninitiëren om de lager gelegen services te coördineren. Transacties bui-ten de grenzen van het eigen netwerk zijn meestal geen goed idee,dus je moet wel hele goede redenen hebben om dat toe te staan. Voormulti-nationals kan ook de latency een rol spelen in de richtlijnen. Persoonlijk vind ik het heel handig om de richtlijnen die je kiest vast teleggen in een duidelijk plaatje. Een plaatje kun je namelijk makkelijkergens ophangen om mensen te herinneren aan de richtlijnen. Bovendien zijn plaatjes beter te onthouden dan regeltjes tekst. Afbeelding 1 laat een voorbeeld zien van een plaatje waarin detransactierichtlijnen gevat zijn. •

TIP:Als je Google Chrome installeert kun je de standaard Search engine instellen. Daarvoor kun je kiezen uit: Google, Yahoo en Microsoft Bing. Dus zelfs in Chrome kun je bingen ;-)

Op 26 maart 2011 zal SharePoint Saturday en devolgende CodeCamp in Nederland georganiseerdworden door de gezamelijke communities. Blijf opde hoogte via Twitter en vol http://twitter.com/codecampnl

E-Office (www.e-office.com) is platina sponsor enMacaw (www.macaw.nl) is gold sponsor.

26 maart 2011CodeCamp

Page 38: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

IW Anita Boerboom

• Summary - the title for the rule• Explanation - displayed in the Health Reports list when the rule fails• Remedy - displayed in the Health Reports list when the rule fails• ErrorLevel - severity of the failure of the rule

All rule definitions can be found in the rule definition list: Central Administration, Monitoring, Review rule definitions. The Health Reportslist can be found in the Central Administration, Monitoring, Review problems and solutions. The Health Reports list explains the issue, failing servers and services and the remedy to the problem. The difference between the two lists is that the rule definition list displays all the existing rules; the Health Reports list displays the ruleswhich cause problems in the farm.The rules are categorized in both lists. Code listing 1 lists the customrule in the Configuration category.

public override SPHealthCategory Category

{

get

{

return SPHealthCategory.Configuration;

}

}

Listing 1: Override the Category property

The title of the rule can be set by overriding the Summary property asshown in code listing 2.

public override string Summary

{

get

{

return "Verify the sandbox related jobs are started.";

}

}

Listing 2: Override the Summary property

The Summary is shown in the rule definition list and the health reportslist. The custom rule can be scheduled by overriding the Automati-cExecutionParameters property. In the get accessor a SPHealthAnalysisRuleAutomaticExecutionParameters object is returned.

When the property isn’t overridden the rule can be scheduled

Building a custom Health Rule

Functionality of the custom health ruleSandboxed solutions can be monitored a little bit better than Share-Point default provides.When the Microsoft SharePoint Foundation Sandboxed Code Serviceis started sandboxed solutions can be deployed and used. To monitor the resources consumed by the sandboxed solutions a couple of timer jobs measure and collect the consumed resources: • Solution Daily Resource Usage Update • Solution Resource Usage Log Processing • Solution Resource Usage Update

It is possible to deploy sandboxed solution when the timer jobs arenot running. In that case the resources consumed by the sandboxedsolutions are not measured. This means when the sandboxed soluti-ons are consuming a lot of resources the farm can get down in not anice way. One of the strengths of sandboxed solutions is that they arehosted in a partially trusted context so they do not affect the rest of theSharePoint implementation...

Wouldn’t it be nice to be sure the timer jobs are running when theSandboxed Code Service is running?

Build the ruleTo set up a health analyzer rule an empty SharePoint project is created. A class is added which inherits from SPHealthAnalysisRule.This is the class to implement the rule definition. The class can also beinherited from SPRepairableHealthAnalysisRule. This means the rulecan repair the problem itself. When inheriting from SPRepairableHeal-thAnalysisRule the method Repair() has to be implemented as well.

To define a rule some properties has to be overridden:• Category - rule definitions are grouped by Category in the default view

SharePoint 2010 and governance are tightly connected these days. Governance consists ofpolicies, roles, responsibilities and processes to ‘avoid’ chaos in the SharePoint environment.Some of the possible policies implemented by an organization can be monitored by SharePointitself by the new feature called SharePoint Health Analyzer. The Health Analyzer is rule basedand the rules check the farm for potential problems. SharePoint has several out of the box rules,like ‘Drives are running out of disk space’ and ‘The server farm account should not be used forother services’. To make administrators aware of possible issues with the farm all errors are listed in the Health Reports list. To monitor additional items not available out of the box, customhealth rules can be built.

One of the strengths of sandboxedsolutions is that they are hosted in apartially trusted context so they donot affect the rest of the SharePointimplementation

MAGAZINE

38

Page 39: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

IW

manually by a farm administrator.

public override SPHealthAnalysisRuleAutomaticExecutionParameters

AutomaticExecutionParameters

{

get

{

SPHealthAnalysisRuleAutomaticExecutionParameters

parameter = new

SPHealthAnalysisRuleAutomaticExecutionParameters();

parameter.Schedule = SPHealthCheckSchedule.Hourly;

parameter.Scope = SPHealthCheckScope.Any;

parameter.RepairAutomatically = false;

parameter.ServiceType = typeof(SPTimerService);

return parameter;

}

}

Listing 3: Overriding property SPHealthAnalysisRuleAutomaticExecutionParameters

In code listing 3 the rule is scheduled on an hourly basis and the scopeis set to SPHealthCheckScope.Any. This means the rule will run on anhourly basis on the first available computer with the specified service. The code that identifies the real problem is the Check() method. TheCheck() method returns the outcome of the check: SPHeathSta-tus.Failed or SPHealthStatus.Passed. When SPHeathStatus.Failed isthe result of the check, the rule will be displayed in the Health Reportslist to make the administrator aware of the problem.

public override SPHealthCheckStatus Check()

{

jobTitleOfDisabledJobs.Clear();

SPUserCodeService userCodeService =

SPUserCodeService.Local;

if (userCodeService.IsEnabled)

{

using (SPSite site = new SPSite("your_site_url"))

foreach (SPJobDefinition job

in site.WebApplication.JobDefinitions)

{

switch (job.Title)

{

case "Solution Daily Resource Usage Update":

AddJobTitle(job);

break;

case "Solution Resource Usage Log Processing":

AddJobTitle(job);

break;

case "Solution Resource Usage Update":

AddJobTitle(job);

break;

default:

break;

}

}

if (jobTitleOfDisabledJobs.Count != 0)

{

return SPHealthCheckStatus.Failed;

}

}

return SPHealthCheckStatus.Passed;

}

Listing 4: Implementation of the Check() method

The code in listing 4 checks if the Sandboxes Code Service is started.If the service is started, it checks if the timer jobs involved in measu-ring the resources consumed by the solutions are enabled. When theservice isn’t started there are no running sandboxed solutions and noresources have to be measured. The AddJobTitle() method adds thetitle(s) of the disabled job(s) to a generic list of strings as stated in codelisting 5.

private void AddJobTitle(SPJobDefinition job)

{

if (job.IsDisabled)

{

jobTitleOfDisabledJobs.Add(job.Title);

}

}

Listing 5: Collection of titles of disabled jobs

The generic list is used at the Explanation property to inform the farmadministrator exactly which job(s) aren't enabled. Code listing 6 over-rides the Explanation property and returns an informative messageincluding the titles of the jobs which aren’t enabled.

public override string Explanation

{

get

{

string jobTitles = string.Empty;

for (int i = 0; i < jobTitleOfDisabledJobs.Count; i++)

{

jobTitles += jobTitleOfDisabledJobs[i].ToString();

if (i != jobTitleOfDisabledJobs.Count - 1)

{

jobTitles += " / ";

}

}

return "The Microsoft SharePoint Foundation Sandboxed

Code Service is started, but not all the " +

"timerjobs are: " + jobTitles;

}

}

Listing 6: Display an informative message in the Explanation property of the rule

Besides explaining the issue in detail a message can be displayed tothe administrator on how to act on the issue. Code listing 7 overridesthe Remedy property.

public override string Remedy

{

get

{

return "Start the timerjobs: Solution Daily Usage

Update, Solution Resource Usage Log Processing

and/or Solution Resource Usage Update.";

}

}

Listing 7: Override the Remedy property

Code listing 8 overrides the ErrorLevel property and sets the severityof the issue to Warning.

magazine voor software development 39

Page 40: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

IW

public override SPHealthCheckErrorLevel ErrorLevel

{

get

{

return SPHealthCheckErrorLevel.Warning;

}

}

Listing 8: Override the ErrorLevel property

Deploy the ruleThe rule can be deployed by adding a farm level scoped feature to the solution, and add an event receiver to the feature.Code listing 9 overrides the FeatureInstalled and FeatureUninstallingto register and unregister the rule.

public override void FeatureInstalled

(SPFeatureReceiverProperties properties)

{

try

{

Assembly currentAssembly = Assembly.GetExecutingAssem-

bly();

IDictionary<Type, Exception>

exceptions =

SPHealthAnalyzer.RegisterRules(currentAssembly);

if (exceptions != null)

{

if (exceptions.Count == 0)

{

//ok

}

else

{

//something went wrong, take appropriate action

}

}

}

catch (Exception ex)

{

throw new Exception("There was an error registering

the health rule: " + ex.Message);

}

}

public override void FeatureUninstalling

(SPFeatureReceiverProperties properties)

{

try

{

Assembly currentAssembly = Assembly.GetExecutingAssembly();

IDictionary<Type, Exception>

exceptions =

SPHealthAnalyzer.UnregisterRules(currentAssembly);

if (exceptions != null)

{

if (exceptions.Count == 0)

{

//ok

}

else

{

//something went wrong, take appropriate action

}

}

}

catch (Exception ex)

{

throw new Exception("There was an error removing

the health rule: " + ex.Message);

}

}

Listing 9: Register and unregister the rule

After the deployment, the rule can be found in the rule definition list:Central Administration, Monitoring, Review rule definitions. Details ofthe rule are shown in Figure 1.

Fig. 1: The rule definition

The default view of the rule definition list is showing all the defined rulesEXCEPT the rules defined with the category ‘System’. Of course it'spossible to create an additional view to show all the rules.

Run and test the ruleBy disabling for example the ‘Solution Daily Resource Usage Update’job and the ‘Solution Resource Usage Update’ job the rule can be tested to fail.

The rule is scheduled to run every hour as defined in code listing 3and shown in Figure 1. To speed things up the rule can be selected torun directly by pressing Run Now. The timer job which actually runs theHealth Analyzer jobs, dependent of the schedule, is in this case Health Analysis Job (Hourly, Microsoft SharePoint Foundation Timer,Any Server). The job can be found in Central Administration, Monito-ring, Review Job Definitions. By selecting the job title the details of thejob are shown and the job can run immediately by selecting Run Now.

The rule fails and shows up in the Health Reports list as shown in Figure 2.

Fig. 2: The rule fails

The little yellow sign at the bottom of the icon in Figure 2 shows a visual representation of the ErrorLevel set in code listing 8. The Sum-mary of the rule set in code listing 2 is displayed as the title of the rule.

The details of the rule can be viewed by selecting the text in the Health Reports list. A dialog opens as shown in Figure 3. Note thatthe Explanation of the rule changes when different sandbox timer jobsare disabled or enabled and the rule is reanalyzed. The Explanationproperty displays exactly which timer jobs aren´t enabled.

MAGAZINE

40

Page 41: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

IW

Keep in mind to attach the debugger to the timer services when debugging the rules: OWSTimer.exe process.

Fig. 3: Details of the failed rule

Settings are not updatedIt is possible that a property like the category will change during development. A mistake is easily made and the rule has to move fromthe Configuration to the Performance category. Code listing 10 displays the minor change in code.

public override SPHealthCategory Category

{

get

{

return SPHealthCategory.Performance;

}

}

Listing 10: Changing the Category of the rule definitionAfter the deployment of the solution with the changed Category property the rule fails, but the rule shows up at the 'old' category Configuration. This is one of the possible 'issues' which can occur if the Timer Service Recycle timer job isn’t restarted. The job is like an iisreset, butfor the timer service, it recycles the Timer Service to free resources.

ConclusionIt is a good practice to implement health rules to monitor the farm, beinformed about issues and take the appropriate action. The rules arenot that hard to program, but can be really useful to have an overviewof issues.Whenever possible implement health rules that comply withthe governance plan of the organization. It will be easier and maybeavoids chaos in the SharePoint environment. •

Anita Boerboom

Anita Boerboom is an independentSharePoint developer and consul-tant in The Netherlands. She combines programming knowledgewith good communication skills anda high quality standard in all her projects. Anita has worked in several industries with focus on several knowledge areas withinSharePoint. She's very fond of thejQuery library SPServices.

DELPHI TIP:CD/DVD Drive OpenenSoms is het handig om de CD/DVD driver van je computer oflaptop te openen. Hier kunnen we de mciSendString functie uitde MMSystem unit gebruiken. Om de CD drive te openen moe-ten we de string “Set cdaudio door open wait” sturen, en omhem te sluiten de string “Set cdaudio door closed wait”.Om een specifieke drive X te openen kunnen we de string “X:Alias Drive_X type cdaudio” sturen om X: als alias voor Driver_Xop te geven, gevolgd door “set Drive_X door open”. De vol-gende functie kan gebruikt worden om een willekeurige Drive teopenen, of de default driver (als je #0 meegeeft als argument):

function OpenDrive(DriveLetter: Char): LongInt;

var

ParamString: string;

begin

if DriveLetter = #0 then

begin

ParamString := 'set cdaudio door open';

Result := mciSendString(PChar(ParamString),nil,0,0)

end

else

begin

ParamString := DriveLetter + ': Alias Drive_' +

DriveLetter

+ ' Type CDAudio';

Result := mciSendString(PChar('open ' +

ParamString),nil,0,0);

if Result = 0 then

Result := mciSendString(PChar('set ' + 'Drive_' +

DriveLetter

+ ' door open'),nil,0,0)

end

end;

TIP:Het Windows Phone 7 product team heeft het boek over Programming the Windows Phone 7 van Charles Petzold beschikbaar gesteld aan de community. In dit boek kun je alleslezen, hoe je zelf applicaties kunt maken voor de Windows Phone7. In principe heb je daarvoor geen toestel nodig en kun je alles uitproberen in de emulator. Het boek is te downloaden op: http://bit.ly/9PBQNr en de bijbehorende sources op: http://bit.ly/aB0N08.

magazine voor software development 41

Page 42: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

GENERAL Robert Blom

Een forum is al jaren een bekende ontmoetingsplaats om kennis tedelen: de een vraagt, de ander antwoordt, weer een ander corrigeertof vult aan. Het succes van Wikipedia is hierop gebaseerd, duizendenauteurs bepalen het succes en de waarheidsgetrouwheid.In de wereld van software-ontwikkeling zijn er op internet vanzelf-sprekend al verschillende fora te vinden. Het ene forum is populairderdan de ander of richt zich op één specifieke ontwikkelomgeving. Envaak is het antwoord op een brandende vraag in het buitenland en/ofin een andere taal te vinden. Daarbij blijft Google een veelgebruikt vertrekpunt voor een prangende vraag.Een forum in je eigen moerstaal blijft toch het meest ideaal. Want watis er nou handiger om via het forum nog even - in je eigen taal - con-tact met de vragensteller op te nemen of om via het forum een geza-menlijk probleem aan te pakken. Het onderwerp sfeer is daarmee een‘hot issue’ geworden. Elke moderator probeert zijn (of haar!) forum uitte bouwen, veel leden te werven en qua inhoud en populariteit op in-ternet tot een succes te maken. Wat dat betreft heeft NLDeveloper alskennistank, forum, blog of ‘ontmoetingsplaats’ niets nieuws te melden.

En toch is er wat nieuws onder de zon. NLDeveloper richt zich niet opéén specifieke ontwikkeltaal! . En dat is handig voor leden, lezers énbedrijven als Microsoft (.Net, VB), Sun (Java/J2EE), Embarcadero (Del-phi, Prism) en Oracle. Als lid van NLDeveloper blijf je op de hoogtevan de nieuwste ontwikkelingen. Je maakt deel uit van een netwerkvan professionele ontwikkelaars die elkaar op een professionele wijzete hulp staan. Hierdoor is er altijd een technische vraagbaak binnenhandbereik waardoor je bij het oplossen van vraagstukken een aan-zienlijke tijdwinst realiseert. Zowel formeel als informeel heeft hetNLDeveloper uitstekende contacten met leveranciers.

NLDeveloper is daardoor altijd op de hoogte van de nieuwste ontwik-kelingen; een voorsprong die natuurlijk ten goede komt aan de actieveleden van het forum. Op zowel de website als via Twitter, Facebook,LinkedIn en media besteden we aandacht aan nieuwe ontwikkelingenen technieken die de moderne software-ontwikkelaar helpt nog beterin zijn/haar werk te worden en te blijven.NLDeveloper komt niet zomaar uit de lucht vallen. In een tijd datCloud-computing en Social Media het gesprek van de dag zijn, zijnde moderators (en tevens initiatiefnemers) al jaren werkzaam in de we-reld van software-ontwikkeling en hebben hun sporen op dit gebied allang verdiend. Betekent dat dan een probleemloze start van hetnieuwe forum? Mede-initiatiefnemer Robert Blom: “Welnee. Elkenieuwe site, forum, blog, concept of dienst op internet vraagt omvoortdurende aandacht en waar nodig bijsturen. Natuurlijk, de site kanalleen een succes worden bij voldoende ‘verstandige’ vragen en ‘ver-standige’ antwoorden. Ongeacht het kennisniveau van de bezoeker:men moet zich op NLDeveloper thuis (gaan) voelen. Tweerichtings-verkeer dus. Maar ook de artikelen, blogs, speciale aanbieden, be-richtgevingen, aankondigingen moeten aantrekkelijk zijn én blijven.Waarbij ook de sfeer niet uit het oog verloren wordt.”

NLDeveloper is dus nieuw. De mensen achter de website willen eenmodern, informatief en succesvol platform realiseren. Dit kan uitslui-tend met de medewerking van lezers en leden. “Heb je vragen en/ofopmerkingen, aarzel dan niet om contact met ons op te nemen of eenvraag te stellen op ons forum. Alleen met elkaar kunnen we NLDeve-loper voor elkaar een succes laten worden.” Meer weten? Kijk op www.nldeveloper.com. Wedden dat het klikt? •

“Nieuw” in Nederland: NLDeveloperDe marktwaarde van elke software-ontwikkelaar wordt al jaren bepaald door de expertise diehij of zij meebrengt. Elke werkgever is tenslotte gebaat bij goed-functionerende software, of ernu sprake is van een detacherings-opdracht of het uitvoeren van projecten onder eigen dak. Het is daarom niet verwonderlijk dat er voortdurend wordt bijgeleerd: via cursussen, seminars,workshops, competence centers, fora etc.

Robert Blom

Robert Blom adviseert en produ-ceert. Voegt de daad bij het woord.Met als resultaat: een lange reeksaan enthousiaste opdrachtgevers.Plus een lange reeks succesvollebrochures, websites en andere ui-tingen. Complete producten, vanconcept tot uitvoering - inclusief de-sign, fotografie, copywriting, druk-werk en meer. Kortom, alles wat u

nodig hebt om u met effect in de markt bekend te stellen. Zieook www.RobertBlom.nl

MAGAZINE

42

Page 43: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

GENERAL Mark Wolzak

De gateway server wordt geplaatst binnen de trust boundary van deagents en verzorgt authenticatie voor de agents met de manage-mentgroup met behulp van een certificaat. Omdat de agents zich indezelfde trust boundary bevinden als de gateway kunnen zij zich authenticeren bij de gateway met behulp van Kerberos en hebbenhierdoor zelf geen certificaat nodig. Dit kan een aanzienlijke besparingopleveren in beheer van certificaten op het moment dat er veel agentsin betreffende omgeving gemonitord moeten worden. Een ander voor-deel is dat de agents zelf geen internetverbinding nodig hebben.

Op den duur kan het noodzakelijk worden om een gateway server tevervangen, bijvoorbeeld doordat hardware verouderd is. De proce-dure die hiervoor is beschreven in de Operations Administrator’s Guidevan Microsoft werkt echter niet altijd vlekkeloos. In dit artikel wordeneen aantal extra benodigde stappen besproken om tot het gewensteeindresultaat te komen.

De procedure volgens Microsoft in praktijk gebrachtDe procedure zoals beschreven in de SCOM 2007 R2 Operations Administrators Guide1 is als volgt:1. Log in op een managementserver (MS) met een account dat lid is van de Operations Manager Administrators groep en open de console;

2. Ga naar het Administration scherm en ga naar Administration > Device Management en klik ‘Agent Managed’;

3. Selecteer de Computers waarvoor de primary managementserver gewijzigd moet worden, doe rechtermuisklik en selecteer ‘Change Primary Management Server’;

4. De-installeer de gateway server software van de computer;5. Verwijder de gateway server uit de groep.

Met deze procedure bestaat er een kans dat de agents communica-tie verliezen met de managementgroep. Vooral als agents niet gecon-figureerd zijn met een failover managementserver.

In principe zou nu het volgende moeten gebeuren:1. De Root Management Server (RMS) verwerkt de aanpassing waardoor de ‘state cookies’ van Gateways (GTW) ‘A’ en ‘B’ en van‘Agt X’ verlopen en deze een nieuwe configuratie nodig hebben;

2. Gateway ‘A’ controleert of zijn state cookie nog geldig is en vraagtde nieuwe configuratie op;

3. De nieuwe configuratie wordt overgebracht naar Gateway ‘A’ waarinis aangegeven dat ‘Agt X’ moet rapporteren aan Gateway ‘B’;

4. ‘Agt X’ controleert of zijn state cookie nog geldig is en vraagt de nieuwe configuratie op;

5. De nieuwe configuratie wordt overgebracht naar ‘Agt X’ waarin is

aangegeven dat ‘Agt X’ moet rapporteren aan Gateway ‘B’;6. Communicatie met Gateway ‘B’ wordt opgestart en ‘Agt X’ rapporteert voortaan met Gateway ‘B’.

Op het moment dat de configuratie gewijzigd wordt volgens boven-staande procedure zullen agents die niet geconfigureerd zijn met eenfailover managementserver, connectie met de managementgroep ver-liezen. De oorzaak hiervan ligt primair in de volgorde waarin de confi-guratie wordt ontvangen en de wijze waarop de managementservershierop reageren. Omdat in stap 3 de configuratiewijziging aankomt bijGateway ‘A’ zal deze server elke volgende communicatie met ‘Agt X’weigeren. Volgens de configuratie van deze gateway communiceert‘Agt X’ immers niet langer met Gateway ‘A’. Dit betekent dat de agentna stap 4 de communicatie met de managementgroup verliest.

Symptomen bij verliezen communicatieDe symptomen voor het verliezen van de communicatie zullen terugte vinden zijn in de console en in de ‘Operations Manager’ eventlogsvan de agent en van de oude en de nieuwe gateway server.

ConsoleIn de console zal een heartbeat failure te zien zijn waardoor de agentgrijs weergegeven zal worden in de console.

Best practices bij het vervangen van een

SCOM Gateway ServerBij het monitoren van agents binnen System Center Operations Manager (SCOM) 2007 R2wordt gebruik gemaakt van Kerberos voor onderlinge authenticatie binnen de trust boundary vaneen domein. Buiten trust boundaries wordt gebruik gemaakt van certificaten. Sinds SCOM 2007kan voor monitoring van agents buiten de trust boundary ook gebruik gemaakt worden van eenGateway server.

magazine voor software development 43

Page 44: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

GENERAL

Tevens zullen in de alertview de volgende errors te zien zijn

AgentIn de eventlog zal bij het maken van een connectie met de oorspron-kelijke Gateway server een error met eventid 20070 met als source‘OpsMgr Connector’ optreden.

Naast de error in de eventlog is het probleem te zien in de configura-tie van de agent in de registry onder ‘HKLM\SOFTWARE\Micro-soft\Microsoft Operations Manager\3.0\Agent ManagementGroups\[Managementgroup Name]\Parent Health Services\0’.Hier zal te zien zijn dat de genoemde managementserver (Authenti-cationName en NetworkName), nog steeds de oude server betreft.

Oorspronkelijke en nieuwe Gateway serverIn de eventlogs van de oorspronkelijke en de nieuwe gateway serverzullen errors met respectievelijke EventId’s 20000 en 20022 vanSource ‘OpsMgr Connector’ gelogd worden. Hierbij geeft de eersteaan dat een device welke geen lid is van de managementgroup heeftgeprobeerd contact te maken. De tweede geeft aan dat de agent geenheartbeat heeft.

Oplossen en voorkomenHet beschreven probleem kan het best opgelost en voorkomen wor-den door bij het vervangen van een gateway server een aantal regelsaan te houden:

1. Verwijder een gateway server pas (stap 5 in de procedure) op hetmoment dat alle agents succesvol communiceren met hun nieuwemanagementserver;

2. Zorg ervoor dat agents, indien er een nieuwe primaire managementserver aangewezen wordt, de oorspronkelijke managementserver, al dan niet tijdelijk, als failover management–server toegewezen krijgen.

Indien de oorspronkelijke gateway server niet meer ingezet kan worden, bijvoorbeeld doordat deze niet meer actief is, kan de configuratie van de agent ook handmatig aangepast worden.

Oorspronkelijke gateway server als failover aanwijzenDoor het inzetten van de oorspronkelijke managementserver als failover management server is de agent geautoriseerd om contact opte nemen met de managementgroup via zijn oorspronkelijke primairemanagementserver en wordt de agent in staat gesteld om de juisteconfiguratie op te halen van de managementgroup.

De procedure kan uitgevoerd worden met behulp van onderstaandepowershell script (uit te voeren via de operations manager shell):012345678901234567890123456789012345678901234567890123456

MAGAZINE

44

Page 45: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

GENERAL

$primaryMS = Get-GatewayManagementServer

| where {$_.Name -eq 'ExtGWt02.clientx.local'}

$failoverMS = Get-GatewayManagementServer

| where {$_.Name -eq 'ExtGWt01.clientx.local'}

$agent = Get-agent

| where {$_.Name -eq 'ExtADt01.clientx.local'}

Set-ManagementServer -AgentManagedComputer: $agent

-PrimaryManagementServer: $primaryMS

-FailoverServer: $failoverMS

In bovenstaand voorbeeld is ExtGWt01.clientx.local de originele managementserver (gateway) en ExtGWt02.clientx.local de nieuw in tezetten managementserver (gateway).

Na uitvoeren van het script zal communicatie met de management-group hersteld worden en kan, zodra de agent de nieuwe configura-tie opgehaald heeft, de failover managementserver verwijderd wordenuit de configuratie van de agent door onderstaande script via de operations manager shell uit te voeren:

$primaryMS = Get-GatewayManagementServer

| where {$_.Name -eq 'ExtGWt02.clientx.local'}

$agent = Get-agent

| where {$_.Name -eq 'ExtADt01.clientx.local'}

Set-ManagementServer -AgentManagedComputer: $agent

-PrimaryManagementServer: $primaryMS

Handmatig aanpassen van de configuratieIndien de oorspronkelijke gateway server niet meer ingezet kan wor-den kan onderstaande procedure gebruikt worden om de configura-tie aan te passen:1. Stop de service ‘System Center Management’ op de server waar deagent draait;

2. Verwijder de inhoud van de directory ‘D:\Program Files\System Center Operations Manager 2007\Health Service State\ConnectorConfiguration Cache\[Managementgroup name]’;

3. Open ‘Add/Remove programs’ (of ‘Programs and Features’ in server 2008)

4. Selecteer ‘System Center Operations Manager 2007 R2 Agent’ enklik ‘Change’;

5. Klik ‘Next’, selecteer ‘Modify’ en ‘Next’;6. Selecteer ‘Modify Management Group’, selecteer de juiste managementgroup en klik ‘Next’;

7. Verifieer dat ‘Specify Management Group Information’ is aangevinkten klik ‘Next’;

8. Onder ‘management server’ kan nu de juiste managementserver aangegeven worden. Klik ‘Next’ en klik ‘Install’.

Na afloop van deze installatie zal de communicatie met de manage-mentgroup hervat worden.

ConclusieDe procedure die door Microsoft is beschreven voor het vervangenvan een Gateway server functioneert niet altijd vlekkeloos. Problemendie hieruit voortvloeien zijn echter niet onoverkomelijk en kunnen voor-komen worden door een paar eenvoudige regels te hanteren. •

1 http://download.microsoft.com/download/B/F/D/BFDD0F66-1637-4EA3-

8E6E-8D03001E5E66/OM2007R2_OperationsAdministratorsGuide.docx

Mark Wolzak

Ik ben 10 jaar werkzaam in de IT enals ontwerper infrastructuur / con-sultant werkzaam bij Info Support inVeenendaal. Ik werk onder anderemet SQL Server, ISA/TMG, Ex-change en System Center VirtualMachine manager, maar heb me ge-specialiseerd in System CenterOperations Manager waarvoor ik di-verse implementaties heb verzorgd

bij uiteenlopende klanten.

.NET TIP:Welke .NET versie draai ikAls je wilt weten welke versie van het .NET framework je alle-maal hebt geinstalleerd, kun je dat doen door in de registry tezoeken en de directories op je disk te controleren. Maar dit iser arbeidsintensief en niet geheel foutloos. Via twitter kwamdeze link http://www.asoft.be/prod_netver.html.

magazine voor software development 45

Page 46: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

GENERAL

StickerenIn de horeca is het al jaren een goed gebruik, het stickeren van le-vensmiddelen, zo weet ik van afzichtelijke televisieprogramma’s alsKeuringsdienst Van Waren. Een eenvoudige sticker vertelt wanneerhet product is opengemaakt, en tot wanneer het houdbaar is. Is dezeuiterste houdbaarheidsdatum verstreken, dan wordt het product weg-gegooid, onbruikbaar voor consumptie. Tenminste dat hoop je dan.

Maar dan. De uiterste houdbaarheidsdatum van requirements? Het onderwerp kwam ter tafel toen een van de cursisten vertelde opdit moment te werken aan de requirements van een request for change (RFC) die inmiddels twee jaar oud is. Twee jaar oude requirements? De kans is groot dat deze requirements inmiddels albehoorlijk beschimmeld zijn; wet- en regelgeving is gewijzigd en dewensen van de gebruikers zijn ontegenzeggelijk veranderd. Als tijdenseen gemiddeld project de requirements al 20-25% wijzigen, hoe vergaat het dan requirements die ergens op een plank liggen te verstoffen?

Requirements en kaasWelbeschouwd zijn requirements te vergelijken met kaas. Je hebtjonge requirements, net rijp genoeg om te consumeren, jong belegenrequirements die eigenlijk al hadden moeten worden gerealiseerd, endan oude requirements, die opzichtig beginnen te brokkelen. Tenslottezijn alle ongebruikte requirements overjarig. Wellicht smaakvol, maarze vallen al uit elkaar op het moment dat ze worden gehanteerd.

En net als kaas die op een plank ligt te rijpen verdienen requirementsdezelfde zorgzame aandacht willen ze na een of twee jaar nog consumeerbaar zijn. Ze moeten worden omgedraaid, geevalueerd enverzorgd. Gebeurt dit niet dan verschimmelen ze en moeten ze eenvoudigweg uit de handel worden genomen, ongeschikt voor comsumptie. Ik denk dan ook dat het een goed idee is ook require-ments te stickeren, net als alle andere bederfelijke waar. Wanneer zijnze aangemaakt, en belangrijker nog, wanneer dienen de requirementsgerealiseerd te zijn voor ze definitief verschimmelen.Maar wanneer zijn onze requirements eigenlijk bedorven? Een kritischagile luisteraar zal wellicht zeggen dat requirements beginnen met rot-ten zodra ze zijn opgeschreven. Immers, voortschrijdend inzicht begintdirect te werken. Misschien is het een idee om een standaardtermijnvoor bederf te hanteren – zeg een half jaar. En misschien zijn require-ments voor de user interface wel nog sneller bedorven. Die krijgen daneen sticker van drie of vier maanden. En wanneer requirements overhun uiterste houdbaarheidsdatum heen zijn? Niet aarzelen. Gewoonweggooien!

YAGNIHet is overigens goed mogelijk de uiterste houdbaarheidsdatum terekken. Hier komt het bekende YAGNI-principe goed van pas. You aren’t gonna need it. Ofwel voorkom in projecten al het werk datop dit moment (nog) niet nodig is. Doorvertaald naar requirementskomt dit er op neer dat alhoewel het verstandig is aan het begin vaneen project vast te stellen welke requirements we graag willen implemeteren, de details van deze requirements pas echt nodig zodrade implementatie ervan begint. En dat is mogelijk pas veel later. Dit verklaart ook deels het succes van agile, kort-iteratieve projecten.De details (analyse en ontwerp) van een requirement worden pas bepaald zodra deze tijdens een van de iteraties daadwerkelijk wordtgebouwd. Zo wordt voorkomen dat er vroeg in een project veel werkin requirements wordt gestoken die nooit worden gerealiseerd, zoalsin watervalprojecten nog wel eens het geval is. En bovendien, wanneerde details bijvoorbeeld pas na een half jaar worden onderzocht, is hetvoortschrijdend inzicht van dat half jaar automatisch geborgd. Om inde metafoor te blijven, zo zijn requirements altijd vers.

Ik benieuwd overigens wat de uiterste houdbaarheidsdatum van dezecolumn zal blijken te zijn. •

Onlangs gaf ik – voor de zoveelste keer – training in het identificeren en modelleren van smart use cases.Dit keer bevond ik me in de hippe ruimtes van Meeting Plaza Utrecht, boven het altijd sfeervolle HoogCatharijne. Tijdens de goed verzorgde lunch werd het onderwerp al snel bepaald door de uiterste houd-baarheidsdatum. Van levensmiddelen, maar meer nog, van requirements.

De uiterste houdbaarheidsdatumvan requirements

MAGAZINE

46

Page 47: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

DOTNETNUKE

Charles Nurse

The Razor Host ModuleIn addition to the new bits that are available as part of the WebMatrixsuite, the Razor parser and the new WebPages Framework requiresASP.NET 4.0. As we still wish to retain compatibility with ASP.NET 3.5we cannot directly integrate support for Razor scripts into the DotNetNuke core, as this will force all of our users to upgrade toASP.NET 4.0.

Therefore, our approach to providing support for Razor scripts is toprovide a “Razor Host” module. If DotNetNuke users wish to useRazor scripts as part of their sites, they will need to install this module. A Beta of this module has been available since early December andwas used as the basis for the recent Hackathon contest. However,DotNetNuke 5.6.1 will contain an initial release of the Razor Host module.

Adding the Razor Host Module to a PageAn instance of this module can be added to a DotNetNuke page in theusual way (see Figure 1).

Fig. 1: Adding an instance of the Razor Host module to a page

The resulting module looks pretty sparse (see Figure 2). The body ofthe module does not display anything - as no script is selected - andthere is only a single Action – Edit Script - which allows Host users tocreate and edit scripts.

Fig. 2: The Razor Host Module on a page

It is very important to note that the only users who will see the “EditScript” Action button or menu item are Host (or Super) Users. This isbecause you can do anything in Razor script, so only users with thehighest level of access should be able to create Razor scripts.

Configuring the Razor Host ModuleAs with most modules in DotNetNuke the Razor Host module doeshave settings - actually a single setting - the ability to select a previ-ously created Razor script (see Figure 3).

Fig. 3: Setting the Razor Script to use

DotNetNuke

supports RazorOn January 13th at CodeMash in Sandusky, Ohio, Microsoft introduced Razor - a newlightweight syntax for developing WebPages as part of its WebMatrix offering. In a separate article in this issue, Andrew Nurse, one of the developers who created Razor describes the motivations behind this new syntax and an overview of the syntax itself. In this article I will focuson how you can use Razor scripts in DotNetNuke 5.6.1.

Only Host Users can Create or EditRazor Scripts

magazine voor software development 47

Page 48: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

DOTNET

NUKE

While editing and creating scripts can only be done by a Host User,any user with Edit permissions can select an existing script.

In the example shown in Figure 3, selecting the PageInfo.cshtml scriptwill result in the module displaying the content shown in Figure 4.

Fig. 4: The Rendered Razor Script

Creating and Editing Razor ScriptsSo selecting a previously created script is fairly easy, but how can weedit or create scripts. When logged in as a Host user, selecting thepreviously described “Edit Script” Action will bring up the “Edit Script”control (Figure 5).

Fig. 5: Editing a Razor Script using the Edit Script control

This control allows you to:• Add a new Script File• Choose a Script file to Edit• Modify the Script source in the Text Area• Set the current Script to be the Active Script (Is Active) - as an alternative to choosing the “Active” script in the Module Settings

• Save the Modified Script.

The script files are all stored in the “Scripts” sub-folder.

Fig. 6: Editing a Razor Script using the WebMatrix IDE

The Text Area does not provide any Syntax Highlighting (or Syntaxchecking). But if you want some “Syntax Highlighting” you can usethe WebMatrix IDE to modify the script files (Figure 6) or even Visual Studio 2010.

Note that in the WebMatrix IDE the C# code has a different highlightingthan the HTML.

Hosting the Razor EngineSo far we have seen how we can use the Razor Host Module, buthow is this achieved?

Razor can actually be thought of as a templating engine and if you areplanning on building a module that requires templates you might wantto consider Razor. So, by describing how we host the Razor Enginehopefully I will be able show how you might do that.

The WebPage ClassThe WebPage Class (actually WebPageBase) is the basis of the newWebPages Framework, in the same way that the “Page” class is thebasis of the WebForms Framework.Essentially the approach we use in our “Razor Host” module is as follows.

1. Identify the Razor script file (e.g. Twitter.cshtml)2. Call BuildManager.GetType(scriptFile) to create an instance of WebPage. Note that the System.Web.WebPages assembly contains a special class - PreApplicationStartCode - that ensuresthat the extensions cshtml and vbhtml are registered with theBuildManager

3. Call the ExecutePageHierarchy method of the WebPage class andcapture the rendered content.

4. Create a LiteralControl with the rendered content and add it to thecontrol tree.

In order to achieve this there are two new classes in a new assembly(DotNetNuke.Web.Razor.dll) which is distributed as part of the “RazorHost” Module.

1. RazorModuleBase – this class implements IModuleControl by sub-classing ModuleUserControlBase

2. DotNetNukeWebPage – this class subclasses WebPageBase andprovides some DNN specific enhancements.

The RazorModuleBase ClassThe RazorModuleBase class is where everything comes together. AllDNN Modules need to implement the IModuleControl Interface - thisis how the module injection logic knows what to inject. RazorModule-Base is a new base class that implements IModuleControl and is usedas the base class for the Razor Host Module.

In the OnPreRender method of the class we first check if our script -RazorScriptFile - exists. If it does we call the CreateWebPageInstancemethod to get an instance of the DotNetNukeWebPage.

Protected Overrides Sub OnPreRender(ByVal e As System.EventArgs)

MyBase.OnPreRender(e)

Try

If File.Exists(Server.MapPath(RazorScriptFile)) Then

Dim instance As Object = CreateWebPageInstance()

If instance Is Nothing Then

Throw New InvalidOperationException( _

String.Format( _

CultureInfo.CurrentCulture, _

MAGAZINE

48

Page 49: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

DOTNET

NUKE

"The webpage found at '{0}' was not created.", _

RazorScriptFile))

End If

Dim webPage As DotNetNukeWebPage =

TryCast(instance, DotNetNukeWebPage)

If webPage Is Nothing Then

Throw New InvalidOperationException( _

String.Format( _

CultureInfo.CurrentCulture,

"The webpage at '{0}' must derive from

DotNetNukeWebPage.",

RazorScriptFile))

End If

webPage.SetContext(Me.ModuleContext)

InitHelpers(webPage)

Dim writer As New StringWriter

webPage.ExecutePageHierarchy(

New WebPageContext(HttpContext), writer, webPage)

Controls.Add(

New LiteralControl(Server.HtmlDecode

(writer.ToString())))

End If

Catch ex As Exception

ProcessModuleLoadException(Me, ex)

End Try

End Sub

Listing 1: The OnPreRender method of the RazorModuleBase class

We then set the WebPage’s module context by calling its SetContextmethod. This allows us to access the ModuleContext in Razor script.Finally we call the WebPage’s ExecutePageHierarchy method to getthe rendered content, which we add as a LiteralControl to the Controlscollection of the module.

In the above description I glossed over two important points: the RazorScriptFile property and the CreateWebPageInstance property.

The RazorScriptFile PropertyThe RazorScriptFile property (Listing 2) returns the virtual path of a“default” script file. In the Razor Host module, we override this property and return the currently selected script, but the default behaviour in the base class is to return “MyScript.cshtml” if the currentcontrol is “MyScript.ascx”.

Protected Overridable ReadOnly Property RazorScriptFile As String

Get

Return Me.AppRelativeVirtualPath.Replace("ascx", "cshtml")

End Get

End Property

Listing 2: The RazorScriptFile property

The CreateWebPageInstance MethodThe CreateWebPageInstance method (Listing 3) uses the Razor -ScriptFile property to create an instance of a DotNetNukeWebPage(Listing 3), calling BuildManager.GetCompiledType, which returns aType and then calling Activator.CreateInstance to return an instance ofthe DotNetNukeWebPage.

Listing 3: The CreateWebPageInstance method

Earlier in this article I mentioned that BuildManager knew to “build” aWebPage instance from a cshtml or vbhtml because of some codethat exists in the WebPages Framework that registers the extension.

So why do we get an instance of DotNetNukeWebPage rather than aninstance of WebPage? The answer lies in the included web.config file (Listing 4) that sits in thesame folder as the Razor Host Module. By default the Razor Enginewill return an instance of WebPage, but this can be modified in thenew system.web.webPages.razor section of web.config, where wehave indicated that an instance of DotNetNukeWebPage should bereturned.

Listing 4: The Razor Host Module’s web.config file

ConclusionRazor is an exciting addition to our list of technologies that we canuse to create dynamic webistes. By hosting the Razor Engine in DotNetnuke, the Razor Host Module can be used to host Razor scriptsin DotNetNuke 5.6.1. Take the opportunity to investigate Razor by installing the Razor HostModule and play with the included script files – or goto the DotNet-Nuke site (www.dotnetnuke.com) and download one of the RazorHackathon entries. •

Charles Nurse

Since 2006 he has been Senior Ar-chitect for DotNetNuke Corporationthe creators of the DotNetNukeOpen Source Web Application Plat-form. Charles has been workingwith the .NET Framework since itsfirst release, specializing in Web Ap-plications using ASP.NET and he isa Microsoft MVP and an ASPInsider.He has spoken at many major con-ferences including the Software De-

velopers Conference (SDC) (www.sdc.nl), DevConnections(www.devconnections.com), DevTeach (www.devteach.com)and Microsoft Tech Days, and he is a frequent speaker at localUser Groups and Code Camps.

Private Function CreateWebPageInstance() As Object

Dim type As Type = BuildManager.GetCompiledType(RazorScriptFile)

Dim instance As Object = Nothing

If type IsNot Nothing Then

instance = Activator.CreateInstance(type)

End If

Return instance

End Function

<system.web.webPages.razor>

<pages pageBaseType="DotNetNuke.Web.Razor.DotNetNukeWebPage">

<namespaces>

<add namespace="Microsoft.Web.Helpers" />

<add namespace="WebMatrix.Data" />

</namespaces>

</pages>

</system.web.webPages.razor>

magazine voor software development 49

Page 50: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

GENERAL Joachim Nilsson

In the pre-agile world, I could sometimes feel that I and my team attimes would drift away from the solution we were supposed to create.The time to market is putting pressure on the deliveries, and a complex technological surrounding forced us to work in a speed thatleft no time to correct bad input values in requirements. When thinking about this I also came to an insight that the agile practices thatI have selected to work with, gives me a scheduled time to reflect.

Reflection loop 1: SelfStart by looking at Test Driven Development or TDD. When we implement this in both unit testing and automated functional testing,the practice will force us to reflect on and validate the requirements asa first step. So before starting to write a single line of code, we makesure that our requirements are testable since otherwise we cannotwrite our automated tests for the feature. The reflection is done by thetest writer him- or herself and is done within a very short time frame.

Reflection loop 2: The pairPair programming is my next selected practice. It is seldom imple-mented to 100% since it appears to cut the production speed in half.And that is true! It is true - if all developers• …never write any poorly designed code• …never introduce any bugs • …and always are up to date with the architecture of the rest of thedevelopment department.

If you have this situation in your teams: Congratulations!

When pair programming actually is done, it will give the benefit of forcing the developer to reflect on the design and solution of the problem. If the design is incorrect or the solution seems unclear, the navigator or co-pilot will interrupt with a question. In order to answer, the developer must of course have a clear thought of the solution or think about it for a while. The reflection is done together withthe team mate and perhaps a few times during the day.

Reflection loop 3: Stand-up meeting When I look at the stand-up meeting with reflection in mind, I see thatin order to get the reflective mindset in the team it is best if my teammembers are all focused on the same task. When they have differenttasks, the interest between the team members decreases and I endup with sub tasks being forgotten or issues being missed. Done properly, with same goal in mind and with an attitude to help eachother, I find that reflection is done in the whole team.

Reflection loop 4: DemonstrationWhen we do demonstrations from our team, we invite the product owners, the architects and the other teams that work in our product.It is an excellent way to get feedback on the completed task. Can weconsider it done or not. Are there any issues that have arisen from our

assumptions and limitations that need to be handled? The one thingI want to improve on is to hold demos more often, for any type ofchange that can be demonstrated:• Test cases - to verify with stakeholders that the requirements areinterpreted correctly.

• Architectural changes – to make our surrounding teams understandhow the latest code works.

• Working code – the normal demonstration

Reflection loop 5: RetrospectiveWe hold our retrospective once a sprint as normal. And this is the bestpractice of all because it allows our team to constantly improve in apace that fits us. It also provides feedback and learning to the de-partment in terms of how we can make all teams work more efficient.

SummaryTo summarize, I find that the practices I have chosen to follow will allowme and my team to reflect in a number of ways, starting from the smallest feedback loop up to the largest. This is also a lesson that I think is worth sharing, to find reasons behind the agile practices that you choose to follow. Reasons are ofcourse several, but bring them up to discussion within your own teamand see that it will be a lot easier to follow practices since there is acommon understanding of why you do the things you do. •

Reflection loops of AgileThe agile way of working has now come upon us with full strength; some projects with poor results and others with excellent results. Since the agile way includes elements of self-improvement, any poor results should soon become good ones and finally excellent ones. As a Software Engineer, I really like this way to work since it provides me with some great tools.

Joachim Nilsson

Joachim Nilsson is a consultant atCapgemini, Sweden. He has aM.Sc. in computer sciences fromLund institute of Technology andhas been working in different rolesof software development during thelast 16 years.

MAGAZINE

50

Page 52: SOFTWARE DEVELOPMENT NETWORK · Daarnaast draagt de Microsoft-software bij aan de toenemende vraag naar transparantie en voorspel-baarheid, vindt Thissen. “Team Foundation Server

Volgende maand werk jij bij Macaw.

[email protected]

Wat doe jij volgende maand?

.NET Developer

t doe jij vaW t doe jij v ende maand?olgt doe jij v ende maand?ende maand?

.NET

ende maand wolgV de maand w

[email protected]