Skip to content

Instantly share code, notes, and snippets.

@aholmes
Last active January 3, 2016 17:59
Show Gist options
  • Save aholmes/8498953 to your computer and use it in GitHub Desktop.
Save aholmes/8498953 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace aaronholmes.net.Services
{
public class GitHub
{
private String apiUrl = "https://api.github.com:443";
private String ClientName = "...";
private String GitHubAPIVersion = "application/vnd.github.v3.raw+json";
public String username { get; set; }
public String password { get; set; }
public String authUsername = "...";
public String authPassword = "...";
private void initHeaders(HttpWebRequest httpWebRequest)
{
httpWebRequest.Accept = GitHubAPIVersion;
httpWebRequest.UserAgent = ClientName;
httpWebRequest.Method = "GET";
}
private void authenticate(HttpWebRequest httpWebRequest)
{
NetworkCredential cred = new NetworkCredential(authUsername, authPassword);
CredentialCache credsCache = new CredentialCache();
credsCache.Add(new Uri(apiUrl), "Basic", cred);
httpWebRequest.Credentials = credsCache;
}
private async Task<String> doWebRequestAsync(String uri)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(apiUrl + uri);
initHeaders(httpWebRequest);
authenticate(httpWebRequest);
WebResponse webResponse = null;
try
{
webResponse = await httpWebRequest.GetResponseAsync();
return await getResponseBodyAsync(webResponse);
}
catch (WebException e)
{
throw new GitHubWebException(getResponseBody(e.Response), e);
}
finally
{
if (webResponse != null) webResponse.Dispose();
}
}
private async Task<string> getResponseBodyAsync(WebResponse webResponse)
{
StreamReader streamReader = null;
try
{
streamReader = new StreamReader(webResponse.GetResponseStream());
return await streamReader.ReadToEndAsync();
}
finally
{
if (streamReader != null) streamReader.Dispose();
}
}
public async Task<String> getUserAsync()
{
return await doWebRequestAsync("/users/" + username);
}
public async Task<String> getUserRepositoriesAsync()
{
return await doWebRequestAsync("/users/" + username + "/repos");
}
public async Task<String> getRepositoryAsync(String repository)
{
return await doWebRequestAsync("/repos/" + username + "/" + repository);
}
public async Task<String> getRepositoryPathAsync(String repository, String path)
{
return await doWebRequestAsync("/repos/" + username + "/" + repository + "/contents/" + path.TrimStart('/'));
}
}
[Serializable]
public class GitHubWebException : ApplicationException
{
private int _HTTPStatusCode = 0;
public String APIErrorMessage { get; set; }
public int HTTPStatusCode
{
get
{
if (this._HTTPStatusCode != 0) return this._HTTPStatusCode;
var innerException = this.InnerException as WebException;
if (innerException.Status == WebExceptionStatus.ProtocolError)
{
HttpWebResponse response = innerException.Response as HttpWebResponse;
if (response != null)
{
this._HTTPStatusCode = (int)response.StatusCode;
}
}
return this._HTTPStatusCode;
}
}
protected GitHubWebException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
if (info != null)
{
this.APIErrorMessage = info.GetString("APIErrorMessage");
}
}
public GitHubWebException()
{
this.APIErrorMessage = "Unknown error from GitHub web API.";
}
public GitHubWebException(string message)
{
this.APIErrorMessage = JsonConvert.DeserializeObject<GitHubWebError>(message).message;
}
public GitHubWebException(string message, Exception innerException)
: base(message, innerException)
{
this.APIErrorMessage = JsonConvert.DeserializeObject<GitHubWebError>(message).message;
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
if (info != null)
{
info.AddValue("APIErrorMessage", this.APIErrorMessage);
}
}
}
public class GitHubWebError
{
public string message { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment