Exe destroys itself - c#

I have made an console app (exe) with C#. Application is used to send some http requests to server. It sends json to call server's API to execute some work. I save cookies in environmental variable.
We have noticed some weird behavior with this exe. With some sequence(we were not able to find out what sequence this is) of API calls ( api is called by command line arguments) the exe destroys itself. Its size becomes 0KB from starting 15MB. I have never seen that kind of behavior before. Do you have any idea what could it be?
This is the main part of code that creates http request, and other uploads file...
static public JObject UploadFile(string fileName)
{
HttpWebRequest requestToServer = (HttpWebRequest)WebRequest.Create(serverDomain + directory + "/File");
string boundaryString = "----SomeRandomText";
requestToServer.AllowWriteStreamBuffering = false;
requestToServer.Method = WebRequestMethods.Http.Post;
requestToServer.ContentType = "multipart/form-data; boundary=" + boundaryString;
requestToServer.KeepAlive = false;
if (Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User) != null)
{
CookieContainer cookies = new CookieContainer();
cookies.Add(new Uri(serverDomain), new Cookie("dopinus.e2.session", Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User).ToString()));
requestToServer.CookieContainer = cookies;
}
ASCIIEncoding ascii = new ASCIIEncoding();
string boundaryStringLine = "\r\n--" + boundaryString + "\r\n";
byte[] boundaryStringLineBytes = ascii.GetBytes(boundaryStringLine);
string lastBoundaryStringLine = "\r\n--" + boundaryString + "--\r\n";
byte[] lastBoundaryStringLineBytes = ascii.GetBytes(lastBoundaryStringLine);
string myFileDescriptionContentDisposition = String.Format(
"Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}",
"myFileDescription",
"A sample file description");
byte[] myFileDescriptionContentDispositionBytes = ascii.GetBytes(myFileDescriptionContentDisposition);
string fileUrl = fileName;
string myFileContentDisposition = String.Format(
"Content-Disposition: form-data;name=\"{0}\"; " + "filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n",
"myFile", Path.GetFileName(fileUrl), Path.GetExtension(fileUrl));
byte[] myFileContentDispositionBytes = ascii.GetBytes(myFileContentDisposition);
FileInfo fileInfo = new FileInfo(fileUrl);
long totalRequestBodySize = boundaryStringLineBytes.Length * 2 + lastBoundaryStringLineBytes.Length + myFileDescriptionContentDispositionBytes.Length + myFileContentDispositionBytes.Length + fileInfo.Length;
requestToServer.ContentLength = totalRequestBodySize;
using (Stream s = requestToServer.GetRequestStream())
{
s.Write(boundaryStringLineBytes, 0, boundaryStringLineBytes.Length);
s.Write(myFileDescriptionContentDispositionBytes, 0,
myFileDescriptionContentDisposition.Length);
s.Write(boundaryStringLineBytes, 0, boundaryStringLineBytes.Length);
s.Write(myFileContentDispositionBytes, 0,
myFileContentDispositionBytes.Length);
FileStream fileStream = new FileStream(fileUrl, FileMode.Open,
FileAccess.Read);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
s.Write(buffer, 0, bytesRead);
}
fileStream.Close();
s.Write(lastBoundaryStringLineBytes, 0, lastBoundaryStringLineBytes.Length);
}
WebResponse response = requestToServer.GetResponse();
StreamReader responseReader = new StreamReader(response.GetResponseStream());
string replyFromServer = responseReader.ReadToEnd();
JObject jsonResult = JObject.Parse(replyFromServer);
//CreateErrorLog(replyFromServer);
CreateResponse(replyFromServer);
return jsonResult;
}
static public JObject request(string json)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(serverDomain + directory + "/json.rpc");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
httpWebRequest.CookieContainer = new CookieContainer();
if (Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User) != null)
{
CookieContainer cookies = new CookieContainer();
cookies.Add(new Uri(serverDomain), new Cookie("dopinus.e2.session", Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User).ToString()));
httpWebRequest.CookieContainer = cookies;
httpWebRequest.Headers.Add("dopinus.e2.session", Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User).ToString());
}
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
if (Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User) == null)
{
foreach (Cookie cook in httpResponse.Cookies)
{
Environment.SetEnvironmentVariable(cook.Name, cook.Value, EnvironmentVariableTarget.User);
}
}
else if (Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User) != null)
{
foreach (Cookie cook in httpResponse.Cookies)
{
if (cook.Name == "dopinus.e2.session" && cook.Value != Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User))
{
Environment.SetEnvironmentVariable(cook.Name, cook.Value, EnvironmentVariableTarget.User);
}
}
}
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
JObject jsonResult = JObject.Parse(result);
//CreateErrorLog(result);
CreateResponse(result);
return jsonResult;
}
}
}

Related

Not receiving cookie suddenly for HttpWebRequest POST placed through Visual Studio C# code

There is a common framework in our company where we pass username, password, url and get the cookie back. It was working for me for a long time and suddenly it stopped working. My team mates are able to get the cookie successfully with no issues. Here is the common function that we use to get the cookie back. Please help me to complete the troubleshooting
public static CookieContainer GetAvidAuthCookies(string url, string userName, string password, bool allowAutoRedirect = false)
{
HttpWebRequest req = null;
HttpWebResponse resp = null;
CookieContainer cookieContainer = new CookieContainer();
req = (HttpWebRequest) WebRequest.Create(url);
req.CookieContainer = cookieContainer;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
// req.ContentType = "text/xml;charset=UTF-8"; //for SOAP
req.Timeout = 30000;
req.AllowAutoRedirect = allowAutoRedirect;
req.AllowWriteStreamBuffering = true;
req.Referer = url;
//req.Host = "api.avidxchange.net";
req.Headers["Authorization"] = "Basic " +
Convert.ToBase64String(
System.Text.Encoding.ASCII.GetBytes(userName + ":" + password));
var request = Common.GetMemoryStream("username=" + userName + "&password=" + password + "&submit=");
if (request != null)
{
req.ContentLength = request.Length;
Stream sw = req.GetRequestStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;
request.Position = 0;
while ((bytesRead = request.Read(buffer, 0, buffer.Length)) != 0)
{
sw.Write(buffer, 0, bytesRead);
}
request.Flush();
request.Close();
sw.Flush();
sw.Close();
}
try
{
resp = (HttpWebResponse) req.GetResponse();
}
catch (WebException we)
{
resp = (HttpWebResponse) we.Response;
Debug.WriteLine("Response:" + we.InnerException + "\r\n" + resp.StatusCode + ":" +
new StreamReader(we.Response.GetResponseStream()).ReadToEnd());
var responseStream = we.Response.GetResponseStream();
if (responseStream != null) responseStream.Position = 0;
}
var rStream = resp.GetResponseStream();
var responseText = new StreamReader(rStream).ReadToEnd();
var t = resp.Cookies;
return cookieContainer;
}

How to upload files from a .NET-Application to a Rocket.Chat-Channel?

I need to make a feedback-form in my .NET application, which sends messages to a Rocket.Chat-Channel (What is Rocket.Chat?).
I am already able to send a textmessage with the api of Rocket.Chat.
I found a documentation, how to send files with an api, but i never had done this before. How can I send the files with my Json?
Someone did that before? Maybe somebody can give me a small example to get this done.
This is the code of my method, which sends the textmessage.
private void SendToRocketChat()
{
var baseAddress = "https://plc.ifm-sw.net/api/v1/chat.sendMessage";
var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Method = "POST";
http.ContentType = "application/json";
http.Headers.Add("X-Auth-Token", "4ZLqSyN9IEFIkj6SqIde2a4orHhEdL8S0eGPEFdfS9C");
http.Headers.Add("X-User-Id", "rocket.cat");
string rid = "F24Ydk2kkTXAPWsQ9";
JObject Json = new JObject(new JProperty("message", new JObject(new JProperty("rid", rid), new JProperty("msg", WebUtility.HtmlEncode(FeedbackText)))));
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(Json.ToString());
Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
logger.LogInformation(JsonConvert.DeserializeObject(content).ToString().Trim('{', '}'));
}
And this is what i already tried for the Fileupload. Where is my error?
private void SendFileToRocketChat()
{
var url = "https://example-sw.net/api/v1/rooms.upload/:gdfgfgdkTXAPWsQ9";
var filePath = "Abbildung13.jpg";
var httpClient = (HttpWebRequest)WebRequest.Create(new Uri(url));
httpClient.Method = "POST";
httpClient.Headers.Add("X-Auth-Token", "4ZLqSyN9IEhEdLgfd8S0eGPEFdfS9C");
httpClient.Headers.Add("X-User-Id", "rocket.cat");
httpClient.ContentType = "multipart/form-data";
MultipartFormDataContent form = new MultipartFormDataContent();
FileStream fs = File.OpenRead(filePath);
var streamContent = new StreamContent(fs);
var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
form.Add(imageContent, "file", Path.GetFileName(filePath));
form.Add(imageContent, "msg", "This is a message with a file");
form.Add(imageContent, "description", "Simple text file");
var response = httpClient.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
logger.LogInformation(JsonConvert.DeserializeObject(content).ToString().Trim('{', '}'));
}
After some time i got a code, which is working fine. Maybe it will help someone later.
private void SendFileToRocketChat()
{
var url = "https://exampleurl.net/api/v1/rooms.upload/fsgfadgTXAPWsQ9";
var filePath = "text.zip";
NameValueCollection formFields = null;
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
request.Headers.Add("X-Auth-Token", "4ZLqSyN9IEgfasgfdagsdg8S0eGPEFdfS9C");
request.Headers.Add("X-User-Id", "rocket.bot");
Stream memStream = new System.IO.MemoryStream();
var boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
var endBoundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--");
string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
string files = filePath;
if (formFields != null)
{
foreach (string key in formFields.Keys)
{
string formitem = string.Format(formdataTemplate, key, formFields[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
memStream.Write(formitembytes, 0, formitembytes.Length);
}
}
string headerTemplate = "Content-Disposition: form-data; name=\"file\"; filename=\"{1}\"\r\n" + "Content-Type: application/zip\r\n\r\n";
memStream.Write(boundarybytes, 0, boundarybytes.Length);
var header = string.Format(headerTemplate, "file", files);
var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
memStream.Write(headerbytes, 0, headerbytes.Length);
using (var fileStream = new FileStream(files, FileMode.Open, FileAccess.Read))
{
var buffer = new byte[1024];
var bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
memStream.Write(buffer, 0, bytesRead);
}
}
memStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
request.ContentLength = memStream.Length;
using (Stream requestStream = request.GetRequestStream())
{
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
}
using (var response = request.GetResponse())
{
Stream stream2 = response.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
string res = reader2.ReadToEnd();
logger.LogInformation(JsonConvert.DeserializeObject(res).ToString().Trim('{', '}'));
}
}

Failed to get response for large file HTTP put create file using c#

Failed to get response for large file HTTP put create file using c#
I am using file watcher service service monitor, when user created file or folder we are uploading to cloud
if file size more than 512 MB it is taking too much time to get the response
here I am confusing here the issue with my code or server
and reason for this error
if any changes on my code suggest me.
{
var fileFolderObj1 = new FileFolder();
var postURL = apiBaseUri + "/filefolder/create/file/user/" + userId; // +"?type=file";
code = HttpStatusCode.OK;
HttpWebResponse response = null;
FileInfo f = new FileInfo(filePath);
long filesizeF = f.Length;
try
{
string selectedFile = null;
selectedFile = filePath;
var fi = System.IO.Path.GetFileName(filePath);
////commented for some reason
var postParameters = new Dictionary<string, object>();
postParameters.Add("file", new FileParameter(filePath, ""));
postParameters.Add("parentId", parentId);
postParameters.Add("newName", fi);
postParameters.Add("cloudId", cloudId);
postParameters.Add("isSecure", isSecure);
//postParameters.Add("fileSize", fi.Length);
postParameters.Add("fileSize", filesizeF);
var userAgent = "Desktop";
var formDataBoundary = "----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x");
var uri = new Uri(postURL);
var createFileRequest = WebRequest.Create(uri) as HttpWebRequest;
this.SetBasicAuthHeader(createFileRequest, userId, password);
createFileRequest.ContentType = "multipart/form-data";
createFileRequest.Method = "PUT";
createFileRequest.Timeout = System.Threading.Timeout.Infinite;
createFileRequest.KeepAlive = false;/*true;*/
createFileRequest.UserAgent = userAgent;
createFileRequest.CookieContainer = new CookieContainer();
try
{
using (var requestStream = createFileRequest.GetRequestStream())
{
}
using (response = (HttpWebResponse)createFileRequest.GetResponse())
{
StreamReader(response.GetResponseStream()).ReadToEnd();
fileFolderObj1 = JsonConvert.DeserializeObject<FileFolder>(reslut);
}
}
catch (Exception exc)
{
if (response != null)
{
code = response.StatusCode;
}
}
}
catch (Exception exc)
{
}
}
}
private static readonly Encoding encoding = Encoding.UTF8;
private void WriteMultipartFormData(Dictionary<string, object> postParameters, string boundary, Stream requestStream, ILogService logService = null)
{
var needsCLRF = false;
foreach (var param in postParameters)
{
// Skip it on the first parameter, add it to subsequent parameters.
if (needsCLRF)
{
requestStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n"));
}
needsCLRF = true;
if (param.Value is FileParameter)
{
var fileToUpload = (FileParameter)param.Value;
// Add just the first part of this param, since we will write the file data directly to the Stream
var header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
boundary,
param.Key,
fileToUpload.FileName ?? param.Key,
fileToUpload.ContentType ?? "application/octet-stream");
requestStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));
// Write the file data directly to the Stream, rather than serializing it to a string.
FileStream fileStream = new FileStream(fileToUpload.FileName, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0,buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
logService.Debug("WRITEMULTIPART FORM DATA Bufferlent Running :{0}", bytesRead);
}
fileStream.Close();
}
else
{
var postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
boundary,
param.Key,
param.Value);
requestStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
}
}
// Add the end of the request. Start with a newline
var footer = "\r\n--" + boundary + "--\r\n";
requestStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));
}
}

WPF(C#) how to use a post request to transfer file?

I have a picture that is presented in the form of a byte array. I need to save it to a file and send a post request. Tell me how to do it better
Here is what I do
private Stream file;
public void Fun1()
{
using (file = IsolatedStorageHelper.OpenFile(Picture, FileMode.Create))
{
file.Write(bt, 0, bt.Length);
_cookies = DataHolder.Instance.Cookies;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Concat("http:// Mysite.com/image.php?image=FILE",file));
request.Method = "POST";
request.ContentType = "multipart/form-data";
request.CookieContainer = _cookies;
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackPlayersfun1), request);
}
}
private void GetRequestStreamCallbackPlayersfun1(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
using (file = IsolatedStorageHelper.OpenFile(Picture, FileMode.Open))
{
BinaryReader br = new BinaryReader(file, Encoding.UTF8);
byte[] buffer = br.ReadBytes(2048);
while (buffer.Length > 0)
{
postStream.Write(buffer, 0, buffer.Length);
buffer = br.ReadBytes(2048);
}
}
postStream.Close();
request.BeginGetResponse(new AsyncCallback(ReadCallbackSavePlayersfun1), request);
}
private void ReadCallbackSavePlayersfun1(IAsyncResult asynchronousResult)
{
lock (__SYNC)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
}
}
As a result, the server did not come, tell me what am I doing wrong
thanks for your reply.
But I have another problem. My picture is encoded in a string, the string I write to the stream and try to send to the server. In response comes everything is OK, but the type of request is "Get"(variable respons, method ReadCallbackSavePlayersfun1). Please tell me what's wrong
public void Fun1()
{
string str = "iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAA";
using (file = IsolatedStorageHelper.OpenFile(Picture, FileMode.Create))
{
StreamWriter w = new StreamWriter(file,Encoding.UTF8);
w.WriteLine(str);
_cookies = DataHolder.Instance.Cookies;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Concat("http://Mysite.com/image.php"));
string boundary = "----------" + DateTime.UtcNow.Ticks.ToString("x", CultureInfo.InvariantCulture);
request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.CookieContainer = _cookies;
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackPlayersfun1), request);
w.Close();
}
}
private void GetRequestStreamCallbackPlayersfun1(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
string boundary = "----------" + DateTime.UtcNow.Ticks.ToString("x", CultureInfo.InvariantCulture);
var sbHeader = new StringBuilder();
if (file != null)
{
sbHeader.AppendFormat("--{0}\r\n", boundary);
sbHeader.AppendFormat("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n", "picture", file);
sbHeader.AppendFormat("Content-Type: {0}\r\n\r\n", request.ContentType);
}
using (file = IsolatedStorageHelper.OpenFile(Picture, FileMode.Open))
{
byte[] header = Encoding.UTF8.GetBytes(sbHeader.ToString());
byte[] footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
long contentLength = header.Length + (file != null ? file.Length : 0) + footer.Length;
postStream.Write(header, 0, header.Length);
if (file != null)
{
BinaryReader br = new BinaryReader(file, Encoding.UTF8);
byte[] buffer = br.ReadBytes(2048);
while (buffer.Length > 0)
{
postStream.Write(buffer, 0, buffer.Length);
buffer = br.ReadBytes(2048);
}
br.Close();
}
postStream.Write(footer, 0, footer.Length);
postStream.Flush();
postStream.Close();
}
request.BeginGetResponse(new AsyncCallback(ReadCallbackSavePlayersfun1), request);
}
private void ReadCallbackSavePlayersfun1(IAsyncResult asynchronousResult)
{
lock (__SYNC)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
try
{
String doc = "";
using (Stream streamResponse = response.GetResponseStream())
{
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(streamResponse, encode);
Char[] read = new Char[256];
int count = readStream.Read(read, 0, 256);
while (count > 0)
{
String str = new String(read, 0, count);
doc += str;
count = readStream.Read(read, 0, 256);
}
}
}
catch
{ }
}
}
Posting web byte[] data in .Net is not that simple. Saving a byte[] to storage is easy, so I wont have code for that, but here is the method I use to post binary data.
This is originally from http://skysanders.net/subtext/archive/2010/04/12/c-file-upload-with-form-fields-cookies-and-headers.aspx with my modifications to suit
And to get the FileInfo, simply pass in
new FileInfo(fullPath)
Good luck : )
/// <summary>
/// Create a new HttpWebRequest with the default properties for HTTP POSTS
/// </summary>
/// <param name="url">The URL to be posted to</param>
/// <param name="referer">The refer</param>
/// <param name="cookies">CookieContainer that should be used in this request</param>
/// <param name="postData">The post data</param>
private string CreateHttpWebUploadRequest(string url, string referer, CookieContainer cookies, NameValueCollection postData, FileInfo fileData, string fileContentType)
{
var request = (HttpWebRequest)HttpWebRequest.Create(url);
string boundary = "----------" + DateTime.UtcNow.Ticks.ToString("x", CultureInfo.InvariantCulture);
// set the request variables
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.CookieContainer = cookies;
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.55 Safari/533.4";
request.Accept = "image/gif, image/jpeg, image/pjpeg, image/pjpeg, */*";
request.Headers.Add("Accept-Encoding: gzip,deflate");
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
request.Headers.Add("Accept-Language: en-us");
request.Referer = referer;
request.KeepAlive = true;
request.AllowAutoRedirect = false;
// process through the fields
var sbHeader = new StringBuilder();
// add form fields, if any
if (postData != null)
{
foreach (string key in postData.AllKeys)
{
string[] values = postData.GetValues(key);
if (values != null)
{
foreach (string value in values)
{
if (!string.IsNullOrEmpty(value))
sbHeader.AppendFormat("--{0}\r\n", boundary);
sbHeader.AppendFormat("Content-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}\r\n", key, value);
}
}
}
}
if (fileData != null)
{
sbHeader.AppendFormat("--{0}\r\n", boundary);
sbHeader.AppendFormat("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n", "media", fileData.Name);
sbHeader.AppendFormat("Content-Type: {0}\r\n\r\n", fileContentType);
}
byte[] header = Encoding.UTF8.GetBytes(sbHeader.ToString());
byte[] footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
long contentLength = header.Length + (fileData != null ? fileData.Length : 0) + footer.Length;
// set content length
request.ContentLength = contentLength;
// ref http://stackoverflow.com/questions/2859790/the-request-was-aborted-could-not-create-ssl-tls-secure-channel
// avoid The request was aborted: Could not create SSL/TLS secure channel exception
ServicePointManager.Expect100Continue = false;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(header, 0, header.Length);
// write the uploaded file
if (fileData != null)
{
// write the file data, if any
byte[] buffer = new Byte[fileData.Length];
var bytesRead = fileData.OpenRead().Read(buffer, 0, (int)(fileData.Length));
requestStream.Write(buffer, 0, bytesRead);
}
// write footer
requestStream.Write(footer, 0, footer.Length);
requestStream.Flush();
requestStream.Close();
using (var response = request.GetResponse() as HttpWebResponse)
using (var stIn = new System.IO.StreamReader(response.GetResponseStream()))
{
return stIn.ReadToEnd();
}
}
}

Box-api file upload timeout

I have been fighting with this upload problem for a couple of days and searched the forum for a good answer but have not seen it yet. I am using asp.net and I am currently receiving a timeout when I try to post a file to upload. I have taken the MultipartWebRequest class from the V1 C# Api and changed it(i believe to be correctly but it may be my problem) to work with my program.
public sealed class MultipartWebRequest
{
public string AcceptCharset { get; set; }
public string AcceptEncoding { get; set; }
public string Url { get; set; }
public string Boundary { get; set; }
public string ApiKey { get; private set; }
public string Token { get; private set; }
public MultipartWebRequest(string apiKey, string token, string submitUrl,string acceptCharset = "ISO-8859-1", string acceptEncoding = "gzip,deflate" )
{
Boundary = "----------------" + DateTime.Now.Ticks;
ApiKey = apiKey;
Token = token;
Url = submitUrl;
AcceptCharset = acceptCharset;
AcceptEncoding = acceptEncoding;
}
public string SubmitFiles(
//string[] filePaths,
UploadableFile[] files,
bool isShared,
string message,
string[] emailsToNotify,
string folderId)
{
byte[] buffer;
using (MemoryStream resultStream = new MemoryStream())
{
if (files != null)
{
buffer = AssembleFilesBlock(files, folderId);
resultStream.Write(buffer, 0, buffer.Length);
}
if (!string.IsNullOrEmpty(message))
{
buffer = AssembleMessageBlock(message);
resultStream.Write(buffer, 0, buffer.Length);
}
//buffer = AssembleSharedBlock(isShared);
//resultStream.Write(buffer, 0, buffer.Length);
if (emailsToNotify != null)
{
buffer = AssembleEmailsBlock(emailsToNotify);
resultStream.Write(buffer, 0, buffer.Length);
}
buffer = GetFormattedBoundary(true);
resultStream.Write(buffer, 0, buffer.Length);
resultStream.Flush();
buffer = resultStream.ToArray();
}
HttpWebRequest myRequest = CreateRequest(buffer.Length);
using (Stream stream = myRequest.GetRequestStream())
{
stream.Write(buffer, 0, buffer.Length);
stream.Close();
}
string response;
using (HttpWebResponse myHttpWebResponse = (HttpWebResponse)myRequest.GetResponse())
using (Stream responseStream = myHttpWebResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream);
response = reader.ReadToEnd();
responseStream.Close();
}
myHttpWebResponse.Close();
return response;
}
private byte[] GetFormattedBoundary(bool isEndBoundary)
{
string template = isEndBoundary ? "--{0}--{1}" : "--{0}{1}";
return Encoding.ASCII.GetBytes(string.Format(template, Boundary, Environment.NewLine));
}
private byte[] AssembleEmailsBlock(string[] emailsToNotify)
{
return new byte[1];
}
private byte[] AssembleSharedBlock(bool isShared)
{
byte[] boundaryContent = GetFormattedBoundary(false);
return new byte[1];
}
private byte[] AssembleMessageBlock(string message)
{
return new byte[1];
}
private byte[] AssembleFilesBlock(UploadableFile[] files, string folderId)
{
byte[] buffer = null;
using (MemoryStream resultStream = new MemoryStream())
{
for (int i = 0; i < files.Length ; i++)
{
buffer = GetFormattedBoundary(false);
resultStream.Write(buffer, 0, buffer.Length);
buffer = AssembleFile(files[i]);
resultStream.Write(buffer, 0, buffer.Length);
}
buffer = GetFormattedBoundary(false);
resultStream.Write(buffer, 0, buffer.Length);
buffer = AssembleStringValue("folder_id", folderId);
resultStream.Write(buffer, 0, buffer.Length);
resultStream.Flush();
buffer = resultStream.ToArray();
}
return buffer;
}
private byte[] AssembleStringValue(string paramName, string paramValue)
{
StringBuilder result = new StringBuilder();
result.AppendFormat("Content-Disposition: form-data; name=\"{0}\"{1}", paramName, Environment.NewLine);
result.AppendLine();
result.AppendLine(paramValue);
return Encoding.ASCII.GetBytes(result.ToString());
}
private byte[] AssembleFile(UploadableFile file)
{
byte[] buffer;
using (MemoryStream resultStream = new MemoryStream())
{
buffer = Encoding.ASCII.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}", Guid.NewGuid(), file.FileName, Environment.NewLine));
resultStream.Write(buffer, 0, buffer.Length);
buffer = Encoding.ASCII.GetBytes("Content-Type: application/octet-stream" + Environment.NewLine + Environment.NewLine);
resultStream.Write(buffer, 0, buffer.Length);
buffer = Encoding.ASCII.GetBytes(file.FileContents);
//buffer = File.ReadAllBytes(filePath);
resultStream.Write(buffer, 0, buffer.Length);
buffer = Encoding.ASCII.GetBytes(Environment.NewLine);
resultStream.Write(buffer, 0, buffer.Length);
resultStream.Flush();
buffer = resultStream.ToArray();
}
return buffer;
}
private HttpWebRequest CreateRequest(long contentLength)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Url);
webRequest.Method = "POST";
//webRequest.AllowWriteStreamBuffering = true;
webRequest.ContentType = string.Concat("multipart/form-data;boundary=", Boundary);
webRequest.Headers.Add("Authorization", "BoxAuth api_key=" + ApiKey + "&auth_token=" + Token);
webRequest.Headers.Add("Accept-Encoding", AcceptEncoding);
webRequest.Headers.Add("Accept-Charset", AcceptCharset);
webRequest.ContentLength = contentLength;
webRequest.ServicePoint.ConnectionLeaseTimeout = 0;
return webRequest;
}
}
Here is my default asp.net page... This is mainly just a testing page. And I can to GET requests and login and get the token and folders and everything else.
public partial class _Default : System.Web.UI.Page
{
public const string APIKEY = "{APIKEY}";
public const string AUTH_STRING = "https://www.box.com/api/1.0/auth/";
public const string GET_TOKEN_STRING = "https://www.box.com/api/1.0/rest?action=get_auth_token&api_key={0}&ticket={1}";
public const string BASE_URL = "https://api.box.com/2.0/";
public string ticket = "";
public string token = "";
public string login = "";
public BoxUser boxUser;
HttpContext http;
protected void Page_Load(object sender, EventArgs e)
{
http = HttpContext.Current;
ticket = http.Request["ticket"];
token = http.Request["auth_token"];
login = http.Request["login"];
}
protected void btnBoxLogin_Click(object sender, EventArgs e)
{
string bURL = "https://www.box.com/api/1.0/rest?action=get_ticket&api_key=" + APIKEY;
HttpWebRequest wGetUrl = (HttpWebRequest)WebRequest.Create(bURL);
wGetUrl.ServicePoint.ConnectionLeaseTimeout = 0;
WebResponse response = wGetUrl.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
if (reader != null)
{
string xmlString = "";
string tmpString = reader.ReadLine();
while (tmpString != null)
{
xmlString += tmpString;
tmpString = reader.ReadLine();
}
//txtResponse.Text = xmlString;
GetResponseTicket(xmlString);
}
if(ticket != "")
txtResponse.Text = "\nThe Ticket returned is: " + ticket;
response.Close();
stream.Close();
Response.Redirect(AUTH_STRING + ticket, false);
}
protected void btnGetAuthToken_Click(object sender, EventArgs e)
{
string bURL = "https://www.box.com/api/1.0/rest?action=get_auth_token&api_key="+APIKEY+"&ticket=" + ticket;
HttpWebRequest wGetUrl = (HttpWebRequest)WebRequest.Create(bURL);
wGetUrl.ServicePoint.ConnectionLeaseTimeout = 0;
WebResponse response = wGetUrl.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
if (reader != null)
{
string xmlString = "";
string tmpString = reader.ReadLine();
while (tmpString != null)
{
xmlString += tmpString;
tmpString = reader.ReadLine();
}
//txtResponse.Text = xmlString;
GetResponseUser(xmlString);
}
//txtResponse.Text += token + "\n";
//txtResponse.Text += login;
response.Close();
reader.Close();
stream.Close();
}
protected void btnGetUserFolderInfo_Click(object sender, EventArgs e)
{
string usersUrl = "folders/0/items";
string url = BASE_URL + usersUrl;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Add("Authorization", "BoxAuth api_key=" + APIKEY + "&auth_token=" + token);
request.ServicePoint.ConnectionLeaseTimeout = 0;
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
JavaScriptSerializer js = new JavaScriptSerializer();
object o = js.DeserializeObject(reader.ReadLine());
if (reader != null)
{
string txt = reader.ReadLine();
txtResponse.Text += "\n" + txt;
while (!reader.EndOfStream)
{
txt = reader.ReadToEnd();
txtResponse.Text += "\n" + txt;
}
}
stream.Close();
response.Close();
reader.Close();
}
private void GetResponseTicket(string xmlString)
{
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
reader.ReadToFollowing("status");
string status = reader.ReadElementContentAsString();
if (status != null && status == "get_ticket_ok")
{
ticket = reader.ReadElementContentAsString();
if (String.IsNullOrEmpty(ticket))
throw new Exception("Ticket was empty");
}
else
throw new Exception("For some reason Status was null or not right");
}
}
private void GetResponseUser(string xmlString)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
XmlNode root = doc.DocumentElement;
XmlNode user = root.LastChild;
//XmlNamespaceManager xmlns = new XmlNamespaceManager(doc.NameTable);
//XmlNode node = root.SelectSingleNode(login).InnerText
string login = user.SelectSingleNode("login").InnerText;
string email = user.SelectSingleNode("email").InnerText;
string access_id = user.SelectSingleNode("access_id").InnerText;
string user_id = user.SelectSingleNode("user_id").InnerText;
long space_amount = long.Parse(user.SelectSingleNode("space_amount").InnerText);
long space_used = long.Parse(user.SelectSingleNode("space_used").InnerText);
long max_upload_size = long.Parse(user.SelectSingleNode("max_upload_size").InnerText);
boxUser = new BoxUser(login, email, access_id, user_id, space_amount, space_used, max_upload_size);
}
protected void CreateNewFolder_Click(object sender, EventArgs e)
{
string url = BASE_URL + "folders/389813359";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Add("Authorization", "BoxAuth api_key=" + APIKEY + "&auth_token=" + token);
request.Method = "POST";
request.ServicePoint.ConnectionLeaseTimeout = 0;
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "{\"name\":\"" + txtNewFolderName.Text+"\"}";
byte[] data = encoding.GetBytes(postData);
using (Stream datastream = request.GetRequestStream())
{
datastream.Write(data, 0, data.Length);
datastream.Close();
}
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string responseFromServer = reader.ReadToEnd();
lblResult.Text = responseFromServer;
reader.Close();
stream.Close();
response.Close();
}
protected void UploadNewFile_Click(object sender, EventArgs e)
{
//string url = BASE_URL + "files/data";
string url = "https://upload.box.com/api/2.0/" + "files/data";
//string url = "https://upload.box.com/api/1.0/upload" + token + "/0";
/*string boundary = "----------------------" + DateTime.Now.Ticks;
var newLine = Environment.NewLine;
string propFormat = "--" + boundary + newLine + "Content-Disposition: form-data; {0}={1}" + newLine;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Headers.Add("Authorization", "BoxAuth api_key=" + APIKEY + "&auth_token=" + token);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "multipart/form-data; boundary=" + boundary;
string fileName = fileUpload.FileName;
byte[] file = fileUpload.FileBytes;
using (Stream stream = request.GetRequestStream())
{
StreamWriter writer = new StreamWriter(stream);
string tmp = String.Format(propFormat, fileName, file);
writer.Write(tmp);
tmp = String.Format(propFormat, "folder_id", "389813359");
writer.Write(tmp);
writer.Write("--" + boundary + "--");
writer.Flush();
}
WebResponse response = request.GetResponse();
using (Stream resStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(resStream);
lblResult.Text = reader.ReadToEnd();
}*/
Stream stream = fileUpload.PostedFile.InputStream;
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
UploadableFile file = new UploadableFile(fileUpload.FileName, text, ".txt");
UploadableFile[] files = new UploadableFile[1];
files[0] = new UploadableFile(fileUpload.FileName, text, ".txt"); ;
MultipartWebRequest myRequest = new MultipartWebRequest(APIKEY,token,url);
string response = myRequest.SubmitFiles(files, false, null, new string[] { }, "0");
txtResponse.Text = response;
}
}
As you can see I have tried all of the different upload urls that I have found around the site. And with all the different ones, not sure exactly which one to use, but doc appears to be the latest "most" correct one? Any help with this would be greatly appreciated as I am fairly new (but understand) to post requests in C#, but VERY new (never done one) to multipart forms in C# (or really anywhere).
The current recommended URL for the API (including file uploads) appears to now be https://api.box.com/2.0. Have you tried using that base URL?

Categories