• Save
Dev buchan leveraging the notes c api
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

Dev buchan leveraging the notes c api

on

  • 443 views

 

Statistics

Views

Total Views
443
Views on SlideShare
443
Embed Views
0

Actions

Likes
0
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Dev buchan leveraging the notes c api Presentation Transcript

  • 1. © 2007 Wellesley Information Services. All rights reserved.Leveraging the NotesC API in LotusScript:“A How-to Guide”Bill BuchanHADSL
  • 2. 2What We’ll Cover …• Introduction• Architectures• Platform differences• Calling simple Notes C API• Notes C API handles• Custom classes help hide platform differences• Complex Notes C API• Pros and cons• Wrap-up
  • 3. 3Target and Purpose• Who is the target audience? Advanced Lotus Notes Developers Developers who have a little experience in C API• What is this about? This talk demonstrates advanced LotusScript, showing theNotes C API interface• Why Notes C API? 900+ supported methods Many complex tasks can be called via API
  • 4. 4Who Am I?• Bill Buchan• Dual Principal Certified Lotus Professional (PCLP) in v3,v4, v5, v6, v7• 10+ years senior development consultancy for Enterprisecustomers Learn from my pain!• 5+ years code auditing• CEO of HADSL Developing best-practice tools
  • 5. 5Notes C API Programming Toolkit• Where can you find information on C API? The Lotus Notes C Programming toolkit• The toolkit: Contains two documentation databases Documents each function and structure Includes a large number of sample C programs Provides compile-time libraries for all platforms• Generally speaking, backward compatibility is good For instance, if you have v6 and v7 servers, creating theprogram using v6 of the API toolkit means that it will run on v6and v7 servers
  • 6. 6What We’ll Cover …• Introduction• Architectures• Platform differences• Calling simple Notes C API• Notes C API handles• Custom classes help hide platform differences• Complex Notes C API• Pros and cons• Wrap-up
  • 7. 7Notes/Domino Architectures• Domino is a multi-platform server product• Notes now supports four clients: Windows, Mac (Power PC), Mac (Intel), Linux• LotusScript supported from v4.x of Notes, on all serverand client platforms Rich set of APIs for general business logic Robust, supported environment for general businessapplications Amazing level of multi-platform support• What if you want to go further? Exploit a piece of Notes C API interface? Call a platform-specific DLL?
  • 8. 8Why Worry About Platform Independence?• Currently, something like: 90% of all Domino servers run on Windows 95% of all Notes clients run on Windows• Why not write platform code for that and that alone? A short-sighted decision Your environment may start supporting more platforms Windows 64-bit coming over the horizon Treat it as a separate platform As was 16-bit Windows• Corporate push to centralize and consolidate Especially on medium-high level platforms Linux, Solaris, AIX, HP/UX
  • 9. 9Be Pragmatic — The Skills TriangleFew Code ExamplesC APILotusScript, JavaMany Code ExamplesEasierHarder
  • 10. 10Be Pragmatic• Call the Notes C API from LotusScript if: You cannot find a supported architectural solution You have the skills to support Notes C API coding You might possibly require multi-platform code You accept that this code will be harder to write, harder tomaintain, and harder to support
  • 11. 11Architectures — Conclusion• If you have to step outside the comfort zone, you havetwo choices: LotusScript eXtension Toolkit (LSX) This builds a library — on Windows, a DLL — which allowsyou to extend LotusScript with custom C code Fairly straightforward Not part of this presentation LotusScript calling the Notes C API interface directly Not straightforward One code base can cover all platforms
  • 12. 12What We’ll Cover …• Introduction• Architectures• Platform differences• Calling simple Notes C API• Notes C API handles• Custom classes help hide platform differences• Complex Notes C API• Pros and cons• Wrap-up
  • 13. 13Platform Differences: Definitions• In LotusScript, platform differences are taken care of Not so in direct LotusScript to C API calls• Each platform represents data in a subtly differentmanner For instance, the HANDLE datatype has different lengths ondifferent platforms: 32 bits long in Windows and OS/400 16 bits long on AIX, Macintosh, etc. Memory alignment widths on iSeries are different from otherplatforms
  • 14. 14Platform-Specific Implementations• In order to call the Notes library, you will have to link todifferent library files on each platform: Windows/32: nnotes.dll Solaris, Linux: libnotes.so AIX: lnotes_r.a HPUX: libnotes.sl MacOs, OS/X: NotesLib OS/400: libnotes.srvpgm OS/390 libnotes OS/2: lnotes.dll Windows Alpha: anotes.dll
  • 15. 15Platform Differences: Endians• Little endians Some platforms represent multi-byte numbers with the lowestvalue bytes in the lower segments of memory• Big endians Macintosh (on PowerPC!) represents the larger value bytes inthe lower segments of memory
  • 16. 16Coding for Platform Differences• Our challenge is to construct a code sequence that: Knows which platform it’s running on Makes calls to the platform-specific library file Understands platform differences in terms of alignment anddata item size And most importantly — fails “safe” when presented with a newplatform that it cannot deal with• This is not a trivial exercise My estimate is that this exercise will take at least 5-10 timesmore effort — development and testing — than a normalLotusScript business function
  • 17. 17Decoding SignaturesBold indicates a different memory structure for the same type across platforms. In other words, “Watch out!”
  • 18. 18What We’ll Cover …• Introduction• Architectures• Platform differences• Calling simple Notes C API• Notes C API handles• Custom classes help hide platform differences• Complex Notes C API• Pros and cons• Wrap-up
  • 19. 19Calling a Simple C API Function• Let’s get our feet wet with some simple API No complex sequence of calls handling a shared memoryresource A single call with simple datatypes A call that will not result in client memory corruption should weget it wrong Hopefully• Let’s call it from Windows and ignore other platforms A function that tells you the network latency, in milliseconds,between the current Notes instance and a target server NSFGetServerLatency
  • 20. 20NSFGetServerLatency() — API Reference• We shall call NSFGetServerLatency() This returns the network latency time described in millisecondsfor a call to a remote server• Useful to decide which server is closest in terms ofnetwork response• Its signature from the C API reference is:STATUS LNPUBLIC NSFGetServerLatency(char far *ServerName,DWORD Timeout,DWORD far *retClientToServerMS,DWORD far *retServerToClientMS,WORD far *ServerVersion);
  • 21. 21NSFGetServerLatency() — API Reference (cont.)• From Lotus C API Notes/Domino 7.0 Reference:Input ParametersServerName — Null-terminated string containing the name of theserver to query.Timeout — Number of milliseconds to wait for a reply from the server.A timeout of 0 indicates that the default timeout value is to be used.Output Parameters(routine) — Return status from this call:NOERROR — SuccessretClientToServerMS — Optional — If not NULL, the number ofmilliseconds required to send the request to the server is stored at thisaddress.retServerToClientMS — Optional — If not NULL, the number ofmilliseconds required for the reply to return from the server is stored atthis address.ServerVersion — Optional — If not NULL, the server version (theDomino build number for the server) is stored at this address.
  • 22. 22Simple C API Calling This is a constant for our windows-based Library file:Const LIB_W32 = "nnotes.dll" Declare our function for windowsDeclare Function W32_NSFGetServerLatency _Lib LIB_W32 Alias {NSFGetServerLatency} (_Byval ServerName As Lmbcs String, _Byval Timeout As Long, _retClientToServerMS As Long, _retServerToClientMS As Long, _ServerVersion As Integer) As Integer
  • 23. 23Simple C API Calling: Execution A function to get network latency time...Public Function getServerLatency _(strServer As String) As LongDim nnServer As New NotesName(strServer)Dim ToServer As Long, fromServer As LongDim ver As IntegerDim timeout As Longtimeout = 1000 1000ms == 1 secondCall W32_NSFGetServerLatency(nnServer.Canonical,_timeout, toServer, fromServer, ver) Return both directional latencies added togethergetServerLatency = fromServer + ToServerEnd Function
  • 24. 24Simple C API Calling: Execution (cont.)Sub initialisePrint “Calling function”Print “Latency is: “ + _cstr(getServerLatency(“domino-90.hadsl.com/HADSL/US”))Print “Finished calling”end sub
  • 25. 25Database Handle Class — IntroductionDemo ofGetServerLatency
  • 26. 26• Running the agent “Example1” in the database producesthe following runtime output:• Now, this is not production code! It requires: Error handling Multi-platform supportSimple C API Calling: The Results
  • 27. 27What Can’t You Call?• Callback routines Some Notes C API functions require you to specify mandatorycallback routines — other pieces of C API that will get called bythe target C API routine LotusScript does not (and, IMHO, never will) support this This rules out: Extension Manager routines Menu Addin routines In terms of callback routines that allow you to specify optionalcallbacks (progress status indicators, etc.), you can pass inNULL (or ZERO), and the callback function will be ignored
  • 28. 28What We’ll Cover …• Introduction• Architectures• Platform differences• Calling simple Notes C API• Notes C API handles• Custom classes help hide platform differences• Complex Notes C API• Pros and cons• Wrap-up
  • 29. 29API Handles• A handle is a numeric reference to a structure in memorythat the C API interface has created For example, a handle to a Notes database• You do not deal with the memory structure itself; you dealwith the handle to the memory structure Example: NSFDbOpen() creates a new memory structure andgives you back the handle to that You perform some work using NSFDInfoGet() You close the database using NSFDbClose()
  • 30. 30Some Rules on Handles• There are different types of handles: Document handle, database handle, etc. Do not mix these handles up! Doing so will crash the session/client/server• Always properly close your handles: You have to properly trap all code branches You have to keep track of the handle until you specificallyde-allocate it Not doing so will crash the session/client/server It may not crash immediately It may crash when the session, client, or server closes• You cannot change the value of the handle: Doing so will crash the session/client/server
  • 31. 31Coding Around Handles• Track handles with classes Perform the “open” of the handle on the class constructor Perform the “close” of the handle on the class destructor This means that no matter what happens, the handleoperation will be properly closed — even if this is notspecifically coded in your LotusScript All the code specific to this handle operation is embedded inthe class And can include multi-platform code All the consumer sees is an operation with this specific class
  • 32. 32Handle Summary• If you get a handle, you have to de-allocate it• Only use handle data you know is valid If a handle == NULLHANDLE (or ZERO), then its not a validhandle• Bonus NotesDocument.handle returns the current handle You can easily use LotusScript to: Find a document Use direct calls to update information that the object modeldoes not support (at the moment) e.g., writing Notes replica items
  • 33. 33What We’ll Cover …• Introduction• Architectures• Platform differences• Calling simple Notes C API• Notes C API handles• Custom classes help hide platform differences• Complex Notes C API• Pros and cons• Wrap-up
  • 34. 34Custom Classes Can Help Us Considerably• We can construct classes which “hide” the platformdifferences• Each platform will have its own set of classes• Each code sequence will be small, easily maintainable• We can reuse common code• We can use the custom class constructor and destructorto ensure that resources are properly returned
  • 35. 35Custom Classes: ArchitectureBase ClassObjectHandlerPlatformSpecificObjectHandlersPlatformSpecificObjectHandlersPlatformSpecificObjectHandlersFactoryUser CodeDim F As New APIFactoryClass()Dim dbH As VariantSet dbH = F.getDbHandler()…Hidden Code
  • 36. 36Custom Classes• Our base class carries infrastructure code Logging, string handling, etc.• Our object base class: Defines the functions that we will use Defines the business logic• Our platform-specific classes: Override platform-specific functions with that platform’simplementation• Our factory class: Helps the user of the code find the correct platform-specificclass to use
  • 37. 37Is This Over-Engineered?• At first sight, this looks complex• However, it does allow us to: Keep platform-specific code in well-defined classes Leverage class constructor/destructor calls to ensure handlesare properly managed Perform a simple “Copy+Paste” of the object class to port to anew platform Keep code sequences short and clear Hide the implementation of the code from the consumer ofthe code
  • 38. 38Database Handle Class — IntroductionDemo ofIDRefresh
  • 39. 39What We’ll Cover …• Introduction• Architectures• Platform differences• Calling simple Notes C API• Notes C API handles• Custom classes help hide platform differences• Complex Notes C API• Pros and cons• Wrap-up
  • 40. 40Defining Complex C API• Complex C API is where: More than one function call is required to perform a task And/or A HANDLE of some description is needed to reference adata object
  • 41. 41Complex C API• Where more than one function call is required to performa function it is recommended that: You use defensive coding techniques to understand and make“safe” every single coding branch possible Any handle information used during this sequence is kept safeand its de-allocation specifically catered to You use classes to ensure proper construction and destructionof handle information
  • 42. 42Our Complex Example• Is passed through a server and database path• Opens and gets the DBHANDLE for that database• Extracts the replication flags into a memory structure• Checks to see if the “Disable Replication” flag is on If it is, switches that flag off Saves the replication flags• Finally, closes the DBHANDLE
  • 43. 43We Use Custom Classes To …• Ensure that the DBHANDLE is always properly returned• Insulate the consumer of the code from the platformdifferences• Contain all the platform-specific code in separate classes• Keep it simple!
  • 44. 44Database Handle Class — IntroductionDemo ofDbHandleManager
  • 45. 45What We’ll Cover …• Introduction• Architectures• Platform differences• Calling simple Notes C API• Notes C API handles• Custom classes help hide platform differences• Complex Notes C API• Pros and cons• Wrap-up
  • 46. 46Know Your Battleground• LotusScript coding is: Fairly straightforward Supported Platform-independent• Stepping outside of this comfort zone is going to be hard Take far more time in development and testing Push development resources to the limit Only do this if you have an absolute business need
  • 47. 47LSX vs. Notes C API• You need to establish, based on your requirements,which is the best fit:Feature LSX LotusScript calling Notes C APIDeployment Requires code deployment No deployment requiredMulti-platform Recompile LSX for eachplatformSame code in libraryC API integration Very good integration —supports callbacks, etc.Basic integrationCode difficulty Medium HardStability Extremely stable Stable
  • 48. 48What We’ll Cover …• Introduction• Architectures• Platform differences• Calling simple Notes C API• Notes C API handles• Custom classes help hide platform differences• Complex Notes C API• Pros and cons• Wrap-up
  • 49. 49Resources• Normunds Kalnberzin, LotusScript to Lotus C APIProgramming Guide (November, 2003). The ultimate reference www.ls2capi.com• Tools for Lotus Notes and Domino Lotus Notes API tips www.nsftools.com/tips/APITips.htm• Working application with several Notes C API calls Included on the conference CD
  • 50. 507 Key Points to Take Home• Calling Notes C API is difficult Only use it if absolutely required• It has to be tested on all platforms• It can easily take out a client or server process• Use defensive coding!• Use classes to hide platform differences• It’s the next stage beyond the well-regulatedLotusScript sandbox• It gives you all possible Notes capability
  • 51. 51Your Turn!How to contact me:Bill BuchanBill@hadsl.com