Click here to Skip to main content
15,884,298 members
Articles / Programming Languages / C# 4.0

Gett.NET - A library for Ge.tt Web Services

Rate me:
Please Sign up or sign in to vote.
4.98/5 (14 votes)
18 Jan 2016CPOL7 min read 54K   1.3K   45  
Use Ge.tt Web Services for real-time file publishing and sharing.
#region License information
/*

  Copyright (c) 2012 Togocoder (http://www.codeproject.com/Members/Kim-Togo)
 
  This file is part of Gett.NET library that uses the Ge.tt REST API, http://ge.tt/developers

  Gett.NET is a free library: you can redistribute it and/or modify as nessery
  it under the terms of The Code Project Open License (CPOL) as published by
  the The Code Project, either version 1.02 of the License, or (at your option) any later version.

  Gett.NET is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY OF ANY KIND. The software is provided "as-is".
 
  Please read the The Code Project Open License (CPOL) at http://www.codeproject.com/info/cpol10.aspx

  I would appreciate getting an email, if you choose to use this library in your own work.
  Send an email to togocoder(at)gmail.com with a little description of your work, thanks! :-)

  ---
  Gett.NET library makes heavy use of Json.NET - http://json.codeplex.com/ for serialize and deserialize
  of JSON class, Newtonsoft.Json.dll.
 
  License information on Json.NET, see http://json.codeplex.com/license.
  Copyright (c) 2007 James Newton-King

  Permission is hereby granted, free of charge, to any person obtaining a copy of
  this software and associated documentation files (the "Software"), to deal in the Software without restriction,
  including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
  and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
  ---
  Gett.NET library make use of WebSocket protocol client from https://github.com/sta/websocket-sharp
  The library is used to make a connection to Ge.tt Live API.
  Please see WsStream.cs for license information.

*/
#endregion

using System;
using System.Net;
using System.Text;
using Newtonsoft.Json;

namespace Gett.Sharing
{
  /// <summary>
  /// Represent a file in a share for user.
  /// http://ge.tt/developers - REST API for Ge.tt Web service - file API.
  /// </summary>
  [System.Diagnostics.DebuggerDisplay("FileId = {fileInfo.FileId}, FileName = {fileInfo.FileName}, CreatedUtc = {fileInfo.CreatedUtc}")]
  public class GettFile : GettBaseUri
  {
    #region HashCode and Equals overrides
    public override int GetHashCode()
    {
      return this.fileInfo == null ? base.GetHashCode() : this.fileInfo.FileId.GetHashCode();
    }

    public override bool Equals(object obj)
    {
      GettFile file = obj as GettFile;
      return file == null ? false : file.fileInfo.FileId == this.fileInfo.FileId;
    }

    public override string ToString()
    {
      return string.Format("FileName:{0}, Size:{1}, DL:{2}, CreatedUtc:{3}", this.fileInfo.FileName, this.fileInfo.Size, this.fileInfo.Downloads, this.fileInfo.CreatedUtc);
    }
    #endregion

    #region JSON Serialize/Deserialize classes
    [System.Diagnostics.DebuggerDisplay("FileInfo = {FileId}, FileName = {FileName}, CreatedUtc = {CreatedUtc}")]
    [JsonObject(MemberSerialization.OptOut)]
    public class FileInfo
    {
      [JsonIgnore]
      public readonly DateTime Timestamp = DateTime.Now;
      [JsonProperty("fileid")]
      public string FileId = null;
      [JsonProperty("created")]
      [JsonConverter(typeof(Newtonsoft.Json.Converters.UnixDateTimeConverter))]
      public DateTime? CreatedUtc = null;
      [JsonProperty("filename")]
      public string FileName = null;
      [JsonProperty("size")]
      public long Size = 0;
      [JsonProperty("downloads")]
      public int Downloads = 0;
      [JsonProperty("readystate")]
      public string ReadyState = null;
      [JsonProperty("sharename")]
      public string ShareName = null;
      [JsonProperty("getturl")]
      public string GettUrl = null;
      [JsonProperty("upload")]
      public UploadInfo Upload = null;
    }

    [System.Diagnostics.DebuggerDisplay("PostUrl = {PostUrl}, PutUrl = {PutUrl}")]
    [JsonObject(MemberSerialization.OptOut)]
    public class UploadInfo
    {
      [JsonProperty("puturl")]
      public string PutUrl = null;
      [JsonProperty("posturl")]
      public string PostUrl = null;
    }
    #endregion

    #region Variables
    /// <summary>
    /// Provides access to GettUser object, Token etc.
    /// </summary>
    private GettUser gettUser;

    /// <summary>
    /// Provides access to GettShare object.
    /// </summary>
    internal GettShare gettShare;

    /// <summary>
    /// Provides information on what File we are working on.
    /// </summary>
    internal FileInfo fileInfo;
    #endregion

    #region ctor
    /// <summary>
    /// Internal ctor, GettShare class creates new instance for this class.
    /// </summary>
    /// <param name="gettUser">GettUser class</param>
    /// <param name="gettShare">GettShare class</param>
    /// <param name="fileInfo">Information for this share</param>
    internal GettFile(GettUser gettUser, GettShare gettShare, FileInfo fileInfo)
    {
      this.gettUser = gettUser;
      this.gettShare = gettShare;
      this.fileInfo = fileInfo;
    }
    #endregion

    #region Common information about this file
    /// <summary>
    /// Parent of this class. GettShare class.
    /// </summary>
    public GettShare Parent { get { return this.gettShare; } }

    /// <summary>
    /// Access to file information.
    /// </summary>
    public FileInfo Info { get { return this.fileInfo; } }
    #endregion

    #region Refresh file information - /files/{sharename}/{fileid}
    /// <summary>
    /// Refresh file information.
    /// </summary>
    public void Refresh()
    {
      // Build Uri
      UriBuilder baseUri = new UriBuilder(GettBaseUri.BaseUri);
      baseUri.Path = baseUri.Path + string.Format(base.FileList, this.gettShare.shareInfo.ShareName, this.fileInfo.FileId);
      baseUri.Query = string.Format("accesstoken={0}", this.gettUser.Token.AccessToken);

      // GET request
      WebClient gett = new WebClient();
      gett.Encoding = System.Text.Encoding.UTF8;
      byte[] response = gett.DownloadData(baseUri.Uri);

      // Response
      FileInfo fileInfo = JsonConvert.DeserializeObject<FileInfo>(Encoding.UTF8.GetString(response));
      this.fileInfo = fileInfo;
    }

    /// <summary>
    /// Begins an asynchronous refresh file information.
    /// </summary>
    public IAsyncResult BeginRefresh(AsyncCallback callBack, object state)
    {
      System.Threading.Tasks.Task t = System.Threading.Tasks.Task.Factory.StartNew(_ => Refresh(), state);

      if (callBack != null)
        t.ContinueWith((res) => callBack(t));

      return t;
    }

    /// <summary>
    /// Handles the end of an asynchronous Refresh. 
    /// </summary>
    /// <param name="ar"></param>
    public void EndRefresh(IAsyncResult ar)
    {
      try
      {
        System.Threading.Tasks.Task t = (System.Threading.Tasks.Task)ar;

        if (t.IsFaulted)
          throw t.Exception.InnerException;
      }
      catch (AggregateException ae)
      {
        throw ae.InnerException;
      }
    }
    #endregion

    #region Prepare to overwrite file - /files/{sharename}/{fileid}/upload
    /// <summary>
    /// Prepare to overwrite existing file. Get new upload uri.
    /// </summary>
    public void RefreshUpload()
    {
      // Build Uri
      UriBuilder baseUri = new UriBuilder(GettBaseUri.BaseUri);
      baseUri.Path = baseUri.Path + string.Format(base.FileUpload, this.gettShare.shareInfo.ShareName, this.fileInfo.FileId);
      baseUri.Query = string.Format("accesstoken={0}", this.gettUser.Token.AccessToken);

      // GET request
      WebClient gett = new WebClient();
      gett.Encoding = System.Text.Encoding.UTF8;
      byte[] response = gett.DownloadData(baseUri.Uri);

      // Response
      UploadInfo uploadInfo = JsonConvert.DeserializeObject<UploadInfo>(Encoding.UTF8.GetString(response));
      this.fileInfo.Upload = uploadInfo;
    }

    /// <summary>
    /// Begins an asynchronous prepare to overwrite existing file. Get new upload uri.
    /// </summary>
    public IAsyncResult BeginRefreshUpload(AsyncCallback callBack, object state)
    {
      System.Threading.Tasks.Task t = System.Threading.Tasks.Task.Factory.StartNew(_ => RefreshUpload(), state);

      if (callBack != null)
        t.ContinueWith((res) => callBack(t));

      return t;
    }

    /// <summary>
    /// Handles the end of an asynchronous RefreshUpload. 
    /// </summary>
    /// <param name="ar"></param>
    public void EndRefreshUpload(IAsyncResult ar)
    {
      try
      {
        System.Threading.Tasks.Task t = (System.Threading.Tasks.Task)ar;

        if (t.IsFaulted)
          throw t.Exception.InnerException;
      }
      catch (AggregateException ae)
      {
        throw ae.InnerException;
      }
    }
    #endregion

    #region Delete a file and the binary contents - /files/{sharename}/{fileid}/destroy
    /// <summary>
    /// Delete file.
    /// </summary>
    public bool Destroy()
    {
      // Build Uri
      UriBuilder baseUri = new UriBuilder(GettBaseUri.BaseUri);
      baseUri.Path = baseUri.Path + string.Format(base.FileDestroy, this.gettShare.shareInfo.ShareName, this.fileInfo.FileId);
      baseUri.Query = string.Format("accesstoken={0}", this.gettUser.Token.AccessToken);

      // POST request
      WebClient gett = new WebClient();
      gett.Encoding = System.Text.Encoding.UTF8;
      byte[] request = new byte[0];
      byte[] response = gett.UploadData(baseUri.Uri, request);

      // Response
      string jsonResponse = Encoding.UTF8.GetString(response);
      return jsonResponse.Contains("true");
    }

    /// <summary>
    /// Begins an asynchronous delete file.
    /// </summary>
    public IAsyncResult BeginDestroy(AsyncCallback callBack, object state)
    {
      System.Threading.Tasks.Task t = System.Threading.Tasks.Task.Factory.StartNew(_ => Destroy(), state);

      if (callBack != null)
        t.ContinueWith((res) => callBack(t));

      return t;
    }

    /// <summary>
    /// Handles the end of an asynchronous Destroy. 
    /// </summary>
    /// <param name="ar"></param>
    public void EndDestroy(IAsyncResult ar)
    {
      try
      {
        System.Threading.Tasks.Task t = (System.Threading.Tasks.Task)ar;

        if (t.IsFaulted)
          throw t.Exception.InnerException;
      }
      catch (AggregateException ae)
      {
        throw ae.InnerException;
      }
    }
    #endregion

    #region Upload and Download - posturl or puturl
    /// <summary>
    /// Upload file content to POST URL.
    /// </summary>
    /// <param name="fileName">File to upload content</param>
    /// <returns>True if uploads is successful</returns>
    public bool UploadFile(string fileName)
    {
      // POST request
      WebClient gett = new WebClient();
      byte[] response = gett.UploadFile(this.fileInfo.Upload.PostUrl, fileName);

      // Response
      string jsonResponse = Encoding.UTF8.GetString(response);
      return jsonResponse.Contains("computer says yes");
    }

    /// <summary>
    /// Begins an asynchronous upload file content to POST URL.
    /// </summary>
    public IAsyncResult BeginUploadFile(string fileName, AsyncCallback callBack, object state)
    {
      System.Threading.Tasks.Task<bool> t = System.Threading.Tasks.Task.Factory.StartNew<bool>(_ => UploadFile(fileName), state);

      if (callBack != null)
        t.ContinueWith((res) => callBack(t));

      return t;
    }

    /// <summary>
    /// Handles the end of an asynchronous UploadFile. 
    /// </summary>
    /// <param name="ar"></param>
    /// <returns>True if uploads is successful</returns>
    public bool EndUploadFile(IAsyncResult ar)
    {
      try
      {
        System.Threading.Tasks.Task<bool> t = (System.Threading.Tasks.Task<bool>)ar;

        if (t.IsFaulted)
          throw t.Exception.InnerException;

        return t.Result;
      }
      catch (AggregateException ae)
      {
        throw ae.InnerException;
      }
    }

    /// <summary>
    /// Upload byte array content to PUT URL.
    /// </summary>
    /// <param name="data">Byte array</param>
    /// <returns>True if uploads is successful</returns>
    public bool UploadData(byte[] data)
    {
      // POST request
      WebClient gett = new WebClient();
      byte[] response = gett.UploadData(this.fileInfo.Upload.PutUrl, "PUT", data);

      // Response
      string jsonResponse = Encoding.UTF8.GetString(response);
      return jsonResponse.Contains("computer says yes");
    }

    /// <summary>
    /// Begins an asynchronous upload byte array content to PUT URL.
    /// </summary>
    public IAsyncResult BeginUploadData(byte[] data, AsyncCallback callBack, object state)
    {
      System.Threading.Tasks.Task<bool> t = System.Threading.Tasks.Task.Factory.StartNew<bool>(_ => UploadData(data), state);

      if (callBack != null)
        t.ContinueWith((res) => callBack(t));

      return t;
    }

    /// <summary>
    /// Handles the end of an asynchronous UploadData. 
    /// </summary>
    /// <param name="ar"></param>
    /// <returns>True if uploads is successful</returns>
    public bool EndUploadData(IAsyncResult ar)
    {
      try
      {
        System.Threading.Tasks.Task<bool> t = (System.Threading.Tasks.Task<bool>)ar;

        if (t.IsFaulted)
          throw t.Exception.InnerException;

        return t.Result;
      }
      catch (AggregateException ae)
      {
        throw ae.InnerException;
      }
    }

    /// <summary>
    /// Download file content.
    /// </summary>
    /// <param name="fileName">File to store content</param>
    public void DownloadFile(string fileName)
    {
      // Build Uri
      UriBuilder baseUri = new UriBuilder(GettBaseUri.BaseUri);
      baseUri.Path = baseUri.Path + string.Format(base.FileDownloadBlob, this.gettShare.shareInfo.ShareName, this.fileInfo.FileId);

      // GET request
      WebClient gett = new WebClient();
      gett.DownloadFile(baseUri.Uri, fileName);
    }

    /// <summary>
    /// Begins an asynchronous download file content.
    /// </summary>
    /// <param name="fileName">File to store content</param>
    public IAsyncResult BeginDownloadFile(string fileName, AsyncCallback callBack, object state)
    {
      System.Threading.Tasks.Task t = System.Threading.Tasks.Task.Factory.StartNew(_ => DownloadFile(fileName), state);

      if (callBack != null)
        t.ContinueWith((res) => callBack(t));

      return t;
    }

    /// <summary>
    /// Handles the end of an asynchronous DownloadFile. 
    /// </summary>
    /// <param name="ar"></param>
    public void EndDownloadFile(IAsyncResult ar)
    {
      try
      {
        System.Threading.Tasks.Task t = (System.Threading.Tasks.Task)ar;

        if (t.IsFaulted)
          throw t.Exception.InnerException;

      }
      catch (AggregateException ae)
      {
        throw ae.InnerException;
      }
    }

    /// <summary>
    /// Download file content and return an array of bytes.
    /// </summary>
    /// <returns>Byte array of file content</returns>
    public byte[] DownloadData()
    {
      // Build Uri
      UriBuilder baseUri = new UriBuilder(GettBaseUri.BaseUri);
      baseUri.Path = baseUri.Path + string.Format(base.FileDownloadBlob, this.gettShare.shareInfo.ShareName, this.fileInfo.FileId);

      // GET request
      WebClient gett = new WebClient();
      return gett.DownloadData(baseUri.Uri);
    }

    /// <summary>
    /// Begins an asynchronous download file content and return an array of bytes.
    /// </summary>
    public IAsyncResult BeginDownloadData(AsyncCallback callBack, object state)
    {
      System.Threading.Tasks.Task<byte[]> t = System.Threading.Tasks.Task.Factory.StartNew<byte[]>(_ => DownloadData(), state);

      if (callBack != null)
        t.ContinueWith((res) => callBack(t));

      return t;
    }

    /// <summary>
    /// Handles the end of an asynchronous UploadData. 
    /// </summary>
    /// <param name="ar"></param>
    /// <returns>Byte array of file content</returns>
    public byte[] EndDownloadData(IAsyncResult ar)
    {
      try
      {
        System.Threading.Tasks.Task<byte[]> t = (System.Threading.Tasks.Task<byte[]>)ar;

        if (t.IsFaulted)
          throw t.Exception.InnerException;

        return t.Result;
      }
      catch (AggregateException ae)
      {
        throw ae.InnerException;
      }
    }
    #endregion

    #region Asynchron Upload and Download using EAP Patterns. - posturl or puturl
    /// <summary>
    /// Object used for thread-safe for WebClient gettAsync.
    /// </summary>
    private object syncRootAsync = new object();
    
    /// <summary>
    /// WebClient used for Asynchron operation.
    /// </summary>
    private WebClient gettAsync = null;

    /// <summary>
    /// Cancel Async upload or download.
    /// </summary>
    public void CancelAsync()
    {
      lock (this.syncRootAsync)
      {
        // Abort other operation.
        if (this.gettAsync != null)
        {
          this.gettAsync.DownloadDataCompleted -= this.Gett_DownloadDataCompleted;
          this.gettAsync.DownloadFileCompleted -= this.Gett_DownloadFileCompleted;
          this.gettAsync.DownloadProgressChanged -= this.Gett_DownloadProgressChanged;
          this.gettAsync.UploadDataCompleted -= this.Gett_UploadDataCompleted;
          this.gettAsync.UploadFileCompleted -= this.Gett_UploadFileCompleted;
          this.gettAsync.UploadProgressChanged -= this.Gett_UploadProgressChanged;

          if (this.gettAsync.IsBusy)
            this.gettAsync.CancelAsync();
        }
      }
    }

    /// <summary>
    /// This event is raised each time file upload operation completes.
    /// </summary>
    public event UploadFileCompletedEventHandler UploadFileCompleted;

    /// <summary>
    /// This event is raised each time upload makes progress.
    /// </summary>
    public event UploadProgressChangedEventHandler UploadProgressChanged;

    /// <summary>
    /// Upload file content asynchron.
    /// Progress is signaled via UploadProgressChanged and UploadFileCompleted event.
    /// </summary>
    /// <param name="fileName">File to upload content</param>
    public void UploadFileAsync(string fileName)
    {
      lock (this.syncRootAsync)
      {
        // Abort other operation.
        if (this.gettAsync != null)
        {
          this.gettAsync.DownloadDataCompleted -= this.Gett_DownloadDataCompleted;
          this.gettAsync.DownloadFileCompleted -= this.Gett_DownloadFileCompleted;
          this.gettAsync.DownloadProgressChanged -= this.Gett_DownloadProgressChanged;
          this.gettAsync.UploadDataCompleted -= this.Gett_UploadDataCompleted;
          this.gettAsync.UploadFileCompleted -= this.Gett_UploadFileCompleted;
          this.gettAsync.UploadProgressChanged -= this.Gett_UploadProgressChanged;

          if (this.gettAsync.IsBusy)
            this.gettAsync.CancelAsync();
        }

        // GET request
        this.gettAsync = new WebClient();
        this.gettAsync.UploadFileCompleted += new UploadFileCompletedEventHandler(this.Gett_UploadFileCompleted);
        this.gettAsync.UploadProgressChanged += new UploadProgressChangedEventHandler(this.Gett_UploadProgressChanged);
        this.gettAsync.UploadFileAsync(new Uri(this.fileInfo.Upload.PostUrl), fileName);
      }
    }

    /// <summary>
    /// This event is raised each time upload makes progress.
    /// </summary>
    private void Gett_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
    {
      UploadProgressChangedEventHandler copyUploadProgressChanged = this.UploadProgressChanged;
      if (copyUploadProgressChanged != null)
        copyUploadProgressChanged(this, e);
    }

    /// <summary>
    /// This event is raised each time file upload operation completes.
    /// </summary>
    private void Gett_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
    {
      UploadFileCompletedEventHandler copyUploadFileCompleted = this.UploadFileCompleted;
      if (copyUploadFileCompleted != null)
        copyUploadFileCompleted(this, e);
    }

    /// <summary>
    /// This event is raised each time an asynchronous data upload operation completes.
    /// </summary>
    public event UploadDataCompletedEventHandler UploadDataCompleted;

    /// Upload byte array content asynchron.
    /// Progress is signaled via UploadProgressChanged and UploadDataCompleted event.
    /// </summary>
    /// <param name="data">Byte array</param>
    public void UploadDataAsync(byte[] data)
    {
      lock (this.syncRootAsync)
      {
        // Abort other operation.
        if (this.gettAsync != null)
        {
          this.gettAsync.DownloadDataCompleted -= this.Gett_DownloadDataCompleted;
          this.gettAsync.DownloadFileCompleted -= this.Gett_DownloadFileCompleted;
          this.gettAsync.DownloadProgressChanged -= this.Gett_DownloadProgressChanged;
          this.gettAsync.UploadDataCompleted -= this.Gett_UploadDataCompleted;
          this.gettAsync.UploadFileCompleted -= this.Gett_UploadFileCompleted;
          this.gettAsync.UploadProgressChanged -= this.Gett_UploadProgressChanged;

          if (this.gettAsync.IsBusy)
            this.gettAsync.CancelAsync();
        }

        // GET request
        this.gettAsync = new WebClient();
        this.gettAsync.UploadDataCompleted += new UploadDataCompletedEventHandler(this.Gett_UploadDataCompleted);
        this.gettAsync.UploadProgressChanged += new UploadProgressChangedEventHandler(this.Gett_UploadProgressChanged);

        this.gettAsync.UploadDataAsync(new Uri(this.fileInfo.Upload.PutUrl), "PUT", data);
      }
    }

    /// <summary>
    /// This event is raised each time an asynchronous data upload operation completes
    /// </summary>
    private void Gett_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
    {
      UploadDataCompletedEventHandler copyUploadDataCompleted = this.UploadDataCompleted;
      if (copyUploadDataCompleted != null)
        copyUploadDataCompleted(this, e);
    }

    /// <summary>
    /// This event is raised each time file download operation completes.
    /// </summary>
    public event System.ComponentModel.AsyncCompletedEventHandler DownloadAsyncFileCompleted;
    
    /// <summary>
    /// This event is raised each time download makes progress.
    /// </summary>
    public event DownloadProgressChangedEventHandler DownloadAsyncProgressChanged;

    /// <summary>
    /// Download file content asynchron.
    /// Progress is signaled via DownloadAsyncProgressChanged and DownloadAsyncFileCompleted event.
    /// </summary>
    /// <param name="fileName">File to store content</param>
    public void DownloadFileAsync(string fileName)
    {
      lock (this.syncRootAsync)
      {
        // Abort other operation.
        if (this.gettAsync != null)
        {
          this.gettAsync.DownloadDataCompleted -= this.Gett_DownloadDataCompleted;
          this.gettAsync.DownloadFileCompleted -= this.Gett_DownloadFileCompleted;
          this.gettAsync.DownloadProgressChanged -= this.Gett_DownloadProgressChanged;
          this.gettAsync.UploadDataCompleted -= this.Gett_UploadDataCompleted;
          this.gettAsync.UploadFileCompleted -= this.Gett_UploadFileCompleted;
          this.gettAsync.UploadProgressChanged -= this.Gett_UploadProgressChanged;
          
          if (this.gettAsync.IsBusy)
            this.gettAsync.CancelAsync();
        }

        // Build Uri
        UriBuilder baseUri = new UriBuilder(GettBaseUri.BaseUri);
        baseUri.Path = baseUri.Path + string.Format(base.FileDownloadBlob, this.gettShare.shareInfo.ShareName, this.fileInfo.FileId);

        // GET request
        this.gettAsync = new WebClient();
        this.gettAsync.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(this.Gett_DownloadFileCompleted);
        this.gettAsync.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.Gett_DownloadProgressChanged);
        this.gettAsync.DownloadFileAsync(baseUri.Uri, fileName);
      }
    }

    /// <summary>
    /// This event is raised each time download makes progress.
    /// </summary>
    private void Gett_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
      DownloadProgressChangedEventHandler copyDownloadAsyncProgressChanged = this.DownloadAsyncProgressChanged;
      if (copyDownloadAsyncProgressChanged != null)
        copyDownloadAsyncProgressChanged(this, e);
    }

    /// <summary>
    /// This event is raised each time file download operation completes.
    /// </summary>
    private void Gett_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
    {
      System.ComponentModel.AsyncCompletedEventHandler copyDownloadAsyncFileCompleted = this.DownloadAsyncFileCompleted;
      if (copyDownloadAsyncFileCompleted != null)
        copyDownloadAsyncFileCompleted(this, e);
    }

    /// <summary>
    /// This event is raised each time an asynchronous data download operation completes.
    /// Downloaded data is in DownloadDataCompletedEventArgs.Result byte array. Remember to check DownloadDataCompletedEventArgs.Error and .Cancel results.
    /// </summary>
    public event DownloadDataCompletedEventHandler DownloadDataCompleted;

    /// <summary>
    /// Download file content asynchron.
    /// Progress is signaled via DownloadAsyncProgressChanged and DownloadAsyncFileCompleted event.
    /// </summary>
    /// <param name="fileName">File to store content</param>
    public void DownloadDataAsync(string fileName)
    {
      lock (this.syncRootAsync)
      {
        // Abort other operation.
        if (this.gettAsync != null)
        {
          this.gettAsync.DownloadDataCompleted -= this.Gett_DownloadDataCompleted;
          this.gettAsync.DownloadFileCompleted -= this.Gett_DownloadFileCompleted;
          this.gettAsync.DownloadProgressChanged -= this.Gett_DownloadProgressChanged;
          this.gettAsync.UploadDataCompleted -= this.Gett_UploadDataCompleted;
          this.gettAsync.UploadFileCompleted -= this.Gett_UploadFileCompleted;
          this.gettAsync.UploadProgressChanged -= this.Gett_UploadProgressChanged;

          if (this.gettAsync.IsBusy)
            this.gettAsync.CancelAsync();
        }

        // Build Uri
        UriBuilder baseUri = new UriBuilder(GettBaseUri.BaseUri);
        baseUri.Path = baseUri.Path + string.Format(base.FileDownloadBlob, this.gettShare.shareInfo.ShareName, this.fileInfo.FileId);

        // GET request
        this.gettAsync = new WebClient();
        this.gettAsync.DownloadDataCompleted += new DownloadDataCompletedEventHandler(this.Gett_DownloadDataCompleted);
        this.gettAsync.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.Gett_DownloadProgressChanged);
        this.gettAsync.DownloadDataAsync(baseUri.Uri, fileName);
      }
    }

    /// <summary>
    /// This event is raised each time an asynchronous data download operation completes
    /// </summary>
    private void Gett_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
    {
      DownloadDataCompletedEventHandler copyDownloadDataCompleted = this.DownloadDataCompleted;
      if (copyDownloadDataCompleted != null)
        copyDownloadDataCompleted(this, e);
    }
    #endregion
  }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Miralix
Denmark Denmark
Has worked as a programmer since 1999, starting with C++/MFC, Java, PHP and MySQL. Now it is all about C# (my favorite programming language), MS SQL, Azure and Xamarin (iOS/Android/WP8)

My primary work is to create applications that interacts with PABC/PBX, Microsoft Lync / UCMA.

Comments and Discussions