Monday, May 26, 2008

Code samples: invoking APIs using C#

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

As with modern Visual Basic, C# is a .NET-based language. It's therefore fairly straightforward to translate our previous Visual Basic sample code into C#. As with the Visual Basic code, we will use an instance of System.Net.WebClient to make the API calls.

System.Net.WebClient client = new System.Net.WebClient();

Again, we need to set the credentials that WebClient will use for the HTTP basic authentication process. We must set the user name to a non-empty value to ensure that WebClient sends the authentication header, but the exact value doesn't matter since EKP ignores it. The password must match the value of the authentication.key property configured in the file WEB-INF/conf/ekp.properties.

String userName = "dummy";
String key = "mysecretkey";
client.Credentials = new System.Net.NetworkCredential(userName, key);

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.

String data1 = "Action,UserID,Password,FamilyName,GivenName\r\n"
             + "A,joestudent,dummypass,Student,Joe\r\n";
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.

String data2 = "USERID,LEARNINGID\r\n"
             + "joestudent,Derivatives_101\r\n";
client.UploadString("https://ekp.example.com/ekp/enrollmentHandler", data2);

No comments: