Skip to content

Instantly share code, notes, and snippets.

@jeffrydegrande
Created May 20, 2012 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffrydegrande/2759216 to your computer and use it in GitHub Desktop.
Save jeffrydegrande/2759216 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public class Event
{
private DateTime date;
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("summary")]
public string Summary { get; set; }
[JsonProperty("diocese")]
public string Diocese { get; set; }
[JsonProperty("parish")]
public string Parish { get; set; }
[JsonProperty("date")]
public DateTime Date {
get {
return this.date;
}
set {
this.date = value.ToUniversalTime();
}
}
public static Event FromJson(string json)
{
return JsonConvert.DeserializeObject<Dictionary<string, Event>>(json)["event"];
}
public static List<Event> ListFromJson(string json)
{
var parsedJson = JsonConvert.DeserializeObject<List<Dictionary<string, Event>>>(json);
return ListFromJson(parsedJson);
}
private static List<Event> ListFromJson(IEnumerable<Dictionary<string, Event>> eventsFromJson)
{
List<Event> events = new List<Event>();
foreach (Dictionary<string, Event> e in eventsFromJson)
{
events.Add(e["event"]);
}
return events;
}
public String ToJsonString()
{
Dictionary<string, Event> aHash = new Dictionary<string, Event>();
aHash["event"] = this;
return JsonConvert.SerializeObject(aHash, new IsoDateTimeConverter());
}
public override String ToString()
{
return this.Name;
}
}
// exemplo de como user
HTTP http = new HTTP();
http.Host = "http://blahblah.heroku.com";
http.Username = "test@example.com";
http.Password = "blaah";
Event anEvent = new Event(whatever);
bool success = http.Post(anEvent);
// e por ai vai
using System;
using System.Net;
using System.IO;
using System.Text;
public class HTTP
{
public string Host { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public HttpStatusCode StatusCode { get; private set; }
public string Body { get; private set; }
public HTTP()
{
this.Body = String.Empty;
this.Username = String.Empty;
this.Password = String.Empty;
}
public HTTP(string host) : this()
{
Host = host;
}
public HTTP(string host, string username, string password)
: this(host)
{
Username = username;
Password = password;
}
public bool Get(string url)
{
HttpWebRequest request = NewRequest(url);
request.Method = "GET";
return Execute(request);
}
public bool Post(Event anEvent)
{
string url = String.Format("{0}/admin/events.json", Host);
string json = anEvent.ToJsonString();
return Post(url, json);
}
public bool Post(string url, string data)
{
if (Host == null)
return false;
HttpWebRequest request = NewRequest(url);
request.Method = "POST";
WritePostData(data, request);
return Execute(request);
}
private bool Execute(WebRequest request)
{
HttpWebResponse response = ExecuteRequest(request);
UpdateWithResponse(response);
return Success();
}
private static HttpWebResponse ExecuteRequest(WebRequest request)
{
HttpWebResponse response;
try {
response = (HttpWebResponse)request.GetResponse();
} catch (System.Net.WebException e) {
if (e.Status == WebExceptionStatus.ProtocolError) {
response = (HttpWebResponse)e.Response;
} else {
throw;
}
}
return response;
}
public bool Success()
{
return (StatusCode == HttpStatusCode.OK || StatusCode == HttpStatusCode.Created);
}
private static void WritePostData(string data, HttpWebRequest request)
{
Stream writeStream = request.GetRequestStream();
byte[] bytes = Encoding.UTF8.GetBytes(data);
writeStream.Write(bytes, 0, bytes.Length);
writeStream.Close();
}
private HttpWebRequest NewRequest(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
AuthenticateWithCredentials(request);
request.ContentType = "application/json; charset=utf-8";
return request;
}
private void UpdateWithResponse(HttpWebResponse response)
{
StatusCode = response.StatusCode;
Body = ExtractBodyFromResponse(response);
}
private string ExtractBodyFromResponse(HttpWebResponse response)
{
Stream responseStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8);
return readStream.ReadToEnd();
}
private void AuthenticateWithCredentials(WebRequest request)
{
if (CredentialsWereProvided())
{
CreateAndCacheNetworkCredentialsFromUsernameAndPassword(request);
AddAuthorizationHeadersToRequest(request);
}
}
private bool CredentialsWereProvided()
{
return (Username != string.Empty && Password != string.Empty);
}
private void CreateAndCacheNetworkCredentialsFromUsernameAndPassword(WebRequest request)
{
CredentialCache mycache = new CredentialCache();
mycache.Add(request.RequestUri, "Basic", new NetworkCredential(Username, Password));
request.Credentials = mycache;
}
private void AddAuthorizationHeadersToRequest(WebRequest request)
{
string usernamePassword = Username + ":" + Password;
string base64EncodedString = Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword));
request.Headers.Add("Authorization", "Basic " + base64EncodedString);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment