Created
March 13, 2014 23:16
-
-
Save brianly/9539171 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 class PostFile | |
{ | |
public T Post<T>(string path, string text, List<Attachment> attachments) | |
{ | |
using (var restClient = new RestClient()) | |
using (var content = new MultipartFormDataContent()) | |
{ | |
// Message part | |
var messageContent = new StringContent(text); | |
var messageDispositionValue = new ContentDispositionHeaderValue("form-data") | |
{ | |
Name = "\"body\"" | |
}; | |
messageContent.Headers.ContentDisposition = messageDispositionValue; | |
content.Add(messageContent); | |
// File attachment part | |
int index = 1; | |
foreach (var attachment in attachments) | |
{ | |
var byteContent = new ByteArrayContent(attachment.ContentBytes); | |
byteContent.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml"); | |
var name = string.Format("attachment{0}", index); | |
var imageDispositionValue = new ContentDispositionHeaderValue("form-data") | |
{ | |
Name = string.Format("\"{0}\"", name), | |
FileName = string.Format("\"{0}\"", attachment.FileName) | |
}; | |
byteContent.Headers.ContentDisposition = imageDispositionValue; | |
content.Add(byteContent); | |
index++; | |
} | |
var postMessage = restClient.CreateMessage(BuildUrl(path), HttpMethod.Post, _accessToken, content); | |
var task = restClient.SendAsync(postMessage); | |
return restClient.ProcessResult<T>(task); | |
} | |
} | |
} | |
public class RestClient : HttpClient | |
{ | |
public RestClient() | |
{ | |
SetUserAgent("YammerApiClient (www.brianlyttle.com)"); | |
} | |
/// <summary> | |
/// Sets a custom user agent for all requests sent by the client. | |
/// </summary> | |
/// <param name="userAgent">String containing the user agent.</param> | |
public void SetUserAgent(string userAgent) | |
{ | |
if (userAgent == null) | |
throw new ArgumentNullException("userAgent"); | |
DefaultRequestHeaders.Add("User-Agent", userAgent); | |
} | |
/// <summary> | |
/// Returns an HTTP message without content. | |
/// </summary> | |
/// <param name="address">Complete URL for service</param> | |
/// <param name="method">HTTP method</param> | |
/// <param name="token">OAuth token</param> | |
/// <returns>HttpRequestMessage</returns> | |
public HttpRequestMessage CreateMessage(Uri address, HttpMethod method, string token) | |
{ | |
if (token == null) throw new InvalidTokenException("token"); | |
var message = new HttpRequestMessage | |
{ | |
RequestUri = address, | |
Method = method | |
}; | |
message.Headers.Add("Authorization", string.Format("Bearer {0}", token)); | |
return message; | |
} | |
/// <summary> | |
/// Returns an HTTP message with content. | |
/// </summary> | |
/// <param name="address">Complete URL for service</param> | |
/// <param name="method">HTTP method</param> | |
/// <param name="token">OAuth token</param> | |
/// <param name="content">Content</param> | |
/// <returns>HttpRequestMessage</returns> | |
public HttpRequestMessage CreateMessage(Uri address, HttpMethod method, string token, HttpContent content) | |
{ | |
if (token == null) throw new InvalidTokenException("token"); | |
var message = new HttpRequestMessage | |
{ | |
RequestUri = address, | |
Method = method, | |
Content = content | |
}; | |
message.Headers.Add("Authorization", string.Format("Bearer {0}", token)); | |
return message; | |
} | |
public HttpRequestMessage CreateMessage(Uri address, HttpMethod method, string token, MultipartFormDataContent content) | |
{ | |
if (token == null) throw new InvalidTokenException("token"); | |
var message = new HttpRequestMessage | |
{ | |
RequestUri = address, | |
Method = method, | |
Content = content | |
}; | |
message.Headers.Add("Authorization", string.Format("Bearer {0}", token)); | |
return message; | |
} | |
/// <summary> | |
/// Deserializes a response from a service. | |
/// </summary> | |
/// <typeparam name="T">Type of expected JSON response</typeparam> | |
/// <param name="task">Task holding the HttpResponseMessage</param> | |
/// <returns>Type of expected JSON response</returns> | |
public T ProcessResult<T>(Task<HttpResponseMessage> task) | |
{ | |
if (task == null) throw new ArgumentNullException("task"); | |
// Throw exception on request failure | |
task.Result.EnsureSuccessStatusCode(); | |
// Deserialize if we have a result | |
return JsonConvert.DeserializeObject<T>(task.Result.Content.ReadAsStringAsync().Result); | |
} | |
/// <summary> | |
/// Converts a list of parameters to a query string (sans URL encoding). | |
/// </summary> | |
/// <param name="parameters">IEnumerable of KeyValuePair</param> | |
/// <returns>string</returns> | |
public string FormatUrlParameters(IEnumerable<KeyValuePair<string, string>> parameters) | |
{ | |
if (parameters == null) return ""; | |
var sb = new StringBuilder("?"); | |
foreach (var keyValuePair in parameters) | |
{ | |
sb.AppendFormat("{0}={1}&", keyValuePair.Key, keyValuePair.Value); | |
} | |
return sb.ToString(); | |
} | |
} | |
public class Attachment | |
{ | |
public string FileName { get; set; } | |
public byte[] ContentBytes { get; set; } | |
public Attachment(string name, byte[] content) | |
{ | |
FileName = name; | |
ContentBytes = content; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment