Skip to content

Instantly share code, notes, and snippets.

@odalet
Created August 15, 2010 16:08
Show Gist options
  • Save odalet/525637 to your computer and use it in GitHub Desktop.
Save odalet/525637 to your computer and use it in GitHub Desktop.
Ohloh API Java sample translated to C#, F# and VB.NET
/*
This is an example of using the Ohloh API from C#.
Detailed information can be found at the Ohloh website:
http://www.ohloh.net/api
This example retrieves an account and simply shows the name associated.
Pass your Ohloh API key as the first parameter to this example.
Ohloh API keys are free. If you do not have one, you can obtain one
at the Ohloh website:
http://www.ohloh.net/api_keys/new
Pass the email address of the account as the second parameter to this script.
*/
using System;
using System.Net;
using System.Xml;
using System.Text;
using System.Security.Cryptography;
namespace ApiExampleCs
{
internal class ApiExample
{
private static readonly char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private static void Usage()
{
Console.Out.WriteLine("Usage:");
Console.Out.WriteLine("ApiExampleCs [api_key] [user_email]");
}
public ApiExample(string apiKey, string userEmail)
{
Initiate(apiKey, userEmail);
}
private void Initiate(string apiKey, string userEmail)
{
Console.Out.WriteLine("Initializing request.");
// Calculate MD5 digest from the email address.
string emailDigest = CalculateDigest(userEmail);
try
{
Uri uri = new Uri("http://www.ohloh.net/accounts/" + emailDigest + ".xml?api_key=" + apiKey + "&v=1");
string response = string.Empty;
using (WebClient client = new WebClient())
{
response = client.DownloadString(uri);
// Check for status OK.
if (client.ResponseHeaders["Status"].StartsWith("200"))
Console.Out.WriteLine("Request succeeded.");
else
{
Console.Out.WriteLine("Request failed. Possibly wrong API key?");
return;
}
}
// Create a document from the URL's input stream, and parse.
XmlDocument doc = new XmlDocument();
doc.LoadXml(response);
XmlNodeList responseNodes = doc.GetElementsByTagName("response");
for (int i = 0; i < responseNodes.Count; i++)
{
XmlElement element = (XmlElement)responseNodes[i];
// First check for the status code inside the XML file. It is
// most likely, though, that if the request would have failed,
// it has already returned earlier.
XmlNodeList statusList = element.GetElementsByTagName("status");
if (statusList.Count == 1)
{
XmlNode statusNode = statusList[0];
// Check if the text inidicates that the request was
// successful.
if (statusNode.InnerText != "success")
{
Console.Out.WriteLine("Failed. " + statusNode.InnerText);
return;
}
}
XmlElement resultElement = (XmlElement)element.GetElementsByTagName("result")[0];
// We assume we only have one account result here.
XmlElement accountElement = (XmlElement)resultElement.GetElementsByTagName("account")[0];
if (accountElement != null)
{
// Lookup name.
string realName = accountElement.GetElementsByTagName("name")[0].InnerText;
Console.Out.WriteLine("Located the real name: " + realName);
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
}
}
private string CalculateDigest(string email)
{
return HexStringFromBytes(CalculateHash(Encoding.Default.GetBytes(email)));
}
private byte[] CalculateHash(byte[] dataToHash)
{
try
{
// Calculate MD5 digest.
return MD5.Create().ComputeHash(dataToHash);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
}
return null;
}
private string HexStringFromBytes(byte[] b)
{
// Conversion from bytes to string.
string hex = "";
int msb;
int lsb = 0;
for (int i = 0; i < b.Length; i++)
{
msb = ((int)b[i] & 0x000000FF) / 16;
lsb = ((int)b[i] & 0x000000FF) % 16;
hex = hex + hexChars[msb] + hexChars[lsb];
}
return hex;
}
private static void Main(string[] args)
{
if (args.Length == 2)
{
// Simply pass arguments.
new ApiExample(args[0], args[1]);
}
else
{
// Show usage information.
Usage();
}
}
}
}
(*
This is an example of using the Ohloh API from F#.
Detailed information can be found at the Ohloh website:
http://www.ohloh.net/api
This example retrieves an account and simply shows the name associated.
Pass your Ohloh API key as the first parameter to this example.
Ohloh API keys are free. If you do not have one, you can obtain one
at the Ohloh website:
http://www.ohloh.net/api_keys/new
Pass the email address of the account as the second parameter to this script.
*)
open System
open System.Net
open System.Xml
open System.Text
open System.Security.Cryptography
let Initiate apiKey userEmail =
let CalculateDigest (email:string) =
let CalculateHash (dataToHash:byte[]) =
try
MD5.Create().ComputeHash dataToHash
with ex ->
printfn "%A" ex
null
let HexStringFromBytes (b:byte[]) =
let hexChars = [| '0'; '1'; '2'; '3'; '4'; '5'; '6'; '7'; '8'; '9'; 'a'; 'b'; 'c'; 'd'; 'e'; 'f' |]
let mutable hex:string = ""
for i=0 to b.Length - 1 do
let msb = (int b.[i] &&& 0x000000FF) / 16
let lsb = (int b.[i] &&& 0x000000FF) % 16
hex <- hex + string hexChars.[msb] + string hexChars.[lsb]
hex
Encoding.Default.GetBytes email |> CalculateHash |> HexStringFromBytes
printfn "Initializing request."
// Calculate MD5 digest from the email address.
let emailDigest = CalculateDigest userEmail
try
let uri = new Uri("http://www.ohloh.net/accounts/" + emailDigest + ".xml?api_key=" + apiKey + "&v=1")
let client = new WebClient()
let response = client.DownloadString uri
// Check for status OK.
if client.ResponseHeaders.["Status"].StartsWith("200") then
printfn "Request succeeded."
else
printfn "Request failed. Possibly wrong API key?"
()
// Create a document from the URL's input stream, and parse.
let doc = new XmlDocument()
doc.LoadXml response
let responseNodes = doc.GetElementsByTagName "response"
for i = 0 to responseNodes.Count - 1 do
let element = responseNodes.[i] :?> XmlElement
// First check for the status code inside the XML file. It is
// most likely, though, that if the request would have failed,
// it has already returned earlier.
let statusList = element.GetElementsByTagName "status"
if statusList.Count = 1 then
let statusNode = statusList.[0]
// Check if the text inidicates that the request was
// successful.
if statusNode.InnerText <> "success" then
printfn "Failed. %s" statusNode.InnerText
()
let resultElement = element.GetElementsByTagName("result").[0] :?> XmlElement
// We assume we only have one account result here.
let accountElement = resultElement.GetElementsByTagName("account").[0] :?> XmlElement
if accountElement <> null then
// Lookup name.
let realName = accountElement.GetElementsByTagName("name").[0].InnerText
printfn "Located the real name: %s" realName
with ex -> printfn "%A" ex
[<EntryPointAttribute>]
let main args =
if args.Length = 2 then
Initiate args.[0] args.[1]
else
printfn "Usage:"
printfn "ApiExampleFs [api_key] [user_email]"
0
' This is an example of using the Ohloh API from VB.Net.
' Detailed information can be found at the Ohloh website:
' http://www.ohloh.net/api
' This example retrieves an account and simply shows the name associated.
' Pass your Ohloh API key as the first parameter to this example.
' Ohloh API keys are free. If you do not have one, you can obtain one
' at the Ohloh website:
' http://www.ohloh.net/api_keys/new
' Pass the email address of the account as the second parameter to this script.
Option Strict On
Option Explicit On
Option Compare Binary
Imports System
Imports System.Net
Imports System.Xml
Imports System.Text
Imports System.Security.Cryptography
Friend Class ApiExample
Private Shared ReadOnly hexChars As Char()
Private Shared Sub Usage()
Console.Out.WriteLine("Usage:")
Console.Out.WriteLine("ApiExampleVb [api_key] [user_email]")
End Sub
Shared Sub New()
hexChars = New Char() {"0"c, "1"c, "2"c, "3"c, "4"c, "5"c, "6"c, "7"c, "8"c, "9"c, "a"c, "b"c, "c"c, "d"c, "e"c, "f"c}
End Sub
Public Sub New(ByVal apiKey As String, ByVal userEmail As String)
Initiate(apiKey, userEmail)
End Sub
Private Sub Initiate(ByVal apiKey As String, ByVal userEmail As String)
Console.Out.WriteLine("Initializing request.")
' Calculate MD5 digest from the email address.
Dim emailDigest As String = CalculateDigest(userEmail)
Try
Dim uri As New Uri("http://www.ohloh.net/accounts/" & emailDigest & ".xml?api_key=" & apiKey & "&v=1")
Dim response As String = String.Empty
Using client As WebClient = New WebClient
response = client.DownloadString(uri)
' Check for status OK.
If client.ResponseHeaders("Status").StartsWith("200") Then
Console.Out.WriteLine("Request succeeded.")
Else
Console.Out.WriteLine("Request failed. Possibly wrong API key?")
Return
End If
End Using
' Create a document from the URL's input stream, and parse.
Dim doc As New XmlDocument
doc.LoadXml(response)
Dim responseNodes As XmlNodeList = doc.GetElementsByTagName("response")
Dim i As Integer
For i = 0 To responseNodes.Count - 1
Dim element As XmlElement = DirectCast(responseNodes(i), XmlElement)
' First check for the status code inside the XML file. It is
' most likely, though, that if the request would have failed,
' it has already returned earlier.
Dim statusList As XmlNodeList = element.GetElementsByTagName("status")
If (statusList.Count = 1) Then
Dim node As XmlNode = statusList(0)
' Check if the text inidicates that the request was
' successful.
If (node.InnerText <> "success") Then
Console.Out.WriteLine(("Failed. " & node.InnerText))
Return
End If
End If
Dim resultElement As XmlElement = DirectCast(element.GetElementsByTagName("result")(0), XmlElement)
Dim accountElement As XmlElement = DirectCast(resultElement.GetElementsByTagName("account")(0), XmlElement)
If (Not accountElement Is Nothing) Then
' Lookup name.
Dim realName As String = accountElement.GetElementsByTagName("name")(0).InnerText
Console.Out.WriteLine(("Located the real name: " & realName))
End If
Next i
Catch ex As Exception
Console.Error.WriteLine(ex.ToString)
End Try
End Sub
Private Function CalculateDigest(ByVal email As String) As String
Return HexStringFromBytes(Me.CalculateHash(Encoding.Default.GetBytes(email)))
End Function
Private Function CalculateHash(ByVal dataToHash As Byte()) As Byte()
Try
' Calculate MD5 digest.
Return MD5.Create.ComputeHash(dataToHash)
Catch ex As Exception
Console.Error.WriteLine(ex.ToString)
End Try
Return Nothing
End Function
Private Function HexStringFromBytes(ByVal b As Byte()) As String
' Conversion from bytes to String.
Dim hex As String = ""
Dim msb As Integer
Dim lsb As Integer = 0
'Dim index As Integer = 0
Dim i As Integer
For i = 0 To b.Length - 1
msb = (CInt(b(i)) And &HFF) \ 16
lsb = (CInt(b(i)) And &HFF) Mod 16
hex = hex & ApiExample.hexChars(msb) & ApiExample.hexChars(lsb)
Next i
Return hex
End Function
Public Shared Sub Main(ByVal args As String())
If (args.Length = 2) Then
Dim foo As New ApiExample(args(0), args(1))
Else
Usage()
End If
End Sub
End Class
@odalet
Copy link
Author

odalet commented Aug 15, 2010

Translated from java

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment