/*******************************************************************************
* Copyright(c) 2014 DongkeSoft All rights reserved. / Confidential
* 类的信息:
* 1.程序名称:FrmAutoUpgradeInfomation.cs
* 2.功能描述:系统自动更新画面
* 编辑履历:
* 作者 日期 版本 修改内容
* 陈晓野 2014/09/20 1.00 新建
*******************************************************************************/
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Dongke.IBOSS.PRD.Client.AutoUpgrade.DKIBOSSPRDService;
namespace Dongke.IBOSS.PRD.Client.AutoUpgrade
{
///
/// 系统自动更新画面
///
public partial class FrmAutoUpgradeInfomation : Form
{
#region 系统DLL引用
///
/// 读取INI文件
///
/// 节点名称
/// 键
/// 值
/// stringbulider对象
/// 字节大小
/// 文件路径
///
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filePath);
[DllImport("user32.dll", EntryPoint = "GetSystemMenu")]
public static extern IntPtr GetSystemMenu(IntPtr hWnd, int bRevert);
[DllImport("User32.dll")]
public static extern bool EnableMenuItem(IntPtr hMenu, int uIDEnableItem, int uEnable);
#endregion
#region 常量
public const int SW_RESTORE = 9;
public const int SC_CLOSE = 0xF060;
public const int MF_ENABLED = 0x00000000;
public const int MF_GRAYED = 0x00000001;
public const int MF_DISABLED = 0x00000002;
public const int WM_SYSCOMMAND = 0x112;
public const int WM_QUERYENDSESSION = 0x11;
public const int WM_CUSTOM_FW = 0x1024;
// 配置文件名
private const string INI_FILE_NAME = "iBossPrdConfig.ini";
// 配置文件业务配置的域名
private const string INI_SECTION_NAME = "NetworkAddress";
// IP地址节点的KEY
private const string INI_IP_KEY = "IP";
// 端口节点的KEY
private const string INI_PORT_KEY = "Port";
// 系统的地址
private const string SYSTEM_WEB_ADDRESS = "http://{0}:{1}/DKService/{2}";
// 主程序名
private const string MAIN_NAME = "IBOSSPRD.exe";
// 主程序名
private const string PUBLIC_MAIN_NAME = "IBOSSPRDPublic.exe";
// 更新服务名
private const string SERVICE_NAME = "DKIBOSSPRDService";
private const string PUBLIC_SERVICE_NAME = "PublicModuleService";
// 缓存及配置文件路径
private const string SETTING_PATH = @"\DongkeSoft\IBOSSPRD\";
#endregion
#region 成员变量
// INI文件的路径
private string _iniFilePath;
private string _localiniFilePath;
// 下载到客户端的地址
private string _downloadFolder;
// 应用程序文件夹
private string _applicationFolder;
// 服务信道
private IDKIBOSSPRD _channel = null;
#endregion
#region 委托声明
private delegate void SetPos();
private delegate void SetContrl(Label lable);
private delegate void SetDownFileValue(int value);
private delegate object AsyncMethod();
#endregion
#region 构造函数
///
/// 构造函数
///
public FrmAutoUpgradeInfomation()
{
try
{
if (Program.IsPublic)
{
if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + MAIN_NAME))
{
Program.IsPublic = false;
}
}
InitializeComponent();
this.lblCon1.Visible = false;
this.lblCon2.Visible = false;
this.lblCon3.Visible = false;
this.lblOk1.Visible = false;
this.lblOk2.Visible = false;
this.lblOk3.Visible = false;
this.txtUpgradeInfo.ReadOnly = true;
this.btnFinish.Visible = false;
_applicationFolder = System.Environment.CurrentDirectory;
StringBuilder personalDataSavePath = new StringBuilder();
personalDataSavePath.Append(System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData));
personalDataSavePath.Append(SETTING_PATH);
_iniFilePath = personalDataSavePath.ToString() + INI_FILE_NAME;
if (Program.IsPublic)
{
_downloadFolder = personalDataSavePath.ToString() + @"UpPublicDownload\";
}
else
{
_downloadFolder = personalDataSavePath.ToString() + @"UpDownload\";
}
_localiniFilePath = AppDomain.CurrentDomain.BaseDirectory + INI_FILE_NAME;
//string ipAddress = this.ReadIniFile(INI_SECTION_NAME, INI_IP_KEY, _iniFilePath);
//string serverPort = this.ReadIniFile(INI_SECTION_NAME, INI_PORT_KEY, _iniFilePath);
string ipAddress = null;
string serverPort = null;
if (File.Exists(_localiniFilePath))
{
ipAddress = this.ReadIniFile(INI_SECTION_NAME, INI_IP_KEY, _localiniFilePath);
serverPort = this.ReadIniFile(INI_SECTION_NAME, INI_PORT_KEY, _localiniFilePath);
}
else
{
ipAddress = this.ReadIniFile(INI_SECTION_NAME, INI_IP_KEY, _iniFilePath);
serverPort = this.ReadIniFile(INI_SECTION_NAME, INI_PORT_KEY, _iniFilePath);
}
string sname = null;
if (Program.IsPublic)
{
sname = SERVICE_NAME;
}
else
{
sname = SERVICE_NAME;
}
string uri = string.Format(SYSTEM_WEB_ADDRESS, ipAddress, serverPort, sname);
EndpointAddress remoteAddress = new EndpointAddress(uri);
ChannelFactory channelFactory = new ChannelFactory(sname, remoteAddress);
channelFactory.Open();
_channel = channelFactory.CreateChannel();
}
catch (Exception ex)
{
MessageBox.Show(string.Format("加载升级页面时出现了如下错误:\r\n{0}", ex.Message), this.Text, MessageBoxButtons.OK,
MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
}
}
#endregion
#region 事件处理
///
/// 窗体加载
///
///
///
private void FrmAutoUpgradeInfomation_Shown(object sender, EventArgs e)
{
try
{
object obj = DoAsync(new AsyncMethod(this.LoadAutoUpgrade));
this.btnFinish.Visible = true;
//if (Program.IsPublic)
{
this.btnFinish_Click(null, null);
}
}
catch (Exception ex)
{
MessageBox.Show(string.Format("加载升级页面时出现了如下错误:\r\n{0}", ex.Message), this.Text, MessageBoxButtons.OK,
MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
}
}
///
/// 完成事件
///
///
///
private void btnFinish_Click(object sender, EventArgs e)
{
Application.Exit();
//Process.Start(MAIN_NAME);
if (Program.IsPublic)
{
Process.Start(System.AppDomain.CurrentDomain.BaseDirectory + PUBLIC_MAIN_NAME);
}
else
{
Process.Start(System.AppDomain.CurrentDomain.BaseDirectory + MAIN_NAME, Program.Parameter);
}
}
///
/// 关闭操作
///
///
///
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
#endregion
#region 私有方法
///
/// 设置关闭按钮可用状态
///
///
private void SetCloseBox(bool value)
{
if (this.Handle == System.IntPtr.Zero)
{
return;
}
IntPtr hMenu = GetSystemMenu(this.Handle, 0);
if (hMenu == System.IntPtr.Zero)
{
return;
}
if (value)
{
EnableMenuItem(hMenu, SC_CLOSE, MF_ENABLED);
}
else
{
EnableMenuItem(hMenu, SC_CLOSE, MF_DISABLED | MF_GRAYED);
}
return;
}
///
/// 窗体的异步处理
///
/// 异步方法
///
private object DoAsync(AsyncMethod method)
{
object result = null;
try
{
this.SetCloseBox(false);
IAsyncResult asyncResult = method.BeginInvoke(null, null);
while (!asyncResult.IsCompleted)
{
Application.DoEvents();
System.Threading.Thread.Sleep(1);
}
result = method.EndInvoke(asyncResult);
}
finally
{
this.SetCloseBox(true);
try
{
AsyncMethod endProgressMethod = new AsyncMethod(EndDoAsync);
IAsyncResult ar = endProgressMethod.BeginInvoke(null, null);
while (!ar.IsCompleted)
{
Application.DoEvents();
System.Threading.Thread.Sleep(1);
}
endProgressMethod.EndInvoke(ar);
}
catch (Exception ex)
{
throw (ex);
}
}
return result;
}
///
/// 异步处理结束
///
///
private object EndDoAsync()
{
return null;
}
///
/// 读取INI文件
///
/// 节点名称
/// 键
/// 文件路径
///
private string ReadIniFile(string section, string key, string filePath)
{
try
{
StringBuilder returnValue = new StringBuilder(1024);
GetPrivateProfileString(section, key, "", returnValue, 1024, filePath);
return returnValue.ToString();
}
catch (Exception ex)
{
throw ex;
}
}
///
/// 异步设置控件
///
///
private void SetLabel(Label label)
{
if (this.InvokeRequired)
{
SetContrl setpos = new SetContrl(SetLabel);
this.Invoke(setpos, new object[] { label });
}
else
{
label.Visible = true;
label.BringToFront();
}
}
///
/// 设置进度条
///
///
private void SetProcess()
{
if (this.InvokeRequired)
{
SetPos setpos = new SetPos(SetProcess);
this.Invoke(setpos);
}
else
{
for (int i = 0; i < 15; i++)
{
this.pbDownFile.Value = i;
Thread.Sleep(100);
}
}
}
///
/// 下载文件的主程序
///
private void DownLoadFile()
{
try
{
SetLabel(this.lblCon1);
if (!Directory.Exists(_downloadFolder))
{
Directory.CreateDirectory(_downloadFolder);
}
string downloadDir = _downloadFolder + "-Upgrade.up";
// 下载更新文件
SetProcess();
ICommunicationObject communicationObject = (ICommunicationObject)_channel;
byte[] downLoadFile = null;
try
{
if (Program.IsPublic)
{
downLoadFile = _channel.DownloadUpgradeFile("Public");
}
else
{
downLoadFile = _channel.DownloadUpgradeFile(null);
}
communicationObject.Close();
}
catch (Exception ex)
{
communicationObject.Abort();
throw ex;
}
// 流转换成压缩文件
File.WriteAllBytes(downloadDir, downLoadFile);
SetLabel(this.lblOk1);
//this.pbDownFile.Value = 20;
SetDownFile(20);
// 正在解压更新文件
SetLabel(this.lblCon2);
ZipFileClass.UnZipFile(downloadDir, _downloadFolder);
SetLabel(this.lblOk2);
//this.pbDownFile.Value = 30;
SetDownFile(30);
// 将需要更新的文件复制到运行文件夹下
bool hasEXE = false;
string exeFname = null;
string upFname = null;
SetLabel(this.lblCon3);
string[] downFiles = Directory.GetFiles(_downloadFolder);
int x = 55 / downFiles.Length;
string mainName = MAIN_NAME;
if (Program.IsPublic)
{
mainName = PUBLIC_MAIN_NAME;
}
foreach (string name in downFiles)
{
string filename = Path.GetFileName(name);
if (filename.StartsWith("AutoUpgrade")
|| "SharpZipLib.dll".Equals(filename)
|| filename.EndsWith(".ini"))
{
continue;
}
if (mainName == filename)
{
hasEXE = true;
exeFname = name;
continue;
}
if ("-Upgrade.up".Equals(filename))
{
upFname = name;
continue;
}
//if (!"SharpZipLib.dll".Equals(filename))
{
string localFile = _applicationFolder + @"\" + filename;
if (File.Exists(localFile))
{
File.Delete(localFile);
}
File.Copy(name, localFile);
File.Delete(name);
}
//this.pbDownFile.Value = 30 + x;
SetDownFile(30 + x);
}
if (File.Exists(upFname))
{
File.Delete(upFname);
}
// 最后更新exe文件
if (hasEXE)
{
string localFileIBOSS = _applicationFolder + @"\" + mainName;
if (File.Exists(localFileIBOSS))
{
File.Delete(localFileIBOSS);
}
File.Copy(exeFname, localFileIBOSS);
File.Delete(exeFname);
//this.pbDownFile.Value = 100;
SetDownFile(100);
}
SetLabel(this.lblOk3);
//MessageBox.Show("更新完成", this.Text, MessageBoxButtons.OK,
// MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
}
catch (Exception ex)
{
throw ex;
}
}
///
/// 加载自动更新信息
///
private object LoadAutoUpgrade()
{
try
{
this.DownLoadFile();
return null;
}
catch (Exception ex)
{
throw ex;
}
}
///
/// 设置进度条
///
///
private void SetDownFile(int value)
{
try
{
if (this.InvokeRequired)
{
SetDownFileValue setpos = new SetDownFileValue(SetDownFile);
this.Invoke(setpos, new object[] { value });
}
else
{
this.pbDownFile.Value = value;
}
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
}
}