Created
August 17, 2010 13:18
-
-
Save bsatrom/529888 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int userId = StackOverflowApiHelper.GetUserId("satrom"); | |
Assert.AreEqual(380135, userId); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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