Streamsend API with C# - c#

I cannot seem to get this code to work with Streamsends API. I have been all over the internet and have found very little info pertaining to what I am trying to do. I am trying to upload a file to their server. Can anyone look at this and maybe help me out here?
I keep getting a 500 error from Streamsends servers which they say is within the Streamsend application itself. What is funny is if I take the line near the bottom that is commented out
(//request.ContentType = "multipart/form-data";)
and uncomment it I get a 422 error which is saying invalid data. It seems like there is something wrong with the boundary.
I am fairly new to C# and this is the first time I have worked with Streamsends API so any help would be greatly appreciated.
m_Method = "POST"
m_Action = "uploads"
private string StreamSendResponse(string Path, string FileName)
{
string sReturn = String.Empty;
string sLocation = String.Empty;
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.ASCII.GetBytes(Environment.NewLine + "--" + boundary + Environment.NewLine);
Uri addy = new Uri(m_URI + m_Action);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(addy);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = m_Method;
request.KeepAlive = true;
request.Headers.Add("Authorization", "Basic " + Merv.base64Encode(m_ID + ":" + m_Key));
Stream rs = request.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n{1}";
NameValueCollection nvc = new NameValueCollection();
foreach (string key in nvc.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n";
string header = string.Format(headerTemplate, "data", FileName);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(Path + FileName, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes(Environment.NewLine + "--" + boundary + "--" + Environment.NewLine);
rs.Write(trailer, 0, trailer.Length);
rs.Close();
request.Accept = "application/xml";
//request.ContentType = "multipart/form-data";
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader srResponse = new StreamReader(response.GetResponseStream());
sLocation = response.Headers["Location"];
sReturn = srResponse.ReadToEnd().Trim();
}
catch (WebException exc)
{
StreamReader srResponse = new StreamReader(response.GetResponseStream());
sReturn = srResponse.ReadToEnd().Trim();
sLocation = exc.Message;
}
if (sReturn == String.Empty)
{
sReturn = sLocation;
}
return sReturn;
}

Related

Http Post file to server from Windows Forms

I'm making a Windows Application that need to make a HTTP post to my Server. In my .NET MVC application i use this code:
Html.BeginForm("Index","UploadData",
FormMethod.Post,
new { enctype = "multipart/form-data", #class = "contact-form", id = "frmUploadData" })
My question is how do i post a File from my computer to the server from a windows forms application?
I have tried to use, this method, but i am not sure how to call it correctly:
public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
{
Console.WriteLine(string.Format("Uploading {0} to {1}", file, url));
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream rs = wr.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, paramName, file, contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
Console.WriteLine(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));
}
catch (Exception ex)
{
Console.WriteLine("Error uploading file", ex);
if (wresp != null)
{
wresp.Close();
wresp = null;
}
}
finally
{
wr = null;
}
}
Not sure if i am calling it correctly, i get a 404 error when i try to call this method:
public static void OnChanged(object sender, FileSystemEventArgs e)
{
NameValueCollection nvc = new NameValueCollection();
nvc.Add("id", "frmUploadData");
HttpUploadFile("http://classicraider.com/UploadData",
#e.FullPath, "file", "lua", nvc);
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}

sending named Mulitpart Data wit HttpClient

I try to Send Multipart Content as a Post to an WebService using c# HttpClient
My Code is the Following
public string UploadDocument(Stream stream)
{
MultipartContent multipart = new MultipartContent();
//multipart.Add(new StreamContent(stream), "importFile");
StreamContent content = new StreamContent(stream);
multipart.Add(content);
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = Client.PostAsync("URL to webservice", multipart).Result;
string result = response.Content.ReadAsStringAsync().Result;
//Wirft eine Exception wenn der StatusCode nicht 200 (OK) ist.
response.EnsureSuccessStatusCode();
return result;
}
I Need the Stream Content to be named, how can i do it.
I found a Java Way to do it, but in C# I don't find a Parameter "Name"
Here the Java Example (see "importFile")
httpRequest = new HttpPostwebviewer/?action=import");
// set headers
httpRequest.setHeader(HEADER_NAME_ACCEPT, "application/json");
// prepare upload entity
MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
meBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
meBuilder.setCharset(Consts.UTF_8);
meBuilder.addPart("importFile", contentBody);
// build upload entity
HttpEntity uploadEntity = meBuilder.build();
// set properties to http request
((HttpPost) httpRequest).setEntity(uploadEntity);
You can use System.Net.HttpWebRequest to do the same, Below is the code that I am using:
public static void UploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
url = handlerLocation + url;
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream rs = wr.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, paramName, file, contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
}
catch (Exception ex)
{
//WriteTrace(ex.Message);
if (wresp != null)
{
wresp.Close();
wresp = null;
}
}
finally
{
wr = null;
}
}

How to get transient document id using adobe echosign api?

This is my C#.net code. When I create transient document id then I send document for signature then I receive it blank file. I think transient document id create for blank file. Could you help for it?
public getDocumentId getTransientDocumentId(string accessToken, string path1,string filename)
{
getDocumentId objGet = new getDocumentId();
var nvc = new NameValueCollection
{
{"File", path1},
{"Content-Type", "multipart/form-data"},
{"Mime-Type", "application/pdf"},
{"File-Name", filename}
};
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] boundarybytesF = System.Text.Encoding.ASCII.GetBytes("--" + boundary + "\r\n"); // the first time it itereates, you need to make sure it doesn't put too many new paragraphs down or it completely messes up poor webbrick.
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("https://api.na1.echosign.com/api/rest/v5/transientDocuments");
wr.Method = "POST";
wr.Headers["Access-Token"] = string.Format(accessToken);
wr.Headers["Authorization"] = string.Format("Bearer");
wr.UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
wr.AllowWriteStreamBuffering = true;
wr.ContentType = "multipart/form-data; boundary=" + boundary;
Stream rs = wr.GetRequestStream();
bool firstLoop = true;
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
if (firstLoop)
{
rs.Write(boundarybytesF, 0, boundarybytesF.Length);
firstLoop = false;
}
else
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
}
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, "File", new FileInfo(path1).Name, "application/octet-stream");
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(path1, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[fileStream.Length];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
try
{
var httpResponse = (HttpWebResponse)wr.GetResponse();
using (var sr = new StreamReader(httpResponse.GetResponseStream()))
{
var result = sr.ReadToEnd();
var jsonSerialization = new JavaScriptSerializer();
var dictObj = jsonSerialization.Deserialize<Dictionary<string, dynamic>>(result);
if (dictObj.Count > 0)
{
objGet.transientDocumentId = Convert.ToString(dictObj["transientDocumentId"]);
objGet.success = "true";
}
else
{
objGet.success = "false";
}
}
}
catch (Exception ex)
{
objGet.success = "false: " + ex.Message.ToString();
}
return objGet;
}
For you purpose where you want to get the documents that you have attached to the agreement using transientDocument, you can get those documents using GET /agreements/{agreementId}/documents API call.
But as the question says "How to get transient documents". Well, there is no way you can get the transientDocument back using any API, reason being transientDocument is for temporary purpose generally used to create a single agreement and is short lived (just 7 days). If you want the uploaded document to be reused to create multiple agreements and can get its documents independently you should create libraryDocument instead using POST /libraryDocument
You can do GET API calls on those library documents to get there various details like documents, auditTrail etc. Here is the documentation link which you can follow to get more understanding on library documets

How send a PDF by POST HttpWebRequest in C#

(i'm french, sorry for my english)
I don't find / understand how send a simple PDF file by post request at a webService (REST protocol).
I tried some examples but it's doesn't word. And when i use a , it's work, but i want do this in the code behind only !
My question is the title : How send this PDF file?
The url : https://test.website.fr/Website/api/transactions/" + sVal + "/contrat
PDF file : questions.pdf
Thanks.
Iris Touchard
I found the solution :
//Identificate separator
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
//Encoding
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
//Creation and specification of the request
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("https://test.website.fr/Website/api/transactions/" + sVal + "/contrat"); //sVal is id for the webService
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
string sAuthorization = "login:password";//AUTHENTIFICATION BEGIN
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(sAuthorization);
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
wr.Headers.Add("Authorization: Basic " + returnValue); //AUTHENTIFICATION END
Stream rs = wr.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; //For the POST's format
//Writting of the file
rs.Write(boundarybytes, 0, boundarybytes.Length);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(Server.MapPath("questions.pdf"));
rs.Write(formitembytes, 0, formitembytes.Length);
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, "file", "questions.pdf", contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(Server.MapPath("questions.pdf"), FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
rs = null;
WebResponse wresp = null;
try
{
//Get the response
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
string responseData = reader2.ReadToEnd();
}
catch (Exception ex)
{
string s = ex.Message;
}
finally
{
if (wresp != null)
{
wresp.Close();
wresp = null;
}
wr = null;
}
This should be what you are looking for:
http://msdn.microsoft.com/en-us/library/debx8sh9.aspx
Here's a quick code example:
byte[] pdfFile = File.ReadAllBytes("pdf file path here");
WebRequest request = WebRequest.Create("https://test.site.fr/Testfile");
request.Method = "POST";
request.ContentLength = pdfFile.Length;
request.ContentType = "application/pdf";
Stream stream = request.GetRequestStream();
stream.Write(pdfFile, 0, pdfFile.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
Console.WriteLine(reader.ReadToEnd());
reader.Close();

HttpWebRequest C# uploading a file

using C#, I'm trying to integrate my web store w/ an email marketing client. I want to upload a comma delimited file of subscribers once a night. They say to get this to work, it has to be a form posts: multipart/form-data, but I'm not using a form. I'm able to connect to their servers but I keep getting back a Data can't be blank. Can anyone help me to get this working?
public static string Create()
{
string authInfo = "username" + ":" + "password";
string root = AppDomain.CurrentDomain.BaseDirectory;
string file = root + "Folder\\work.txt";
FileInfo fi = new FileInfo(file);
int fileLength = (int)fi.Length;
FileStream rdr = new FileStream(file, FileMode.Open);
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Accept = "application/xml";
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
httpWebRequest.Headers["Authorization"] = "Basic " + authInfo;
byte[] requestBytes = new byte[fileLength];
int bytesRead = 0;
httpWebRequest.ContentLength = requestBytes.Length;
using (Stream requestStream = httpWebRequest.GetRequestStream())
{
while ((bytesRead = rdr.Read(requestBytes, 0, requestBytes.Length)) != 0)
{
requestStream.Write(requestBytes, 0, bytesRead);
requestStream.Close();
}
}
//READ RESPONSE FROM STREAM
string responseData;
using (StreamReader responseStream = new StreamReader(httpWebRequest.GetResponse().GetResponseStream()))
{
responseData = responseStream.ReadToEnd();
responseStream.Close();
}
return responseData;
}
I had got the same problem and this following code answered perfectly at this problem :
//Identificate separator
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
//Encoding
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
//Creation and specification of the request
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url); //sVal is id for the webService
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
string sAuthorization = "login:password";//AUTHENTIFICATION BEGIN
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(sAuthorization);
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
wr.Headers.Add("Authorization: Basic " + returnValue); //AUTHENTIFICATION END
Stream rs = wr.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; //For the POST's format
//Writting of the file
rs.Write(boundarybytes, 0, boundarybytes.Length);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(Server.MapPath("questions.pdf"));
rs.Write(formitembytes, 0, formitembytes.Length);
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, "file", "questions.pdf", contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(Server.MapPath("questions.pdf"), FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
rs = null;
WebResponse wresp = null;
try
{
//Get the response
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
string responseData = reader2.ReadToEnd();
}
catch (Exception ex)
{
string s = ex.Message;
}
finally
{
if (wresp != null)
{
wresp.Close();
wresp = null;
}
wr = null;
}

Categories

Resources