Файл: Реализовать приложениесервер в среде MicrosoftVisualStudioна языкеVisualC#.odt

ВУЗ: Не указан

Категория: Не указан

Дисциплина: Не указана

Добавлен: 09.12.2023

Просмотров: 118

Скачиваний: 1

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.

Листинг программы.


#region The private fields
private bool isFinished = false;
private List downloadFileList = null;
private List allFileList = null;
private ManualResetEvent evtDownload = null;
private ManualResetEvent evtPerDonwload = null;
private WebClient clientDownload = null;
#endregion

#region The constructor of DownloadProgress
public DownloadProgress(List downloadFileListTemp)
{
InitializeComponent();

this.downloadFileList = downloadFileListTemp;
allFileList = new List();
foreach (DownloadFileInfo file in downloadFileListTemp)
{
allFileList.Add(file);
}
}
#endregion

#region The method and event
private void OnFormClosing(object sender, FormClosingEventArgs e)
{
if (!isFinished && DialogResult.No == MessageBox.Show(ConstFile.CANCELORNOT, ConstFile.MESSAGETITLE, MessageBoxButtons.YesNo, MessageBoxIcon.Question))
{
e.Cancel = true;
return;
}
else
{
if (clientDownload != null)
clientDownload.CancelAsync();

evtDownload.Set();
evtPerDonwload.Set();
}
}

private void OnFormLoad(object sender, EventArgs e)
{
evtDownload = new ManualResetEvent(true);
evtDownload.Reset();
ThreadPool.QueueUserWorkItem(new WaitCallback(this.ProcDownload));
}

long total = 0;
long nDownloadedTotal = 0;

private void ProcDownload(object o)
{
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;
}
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.Credentials = CredentialCache.DefaultCredentials;
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
{
//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();
}
catch (Exception)
{
//log the error message,you can use the application's log code
}

};

evtPerDonwload.Reset();

//Download the folder file
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.FileFullName), file);

//Wait for the download complete
evtPerDonwload.WaitOne();

clientDownload.Dispose();
clientDownload = null;

//Remove the downloaded files
this.downloadFileList.Remove(file);
}

}
catch (Exception)
{
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);
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 + ConstFile.TEMPFOLDERNAME + tempUrlPath, file.FileName);
}
else
{
oldPath = Path.Combine(CommonUnitity.SystemBinUrl, file.FileName);
newPath = Path.Combine(CommonUnitity.SystemBinUrl + ConstFile.TEMPFOLDERNAME, file.FileName);
}

//just deal with the problem which the files EndsWith xml can not download
System.IO.FileInfo f = new FileInfo(newPath);
if (!file.Size.ToString().Equals(f.Length.ToString()) && !file.FileName.ToString().EndsWith(".xml"))
{
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);
}
File.Move(newfilepath, newPath);
}
}
//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 the error message,you can use the application's log code
}

}

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

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

evtDownload.Set();
}

//To delete or move to old files
void MoveFolderToOld(string oldPath, string newPath)
{
if (File.Exists(oldPath + ".old"))
File.Delete(oldPath + ".old");

if (File.Exists(oldPath))
File.Move(oldPath, oldPath + ".old");

File.Move(newPath, oldPath);
//File.Delete(oldPath



+ ".old");
}

delegate void ShowCurrentDownloadFileNameCallBack(string name);
private void ShowCurrentDownloadFileName(string name)
{
if (this.labelCurrentItem.InvokeRequired)
{
ShowCurrentDownloadFileNameCallBack cb = new ShowCurrentDownloadFileNameCallBack(ShowCurrentDownloadFileName);
this.Invoke(cb, new object[] { name });
}
else
{
this.labelCurrentItem.Text = name;
}
}

delegate void SetProcessBarCallBack(int current, int total);
private void SetProcessBar(int current, int total)
{
if (this.progressBarCurrent.InvokeRequired)
{
SetProcessBarCallBack cb = new SetProcessBarCallBack(SetProcessBar);
this.Invoke(cb, new object[] { current, total });
}
else
{
this.progressBarCurrent.Value = current;
this.progressBarTotal.Value = total;
}
}

delegate void ExitCallBack(bool success);
private void Exit(bool success)
{
if (this.InvokeRequired)
{
ExitCallBack cb = new ExitCallBack(Exit);
this.Invoke(cb, new object[] { success });
}
else
{
this.isFinished = success;
this.DialogResult = success ? DialogResult.OK : DialogResult.Cancel;
this.Close();
}
}

private void OnCancel(object sender, EventArgs e)
{
//bCancel = true;
//evtDownload.Set();
//evtPerDonwload.Set();
ShowErrorAndRestartApplication();
}

private void DealWithDownloadErrors()
{
try
{
//Test Network is OK or not.
Config config = Config.LoadConfig(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConstFile.FILENAME));
WebClient client = new WebClient();
client.DownloadString(config.ServerUrl);
}
catch (Exception)
{
//log the error message,you can use the application's log code
ShowErrorAndRestartApplication();
}
}

private void ShowErrorAndRestartApplication()
{
MessageBox.Show(ConstFile.NOTNETWORK,ConstFile.MESSAGETITLE, MessageBoxButtons.OK, MessageBoxIcon.Information);
CommonUnitity.RestartApplication();
}

#endregion
}
}


using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;
namespace KnightsWarriorAutoupdater

{

public partial class DownloadConfirm : Form

{

#region The private fields

List downloadFileList = null;

#endregion
#region The constructor of DownloadConfirm

public DownloadConfirm(List downloadfileList)

{

InitializeComponent();
downloadFileList = downloadfileList;

}

#endregion
#region The private method

private void OnLoad(object sender, EventArgs e)

{

foreach (DownloadFileInfo file in this.downloadFileList)

{

ListViewItem item = new ListViewItem(new string[] { file.FileName, file.LastVer, file.Size.ToString() });

}
this.Activate();

this.Focus();

}

#endregion

}

}

using System;

using System.Collections.Generic;

using System.Text;

using System.Net;

using System.Xml;

using System.Xml.Serialization;

using System.IO;

using System.Windows.Forms;

using System.Diagnostics;
namespace KnightsWarriorAutoupdater

{

#region The delegate

public delegate void ShowHandler();

#endregion
public class AutoUpdater : IAutoUpdater

{

#region The private fields

private Config config = null;

private bool bNeedRestart = false;

private bool bDownload = false;

List downloadFileListTemp = null;

#endregion
#region The public event

public event ShowHandler OnShow;

#endregion
#region The constructor of AutoUpdater

public AutoUpdater()

{

config = Config.LoadConfig(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConstFile.FILENAME));

}

#endregion
#region The public method

public void Update()

{

if (!config.Enabled)

return;
Dictionary listRemotFile = ParseRemoteXml(config.ServerUrl);
List downloadList = new List();
foreach (LocalFile file in config.UpdateFileList)

{

if (listRemotFile.ContainsKey(file.Path))

{

RemoteFile rf = listRemotFile[file.Path];

Version v1 = new Version(rf.LastVer);

Version v2 = new Version(file.LastVer);

if (v1 > v2)

{

downloadList.Add(new DownloadFileInfo(rf.Url, file.Path, rf.LastVer, rf.Size));

file.LastVer = rf.LastVer;

file.Size = rf.Size;
if (rf.NeedRestart)

bNeedRestart = true;
bDownload = true;

}
listRemotFile.Remove(file.Path);

}

}
foreach (RemoteFile file in listRemotFile.Values)

{

downloadList.Add(new DownloadFileInfo(file.Url, file.Path, file.LastVer, file.Size));
if (file.NeedRestart)

bNeedRestart = true;

}
downloadFileListTemp = downloadList;
if (bDownload)

{

DownloadConfirm dc = new DownloadConfirm(downloadList);
if (this.OnShow != null)

this.OnShow();
if (DialogResult.OK == dc.ShowDialog())

{

StartDownload(downloadList);

}

}

}
public void RollBack()

{

foreach (DownloadFileInfo file in downloadFileListTemp)

{

string tempUrlPath = CommonUnitity.GetFolderUrl(file);

string oldPath = string.Empty;

try

{

if (!string.IsNullOrEmpty(tempUrlPath))

{

oldPath = Path.Combine(CommonUnitity.SystemBinUrl + tempUrlPath.Substring(1), file.FileName);

}

else

{

oldPath = Path.Combine(CommonUnitity.SystemBinUrl, file.FileName);

}
if (oldPath.EndsWith("_"))

oldPath = oldPath.Substring(0, oldPath.Length - 1);
MoveFolderToOld(oldPath + ".old", oldPath);
}

catch (Exception ex)

{

//log the error message,you can use the application's log code

}

}

}

#endregion
#region The private method

string newfilepath = string.Empty;

private void MoveFolderToOld(string oldPath, string newPath)

{

if (File.Exists(oldPath) && File.Exists(newPath))

{

System.IO.File.Copy(oldPath, newPath, true);

}

}
private void StartDownload(List downloadList)

{

DownloadProgress dp = new DownloadProgress(downloadList);

if (dp.ShowDialog() == DialogResult.OK)

{

//

if (DialogResult.Cancel == dp.ShowDialog())

{

return;

}

//Update successfully

config.SaveConfig(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConstFile.FILENAME));
if (bNeedRestart)

{

//Delete the temp folder

Directory.Delete(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConstFile.TEMPFOLDERNAME), true);
MessageBox.Show(ConstFile.APPLYTHEUPDATE, ConstFile.MESSAGETITLE, MessageBoxButtons.OK, MessageBoxIcon.Information);

CommonUnitity.RestartApplication();

}

}

}
private Dictionary ParseRemoteXml(string xml)

{

XmlDocument document = new XmlDocument();

document.Load(xml);
Dictionary list = new Dictionary();

foreach (XmlNode node in document.DocumentElement.ChildNodes)

{

list.Add(node.Attributes["path"].Value, new RemoteFile(node));

}
return list;

}

#endregion
}
}

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

using System.Diagnostics;

using System.Windows.Forms;
namespace KnightsWarriorAutoupdater

{

class CommonUnitity

{

public static string SystemBinUrl = AppDomain.CurrentDomain.BaseDirectory;
public static void RestartApplication()

{

Process.Start(Application.ExecutablePath);

Environment.Exit(0);

}
public static string GetFolderUrl(DownloadFileInfo file)

{

string folderPathUrl = string.Empty;

int folderPathPoint = file.DownloadUrl.IndexOf("/", 15) + 1;

string filepathstring = file.DownloadUrl.Substring(folderPathPoint);

int folderPathPoint1 = filepathstring.IndexOf("/");

string filepathstring1 = filepathstring.Substring(folderPathPoint1 + 1);

if (filepathstring1.IndexOf("/") != -1)

{

string[] ExeGroup = filepathstring1.Split('/');

for (int i = 0; i < ExeGroup.Length - 1; i++)

{

folderPathUrl += "\\" + ExeGroup[i];

}

if (!Directory.Exists(SystemBinUrl + ConstFile.TEMPFOLDERNAME + folderPathUrl))

{

Directory.CreateDirectory(SystemBinUrl + ConstFile.TEMPFOLDERNAME + folderPathUrl);

}

}

return folderPathUrl;

}

}

}

using System;

using System.Collections.Generic;

using System.Text;

using System.Xml;

using System.Xml.Serialization;

using System.IO;
namespace KnightsWarriorAutoupdater

{

public class Config

{

#region The private fields

private bool enabled = true;

private string serverUrl = string.Empty;

private UpdateFileList updateFileList = new UpdateFileList();

#endregion
#region The public property

public bool Enabled

{

get { return enabled; }

set { enabled = value; }

}

public string ServerUrl

{

get { return serverUrl; }

set { serverUrl = value; }

}

public UpdateFileList UpdateFileList

{

get { return updateFileList; }

set { updateFileList = value; }

}

#endregion
#region The public method

public static Config LoadConfig(string file)

{

XmlSerializer xs = new XmlSerializer(typeof(Config));

StreamReader sr = new StreamReader(file);

Config config = xs.Deserialize(sr) as Config;

sr.Close();
return config;

}
public void SaveConfig(string file)

{

XmlSerializer xs = new XmlSerializer(typeof(Config));

StreamWriter sw = new StreamWriter(file);

xs.Serialize(sw, this);

sw.Close();

}

#endregion

}
}

using System;

using System.Collections.Generic;

using System.Text;

using System.IO;
namespace KnightsWarriorAutoupdater

{

public class DownloadFileInfo

{

#region The private fields

string downloadUrl = string.Empty;

string fileName = string.Empty;

string lastver = string.Empty;

int size = 0;

#endregion
#region The public property

public string DownloadUrl { get { return downloadUrl; } }

public string FileFullName { get { return fileName; } }

public string FileName { get { return Path.GetFileName(FileFullName); } }

public string LastVer { get { return lastver; } set { lastver = value; } }

public int Size { get { return size; } }

#endregion
#region The constructor of DownloadFileInfo

public DownloadFileInfo(string url, string name, string ver, int size)

{

this.downloadUrl = url;

this.fileName = name;

this.lastver = ver;

this.size = size;

}

#endregion

}

}

using System;

using System.Collections.Generic;

using System.Text;

using System.Xml;
namespace KnightsWarriorAutoupdater

{

public class RemoteFile

{

#region The private fields

private string path = "";

private string url = "";

private string lastver = "";

private int size = 0;

private bool needRestart = false;

#endregion
#region The public property

public string Path { get { return path; } }

public string Url { get { return url; } }

public string LastVer { get { return lastver; } }

public int Size { get { return size; } }

public bool NeedRestart { get { return needRestart; } }

#endregion
#region The constructor of AutoUpdater

public RemoteFile(XmlNode node)

{

this.path = node.Attributes["path"].Value;

this.url = node.Attributes["url"].Value;

this.lastver = node.Attributes["lastver"].Value;

this.size = Convert.ToInt32(node.Attributes["size"].Value);

this.needRestart = Convert.ToBoolean(node.Attributes["needRestart"].Value);

}

#endregion

}

}