using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Diagnostics;
using System.Threading;
using System.Xml;
using System.Web.Hosting;
using System.Deployment.Application;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Collections;
using Newtonsoft.Json;
using System.Configuration;
using MAutoUpdate.common;
using MAutoUpdate.Models;
namespace MAutoUpdate
{
static class Program
{
static bool f;
static Process pCurrent = Process.GetCurrentProcess();
static Mutex m = new Mutex(true, pCurrent.MainModule.FileName.Replace(":", "").Replace(@"\", "") + "MAutoUpdate", out f);//互斥,
static string ip = ConfigurationManager.AppSettings["IP"].ToString();
static string appPath = AppDomain.CurrentDomain.BaseDirectory;
static int updateCheckInterval = Convert.ToInt32(ConfigurationManager.AppSettings["UpdateCheckInterval"]) * 60;
///
/// 程序主入口
///
/// [0]程序名称,[1]静默更新 0:否 1:是 [3] 0:程序启动检测 1:手动点击检查更新按钮(在于忽略更新的情况下,手动检测时候还是要弹出来的)
[STAThread]
static void Main(string[] args)
{
if (IsRunning())
{
LogTool.AddLog("已存在正在运行的更新程序");
}
else
{
LogTool.AddLog("正在启动定时更新程序");
new EAPClock().AutoStartEap();
DoCheckVersion();
StartTimer();
while (true)
{
Thread.Sleep(1000 * 60*60);
}
}
}
///
/// 是否已启动
///
///
static bool IsRunning()
{
Process[] processes = Process.GetProcesses();
Process currentProcess = Process.GetCurrentProcess();
bool processExist = false;
foreach (Process p in processes)
{
if (p.ProcessName == currentProcess.ProcessName && p.Id != currentProcess.Id)
{
processExist = true;
}
}
return processExist;
}
public static int GetPidByProcessName(string processName)
{
Process[] arrayProcess = Process.GetProcessesByName(processName);
foreach (Process p in arrayProcess)
{
return p.Id;
}
return 0;
}
///
/// 检查版本更新
///
public static void DoCheckVersion()
{
if (f)
{
try
{
if (ApplicationDeployment.IsNetworkDeployed)
{
LogTool.AddLog("当前版本" + ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString());
}
CheckVersion();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
///
/// 启动定时器
///
public static void StartTimer()
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Enabled = true;
//设置执行一次(false)还是一直执行(true)
timer.AutoReset = true;
timer.Interval = updateCheckInterval * 1000;
timer.Elapsed += delegate
{
DoCheckVersion();
};
timer.Start();
}
public static bool startprocess()
{
try
{
Process.Start(Path.Combine(AppDomain.CurrentDomain.BaseDirectory + @"Debug\", "EapForIdle.exe"));
return true;
}
catch
{
return false;
}
}
public static void CheckVersion()
{
try
{
if (!RequireUpdate())
return;
LogTool.AddLog("*******************开始更新****************");
string programName = "EapForIdle";
string isClickUpdate = "0";
string localAddress = appPath;
if (!Directory.Exists(localAddress))
{
Directory.CreateDirectory(localAddress);
}
var files = Directory.GetFiles(localAddress, "*.*");
Hashtable hashtable = new Hashtable();
DirectoryInfo folder = new DirectoryInfo(localAddress);
foreach (FileInfo file in folder.GetFiles("*.*"))
{
hashtable[file.Name] = GetMD5HashFromFile(file.FullName);
}
CompareVersion compareVersion = new CompareVersion();
compareVersion.Versions = hashtable;
string Json = JsonConvert.SerializeObject(compareVersion);
string ss = ip + "CompareVersion/DownloadAppFile";
string result = UntilApi.HttpPost(ss, Json);
EapResponse response = JsonConvert.DeserializeObject(result);
if (response != null)
{
if (response.Code == 1)
{
var ht = JsonConvert.DeserializeObject(response.Data.ToString());
if (ht.Count > 0)
{
UpdateWork updateWork = new UpdateWork(programName, localAddress, isClickUpdate, 1, ht);
updateWork.Do();
}
}
}
}
catch (Exception ex)
{
LogTool.AddLog(ex.ToString() + ex.StackTrace);
}
}
///
/// 检测APP师傅需要更新
///
///
public static bool RequireUpdate()
{
var versionPath = Path.Combine(appPath, "version.json");
if (!File.Exists(versionPath))
return true;
WebAppVersion appVersion = null;
var file = new FileInfo(versionPath);
using (var sr = file.OpenText())
{
var str = sr.ReadToEnd();
appVersion = JsonConvert.DeserializeObject(str);
}
if (appVersion == null)
return true;
try
{
string url = ip + "CompareVersion/GetAppVersion";
string result = UntilApi.HttpGet(url);
EapResponse response = JsonConvert.DeserializeObject(result);
if (response != null && response.Code == 1)
{
var hs = JsonConvert.DeserializeObject(response.Data.ToString());
var serverAppVersion = hs["version"];
LogTool.AddLog("**************检查版本开始***************");
LogTool.AddLog("服务端最新版本:" + serverAppVersion + ",本地版本:" + appVersion.Version);
LogTool.AddLog("**************检查版本结束***************");
if (serverAppVersion.ToString() != appVersion.Version)
return true;
}
return false;
}
catch (Exception ex)
{
LogTool.AddLog(ex.ToString() + ex.StackTrace);
return false;
}
}
public static string GetMD5HashFromFile(string fileName)
{
try
{
FileStream file = new FileStream(fileName, System.IO.FileMode.Open, FileAccess.Read);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(file);
file.Close();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
return sb.ToString();
}
catch (Exception ex)
{
throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
}
}
static void CheckForUpdate()
{
try
{
if (ApplicationDeployment.IsNetworkDeployed)
{
ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
if (ad.CheckForUpdate())
{
LogTool.AddLog("更新版本" + ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString());
//Application.ExitThread();
//Restart();
ad.UpdateAsync();
ad.UpdateCompleted += (s, ee) =>
{
if (ee.Error == null)
{
LogTool.AddLog("更新版本成功" + ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString());
//var vserson= ApplicationDeployment.CurrentDeployment.CurrentVersion;
//var vserson = Assembly.GetExecutingAssembly().GetName().Version;
//ForUpdate FU = new ForUpdate(this);
//FU.ShowDialog();
//FU.Focus();
}
else
{
LogTool.AddLog("更新版本失败" + ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString());
MessageBox.Show(ee.Error.ToString());
}
};
}
else
{
LogTool.AddLog("不需要更新版本");
}
}
}
catch (Exception ex)
{
LogTool.AddLog(ex.Message);
}
}
}
}