Use C # WebService to Update client software

Source: Internet
Author: User

For project reasons, the implementation of customers is too far away from the author, consider providing software online upgrade function. How can we achieve it! Let's talk about the idea first.

Ideas:
First, implement WEB-based Development. We mainly consider using WEBService technology to provide remote service call functions, return the byte content of a file, and then write an upgrade program client, distributed to the machines used by the customer (can be installed together with the customer's software ). the client program connects to webserivce and saves the file to the Local Machine (the customer's machine. you can achieve it!

Implementation Details:
You need to consider providing the customer with software version issues. If you are upgrading a lower version, you do not need to upgrade the latest version. You also need to consider WEB-based user name and password authentication!

Technology used:
ASP. Net WebService development, client asynchronous call WebService method. Database technology!

Start implementation:

1. Create a database and use SQLSERVER2000
1) software project table: softlist (softid, softname, resume, loginname, loginpwd)
Softid: No.
Softname: Software name
Resume: Introduction
Loginname: Customer Login Name
Loginpwd: Password

2) SoftListVersion (softid, subid, version, UpdatePath, olefile)
Softid: Software ID of the master table
Subid: Data number of each version
Version: Software version
Filename: file name for upgrade
Olefile: the binary content of the upgrade file, which is of the image type. (I mainly store the MSI installation package file type. You can use C # For this installation package file)

3) create a view named chkVersion to check the version number.
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) create another view, vOleFile, for downloading files
SELECT dbo. SoftListVersion. subid, dbo. softlist. softname, dbo. SoftListVersion. filename,
Dbo. SoftListVersion. olefile, dbo. SoftListVersion. version
FROM dbo. softlist INNER JOIN
Dbo. SoftListVersion ON dbo. softlist. softid = dbo. SoftListVersion. softid

2. Write a WEBSERVICE
1) Start VS. Net2003 and create a project named babyWebSvc. The project type is (ASP. Net WEB service)
2) Add a SoftUpdate. asmx WEB Service

3) Add a SearchVersion method.

[WebMethod (Description = "returns the highest version of the current software upgrade package")]
Public string SearchVersion (string softname)
{
String sVersion = "";
Webmod. dbConnStart (); // The author connects to the database class, and the user connects to the database.
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 (); // The author connects to the database class, and the user connects to the database.

Return sVersion;
}

4) add DownloadSoft

[WebMethod (Description = "returns the object byte to be downloaded")]
Public byte [] DownloadSoft (string UserName, string PassWord, string SoftDnldName, string SoftHeightVersion)
{
// The author connects to the Database Class and the user connects to the database.
Webmod. dbConnStart ();

// Check user Validity
Bool bMember = CheckAuth (UserName, PassWord); // a function in the WebService that checks the validity of a user. You can complete this function by yourself.
If (! BMember)
{
Webmod. dbConnEnd ();
Return null;
}

Byte [] B = null;

// Obtain the upgrade package of the highest version with the specified software name
String strSQL = "select olefile from vOleFile where (filename = @ softname) and version = @ ver ";
SqlCommand sqlCmd = new SqlCommand (strSQL, webmod. sqlConn );
SqlCmd. CommandTimeout = 0;
SqlCmd. Parameters. Add ("@ softname", SqlDbType. VarChar). Value = SoftDnldName;
SqlCmd. Parameters. Add ("@ ver", SqlDbType. VarChar). Value = SoftHeightVersion;
SqlDataReader sqlRd = sqlCmd. ExecuteReader ();
If (sqlRd. HasRows)
{
SqlRd. Read ();
B = (byte []) sqlRd ["olefile"]; // The byte content of the file
}
SqlRd. Close ();

// (Disconnect) the author connects to the Database Class and the user connects to the database.
Webmod. dbConnEnd ();

Return B;
}

3. after the WEB service method is completed, you can start and test it yourself. Now we will write the client Upgrade Program. Assume that the URL of your WEBSERVICE during development is: http: // localhost/babywebsvc/SoftUpdate. asmx, pay attention to this URL, which we will reference on the client
4. Start VS. Net2003, create a C # Windows project, and add a button on the default FORM,
5. Add a new file type (application configuration file) App. config
App. Config file content

<? Xml version = "1.0" encoding = "UTF-8"?>
<Configuration>
<Deleetask>
<Add key = "user" value = "test"/>
<Add key = "pwd" value = "test"/>
<Add key = "babyRecordSoftName" value = "TEST. EXE"/> <! -- Name of the software recorded in the remote database -->
<Add key = "Version" value = "1.0"/>
</AppSettings>
</Configuration>

6. In the LOAD event started by Form, add the following code:

Private void Form1_Load (object sender, System. EventArgs e)
{
// Read the version number, which is set by the system in AssemblyInfo. cs. [assembly: AssemblyVersion ("1.0")]
// You can change the version number in AssemblyInfo. cs, for example, [assembly: AssemblyVersion ("1.1")].
// This data is required as a parameter in our WEBSERVICE.

String sVersion = Application. ProductVersion;

// Write to App. in the Cofing file, each time the WEBSERVICE method is called. you can also directly use Application. productVersion, which is for unified management and all read from config
This. SaveAppConfig ("Version", sVersion );
}

// Content of the SaveAppConfig Function
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. Start to call the webservice method!
Preparations: 1) Add a WEB reference, (click "project"-"add WEB reference"), and enter the url path: http: // localhost/babywebsvc/SoftUpdate. asmx
2) assume that the webservice url during development is http: // localhost/babywebsvc/SoftUpdate. asmx.
3) Fill in the WEB reference name: AutoUpdateWebSvc
4) Click a button to add a WEB reference.

8. Add the following CODE in your button#click event, mainly using asynchronous calls

Private string svcUser = "";
Private string svcPwd = "";
Private string svcSoftName = "";
Private string svcCurrVersion = "";
Private string svcDnldFileName = "Test. MSI"; // The downloaded file name,
Private byte [] fbyte = null; // the content of the downloaded upgrade File
Private void button#click (object sender, System. EventArgs e)
{
// Read the configuration information in the App. config file
SvcUser = System. Configuration. ConfigurationSettings. deleetask[ "user"]; // the user name that requires authentication
SvcPwd = System. Configuration. ConfigurationSettings. receivettings ["pwd"]; // authentication Password
SvcSoftName = System. Configuration. ConfigurationSettings. receivettings ["babyRecordSoftName"]; // software name
SvcCurrVersion = System. Configuration. ConfigurationSettings. deleettings ["Version"]; // The current Version number.

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

// You can change the URL you actually use. No matter whether the WEB reference is dynamic or static, the call will point to the URL.
ASvc. Url = "http: // localhost/babyWebSvc/SoftUpdate. asmx ";

If (Button1.Text. Trim () = "check ")
{
// Check the latest version
System. AsyncCallback cb = new AsyncCallback (SearchVersionCallBack); // asynchronous callback method, and check whether there is a higher version of the upgraded software
ASvc. BeginSearchVersion (svcSoftName, cb, aSvc );
}
Else if (Button1.Text. Trim () = "litre ")
{
// Start calling the download service
InvokeDownload (); // The CODE below shows the function body.
}

}
Catch (Exception ex)
{
MessageBox. Show (ex. Message );
}
}

// Check the asynchronous callback method of the latest version.
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 "the current version of your software is already up to date. You do not need to upgrade it ...");
Else if (string. Compare (svcCurrVersion. Trim (), sVersion. Trim () =-1)
{

MessageBox. Show ("your current software version is relatively low, you can upgrade ...");
Button1.Text = "Upgrade ";
}

}
Catch (Exception ex)
{
MessageBox. Show (ex. Message );
}
}
}

 

// Call a remote WEB service to start download
Private void InvokeDownload ()
{
Try
{
AutoUpdateWebSvc. SoftUpdate aSvc = new AutoUpdateWebSvc. SoftUpdate ();
// You can change the URL you actually use. No matter whether the WEB reference is dynamic or static, the call will point to the URL.
ASvc. Url = "http: // localhost/babyWebSvc/SoftUpdate. asmx ";

// Start download
System. AsyncCallback cb = new AsyncCallback (DownloadSoftCallBack); // asynchronous callback method to save the file
ASvc. BeginDownloadSoft (svcUser, svcPwd, svcDnldFileName, lblVersion. Text. Trim (), cb, aSvc );

}
Catch (Exception ex)
{
MessageBox. Show (ex. Message );
}
}

// Asynchronous callback method after the download method is executed
Private void DownloadSoftCallBack (System. IAsyncResult ar)
{
If (ar = null)
{
MessageBox. Show ("an error occurred during the upgrade process. You cannot upgrade it. Please try again later ...");
Return;
}
If (ar. IsCompleted)
{
Try
{
AutoUpdateWebSvc. SoftUpdate aSvc = (AutoUpdateWebSvc. SoftUpdate) ar. AsyncState;
Fbyte = aSvc. EndDownloadSoft (ar );
ASvc. Dispose ();

// Use the thread to save the file
Thread th = new Thread (new ThreadStart (Save2Disk ));
Th. Start ();

}
Catch (Exception ex)
{
MessageBox. Show ("an error occurred during upgrade," + ex. Message );
}
}
}

// Save the downloaded byte array as an object
Private void Save2Disk ()
{
Try
{
FileInfo finfo = new FileInfo (Application. ExecutablePath + svcDnldFileName );
If (finfo. Exists) finfo. Delete (); // Delete the object if the object Exists.
Stream stream = finfo. OpenWrite ();

ProsBar. Maximum = fbyte. Length; // prosBar is a progress bar
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 ("Download complete, install the Upgrade Program now...", "prompt message", MessageBoxButtons. OKCancel, MessageBoxIcon. Information, MessageBoxDefaultButton. Button1 );
If (dr = DialogResult. OK)
{
ExecSetup (); // start the downloaded installer.
}
}
Catch (Exception ex)
{
MessageBox. Show ("an error occurred during upgrade," + ex. Message );
}
UiButton2.Enabled = true;
}

9: In summary, the client call is from. Click Buttton1 to start searching for the version number and SearchVersion. When a high version upgrade package is found, run DownloadSoft to download the package and save it to the local Save2Disk.
No matter whether the client call is synchronous or asynchronous, the WEBService method is the same, but the synchronous call directly uses the method name in WEBService. The system automatically generates BeginXXX () for asynchronous calls () the method name with EndXXX () is provided for you to use

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.