Thursday, September 20, 2012

VB.NET Code Snippet: Pardot Login

Sometimes it is hard to appreciate the degree to which the development world has changed over the last ten years or so, especially when one is surrounded by it on a daily basis.

Anyway, I was recently reminded of it while working on a project involving Pardot, the popular online marketing service provider. In past years, finding .NET based code snippets -- or examples -- demonstrating the process of interacting with the application programming interface (API) for such a service would have been relatively easy. The development world, however, has long moved past that and .NET is no longer considered the dominant player it once was. As a result, snippets of the type I referenced earlier have tended to become a bit more scarce.

But there are still a number of .NET users like myself out there, and here is a code snippet I wanted to share which I think others might find helpful. This VB.NET snippet demonstrates the manner in which we can login to the Pardot API. 

Dim sResults As String

'Email address used to login to Pardot         
Dim sPardotEmail As String = ""
'Corresponding password for login 
Dim sPardotPwd As String = "my_pardot_password" 
'Obtained from user settings page in Pardot -- user specific
Dim sPardotUserKey As String = "pardot user key" 

Dim sURL As String = ""
Dim sMsg As String = "email=" & sPardotEmail & "&password=" & sPardotPwd & "&user_key=" & sPardotUserKey
Dim wrRequest As System.Net.WebRequest = System.Net.WebRequest.Create(sURL)

Dim byteArray As Byte() = Encoding.UTF8.GetBytes(sMsg)

wrRequest.Method = "POST"
wrRequest.ContentType = "application/x-www-form-urlencoded"
wrRequest.ContentLength = byteArray.Length

'Post it to Pardot!
Dim dataStream As System.IO.Stream = wrRequest.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)

'Get the response from Pardot
Dim wrResponse As System.Net.WebResponse = wrRequest.GetResponse()
dataStream = wrResponse.GetResponseStream()
Dim dataReader As New System.IO.StreamReader(dataStream)

'Response is an XML document containing the Pardot API key
sResults = dataReader.ReadToEnd() 


Your first step when integrating with Pardot should always be to login, as that process provides the Pardot API key that in turn is used in subsequent API calls.

If you have some useful tips for Pardot API integration and .NET, please share in the comments. Thanks in advance.