Skip to content

Instantly share code, notes, and snippets.

@bsatrom
Created August 17, 2010 13:18
Show Gist options
  • Save bsatrom/529888 to your computer and use it in GitHub Desktop.
Save bsatrom/529888 to your computer and use it in GitHub Desktop.
int userId = StackOverflowApiHelper.GetUserId("satrom");
Assert.AreEqual(380135, userId);
public static class StackOverflowApiHelper
{
private const string DefaultUserId = "22656"; //Jon Skeet
public static string GetUserId(string username)
{
var apiEndpoint = string.Format("http://stack2xml.quickmediasolutions.com/stackoverflow/users?filter={0}", username);
var webRequest = WebRequest.Create(apiEndpoint) as HttpWebRequest;
var webResponse = webRequest.GetResponse() as HttpWebResponse;
if (webResponse != null)
{
string userDataStream;
using (var userStream = new StreamReader(webResponse.GetResponseStream()))
{
userDataStream = userStream.ReadToEnd();
}
return GetUserIdFromXmlResult(userDataStream);
}
return DefaultUserId;
}
private static string GetUserIdFromXmlResult(string userString)
{
XElement userXml = XElement.Parse(userString);
var users = userXml.Descendants("users").ToList();
if (users[0] != null)
return users[0].Element("user").Element("user_id").Value;
return DefaultUserId;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment