Reputation: 129
I'm trying to upload files along with posting some message to Yammer. Posting messages works (all the authorization stuff etc. is ok). The problem appears when I want to attach a file. I tried to follow the code from here: Yammer.Net
But I'm afraided I'm missing some parts (could not reference the entire project, somehow my Visual Studio has problems with it).
That's why I tried to follow the traditional way of specifying the request parameters. Below I put my method:
public bool postMessage(string body, string attachement)
{
var url = "https://www.yammer.com/api/v1/messages.json";
NameValueCollection parameters = new NameValueCollection();
parameters.Add("body", body);
parameters.Add("group_id", group_id);
var authzHeader = oauth.GenerateAuthzHeader(url, "POST");
//new request
var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
request.Headers.Add("Authorization", authzHeader);
request.Method = "POST";
//content type settings
request.ContentType = "multipart/form-data";
request.KeepAlive = true;
//Proxy settings
request.Proxy = new System.Net.WebProxy("my company's proxy", true);
request.Proxy.Credentials = new System.Net.NetworkCredential(user, password);
//prepare the parameters
FileInfo fi = new FileInfo(attachement);
int i = 0;
long postDataSize = fi.Length;
parameters.Add("attachment", "attachment1");
parameters.Add("file", Path.GetFileName(attachement));
int count = 0;
string wdata = string.Empty;
foreach (string key in parameters.Keys)
{
if (count == 0)
{
wdata = key + "=" + oauth.encode(parameters[key]);
}
else
{
wdata += "&" + key + "=" + oauth.encode(parameters[key]);
}
count++;
}
//add the parameters
byte[] postDataBytes = Encoding.ASCII.GetBytes(wdata);
request.ContentLength = postDataBytes.Length + postDataSize;
Stream reqStream = request.GetRequestStream();
reqStream.Write(postDataBytes, 0, postDataBytes.Length);
//write the file
//postDataBytes = Encoding.ASCII.GetBytes(fileHeader);
//reqStream.Write(postDataBytes, 0, postDataBytes.Length);
int bufferSize = 10240;
FileStream readIn = new FileStream(attachement, FileMode.Open, FileAccess.Read);
readIn.Seek(0, SeekOrigin.Begin); // move to the start of the file
byte[] fileData = new byte[bufferSize];
int bytes;
while ((bytes = readIn.Read(fileData, 0, bufferSize)) > 0)
{
// read the file data and send a chunk at a time
reqStream.Write(fileData, 0, bytes);
}
readIn.Close();
reqStream.Close();
using (var response = (System.Net.HttpWebResponse)request.GetResponse())
{
using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
{
string resp = reader.ReadToEnd();
return true;
}
}
}
The code may seem a bit chaotic, but I hope you get the idea. The main problem is:
Does anyone know how to upload files to Yammer, using the API? Peferrably in .NET :)
Upvotes: 1
Views: 4641
Reputation: 628
It is possible to POST binary content to the Yammer messages.json REST endpoint using a MultipartFormDataContent type.
A working example posting a number of images, text and tags:
WebProxy proxy = new WebProxy()
{
UseDefaultCredentials = true,
};
HttpClientHandler httpClientHandler = new HttpClientHandler()
{
Proxy = proxy,
};
using (var client = new HttpClient(httpClientHandler))
{
using (var multipartFormDataContent = new MultipartFormDataContent())
{
string body = "Text body of message";
var values = new[]
{
new KeyValuePair<string, string>("body", body),
new KeyValuePair<string, string>("group_id", YammerGroupID),
new KeyValuePair<string, string>("topic1", "Topic ABC"),
};
foreach (var keyValuePair in values)
{
multipartFormDataContent.Add(new StringContent(keyValuePair.Value), String.Format("\"{0}\"", keyValuePair.Key));
}
int i = 1;
foreach (Picture p in PictureList)
{
var FileName = string.Format("{0}.{1}", p.PictureID.ToString("00000000"), "jpg");
var FilePath = Server.MapPath(string.Format("~/images/{0}", FileName));
if (System.IO.File.Exists(FilePath))
{
multipartFormDataContent.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(FilePath)), '"' + "attachment" + i.ToString() + '"', '"' + FileName + '"');
i++;
}
}
var requestUri = "https://www.yammer.com/api/v1/messages.json";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
var result = client.PostAsync(requestUri, multipartFormDataContent).Result;
}
}
Upvotes: 2