Sunday, May 25, 2008

Code samples: invoking APIs using Visual Basic

I've previously posted sample Java code that demonstrates how to invoke EKP's APIs. Herewith, equivalent code using Visual Basic .NET.

The .NET platform provides a couple of classes for sending HTTP requests, specifically System.Net.HttpWebRequest and System.Net.WebClient. Either will do the job. However, WebClient is a little simpler to work with, so that's what we'll use.

Dim client As Net.WebClient = New Net.WebClient()

API requests must include an HTTP basic authentication header. Fortunately, both WebClient and HttpWebRequest have built-in support for HTTP basic authentication, so this is straightforward. The user name is ignored by EKP; however, we must set the user name to a non-empty value, otherwise WebClient won't send the authentication header. The password must match the value of the authentication.key property configured in the file WEB-INF/conf/ekp.properties.

Dim userName As String = "dummy"    ' any non-empty value is okay
Dim password As String = "mysecretkey"
client.Credentials = New Net.NetworkCredential(userName, password)

To create a user account, we send an HTTP POST request to /ekp/contentHandler/usersCsv, including CSV-formatted data in the body of the request.

Dim data1 As String _
        = "Action,UserID,Password,FamilyName,GivenName" & ControlChars.CrLf _
        & "A,joestudent,dummypass,Student,Joe" & ControlChars.CrLf
client.UploadString("https://ekp.example.com/ekp/contentHandler/usersCsv", _
                    data1)

Similarly, we can enroll the user in a course with ID Derivatives_101 by sending an HTTP POST request to /ekp/enrollmentHandler, again including appropriately-formatted CSV data in the body of the request.

Dim data2 As String = "USERID,LEARNINGID" & ControlChars.CrLf _
                    & "joestudent,Derivatives_101" & ControlChars.CrLf
client.UploadString("https://ekp.example.com/ekp/enrollmentHandler", data2)

No comments: