在WinForm中使用Web Service來實現軟體自動升級

來源:互聯網
上載者:User

來源:互連網

winform程式相對web程式而言,功能更強大編程更方便,但軟體更新卻相當麻煩,要到用戶端一台一台地升級,面對這個實際問題,在最近的一個小項目中,本人設計了一個通過軟體實現自動升級技術方案,彌補了這一缺陷,有較好的參考價值。

一、升級的好處

  長期以來,廣大程式員為到底是使用Client/Server,還是使用Browser/Server結構爭論不休,在這些爭論當中,C/S結構的程式的可維護性差,布置困難,升級不方便,維護成本高就是一個相當重要的因素,也是那些B/S支援者們把Client/Server

結構打入地獄的一個重要原因。現在好了,我們就在最新的基於Microsoft的WinForm上用Web Service來實現軟體的自動升級功能。

二、升級的技術原理

  升級的原理有好幾個,首先無非是將現有版本與最新版本作比較,發現最新的則提示使用者是否升級。當然也有人用其它屬性比較的,例如:檔案大小,或者更新日期。而實現的方法呢?在VB時代,我使用的是XmlHTTP+INet控制項。用XmlHTTP擷取資訊,用INET傳輸升級檔案,而用一個簡單的BAT檔案來實現升級。而BAT檔案有個特性,是可以刪除自己本身。

三、在.Net時代的實現

 在.Net時代,我們就有了更多的選擇,可以使用WebRequest,也可以使用Web Service。在這裡我們將用Web Service來實現軟體的自動升級。實現原理:在Web Service中實現一個GetVer的WebMethod方法,其作用是擷取當前的最新版本。然後將現在版本與最新版本比較,如果有新版本,則進行升級。步驟如下:

1.準備一個作為升級模板用的xml檔案(update.xml)。

<?xml version="1.0" encoding="utf-8" ?>
<product>
 <version>1.0.1818.42821</version>
 <description>修正一些Bug</description>
 <filelist count="4" sourcepath="./update/">
  <item name="City.xml" size="">
   <value />
  </item>
  <item name="CustomerApplication.exe" size="">
   <value />
  </item>
  <item name="Interop.SHDocVw.dll" size="">
   <value />
  </item>
  <item name="Citys.xml" size="">
   <value />
  </item>
 </filelist>
</product>

2.Web Service的GetVer方法。

[WebMethod(Description="取得更新版本")]
public string GetVer()
{
  XmlDocument doc = new XmlDocument();
  doc.Load(Server.MapPath("update.xml"));
  XmlElement root = doc.DocumentElement;
  return root.SelectSingleNode("version").InnerText;
}

3.Web Service的GetUpdateData方法。

[WebMethod(Description="線上更新軟體")]
[SoapHeader("sHeader")]
public System.Xml.XmlDocument GetUpdateData()
{
 //驗證使用者是否登陸
 if(sHeader==null) return null;
 if(!DataProvider.GetInstance.CheckLogin(sHeader.Username,sHeader.Password)) return null;
 //取得更新的xml模板內容
 XmlDocument doc = new XmlDocument();
 doc.Load(Server.MapPath("update.xml"));
 XmlElement root = doc.DocumentElement;
 //看看有幾個檔案需要更新
 XmlNode updateNode = root.SelectSingleNode("filelist");
 string path = updateNode.Attributes["sourcepath"].Value;
 int count = int.Parse(updateNode.Attributes["count"].Value);
 //將xml中的value用實際內容替換
 for(int i=0;i<count;i++)
 {
    XmlNode itemNode = updateNode.ChildNodes[i];
    string fileName = path + itemNode.Attributes["name"].Value;
    FileStream fs = File.OpenRead(Server.MapPath(fileName));
    itemNode.Attributes["size"].Value = fs.Length.ToString();
    BinaryReader br = new BinaryReader(fs);
    //這裡是檔案的實際內容,使用了Base64String編碼
    itemNode.SelectSingleNode("value").InnerText =
    Convert.ToBase64String(br.ReadBytes((int)fs.Length),0,(int)fs.Length);
    br.Close();
    fs.Close();
 }
  return doc;
}

4.在用戶端進行的工作。

首先引用此Web Service,例如命名為:WebSvs
string nVer = Start.GetService.GetVer(); 
if(Application.ProductVersion.CompareTo(nVer)<=0) update();
在本代碼中Start.GetService是WebSvs的一個Static執行個體。
首先檢查版本,將結果與目前的版本進行比較,如果為新版本則執行update方法。
void update()
{
  this.statusBarPanel1.Text = "正在下載...";
  System.Xml.XmlDocument doc = ((System.Xml.XmlDocument)Start.GetService.GetUpdateData());
  doc.Save(Application.StartupPath + @"\update.xml");
 System.Diagnostics.Process.Start(Application.StartupPath + @"\update.exe");
  Close();
  Application.Exit();
}
這裡為了簡單起見,沒有使用非同步方法呼叫,當然使用非同步方法呼叫能更好的提高客戶體驗,這個需要讀者們自己去添加。
update的作用是將升級的XML檔案下載下來,儲存為執行檔案目錄下的一個update.xml檔案。
任務完成,退出程式,等待update.exe 來進行升級。     

5.update.exe的內容。
private void Form1_Load(object sender, System.EventArgs e)
{
   System.Diagnostics.Process[] ps = System.Diagnostics.Process.GetProcesses();
   foreach(System.Diagnostics.Process p in ps)
   {
      //MessageBox.Show(p.ProcessName);
      if(p.ProcessName.ToLower()=="customerapplication")
      {
         p.Kill();
         break;
      }
   }
   XmlDocument doc = new XmlDocument();
   doc.Load(Application.StartupPath + @"\update.xml");
   XmlElement root = doc.DocumentElement;
   XmlNode updateNode = root.SelectSingleNode("filelist");
   string path = updateNode.Attributes["sourcepath"].Value;
   int count = int.Parse(updateNode.Attributes["count"].Value);
   for(int i=0;i<count;i++)
   {
      XmlNode itemNode = updateNode.ChildNodes[i];
      string fileName = itemNode.Attributes["name"].Value;
      FileInfo fi = new FileInfo(fileName);
      fi.Delete();
      //File.Delete(Application.StartupPath + @"\" + fileName);
      this.label1.Text = "正在更新: " + fileName + " (" + itemNode.Attributes["size"].Value + ")...";
      FileStream fs = File.Open(fileName,FileMode.Create,FileAccess.Write);
      fs.Write(System.Convert.FromBase64String(itemNode.SelectSingleNode("value").InnerText),
      0,int.Parse(itemNode.Attributes["size"].Value));
      fs.Close();
   }
   label1.Text = "更新完成";
   File.Delete(Application.StartupPath + @"\update.xml");
   label1.Text = "正在重新啟動應用程式...";
   System.Diagnostics.Process.Start("CustomerApplication.exe");
   Close();
   Application.Exit();
}
這個代碼也很容易懂,首先就是找到主進程,如果沒有關閉,則用Process.Kill()來關閉主程式。然後則用一個XmlDocument來Load程式產生的update.xml檔案。用xml檔案裡指定的路徑和檔案名稱來產生指定的檔案,在這之前先前已經存在的檔案刪除。更新完畢後,則重新啟動主應用程式。這樣更新就完成了。

四、總結:

 從這個執行個體看來,Web Service的工作是很簡單的,也是很容易實現的。好好的使用Web Service能夠為我們的程式帶來很多新的,強的功能。總而言之,.Net是易用的,強大的語言。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.