using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using RunUpdateExe.Lib;
using Oracle.ManagedDataAccess.Client;
using System.Configuration;
using System.Security.Cryptography;
namespace RunUpdateExe
{
public partial class MainForm : Form
{
string strCurFileName = ""; //当前在下载的文件名
private static long SIZE; //总下载大小
private static long UPSIZE; //已经上传多少
private static int NUM; //已经更新件数
private static string[] strArrayFileNames; //需要下载的文件名
private static long lngCurFileSize;
private static bool FinishDownLoad = false;
string strCurPath = "";
WebClient downWebClient = new WebClient();
///
/// 消息处理类申明
///
private static ClassMessage classMsg = new ClassMessage();
private static ClassCheckProIsRun classCPIR = new ClassCheckProIsRun();
private static bool boolUpdateFalg = false;
#region 属性 -> 进度显示
WaiteFrom _WaitForm = null;
#endregion
#region 属性 -> 程序名称
private static string strUpdaterProPath = Application.StartupPath + @"AutoUpdateEx.exe";
#endregion
#region 方法 -> 构造函数
public MainForm()
{
InitializeComponent();
//初始化对应的进度窗口
ShowWaiteForm();
Init();
_WaitForm.ShowMessage("加载完成...");
_WaitForm.Visible = true;
Application.DoEvents();
}
#endregion
#region 方法 -> Init()
private void Init()
{
try
{
//重置数据
//SetUpHelper.SetReplaceValue("servername", SetUpHelper.GetMachineName());
//SetUpHelper.SetReplaceValue("openpath", "");
//杀死程序
//classCPIR.KillExe(ConfigHelper.ConnectPointExe);
//classCPIR.KillExe(CommonHelper.GetKillAppList);
//Ping pingSender = new Ping();
//PingOptions options = new PingOptions();
//options.DontFragment = true;
//string data = "";
//byte[] buffer = Encoding.ASCII.GetBytes(data);
//int timeout = 1000;
//PingReply reply = pingSender.Send(CommonHelper.strIP, timeout, buffer, options);
string xmlPath = CommonHelper.strUpdateURL + ConfigHelper.strUpdateListXmlPath;
WebRequest myRequest = WebRequest.Create(xmlPath);
WebResponse myResponse = myRequest.GetResponse();
myResponse.Close();
//if (reply.Status == IPStatus.Success)
//{
//检查更新
_WaitForm.ShowMessage("正在检查更新...");
Application.DoEvents();
checkUpdate();
//更新完成,书写日期
_WaitForm.ShowMessage("检查更新完成...");
Application.DoEvents();
_WaitForm.Visible = true;
if (boolUpdateFalg == true)
{
//杀死进程
//classCPIR.KillExe(CommonHelper.GetKillAppList);
_WaitForm.ShowMessage("启动更新程序...");
Application.DoEvents();
//直接启动更新--杀死进程
UpdateApplication();
_WaitForm.ShowMessage("正在更新...");
Application.DoEvents();
timer1.Interval = 1000;//一秒钟检索一次
timer1.Tick += timer1_Tick;
timer1.Start();
_WaitForm.Visible = true;
Application.DoEvents();
}
else
{
//StartApplication();
System.Environment.Exit(0);
}
//}
// else
// {
// //StartApplication();
// ClassLog.WriteLog("IPStatus", "网络连接失败");
// System.Environment.Exit(0);
// }
}
catch (Exception ex)
{
ClassLog.WriteLog("Init", ex.Message);
//StartApplication();
System.Environment.Exit(0);
}
}
#endregion
///
/// 启动程序
///
private void StartApplication()
{
StartProc(CommonHelper.strStartApp.Split('|'));
StartProc(ConfigHelper.ConnectPointExe);
System.Environment.Exit(0);
}
void timer1_Tick(object sender, EventArgs e)
{
if (FinishDownLoad)
{
//StartApplication();
//完成下载,关闭当前进程
if (boolUpdateFalg == true)
buildUpdateListXml(getUpdateList(GetAllFilesInDirectory(ConfigHelper.strUpdateFilesPath)));
System.Environment.Exit(0);
}
}
private void checkUpdate()
{
string serverpartcode = "";
string LastUpdate = CommonHelper.strLastUpdateDate;
string ServerUpdate = CommonHelper.getServerUpdateTime();
string[] UpdateServerPart = CommonHelper.getUpadateServerPart();
//string ConnStr = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = localhost )(PORT = 1521))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = ORCL))); User ID=highway_exchange; PassWord=qrwl";
string ConnStr = GetConnectionStringsConfig("orcl");
OracleConnection conn = new OracleConnection(ConnStr);
conn.Open();
string sqlca = "select serverpartcode from highway_exchange.t_syscode order by serverpartcode";
OracleCommand syscode = new OracleCommand(sqlca, conn);
OracleDataReader serverpart = syscode.ExecuteReader();
if (UpdateServerPart.Contains("ALL"))
{
boolUpdateFalg = true;
}
else
{
if (serverpart.HasRows)
{
while (serverpart.Read())
{
serverpartcode = serverpart["SERVERPARTCODE"].ToString();
foreach (string str in serverpartcode.Split('|'))
{
if (UpdateServerPart.Contains(str))
{
boolUpdateFalg = true;
}
}
}
}
}
conn.Close();
conn.Dispose();
if (!String.IsNullOrEmpty(ServerUpdate) && !String.IsNullOrEmpty(LastUpdate) && boolUpdateFalg) //日期都不为空
{
if (DateTime.Compare(
Convert.ToDateTime(ServerUpdate, CultureInfo.InvariantCulture),
Convert.ToDateTime(LastUpdate, CultureInfo.InvariantCulture)) > 0) //字符转日期,并比较日期大小
{
//if (UpdateServerPart.Contains(serverpartcode))
//{
boolUpdateFalg = true; //本次更新日期 大于 最近一次更新日期,有更新,修改更新标记
//}
}
else
{
boolUpdateFalg = false;
}
}
}
#region UpdateApplication
private void UpdateApplication()
{
//关闭程序
//委托下载数据时事件
downWebClient.DownloadProgressChanged += delegate (object wcsender, DownloadProgressChangedEventArgs ex)
{
string ShowString = String.Format(
CultureInfo.InvariantCulture,
"正在下载:{0} [ {1}/{2} ]",
strCurFileName,
CommonHelper.convertSize(ex.BytesReceived),
CommonHelper.convertSize(ex.TotalBytesToReceive));
//呈现内容
lngCurFileSize = ex.TotalBytesToReceive;
};
//委托下载完成时事件
downWebClient.DownloadFileCompleted += delegate (object wcsender, AsyncCompletedEventArgs ex)
{
if (ex.Error != null)
{
_WaitForm.ShowMessage(ex.Error.Message);
_WaitForm.Visible = true;
Application.DoEvents();
}
else
{
UPSIZE += lngCurFileSize;
if (strArrayFileNames.Length > NUM)
{
downloadFile(NUM);
}
else
{
//更新本地xml
CommonHelper.setConfigValue(ConfigHelper.strUpdateXmlPath, "UpDate", CommonHelper.getServerUpdateTime());
//启动程序
FinishDownLoad = true;
}
}
};
SIZE = CommonHelper.getUpdateSize(CommonHelper.strUpdateURL + ConfigHelper.strUpdateListXmlPath);
if (SIZE == 0) //判断要更新的文件是否有大小,如果为0字节则结束更新
throw new Exception("更新大小为0");
NUM = 0;
UPSIZE = 0;
updateList();
string abc = "";
//foreach(string str in strArrayFileNames)
//{
// abc += str;
//}
//MessageBox.Show(abc);
if (strArrayFileNames != null)
downloadFile(0);
}
#endregion
#region 方法 -> 获取文件列表并赋给全局变量
///
/// 获取文件列表并赋给全局变量
///
private static void updateList()
{
string xmlPath = CommonHelper.strUpdateURL + ConfigHelper.strUpdateListXmlPath;
WebClient wc = new WebClient();
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
try
{
StringBuilder sb = new StringBuilder();
XDocument oXDoc = XDocument.Load(xmlPath);
XElement xeRoot = oXDoc.Root;
XElement xele = xeRoot.Element("UpdateFileList");
foreach (var ele in xele.Elements())
{
if (sb.Length == 0)
{
sb.Append(ele.Value);
}
else
{
sb.Append("," + ele.Value);
}
}
strArrayFileNames = sb.ToString().Split(','); //赋给全局变量
}
catch (WebException ex)
{
throw ex;
}
}
#endregion
#region 方法 -> 下载文件
///
/// 下载文件
///
/// 下载序号
private void downloadFile(int arry)
{
try
{
NUM++; //全局变量来记录下载的文件序号
string ReName = "";
strCurFileName = strArrayFileNames[arry];
ReName = strCurFileName;
//如果对应的文件经过处理
//if (strCurFileName.EndsWith(".rar"))
//{
// ReName = strCurFileName.Substring(0, strCurFileName.LastIndexOf(".rar"));
// //ReName = strCurFileName.Replace(".exe.rar", ".exe").Replace(".pbd.rar", ".pbd");
//}
string strFileName = strCurFileName.Substring(strCurFileName.LastIndexOf("\\") + 1); //截取文件名
string ReNameFileName = ReName.Substring(ReName.LastIndexOf("\\") + 1);
strCurPath = strCurFileName.Substring(0, strCurFileName.LastIndexOf("\\") + 1); //截取文件路径
string StrCurReNamePath = ReName.Substring(0, ReName.LastIndexOf("\\") + 1);
string SysDateString = System.DateTime.Now.ToString("yyyyMMdd");
//创建备份日期+更新文件目录
//路径是否存在
if (!Directory.Exists(ConfigHelper.strBackupPath + SysDateString + StrCurReNamePath))
{
//创建多层目录
CommonHelper.createMultipleFolders(ConfigHelper.strBackupPath, SysDateString + StrCurReNamePath);
}
//备份对应的文件--
if (File.Exists(ConfigHelper.strMainProDir + ReNameFileName))
{
//备份当前时间
if (File.Exists(ConfigHelper.strBackupPath + SysDateString + ReName))
File.Delete(ConfigHelper.strBackupPath + SysDateString + ReName);
try
{
File.Move(ConfigHelper.strMainProDir + ReNameFileName, ConfigHelper.strBackupPath + SysDateString + ReName);
}
catch { }
//删除文件
if (File.Exists(ConfigHelper.strMainProDir + ReNameFileName))
File.Delete(ConfigHelper.strMainProDir + ReNameFileName);
}
else if (!Directory.Exists(ConfigHelper.strMainProDir))
{
Directory.CreateDirectory(ConfigHelper.strMainProDir);
}
//下载文件--下载到当前路径
downWebClient.DownloadFileAsync(new Uri(CommonHelper.strUpdateURL + ConfigHelper.strSevUpdateFilesUrl +
strCurFileName.Replace('\\', '/')), ConfigHelper.strMainProDir + ReNameFileName);
}
catch (WebException ex)
{
throw ex;
}
}
#endregion
#region 方法 -> 启动进程
public void StartProc(string ProcName)
{
bool IsRun = false;
Process[] processes = Process.GetProcessesByName(ProcName.Substring(0, ProcName.LastIndexOf('.'))); //同程序名的所有进程
foreach (Process p in processes)//判断当前进程中是否已有该程序
{
if (p.MainModule.ModuleName == ProcName)//通过程序路径判断,而不能通过程序名判断
{
string strVN = p.MainModule.FileVersionInfo.FileVersion; //获取进程中正在运行的这个程序的版本号
p.Kill(); // 结束进程
}
}
//启动程序
Process.Start(ProcName);
}
public void StartProc(string[] ProcNames)
{
foreach (string str in ProcNames)
{
StartProc(str);
}
}
#endregion
#region 方法 -> 隐藏窗体
protected override void SetVisibleCore(bool value)
{
base.SetVisibleCore(false);
}
#endregion
#region 方法 -> 显示等待窗口
public void ShowWaiteForm()
{
_WaitForm = WaiteFrom.GetInstance();
//设置WaitForm的父窗体为当前窗体,以便在WaitForm中使用父窗体对象
_WaitForm.Owner = this;
_WaitForm.ShowMessage("加载中......");
_WaitForm.Show();
Application.DoEvents();
_WaitForm.Refresh();
}
#endregion
#region 方法 -> 更新配置文件
///
/// 生成更新配置文件
///
///
private void buildUpdateListXml(string[] strArray)
{
#region 新的方法,待实现
////加载xml文档
//XmlDocument doc = new XmlDocument();
//string path = Server.MapPath("~/Title.xml");
//doc.Load(path);
////创建节点
//XmlElement xmlElement = doc.CreateElement("Title");
////添加属性
//xmlElement.SetAttribute("ID", "21");
//xmlElement.SetAttribute("Name", "王六");
////将节点加入到指定的节点下
//XmlNode xml = doc.DocumentElement.PrependChild(xmlElement);
//doc.Save(path);
#endregion
if (strArray != null)
{
try
{
XmlDocument xmlDoc = new XmlDocument();
// 创建根节点AutoUpdater
XmlElement xeRoot = xmlDoc.CreateElement("AutoUpdater");
xmlDoc.AppendChild(xeRoot); // 加入到上层节点
// 创建UpdateInfo元素
XmlElement xeUI = xmlDoc.CreateElement("UpdateInfo");
xeRoot.AppendChild(xeUI);
// 创建UpdateTime元素
XmlElement xeUT = xmlDoc.CreateElement("UpdateTime");
//xeUT.SetAttribute("Date", DateTime.Today.ToShortDateString());
xeUT.SetAttribute("Date", DateTime.Now.ToString());
xeUI.AppendChild(xeUT);
// 创建Version元素
XmlElement xeUV = xmlDoc.CreateElement("Version");
xeUV.SetAttribute("Num", getMainProVer());
xeUI.AppendChild(xeUV);
// 创建UpdateSize元素
XmlElement xeUS = xmlDoc.CreateElement("UpdateSize");
xeUS.SetAttribute("Size", getUpdateSize(GetAllFilesInDirectory(ConfigHelper.strUpdateFilesPath)).ToString());
xeUI.AppendChild(xeUS);
// 创建UpdateFileList元素
XmlElement xeUFL = xmlDoc.CreateElement("UpdateFileList");
xeRoot.AppendChild(xeUFL);
for (int i = 0; i < strArray.Length; i++)
{
// 循环创建UpdateFile元素
XmlElement xeUF = xmlDoc.CreateElement("UpdateFile");
xeUF.SetAttribute("Md5", GetMD5(ConfigHelper.strMainProDir + strArray[i]));
xeUF.InnerText = strArray[i];
xeUFL.AppendChild(xeUF); // 加入到上层节点
}
xmlDoc.Save("UpdateList.xml"); // 保存文件
//classMsg.messageInfoBox("配置文件创建完成!");
}
catch (Exception ex)
{
ClassLog.WriteLog("buildUpdateListXml", ex.Message);
}
return;
}
ClassLog.WriteLog("buildUpdateListXml", "UpdateFiles目录中无更新文件!");
}
///
/// 获取所有目录即子目录下的文件完整路径列表
///
/// 返回指定目录下的所有文件信息
/// 返回值
private static string[] getUpdateList(List listFileInfo)
{
string strRelativePath = null;
string[] strArrayRelativePaths = null;
if (listFileInfo != null)
{
foreach (FileInfo fileInfo in listFileInfo)
{
if (!fileInfo.FullName.Contains("lpk.dll"))
{
strRelativePath += fileInfo.FullName.Replace(ConfigHelper.strUpdateFilesPath, "") + ',';
}
}
if (strRelativePath != null)
{
strArrayRelativePaths = strRelativePath.TrimEnd(',').Split(',');
}
}
return strArrayRelativePaths;
}
///
/// 获取所有目录即子目录下的文件总字节大小
///
/// 返回指定目录下的所有文件信息
/// 返回值
private static long getUpdateSize(List listFileInfo)
{
long len = 0;
if (listFileInfo != null)
{
foreach (FileInfo fileInfo in listFileInfo)
{
if (fileInfo.Name != "lpk.dll")
{
len += fileInfo.Length;
}
}
}
return len;
}
///
/// 返回指定目录下的所有文件信息
///
///
///
public List GetAllFilesInDirectory(string strDirectory)
{
//判断文件夹是否存在,不存在则退出
if (!Directory.Exists(strDirectory))
return null;
List listFiles = new List(); //保存所有的文件信息
DirectoryInfo directory = new DirectoryInfo(strDirectory);
DirectoryInfo[] directoryArray = directory.GetDirectories();
FileInfo[] fileInfoArray = directory.GetFiles();
if (fileInfoArray.Length > 0) listFiles.AddRange(fileInfoArray);
foreach (DirectoryInfo _directoryInfo in directoryArray)
{
DirectoryInfo directoryA = new DirectoryInfo(_directoryInfo.FullName);
DirectoryInfo[] directoryArrayA = directoryA.GetDirectories();
FileInfo[] fileInfoArrayA = directoryA.GetFiles();
if (fileInfoArrayA.Length > 0) listFiles.AddRange(fileInfoArrayA);
GetAllFilesInDirectory(_directoryInfo.FullName);//递归遍历
}
return listFiles;
}
#endregion
///
/// 获取主程序文件版本
///
///
private string getMainProVer()
{
string strProVer = "";
if (File.Exists(ConfigHelper.strMainProDir + "\\cashier.exe")) //如果更新中有主程序
{
FileVersionInfo fviMainPro = FileVersionInfo.GetVersionInfo(ConfigHelper.strMainProDir + "\\cashier.exe");
strProVer = fviMainPro.ProductVersion;
}
else if (File.Exists(ConfigHelper.strMainProDir + "\\cashier.exe.rar"))
{
FileVersionInfo fviMainPro = FileVersionInfo.GetVersionInfo(ConfigHelper.strMainProDir + "\\cashier.exe.rar");
strProVer = fviMainPro.ProductVersion;
}
return strProVer;
}
///
/// 依据连接串名字connectionName返回数据连接字符串
///
///
///
private static string GetConnectionStringsConfig(string connectionName)
{
string connectionString =
ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString();
Console.WriteLine(connectionString);
return connectionString;
}
///
/// 获取指定文件MD5
///
///
///
private static string GetMD5(string s)
{
try
{
FileStream file = new FileStream(s, FileMode.Open);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] retval = md5.ComputeHash(file);
file.Close();
StringBuilder sc = new StringBuilder();
for (int i = 0; i < retval.Length; i++)
{
sc.Append(retval[i].ToString("x2"));
}
return sc.ToString().ToUpper();
}
catch (Exception ex)
{
return "";
}
}
}
}