DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

Developing SevenDrops - A Dropbox-based photo uploader for Windows Phone 7 [5/6]

Denzel D. user avatar by
Denzel D.
·
Apr. 06, 11 · Interview
Like (0)
Save
Tweet
Share
10.91K Views

Join the DZone community and get the full member experience.

Join For Free

It's now time to work on the actual upload mechanism for the application. It still relies on OAuth, but as it was shown in the previous article, the foundation for it is already created.

The first thing that I did is create the Upload method - the one that will actually be performing the procedure. Here is what it looks like:

public static void Upload(string name, byte[] content, string token, string apiKey, string consumerSecret, string tokenSecret)
{
    Dictionary<string, string> parameters = new Dictionary<string, string>();

    parameters.Add("oauth_consumer_key", apiKey);
    parameters.Add("oauth_signature_method", "HMAC-SHA1");
    parameters.Add("oauth_timestamp", CurrentUNIXTimestamp.Get());
    parameters.Add("oauth_nonce", Guid.NewGuid().ToString().Replace("-", ""));
    parameters.Add("oauth_token", token);
    parameters.Add("oauth_version", "1.0");
    parameters.Add("file", name);

    string OAuthHeader = GetOAuthHeader(parameters, "POST", "https://api-content.dropbox.com/0/files/dropbox/SevenDrops", consumerSecret, tokenSecret);

    string boundary = Guid.NewGuid().ToString();
    string header = "--" + boundary;
    string footer = "--" + boundary + "--";

    HttpWebRequest uploadRequest = (HttpWebRequest)WebRequest.Create("https://api-content.dropbox.com/0/files/dropbox/SevenDrops");
    uploadRequest.ContentType = "multipart/form-data; boundary=" + boundary;
    uploadRequest.Method = "POST";
    uploadRequest.Headers["Authorization"] = OAuthHeader;

    StringBuilder headers = new StringBuilder();
    headers.AppendLine(header);
    headers.AppendLine("Content-Disposition: file; name=\"file\"; filename=\""+ name +"\"");
    headers.AppendLine("Content-Type: application/octet-stream");
    headers.AppendLine();
    headers.AppendLine(Encoding.GetEncoding("iso-8859-1").GetString(content, 0, content.Length));
    headers.AppendLine(footer);

    byte[] contents = Encoding.GetEncoding("iso-8859-1").GetBytes(headers.ToString());

    object[] data = new object[2] { uploadRequest, contents };
    uploadRequest.BeginGetRequestStream(new AsyncCallback(GetData), data);
}

There are a couple of things you should notice about this method. I am using the same standard set of parameters to create the OAuth signature. However, there is a new one - file. That's where I am setting the file name for the uploaded file.

REMINDER: I will not be operating with direct paths here. I already have an ImageUnit class that contains the byte array (file contents).

Take a look at the URL I am using. I am executing a POST request to https://api-content.dropbox.com/0/files/dropbox/SevenDrops - this is a different subdomain. For other API calls api.dropbox.com was invoked. Here there is api-content. According to the official documentation, this was introduced for performance conservation reasons.

The request itself will be passing multipart data and I am following a standard pattern to build the HTTP headers.

NOTE: Even though you can be uploading different files that have different file types, the MIME type used for the request should always be application/octet-stream.

I am using the ISO 8859-1 charset for conversion purposes. This is the standard character set used in HTML documents and it is one of the recommended charsets to be used for transmitted encoded data.

When I am invoking the asynchronous BeginGetRequestStream, I am passing the state that is in fact an object array, that will contain both the image array and the request, so that I won't have to make the bytes publicly accessible across the class.

The callback is this:

static void GetData(IAsyncResult result)
{
    object[] data = (object[])result.AsyncState;
    byte[] content = (byte[])data[1];

    HttpWebRequest request = (HttpWebRequest)data[0];

    Stream requestStream = request.EndGetRequestStream(result);
    requestStream.Write(content, 0, content.Length);
    requestStream.Close();

    request.BeginGetResponse(new AsyncCallback(GetResponse), request);
   
}

The moment the callback is invoked, I am getting the state information and attempting to write the data to the request stream. Once that process is complete and the stream is closed, I am trying to get the response:

static void GetResponse(IAsyncResult result)
{
    HttpWebRequest request = (HttpWebRequest)result.AsyncState;
    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);

    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        string responseText = reader.ReadToEnd();
        Debug.WriteLine(responseText);
    }
}

A successful web response means that the file upload is complete. Now the uploading core is in place and is added to the OAuthClient static class. All that is left now is put everything together in the main view and wire it.

Windows Phone

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How To Best Use Java Records as DTOs in Spring Boot 3
  • How We Solved an OOM Issue in TiDB with GOMEMLIMIT
  • A Gentle Introduction to Kubernetes
  • Stop Using Spring Profiles Per Environment

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: