Wednesday, 21 August 2013

Form Posts and the BackgroundTransferService

At the time of getting my Windows phone I was the owner of an app membership which at the time allowed me to develop apps for the phone. I wanted to create an app that interacted with a personal file server, which allowed files to be uploaded to it via a form post online. I achieved this by using WebRequest objects, but due to the limitation of Windows phone apps this meant that I had to stay within the app in order to complete the upload, which was not ideal. Then Mango came out and with it the BackgroundTransferService, which allowed uploads and downloads to happen regardless of the state of the app that initiated them. So I set out to upgrade my app to upload the files via this new background service, but couldn't for the life of me to get it to work so I gave up. My app membership then ran out, meaning that I could no longer use the app anyway and the code just became a folder on my computer gathering virtual dust...

Fast forward to a few weeks ago (strangest statement ever) and Microsoft announce that anyone can develop and deploy up to two apps on any one phone, for free. So, I decided to redesign my application from the ground up and starting by attempting to conquer the BackgroundTransferService once again. I started by googling (or binging, yahooing, asking, etc) my problem to see if anyone had had success in this area as a lot can happen in a few years. No one had. I then manged to find a post detailing MY EXACT PROBLEM. My face lit up. Was my search finally over? I scrolled to the bottom for an answer. No answer. I looked to see who posted it. It was me when I was first having the problem. An example that in the XKCD scenario (shown above), the poster doesn't necessarily know of a solution because I knew nothing.

I decided to attempt once again the solution that the post gave me. I downloaded Fiddler, posted a file using the BackgroundTransferService, posted a file using the web form and examined the result. Not surprisingly, the BackgroundTransferService post was missing a bunch of information that was included in the web form post, and instead was just posting the raw file binary. No boundaries of anything. But why would it? I hadn't told it to. After messing around with the Headers property and about to give up, I had one final idea. One that I thought would never work because I thought it was hacky as hell. What if the stream I stated to upload was in fact the contents that are uploaded via a web form post.

using (IsolatedStorageFileStream stream = storage.CreateFile(@"shared/transfers/" + tb_Filename.Text))
    StringBuilder content = new StringBuilder();
    content.AppendLine(String.Format("-----------------------------{0}", boundary));
    content.AppendLine(String.Format("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"", tb_Filename.Text));
    content.AppendLine(String.Format("Content-Type: image/jpeg"));


    byte[] contentAsBytes = Encoding.UTF8.GetBytes(content.ToString());
    stream.Write(contentAsBytes, 0, contentAsBytes.Length);


    _selectedStream.Position = 0;

    byte[] buffer = new byte[16 * 1024];
    int read;
    while ((read = _selectedStream.Read(buffer, 0, buffer.Length)) > 0)
        stream.Write(buffer, 0, read);


    content.AppendLine(String.Format("-----------------------------{0}--", boundary));

    contentAsBytes = Encoding.UTF8.GetBytes(content.ToString());
    stream.Write(contentAsBytes, 0, contentAsBytes.Length);

BackgroundTransferRequest request = new BackgroundTransferRequest(new Uri(Uri.EscapeUriString(Page_Upload.UploadDestination), UriKind.Absolute));
request.UploadLocation = new Uri(@"shared/transfers/" + tb_Filename.Text, UriKind.RelativeOrAbsolute);
request.Method = "POST";
request.Tag = tb_Filename.Text;
request.TransferPreferences = TransferPreferences.AllowCellularAndBattery;

request.Headers.Add(new KeyValuePair("Content-Type", String.Format("multipart/form-data; boundary=---------------------------{0}", boundary)));

I selected a file, hit the Upload button and checked my file server. And with much surprise (although looking back I don't see why), the file was there.

So as can be seen, the BackgroundTransferService can used to upload all types of data in all types of form. You just need to know how. Or in my case try everything else.

Update: It appears this blog post may be more helpful if it includes the php code it was interacting with. So here is a stripped down version of it
 if ($_FILES["file"]["error"] > 0)
  echo "Return Code: " . $_FILES["file"]["error"] . "
 else {
           "./" . $_FILES["file"]["name"]);

  echo "Successful";
<form action="upload_file.php" method="POST" enctype="multipart/form-data">
  File: <input type="file" name="file" />

  <input type="submit" value="Submit" />


  1. Hi David! I'm struggling with it right now. I tried your solution and I can see the BytesSent property increasing, but I could'nt get the image server side... (I'm using PHP and the $_FILES variable is empty). I'm am missing something?

    1. Hi Nobuyuki.

      First, thank you for taking the time in looking at my blog. I've updated the post to include sample php code that the c# code is interacting with. If you can post a sample of your php code and C# code, I might be able to help.


    2. Thank you David! i was missing this header info:

      data.Append(String.Format("Content-Disposition: file; name=\"arquivo\"; filename=\"upload_{0}.jpg\"\r\n", boundary));

      yours is "form-data", but when i changed to "file", it worked! Anyway, thanks to you! Your post was very helpful!

  2. This comment has been removed by the author.

  3. I am thankful for this blog giving unique and helpful knowledge about this topic, I read your blog now share great information here. This blog increase my knowledge source. Business marketing USA may help you to get various ways of communication in the fastest way!

  4. This excellent is undoubtedly fantastic. Most of these minuscule truth is generated applying broad range connected with accreditation know-how. When i benefit taking that approach lots. microsoft office 365 product key

  5. VRay 5 Crack For SketchUp is one of the pinnacle enterprise general render engines, spanning characteristic movie to architectural visualization, deeply embedded in the manufacturing pipelines. it's miles an green, glossy, and maximum versatile app to work with when you get acquainted with its big toolkit. It uses global illumination algorithms that encompass photon mapping, irradiance maps, course tracing, and without delay computed global illumination. The laptop 3-d applications that V-ray supports include SketchUp, Autodesk 3DS Max, Autodesk rivet, Maya, Cinema 4D, Modo, Nuke, rhinoceros, and katana. It lets in you to make the next technology of rendering. Its destiny scene intelligence offers you faster Ray tracing, more correct rendering, and purifier sampling.

  6. Hello, i read your blog ffrom time to time and i own a similar one aand i was just curious if you get a lot of spam feedback?
    If so how do you top it, any pljgin or anything yyou can suggest?
    I get so much lately it’s driving me insane so any assistance is very much appreciated.
    bittorrent pro crack
    cyberlink powerdvd crack
    sketchup pro crack
    plagiarism checker x crack
    driver booster 6 1 pro key

  7. Thank you for another fantastic piece. Where else might somebody receive that type of information in such a well-written format?
    I'm giving a presentation next week, and I'm looking for relevant material.
    anymp4 dvd toolkit crack
    apache openoffice crack
    cubase pro crack

  8. I went to your website. I admire you and your efforts. I appreciate your efforts.
    If you're looking for the most recent edition and what's new, you've come to the right place.
    I hope you find this website useful. Thanks.
    gb whatsapp crack
    internet download manager crack
    fabfilter total bundle crack

  9. Hello just wanted to give you a quick heads up. The text
    in your article seems to be running off the screen in Opera.
    I’m not sure if this is a formatting issue or something to do with web
    browser compatibility but I thought I’d post to let you know.
    The style and design look great though! Hope you get the issue fixed soon. Cheers
    microsoft office 2019 crack
    driver booster pro crack
    fl studio crack
    movavi slideshow maker crack

  10. This is very rare and useful software. You may get many benefits free. Then why do you pay for other software for the same features?

  11. I am greatly thankful to the owner of this website to share this valuable information.Download Now

  12. The site is fantastic, and I wanted to drop you a line to say, "Good job!" Please keep up the good work.
    Most of the ideas I've been looking for have been found on your site. It's great that you shared this!.Download now. Hwidgen

  13. I've never seen anything like your writing style from anyone else I've read. I'll remember to bookmark your blog and keep checking for new information.


  14. Your information was quite beneficial to me, and I appreciate you sharing it with me.
    I'd like to see many more submissions from you in the future.

  15. I've been quite glad to find this website.
    I really need to thank you for a while for this excellent reading!!
    I certainly enjoyed every small part of it and I saved you as a favourite to see your website for new things.
    aimersoft video converter ultimate crack
    aida64 extreme crack
    advanced system repair pro key download
    adobe xd cc crack download

  16. I want to tell you that this software is great and works in a very simple way.


  17. I am very happy to read this article. Thanks for giving us Amazing info. Fantastic post.
    Thanks For Sharing such an informative article, Im taking your feed also, Thanks.nitro pro activation assistant serial number


  18. I am very happy to read this article. Thanks for giving us Amazing info. Fantastic post.
    Thanks For Sharing such an informative article, Im taking your feed also, Thanks.serial number nitro pro 13

  19. Your writing makes me happy because it is useful and provides me with new information.Click here

  20. Thanks for supporting us. Parallels Desktop Torrent is a strong
    competitor of virtual machine ware and workstation users.
    Parallels Desktop Torrent is a strong
    competitor of virtual machine ware and workstation users.

    Your blog is very supporting us. We have regularly reading your blog.
    Matlab Torrent is the world’s most popular and powerful graphics software
    that it is mainly used by scientists and engineers.
    This software allows matrix manipulations, plotting of data and functions.

  22. Wondershare Filmii 2022 Crack is the best tool for making gorgeous videos quickly and fast. It provides you advanced and smart templates. wondershare filmii crack download more software visit.

  23. In addition, it allows It was used by a 3D printer manufacturer, who must have been one of the first to have the software that came with their device. This new Simplify3D Serial Key download has a wealth of cool features for size FDM 3D printers. Later, when I grabbed a copy for myself, I was also impressed with the advanced cutting features that seemed light years away from the alternatives at the time. With powerful online model plating features, you can now 3D print from anywhere.
    Simplify3D License Key
    Parallels Desktop Activation Key Cracked
    TeraCopy Pro License Key
    Boom 3D Serial Key Full Download

  24. Your blog is very supporting us. We have regularly reading your blog.
    Vysor Pro Crack is a great tool for controlling your Android device from your computer.
    Through this software, you can view and control your Android phone on a PC.
    You can use apps, play games, mirror screens, and manage movies, contacts, music,
    and other files using your mouse.


Got an opinion? Who hasn't? Post it here...