Ejemplo n.º 1
0
        private void ProcDownload(object o)
        {
            var    errorMessageStr = new StringBuilder();
            string tempFolderPath  = Path.Combine(CommonUnitity.SystemBinUrl, curBakFolderName);

            if (!Directory.Exists(tempFolderPath))
            {
                Directory.CreateDirectory(tempFolderPath);
            }


            evtPerDonwload = new ManualResetEvent(false);

            foreach (DownloadFileInfo file in this.downloadFileList)
            {
                total += file.Size;
            }
            try
            {
                while (!evtDownload.WaitOne(0, false))
                {
                    if (this.downloadFileList.Count == 0)
                    {
                        break;
                    }

                    DownloadFileInfo file = this.downloadFileList[0];


                    //Debug.WriteLine(String.Format("Start Download:{0}", file.FileName));

                    this.ShowCurrentDownloadFileName(file.FileName);

                    //Download
                    clientDownload = new WebClient();

                    //Added the function to support proxy
                    // clientDownload.Proxy = System.Net.WebProxy.GetDefaultProxy();
                    clientDownload.Proxy             = WebRequest.GetSystemWebProxy();
                    clientDownload.Proxy.Credentials = CredentialCache.DefaultCredentials;
                    //clientDownload.Credentials = System.Net.CredentialCache.DefaultCredentials;//ftp可能不可用
                    if (!string.IsNullOrEmpty(config.PassWord) && !string.IsNullOrEmpty(config.UserName))
                    {
                        clientDownload.Credentials = new NetworkCredential(config.UserName, config.PassWord);
                    }
                    else
                    {
                        clientDownload.Credentials = System.Net.CredentialCache.DefaultCredentials;
                    }
                    //End added

                    clientDownload.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) =>
                    {
                        try
                        {
                            this.SetProcessBar(e.ProgressPercentage, (int)((nDownloadedTotal + e.BytesReceived) * 100 / total));
                        }
                        catch (Exception ex)
                        {
                            _log.Info(ex.Message);
                            //log the error message,you can use the application's log code
                        }
                    };

                    clientDownload.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) =>
                    {
                        try
                        {
                            DealWithDownloadErrors();
                            DownloadFileInfo dfile = e.UserState as DownloadFileInfo;
                            nDownloadedTotal += dfile.Size;
                            this.SetProcessBar(0, (int)(nDownloadedTotal * 100 / total));
                            evtPerDonwload.Set();
                            Console.WriteLine(dfile.FileName + "下载成功");
                        }
                        catch (Exception ex)
                        {
                            _log.Info(ex.Message);
                            //log the error message,you can use the application's log code
                        }
                    };

                    evtPerDonwload.Reset();

                    //Download the folder file
                    string tempFolderPath1 = CommonUnitity.GetFolderUrl(file, curBakFolderName);
                    if (!string.IsNullOrEmpty(tempFolderPath1))
                    {
                        tempFolderPath  = Path.Combine(CommonUnitity.SystemBinUrl, curBakFolderName);
                        tempFolderPath += tempFolderPath1;
                    }
                    else
                    {
                        tempFolderPath = Path.Combine(CommonUnitity.SystemBinUrl, curBakFolderName);
                    }

                    if (!Directory.Exists(tempFolderPath))
                    {
                        Directory.CreateDirectory(tempFolderPath);
                    }

                    clientDownload.DownloadFileAsync(new Uri(file.DownloadUrl), Path.Combine(tempFolderPath, file.FileName), file);
                    //Wait for the download complete
                    evtPerDonwload.WaitOne();

                    clientDownload.Dispose();
                    clientDownload = null;

                    #region 可能会进行下载失败,进行多次重新下载
                    string             tempUrlPath = CommonUnitity.GetFolderUrl(file, curBakFolderName);
                    var                newPath     = Path.Combine(CommonUnitity.SystemBinUrl + curBakFolderName + tempUrlPath, file.FileName);
                    System.IO.FileInfo f           = new FileInfo(newPath);

                    if (file.TryTimes < tryTimes && !file.Size.ToString().Equals(f.Length.ToString()) && !file.FileName.ToString().EndsWith(".xml"))
                    {
                        //下载出错,进行重试
                        file.TryTimes += 1; //尝试次数递增
                        var curItem = config.UpdateFileList.Where(c => c.Version == file.Version).FirstOrDefault();
                        if (curItem != null)
                        {
                            curItem.TryTimes += 1; //失败的文件不保存,用于下次重启
                        }
                        if (_log != null)
                        {
                            _log.Info(string.Format("文件{0}:{1}下载失败后进行了第{2}次重试下载\n\r", file.DownloadUrl, file.Version, file.TryTimes));
                        }
                    }
                    else
                    {
                        //Remove the downloaded files
                        this.downloadFileList.Remove(file);
                    }
                    #endregion
                }
            }
            catch (Exception exp)
            {
                _log.Info(exp.Message);
                ShowErrorAndRestartApplication();
                //throw;
            }

            //When the files have not downloaded,return.
            if (downloadFileList.Count > 0)
            {
                return;
            }

            //Test network and deal with errors if there have
            DealWithDownloadErrors();

            //Debug.WriteLine("All Downloaded");

            foreach (DownloadFileInfo file in this.allFileList)
            {
                string tempUrlPath = CommonUnitity.GetFolderUrl(file, curBakFolderName);
                string oldPath     = string.Empty;
                string newPath     = string.Empty;
                try
                {
                    if (!string.IsNullOrEmpty(tempUrlPath))
                    {
                        oldPath = Path.Combine(CommonUnitity.SystemBinUrl + tempUrlPath.Substring(1), file.FileName);
                        newPath = Path.Combine(CommonUnitity.SystemBinUrl + curBakFolderName + tempUrlPath, file.FileName);
                    }
                    else
                    {
                        oldPath = Path.Combine(CommonUnitity.SystemBinUrl, file.FileName);
                        newPath = Path.Combine(CommonUnitity.SystemBinUrl + curBakFolderName, file.FileName);
                    }

                    //just deal with the problem which the files EndsWith xml can not download
                    System.IO.FileInfo f = new FileInfo(newPath);
                    //errorMessageStr.AppendFormat("{0},", file.FileFullName);
                    //2015.5.11文件不存在可以进行拷贝xml
                    if (!file.Size.ToString().Equals(f.Length.ToString()) && !file.FileName.ToString().EndsWith(".xml"))
                    {
                        //<LocalFile path="packages.config" lastver="" size="370" version="e0d3579f-44ba-4e99-b557-de2b37d9f588" />
                        var errorMsg = string.Format("<LocalFile path=\"{0}\"  lastver=\"\" size=\"{1}\" version=\"{2}\" downLoadUrl=\"{3}\"/>", file.FileFullName, file.Size, file.Version, file.DownloadUrl);
                        errorMessageStr.AppendLine(file.DownloadUrl);
                        var curItem = config.UpdateFileList.Where(c => c.Version == file.Version).FirstOrDefault();
                        if (curItem != null)
                        {
                            config.UpdateFileList.Remove(curItem);//失败的文件不保存,用于下次重启
                        }

                        continue;
                        //  ShowErrorAndRestartApplication();
                    }

                    //Added for dealing with the config file download errors
                    string newfilepath = string.Empty;
                    if (newPath.Substring(newPath.LastIndexOf(".") + 1).Equals(ConstFile.CONFIGFILEKEY))
                    {
                        if (System.IO.File.Exists(newPath))
                        {
                            if (newPath.EndsWith("_"))
                            {
                                newfilepath = newPath;
                                newPath     = newPath.Substring(0, newPath.Length - 1);
                                oldPath     = oldPath.Substring(0, oldPath.Length - 1);
                            }
                            _log.Info(string.Format("{0}->{1}", newfilepath, newPath));
                            File.Copy(newfilepath, newPath, true);
                        }
                    }
                    //End added

                    if (File.Exists(oldPath))//文件存在
                    {
                        MoveFolderToOld(oldPath, newPath);
                    }
                    else
                    {
                        //Edit for config_ file
                        if (!string.IsNullOrEmpty(tempUrlPath))
                        {
                            if (!Directory.Exists(CommonUnitity.SystemBinUrl + tempUrlPath.Substring(1)))
                            {
                                Directory.CreateDirectory(CommonUnitity.SystemBinUrl + tempUrlPath.Substring(1));


                                MoveFolderToOld(oldPath, newPath);
                            }
                            else
                            {
                                MoveFolderToOld(oldPath, newPath);
                            }
                        }
                        else
                        {
                            MoveFolderToOld(oldPath, newPath);
                        }
                    }
                }
                catch (Exception exp)
                {
                    _log.Info(exp.Message);
                    //log the error message,you can use the application's log code
                }
            }

            //After dealed with all files, clear the data
            this.allFileList.Clear();

            if (!string.IsNullOrEmpty(errorMessageStr.ToString()))
            {
                if (_log != null)
                {
                    _log.Info(string.Format("更新内容出错,无大小或者下载出错文件如下,可尝试手动更新,并配置IIS为可访问下载{0}", errorMessageStr.ToString()));
                }
                //CommonUnitity.RestartApplication();
            }
            else
            {
                if (_log != null)
                {
                    _log.Info(string.Format("本次更新成功个数为:{0}", config.UpdateFileList.Count()));
                }
            }


            if (this.downloadFileList.Count == 0)
            {
                Exit(true);
            }
            else
            {
                Exit(false);
            }

            evtDownload.Set();
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="o"></param>
        private void ProcDownload(object o)
        {
            try
            {
                //获取临时文件夹目录
                string tempFolderPath = Path.Combine(CommonUnitity.SystemBinUrl, ConstFile.TEMPFOLDERNAME);
                if (!Directory.Exists(tempFolderPath))
                {
                    Directory.CreateDirectory(tempFolderPath);
                }

                evtPerDonwload = new ManualResetEvent(false);

                //获取文件总大小
                foreach (DownloadFileInfo file in this.downloadFileList)
                {
                    total += file.Size;
                }


                //循环下载
                while (!evtDownload.WaitOne(0, false))
                {
                    if (this.downloadFileList.Count == 0)
                    {
                        break;
                    }

                    //取得下载文件信息
                    DownloadFileInfo file = this.downloadFileList[0];
                    //在UI呈现当前任务信息
                    this.ShowCurrentDownloadFileName(file.FileName, file.Size);
                    //创建网络连接
                    clientDownload = new WebClient();
                    //使用系统代理
                    clientDownload.Proxy = WebRequest.GetSystemWebProxy();
                    //使用应用程序凭据
                    clientDownload.Proxy.Credentials = CredentialCache.DefaultCredentials;
                    //使用应用程序凭据
                    clientDownload.Credentials = System.Net.CredentialCache.DefaultCredentials;
                    //文件下载进度更新
                    clientDownload.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) =>
                    {
                        try
                        {
                            this.SetProcessBar(e.ProgressPercentage, (int)((nDownloadedTotal + e.BytesReceived) * 100 / total));
                        }
                        catch { }
                    };

                    //文件下载完成
                    clientDownload.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) =>
                    {
                        try
                        {
                            //验证网络是否正常
                            DealWithDownloadErrors();
                            DownloadFileInfo dfile = e.UserState as DownloadFileInfo;
                            nDownloadedTotal += dfile.Size;
                            this.SetProcessBar(0, (int)(nDownloadedTotal * 100 / total));
                            //标记已完成
                            evtPerDonwload.Set();
                        }
                        catch { }
                    };
                    //阻隔线程
                    evtPerDonwload.Reset();
                    //创建文件保存路径
                    string tempFolderPath1 = CommonUnitity.GetFolderUrl(file);
                    if (!string.IsNullOrEmpty(tempFolderPath1))
                    {
                        tempFolderPath  = Path.Combine(CommonUnitity.SystemBinUrl, ConstFile.TEMPFOLDERNAME);
                        tempFolderPath += tempFolderPath1;
                    }
                    else
                    {
                        tempFolderPath = Path.Combine(CommonUnitity.SystemBinUrl, ConstFile.TEMPFOLDERNAME);
                    }

                    //开始下载文件
                    clientDownload.DownloadFileAsync(new Uri(file.DownloadUrl), Path.Combine(tempFolderPath, file.FileName), file);
                    //等待任务完成
                    evtPerDonwload.WaitOne();
                    //销毁下载对象
                    clientDownload.Dispose();
                    clientDownload = null;
                    //移除已下载的文件
                    this.downloadFileList.Remove(file);
                }

                //如果没有下载文件,返回
                if (downloadFileList.Count > 0)
                {
                    return;
                }

                //处理网络错误
                //DealWithDownloadErrors();
                //拷贝文件到程序目录
                foreach (DownloadFileInfo file in this.allFileList)
                {
                    string tempUrlPath    = CommonUnitity.GetFolderUrl(file);
                    string destFileName   = string.Empty;
                    string sourceFileName = string.Empty;
                    try
                    {
                        //生成源路径与目标路径
                        if (!string.IsNullOrEmpty(tempUrlPath))
                        {
                            destFileName   = Path.Combine(CommonUnitity.SystemBinUrl + tempUrlPath.Substring(1), file.FileName);
                            sourceFileName = Path.Combine(CommonUnitity.SystemBinUrl + ConstFile.TEMPFOLDERNAME + tempUrlPath, file.FileName);
                        }
                        else
                        {
                            destFileName   = Path.Combine(CommonUnitity.SystemBinUrl, file.FileName);
                            sourceFileName = Path.Combine(CommonUnitity.SystemBinUrl + ConstFile.TEMPFOLDERNAME, file.FileName);
                        }

                        //验证文件是否损坏
                        System.IO.FileInfo f = new FileInfo(sourceFileName);
                        if (!file.Size.ToString().Equals(f.Length.ToString()) && !file.FileName.ToString().EndsWith(".xml"))
                        {
                            ShowErrorAndRestartApplication();
                        }

                        string newfilepath = string.Empty;
                        if (sourceFileName.Substring(sourceFileName.LastIndexOf(".") + 1).Equals(ConstFile.CONFIGFILEKEY))
                        {
                            if (System.IO.File.Exists(sourceFileName))
                            {
                                if (sourceFileName.EndsWith("_"))
                                {
                                    newfilepath    = sourceFileName;
                                    sourceFileName = sourceFileName.Substring(0, sourceFileName.Length - 1);
                                    destFileName   = destFileName.Substring(0, destFileName.Length - 1);
                                }
                                File.Move(newfilepath, sourceFileName);
                            }
                        }

                        if (File.Exists(destFileName))
                        {
                            MoveFolderToOld(destFileName, sourceFileName);
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(tempUrlPath))
                            {
                                if (!Directory.Exists(CommonUnitity.SystemBinUrl + tempUrlPath.Substring(1)))
                                {
                                    Directory.CreateDirectory(CommonUnitity.SystemBinUrl + tempUrlPath.Substring(1));


                                    MoveFolderToOld(destFileName, sourceFileName);
                                }
                                else
                                {
                                    MoveFolderToOld(destFileName, sourceFileName);
                                }
                            }
                            else
                            {
                                MoveFolderToOld(destFileName, sourceFileName);
                            }
                        }
                    }
                    catch
                    {
                        ShowErrorAndRestartApplication();
                    }
                }
                this.allFileList.Clear();
                if (this.downloadFileList.Count == 0)
                {
                    this.DialogResult = DialogResult.OK;
                }
                else
                {
                    this.DialogResult = DialogResult.Cancel;
                }
                evtDownload.Set();
            }
            catch
            {
                ShowErrorAndRestartApplication();
            }
        }
Ejemplo n.º 3
0
 private void ShowErrorAndRestartApplication()
 {
     MessageBox.Show(ConstFile.NOTNETWORK, ConstFile.MESSAGETITLE, MessageBoxButtons.OK, MessageBoxIcon.Information);
     CommonUnitity.RestartApplication();
 }