HP ALM C# REST set attachment for requirement - c#

I've seen many different 'answers' to this, none of them complete. This is my current code for my upload function. It should be complete enough for discussion. I'm getting a (500) error when attempting to upload a .png file. The .png file gets consumed by the formbytes stream, but when it gets to the actual request on the last line, it throws the error. HELP!
public void Upload(string uri, string filePath)
{
FileInfo fi = new FileInfo(filePath);
string fileType = fi.Extension.Replace(".", "");
string slug = fi.Name.Replace(fi.Extension, "");
string formdataTemplate = "Content-Disposition: form-data; name=\"file\" filename=\"{0}\";\r\nContent-Type: application/octet-stream\r\n\r\n";
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Accept = "application/json";
if (cookies != null)
{
// cookies is a cookie container populated by another process, works for creating ALM requirements
request.CookieContainer = cookies;
}
request.Headers.Add("slug", slug);
string formitem = "";
byte[] formbytes = null;
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(boundarybytes, 0, boundarybytes.Length);
formitem = string.Format(formdataTemplate, Path.GetFileName(filePath));
formbytes = Encoding.UTF8.GetBytes(formitem);
requestStream.Write(formbytes, 0, formbytes.Length);
byte[] buffer = new byte[1024 * 4];
int bytesLeft = 0;
while ((bytesLeft = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
requestStream.Write(buffer, 0, bytesLeft);
}
}
}
//request.Headers.Add(formbytes);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { }
}

The answer is that I had to check-out the requirement to add the attachment. It's a simple post, with no body needed, to :
/rest/domains/[domain]/projects/[project]/requirements/[entityId]/versions/check-out
and you can check-in, also no body needed:
/rest/domains/[domain]/projects/[project]/requirements/[entityId]/versions/check-out

Related

Upload Excel file to web server

I was trying to upload a file to a web server through UWP c# using filestream but it always gives me an error i.e 405 method not allowed when I try to upload on http://example.com/httpdocs/content. Even for testing purpose I tried uploading on my localhost but still no luck.
Any Help?
Code :
public async Task<bool> Upload(StorageFile fileName)
{
HttpMultipartFormDataContent form = new HttpMultipartFormDataContent();
cts = new CancellationTokenSource();
using (IInputStream fileStream = await fileName.OpenSequentialReadAsync())
{
HttpStreamContent content = new HttpStreamContent(fileStream);
form.Add(content, "premier", fileName.Name);
using (HttpClient client = new HttpClient())
{
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri("http://example.com/httpdocs/content")))
{
request.Content = form;
request.Headers.TryAppendWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
HttpResponseMessage response = await client.SendRequestAsync(request).AsTask(cts.Token);
var result = response.Content.ReadAsStringAsync().GetResults();
}
}
}
return true;
}
Hye, after trying much I found this code and it works perfectly. With a little correction that the request will be now sent to an aspx page i.e. http://example.com/abc.aspx. If you wanna send high mb's of excel file data then just change 4096 in Math.Min(4096, (int)fileStream.Length) accordingly
Client Side Code-
public static async Task<string> UploadFileEx(string uploadfile, string
url, string fileFormName, string contenttype, NameValueCollection
querystring, CookieContainer cookies)
{
try
{
if ((fileFormName == null) ||
(fileFormName.Length == 0))
{
fileFormName = "file";
}
if ((contenttype == null) ||
(contenttype.Length == 0))
{
contenttype = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
string postdata;
postdata = "?";
if (querystring != null)
{
foreach (string key in querystring.Keys)
{
postdata += key + "=" + querystring.Get(key) + "&";
}
}
Uri uri = new Uri(url + postdata);
string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
webrequest.CookieContainer = cookies;
webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
webrequest.Method = "POST";
// Build up the post message header
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append(fileFormName);
sb.Append("\"; filename=\"");
var sd = sb.Append(Path.GetFileName(uploadfile));
sb.Append("\"");
sb.Append("\r\n");
sb.Append("Content-Type: ");
sb.Append(contenttype);
sb.Append("\r\n");
sb.Append("\r\n");
string postHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
// Build the trailing boundary string as a byte array
// ensuring the boundary appears on a line by itself
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
FileStream fileStream = new FileStream(uploadfile, FileMode.Open, FileAccess.Read);
long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
// webrequest.ContentLength = length;
webrequest.Headers[HttpRequestHeader.ContentLength] = length.ToString();
//Stream requestStream = webrequest.GetRequestStream();
Stream requestStream = await webrequest.GetRequestStreamAsync();
// Write out our post header
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
// Write out the file contents
byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
requestStream.Write(buffer, 0, bytesRead);
// Write out the trailing boundary
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
WebResponse response = await webrequest.GetResponseAsync();
Stream s = response.GetResponseStream();
StreamReader sr = new StreamReader(s);
return sr.ReadToEnd();
}
catch (Exception e)
{
e.ToString();
}
return null;
}

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();

Upload file with HttpWebRequest

Here is my code:
private void UploadFilesToRemoteUrl(string url, string[] files, string logpath, NameValueCollection nvc)
{
long length = 0;
string boundary = "----------------------------" +
DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest2.Method = "POST";
httpWebRequest2.KeepAlive = true;
httpWebRequest2.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream memStream = new System.IO.MemoryStream();
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
foreach(string key in nvc.Keys)
{
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
memStream.Write(formitembytes, 0, formitembytes.Length);
}
memStream.Write(boundarybytes,0,boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\";filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
for(int i=0;i<files.Length;i++)
{
string header = string.Format(headerTemplate,"file"+i,files[i]);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
memStream.Write(headerbytes,0,headerbytes.Length);
FileStream fileStream = new FileStream(files[i], FileMode.Open,
FileAccess.Read);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ( (bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0 )
{
memStream.Write(buffer, 0, bytesRead);
}
memStream.Write(boundarybytes,0,boundarybytes.Length);
fileStream.Close();
}
httpWebRequest2.ContentLength = memStream.Length;
Stream requestStream = httpWebRequest2.GetRequestStream();
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer,0,tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer,0,tempBuffer.Length );
requestStream.Close();
WebResponse webResponse2 = httpWebRequest2.GetResponse();
Stream stream2 = webResponse2.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
MessageBox.Show(reader2.ReadToEnd());
webResponse2.Close();
httpWebRequest2 = null;
webResponse2 = null;
}
And here is how I call it:
string[] filenames = new string[] { #"C:\Users\John\Desktop\ex.txt" };
NameValueCollection nvc = new NameValueCollection();
nvc.Add("cmd", "new");
nvc.Add("sTitle", "bugX");
nvc.Add("token", "someToken");
UploadFilesToRemoteUrl("https://myUrl.fogbugz.com/api.asp", filenames, "", nvc);
And everything is working fine, except the file isn't uploaded.
I also tried this code:
http://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data
and the same thing happens. How to resolve this?
Here is the response from the server:
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<response>
<case ixBug=\"123486\" operations=\"edit,assign,resolve,email,remind\"></case>
</response>
you're just sending a stream to the server, it's impossible to know what happens at the server for us if you don't provide any code for us from the server side. I guess you've forgotten to receive and create the file on the server side.
if this is not the problem I would suggest you get the invaluable tool fiddler and start catching your httprequests and see what they contain.

Upload files from client to server programmatically

I'm working on fileupload control with a simple application which transfer file to server automatically.
I used as references those samples Setting a file to upload inside the WebBrowser component and UploadFileEx but when tested doesn't create a file on the server!
Form Code:
// simulate this form
//<form action ="http://localhost/test.php" method = POST>
//<input type = text name = uname>
//<input type = password name =passwd>
//<input type = FILE name = uploadfile>
//<input type=submit>
I found this class which post file to server using HttpWebRequest:
public static string UploadFileEx( string uploadfile, string url,
string fileFormName, string contenttype,NameValueCollection querystring,
CookieContainer cookies)
{
if( (fileFormName== null) ||
(fileFormName.Length ==0))
{
fileFormName = "file";
}
if( (contenttype== null) ||
(contenttype.Length ==0))
{
contenttype = "application/octet-stream";
}
string postdata;
postdata = "?";
if (querystring!=null)
{
foreach(string key in querystring.Keys)
{
postdata+= key +"=" + querystring.Get(key)+"&";
}
}
Uri uri = new Uri(url+postdata);
string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
webrequest.CookieContainer = cookies;
webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
webrequest.Method = "POST";
// Build up the post message header
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append(fileFormName);
sb.Append("\"; filename=\"");
sb.Append(Path.GetFileName(uploadfile));
sb.Append("\"");
sb.Append("\r\n");
sb.Append("Content-Type: ");
sb.Append(contenttype);
sb.Append("\r\n");
sb.Append("\r\n");
string postHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
// Build the trailing boundary string as a byte array
// ensuring the boundary appears on a line by itself
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
FileStream fileStream = new FileStream(uploadfile, FileMode.Open, FileAccess.Read);
long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
webrequest.ContentLength = length;
Stream requestStream = webrequest.GetRequestStream();
// Write out our post header
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
// Write out the file contents
byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
int bytesRead = 0;
while ( (bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0 )
requestStream.Write(buffer, 0, bytesRead);
// Write out the trailing boundary
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
requestStream.Flush();
requestStream.Close();
WebResponse responce = webrequest.GetResponse();
Stream s = responce.GetResponseStream();
StreamReader sr = new StreamReader(s);
return sr.ReadToEnd();
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
CookieContainer cookies = new CookieContainer();
//add or use cookies
NameValueCollection querystring = new NameValueCollection();
querystring["uname"]="";
querystring["passwd"]="";
string uploadfile;// set to file to upload
uploadfile = "C:\\test.jpg";
UploadFileEx(uploadfile, "http://127.0.0.1/app/Default.aspx", "uploadfile", "image/pjpeg",
querystring, cookies);
}
in my case I want to use this class via WebBrowser control but when I send post to server the file(test.jpg) not created!
It could be a problem of permission on the folder! but when tested localy using IIS I get the same problem?
Thanks
It's a bit difficult to understand your question, so sorry if this isn't the right answer, but if you want to upload a file using a WebRequest with standard POST then it goes like this: Upload files with HTTPWebrequest (multipart/form-data)

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