Saturday, 5 May 2012

Getting total progress on downloading multiple files using WebClient


Below is the code while explains:
 - How to download the file from site Asynchronously and
 - Calculate the Total progress while downloading multiple files using WebClient


  
    class Program
    {
        static Queue<string> downloadUrls = new Queue<string>();
        static long totalFileSize = 0;
        static long bytesRecieved = 0;
        static long totalBytesRecieved = 0;

        #region main
        static void Main(string[] args)
        {
            DownloadFiles();
        }
        #endregion

        #region Download file with progress
        // First get the total size of all the files
        private static void DownloadFiles()
        {
            try
            {
                string file1 = "https://<some site>/file1.jpg";
                string file2 = "https://<some site>/file2.doc";
                string file3 = "https://<some site>/file3.ppt";

                string[] fileUrls = { file1, file2, file3 };

                foreach (string url in fileUrls)
                {
                    downloadUrls.Enqueue(url);

                    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                    webRequest.Credentials = CredentialCache.DefaultCredentials;
                   
                    using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
                    {
                        totalFileSize += webResponse.ContentLength;

    Console.WriteLine("File URL = " + url);
                        Console.WriteLine("File size = " + webResponse.ContentLength);
                    }
                }

                Console.WriteLine("Total size = " + totalFileSize.ToString());
                Console.WriteLine("Start download the file");

                DownloadWithProgress();
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private static void DownloadWithProgress()
        {
            string downloadPath = string.Empty;

            try
            {
                if (downloadUrls.Any())
                {
                    WebClient Client = new WebClient();
                    
                    // Callback method
                    Client.DownloadProgressChanged += DownloadFileProgress;                 
                    Client.DownloadFileCompleted += DownloadFileCompleted;
                    var url = downloadUrls.Dequeue();

                    downloadPath = Environment.GetEnvironmentVariable("TEMP") + "\\" + Path.GetFileName(url);
                    Client.DownloadFileAsync(new Uri(url), downloadPath);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: DownloadWithProgress(): " + ex.Message);
            }
        }

        private static void DownloadFileProgress(object sender, DownloadProgressChangedEventArgs e)
        {
            try
            {
                bytesRecieved = totalBytesRecieved + e.BytesReceived;
                // Calculate the total percentage

                double dProgress = (((double)bytesRecieved / totalFileSize) * 100);
                Console.Write('\r' + "Downloading files: {0}%", Math.Round(dProgress));
            }
            catch { }
        }

        private static void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            try
            {
                totalBytesRecieved = bytesRecieved;
                DownloadWithProgress();
            }
            catch { }
        }
        #endregion
    }


Thursday, 9 February 2012

Important Exception and Solutions found on Web & SharePoint Development

1. 
Exception: 
"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel" on Service call
Solution: 
- Add the folowing entry in web.config
<servicePointManager checkCertificateName="false" checkCertificateRevocationList="false"/>
- Write the following code just before the service call
ServicePointManager.ServerCertificateValidationCallback = (obj,certificate,chain,errors) => true;