天天看點

使用C#的WebService實作用戶端軟體的更新

由于項目原因,要實施的客戶離作者太遠,考慮提供軟體的線上更新功能.我們如何實作呢!先講下思路.

思路:

先實作WEB端的開發,主要考慮使用WEBService技術,提供遠端服務的調用函數,傳回一個檔案的位元組内容,然後寫一個更新程式用戶端,分發給客戶使用的機器中,(可以随客戶的軟體一起安裝).該用戶端程式主要連接配接webserivce,然後将檔案儲存到本地機(客戶的機器)中.就可以實作!

實作的細節:

要考慮提供給客戶軟體版本問題,低版本的更新,最新版本的就不用更新.還要考慮使用者名與密碼在WEB端的認證!

使用技術:

ASP.Net WebService開發,用戶端的異步調用WebService方法.資料庫技術!

開始實作:

1.建立資料庫,使用SQLSERVER2000

1)軟體項目表:softlist(softid, softname, resume, loginname, loginpwd)

softid:編号

softname:軟體名稱

resume:介紹

loginname:客戶登入名

loginpwd:密碼

2)各個軟體的版本表 SoftListVersion(softid, subid, version, UpdatePath, olefile)

softid:主表的軟體編号

subid:各版本資料編号

version:軟體版本

filename:更新檔案名

olefile:更新檔案的二進制内容,是image類型,(我主要存放MSI的安裝封包件類型,可以使用C#做此類安裝封包件)

3)建立一個視圖,chkVersion,用于檢查版本号

SELECT dbo.SoftListVersion.subid, dbo.softlist.softname, dbo.SoftListVersion.version

FROM dbo.softlist INNER JOIN

        dbo.SoftListVersion ON dbo.softlist.softid = dbo.SoftListVersion.softid

4)再建立一個視圖,vOleFile,用于下載下傳檔案

SELECT dbo.SoftListVersion.subid, dbo.softlist.softname, dbo.SoftListVersion.filename, 

        dbo.SoftListVersion.olefile, dbo.SoftListVersion.version

2.寫一個WEBSERVICE

1)啟動VS.Net2003,建立一個叫babyWebSvc的項目,項目類型為(ASP.Net WEB服務)

2)添加一個SoftUpdate.asmx的WEB服務

3)添加一個方法SearchVersion

[WebMethod(Description="傳回目前軟體更新包的最高版本")]

public string SearchVersion(string softname)

{

   string sVersion = "";

   webmod.dbConnStart(); //(連接配接)作者自己的連接配接資料庫類,使用者自己完成資料庫連接配接

   string strSQL = "select MAX(version) as MaxVerID from chkVersion where softname = @softname";

   SqlCommand sqlCmd = new SqlCommand(strSQL,webmod.sqlConn);

   sqlCmd.CommandTimeout = 0;

   sqlCmd.Parameters.Add("@softname",SqlDbType.VarChar).Value = softname;

   SqlDataReader sqlRd = sqlCmd.ExecuteReader();

   if(sqlRd.HasRows)

   {

    sqlRd.Read();

    sVersion = Convert.ToString(sqlRd["MaxVerID"]);

   }

   sqlRd.Close();

   webmod.dbConnEnd(); //(斷開連接配接)作者自己的連接配接資料庫類,使用者自己完成資料庫連接配接

   return sVersion;

}

4)添加下載下傳檔案内容的方法DownloadSoft

[WebMethod(Description="傳回需要下載下傳的檔案位元組")]

public byte[] DownloadSoft(string UserName,string PassWord,string SoftDnldName,string SoftHeightVersion)

   //(連接配接)作者自己的連接配接資料庫類,使用者自己完成資料庫連接配接

   webmod.dbConnStart();

   //檢查使用者合法性

   bool bMember = CheckAuth(UserName,PassWord);//該WebService内的一個檢查使用者合法性的函數,使用者可以自己完成

   if(!bMember)

    webmod.dbConnEnd();

    return null;

   byte[] b = null;

   //我們取出指定軟體名稱的最高版本的更新包

   sqlCmd.Parameters.Add("@softname",SqlDbType.VarChar).Value = SoftDnldName;

   sqlCmd.Parameters.Add("@ver",     SqlDbType.VarChar).Value = SoftHeightVersion;

    b = (byte[])sqlRd["olefile"];//檔案的位元組内容

   //(斷開連接配接)作者自己的連接配接資料庫類,使用者自己完成資料庫連接配接

   webmod.dbConnEnd();

   return b;

3.WEB服務的方法完成後,你自己可以啟動,測試,我們現在來寫用戶端的更新程式,假定你在開發時的WEBSERVICE的URL為:http://localhost/babywebsvc/SoftUpdate.asmx,注意這個URL,我們是要在用戶端引用的

4.啟動VS.Net2003,建立一個C#的Windows項目,在預設的FORM上添加一個按鈕,

5.添加一個新的檔案類型(應用程式配置檔案)App.config

App.Config檔案的内容

<?xml version="1.0" encoding="utf-8"?>

<configuration>

   <appSettings>

    <add key="user" value="test"/>

    <add key="pwd" value="test"/>

    <add key="babyRecordSoftName" value="TEST.EXE"/><!--記錄在遠端的資料庫中的軟體名稱-->

    <add key="Version" value="1.0"/>

   </appSettings>

</configuration>

6.我們在Form啟動的LOAD事件中,添加如下代碼

private void Form1_Load(object sender, System.EventArgs e)

//讀出版本号,該版本号是在AssemblyInfo.cs中由系統本身設定的,[assembly: AssemblyVersion("1.0")]

//以後要更改,可以改此處的AssemblyInfo.cs中的版本号,例:[assembly: AssemblyVersion("1.1")]

//我們的WEBSERVICE中需要這個資料做為參數

string sVersion = Application.ProductVersion;

//寫到App.Cofing檔案中,每次調用WEBSERVICE方法時,從App.Cofing中讀取版本,你也可以直接使用Application.ProductVersion,我是為了統一管理,全部從config中讀取

this.SaveAppConfig("Version",sVersion);

//SaveAppConfig函數的内容

public static void SaveAppConfig(string AppKey,string AppValue)

   XmlDocument xDoc = new XmlDocument();

   xDoc.Load(Application.ExecutablePath + ".config");

   XmlNode xNode;

   XmlElement xElem1;

   XmlElement xElem2;

   xNode = xDoc.SelectSingleNode("//appSettings");

   xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key=" + AppKey + "]");

   if ( xElem1 != null ) xElem1.SetAttribute("value",AppValue);

   else

    xElem2 = xDoc.CreateElement("add");

    xElem2.SetAttribute("key",AppKey);

    xElem2.SetAttribute("value",AppValue);

    xNode.AppendChild(xElem2);

   xDoc.Save(Application.ExecutablePath + ".config");

7.主要部分,開始調用webservice的方法!

準備工作:1)添加一個WEB引用,(先點菜單"項目"-"添加WEB引用"),在彈出中中輸入url的路徑:http://localhost/babywebsvc/SoftUpdate.asmx

   3)填入WEB引用名:AutoUpdateWebSvc

   4)點下按紐完成WEB引用的添加

8.在你的Button1_click事件中添加如下CODE,主要使用異步調用

private string svcUser = "";

private string svcPwd = "";

private string svcSoftName = "";

private string svcCurrVersion = "";

private string svcDnldFileName = "Test.MSI";//下載下傳下來的檔案名,

private byte[] fbyte = null; //下載下傳後的更新檔案的内容

private void Button1_Click(object sender, System.EventArgs e)

//讀取App.config檔案中的配置資訊

svcUser = System.Configuration.ConfigurationSettings.AppSettings["user"]; //需要人證的使用者名

svcPwd = System.Configuration.ConfigurationSettings.AppSettings["pwd"];   //認證密碼

svcSoftName = System.Configuration.ConfigurationSettings.AppSettings["babyRecordSoftName"];//軟體名稱

svcCurrVersion = System.Configuration.ConfigurationSettings.AppSettings["Version"];//目前版本号

   try

    AutoUpdateWebSvc.SoftUpdate aSvc = new AutoUpdateWebSvc.SoftUpdate();

    //此處可以改成自己實際應用時的URL,不管WEB引用是動态還是靜态,調用都會指向該URL

    if(Button1.Text.Trim() == "檢 查")

    {

     //檢查最新版本

     System.AsyncCallback cb = new AsyncCallback(SearchVersionCallBack);//異步回調方法,并檢查是否有高版本的更新軟體存在

     aSvc.BeginSearchVersion(svcSoftName,cb,aSvc);

    }

    else if(Button1.Text.Trim() == "升 級")

     //開始調用下載下傳服務

     InvokeDownload(); //函數體見下面的CODE

   catch(Exception ex)

    MessageBox.Show(ex.Message);

//檢查最新版本的異步回調方法

private void SearchVersionCallBack(System.IAsyncResult ar)

   if(ar==null)return;

   if(ar.IsCompleted)

    try

     AutoUpdateWebSvc.SoftUpdate aSvc = (AutoUpdateWebSvc.SoftUpdate)ar.AsyncState;

     string sVersion = aSvc.EndSearchVersion(ar);

     aSvc.Dispose();

     if(svcCurrVersion.Trim() == sVersion.Trim())

      MessageBox.Show"你的軟體目前版本已經是最新的了,無需進行更新...");

     else if((string.Compare(svcCurrVersion.Trim(),sVersion.Trim()))==-1)

     {

      MessageBox.Show("你的軟體目前版本比較低,可以進行更新...");

      Button1.Text = "升 級";

     }

    catch(Exception ex)

     MessageBox.Show(ex.Message);

//調用遠端的WEB服務,開始下載下傳

private void InvokeDownload()

    //開始下載下傳

    System.AsyncCallback cb = new AsyncCallback(DownloadSoftCallBack);//異步回調方法,儲存檔案

    aSvc.BeginDownloadSoft(svcUser,svcPwd,svcDnldFileName,lblVersion.Text.Trim(),cb,aSvc);

//下載下傳方法執行完成後,異步回調方法

private void DownloadSoftCallBack(System.IAsyncResult ar)

   if(ar==null)

    MessageBox.Show("更新過程中出現錯誤,不能進行更新,請稍後再試...");

    return;

     fbyte = aSvc.EndDownloadSoft(ar);

     //使用線程,儲存檔案

     Thread th = new Thread(new ThreadStart(Save2Disk));

     th.Start();

     MessageBox.Show("更新過程中出現錯誤,"+ex.Message);

//将下載下傳下來的位元組數組儲存成檔案

private void Save2Disk()

    FileInfo finfo = new FileInfo(Application.ExecutablePath+svcDnldFileName);

    if(finfo.Exists)finfo.Delete();//檔案存在就删除它

    Stream stream = finfo.OpenWrite();

    prosBar.Maximum = fbyte.Length;//prosBar是一個進度條

    prosBar.Minimum = 0;

    prosBar.Step = 1;

    int i=0;

    foreach(byte b in fbyte)

     stream.WriteByte(b);

     prosBar.Value += 1;

    stream.Flush();

    stream.Close();

    DialogResult dr = MessageBox.Show("下載下傳完成,是否現在就安裝更新程式...","提示資訊",MessageBoxButtons.OKCancel,MessageBoxIcon.Information,MessageBoxDefaultButton.Button1);

    if(dr == DialogResult.OK)

     ExecSetup();//啟動下載下傳下來的安裝程式,使用者可以自己完成

    MessageBox.Show("更新過程中出現錯誤,"+ex.Message);

   uiButton2.Enabled = true;

9:總結,用戶端調用,是從,點選Buttton1開始,搜尋版本号,SearchVersion,當找到高版本更新包時,開始執行下載下傳的方法DownloadSoft,然後儲存到本地Save2Disk.

不管用戶端的調用是同步還是異步,WEBService的方法都是一樣寫的,隻不過同步調用,是直接使用WEBService中的方法名稱,異步調用則會由系統自動生成BeginXXX()與EndXXX()的方法名稱,提供給你使用

本文轉自yonghu86 51CTO部落格,原文連結:http://blog.51cto.com/yonghu/1321395,如需轉載請自行聯系原作者