ASP.net

Subscribe to ASP.net 18 posts, 9 voices

 
Avatar Harlow 6 posts

Hi,

I am trying to use the API with an ASP.net web application. Iam using the HttpWebRequest object to post the data however kep getting a timeout when uploading the file (despite the timeout being set to a large value on the client side). Does anyone have any examples of code in VB or C# where they have successfully uploaded to the API? Any help would be greatly appreciated.

Thanks, Rob

 
Avatar Bruno Celeste 374 posts

Can you post some sample code please?

 
Avatar Harlow 6 posts

Hi Bruno,

I was a little unsure from the API documentation how exactly to upload the file so I have tried (and failed) with 2 methods. Witrh the first I tried specifying a filename for a file already uploaded onto my server, and with the second uploading directly to the service. Code snippets as follows:

1:

HttpWebRequest request;
HttpWebResponse response;
NetworkCredential cred;
Byte[] ByteData;
String UploadFile;
cred = new NetworkCredential("harlowhair","pa55w0rd");
request =  (HttpWebRequest) WebRequest.Create("http://heywatch.com/upload.xml");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Credentials = cred;
request.PreAuthenticate = true;
request.KeepAlive = true;
//request.SendChunked = true;
UploadFile = FilepathTextbox.Text;
//BinaryReader br = new BinaryReader(File.OpenRead(UploadFile));
StringBuilder data = new StringBuilder();
data.Append("data=" + HttpUtility.UrlEncode("video/in/Bear.wmv"));
data.Append("&title=TestFromC");
data.Append("&key=ec8177950ed90e205ef1a381c3746fa5");
//ByteData = br.ReadBytes((int)br.BaseStream.Length);
ByteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
request.ContentLength = ByteData.Length;
request.Timeout = 300000;
Stream PostStream;
PostStream = request.GetRequestStream();
PostStream.Write(ByteData, 0, ByteData.Length);
try
{
    response = (HttpWebResponse)request.GetResponse();
    StreamReader reader = new StreamReader(response.GetResponseStream());
    String result = reader.ReadToEnd();
    Debug.Write(result);
}
catch(Exception ex)
{
    Debug.Write(ex.ToString());
}

2:

long length = 0;
string boundary = "----------------" +
DateTime.Now.Ticks.ToString("x");
NetworkCredential cred = new NetworkCredential("harlowhair", "pa55w0rd");
HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create("http://heywatch.com/upload.xml");
httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest2.Method = "POST";
httpWebRequest2.KeepAlive = true;
httpWebRequest2.Credentials = cred;
httpWebRequest2.Timeout = 600000;
httpWebRequest2.ReadWriteTimeout = 600000;
//httpWebRequest2.AllowWriteStreamBuffering = true;
//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}";
if (nvc != null)
{
    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);
    }
}
else
{
    string formitem = string.Format(formdataTemplate, "Title", "TestUpload");
    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();
try
{
    WebResponse webResponse2 = httpWebRequest2.GetResponse();
Stream stream2 = webResponse2.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
AccountInfoTextBox.Text = reader2.ReadToEnd();
}
catch (Exception ex)
{
    Debug.Write(ex.ToString());
}
finally
{
}
httpWebRequest2 = null;

From what I can gather from the API, the second method is the correct way to do this however I get a 404 page not found error after a while where it looks like the file is uploading. With the first code snippet I get a 400 Bad request error.

Thanks

 
Avatar Harlow 6 posts

lol after posting I realised I left my password in there, needless to say this has now been changed!

 
Avatar Harlow 6 posts

Any Suggestions?

 
Avatar Bruno Celeste 374 posts

The good solution is the second one (multipart form). The file field name must be “data”.

I can’t help you more on that one because I don’t know .NET

 
Avatar Harlow 6 posts

Thanks, any idea why I could be getting a 404 page not found error?

 
Avatar Bruno Celeste 374 posts

Maybe the request is not built correctly, especially the path (should be /upload.xml)

 
Avatar Harlow 6 posts

The path for the request is http://heywatch.com/upload.xml (5th line). Do I need to specify the pages for success and error?

 
Avatar Bruno Celeste 374 posts

Can you check the network traffic with wireshark or something else?

 
Avatar rvoronyak 8 posts

Hello Harlow,

Were you able to get your C# .net code to upload to HeyWatch successfully? If so could you provide that?

Thanks.

 
Avatar Jason Shultz 1 post

Did anyone find/create some C# asp.net code that works?

 
Avatar manlord 4 posts

I think I have found the bug in your code

byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +boundary + "\r\n");

While it is a correct boundary in between the different request values, the very last boundary need to be followed by ”—”, bottom of page: http://www.w3.org/TR/html4/interact/forms.html

See also my post http://forums.heywatch.com/forums/4/topics/189

Confirmed working code: (a bit dirty yet though, but it works)
  public static string UploadFileEx(string uploadfile, string fileFormName, string contenttype, NameValueCollection querystring, 
        CookieContainer cookies)
        {
            string url = "http://heywatch.com/upload.xml";

            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";
            webrequest.Headers.Add(AuthorizationHeader);
            webrequest.Accept = AcceptHeader;  

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

            // Close the request and file stream
            requestStream.Close();
            fileStream.Close();

            WebResponse responce = webrequest.GetResponse();
            Stream s = responce.GetResponseStream();
            StreamReader sr = new StreamReader(s);

            return sr.ReadToEnd();
        }
 
Avatar Bruno Celeste 374 posts

Thank you Manlord to solve this issue, it’s really appreciated.

 
Avatar milan 1 post

Hi, pls how can I specify format of desired video?

 
Avatar wasif 1 post

hey manlord thanks for the help.your code worked really fine. But the form i want to simulate has too many fields so i cant put them in query string.So i have to send my file and from data both in request stream. Please help me out how to build the message header or or set boundary to separate different fields and from

 
Avatar dorgenn 1 post

 
Avatar TysvdH 2 posts

Hi ya all,

Can anyone help me with this one. I’ve been trying to use the code posted above. But i keep getting a 401 error. (The remote server returned an error: (401) Unauthorized.) How do i provide my username and passw. in a correct way? I’ve used webrequest.Headers.Add(username:password); Or how do i have to use the AuthorizationHeader?

When i try to use NetworkCredential, i get a ServerError 500..

Hope someone can point me in the right direction.

Thanks in advance, Tys