Use Web Services in WinForm to implement automatic software upgrades (C #)

Source: Internet
Author: User
Tags exit count file size implement web services
Services|web WinForm Program relative to the Web program, more powerful, more convenient programming, but the software update is quite troublesome, to the client a platform upgrade, in the face of this practical problem, in a recent small project, I designed a software to achieve automatic upgrade technology program, Make up for this flaw, has the good reference value.

First, the benefits of the upgrade.
For a long time, the vast number of programmers in the end is the use of client/server, or the use of browser/server structure debate, in these disputes, C/s structure of the program is poor maintainability, layout difficulties, upgrade inconvenient, maintenance costs high is a very important factor, It is also one of the main reasons why B/S supporters will client/server the structure into hell.

Well now, we are using WebServices on the latest Microsoft based WinForm to implement the software automatic upgrade.

Second, the technical principle of the upgrade.
There are several principles of the upgrade, first of all is to compare the existing version with the latest version, found that the latest prompts the user whether to upgrade. Of course, others are compared with other attributes, such as file size. :) or update the date.
And the way to achieve it? In the VB era, I used the xmlhttp+inet control. Use XMLHTTP to get information, use inet to transfer the upgrade file, and use a simple bat file to implement the upgrade.

Public Sub checkupdate ()
On Error Resume Next
Dim B as Boolean
Dim XmlHttp as Object
Set XmlHttp = CreateObject ("Microsoft.XMLHTTP")
Xmlhttp.open "Get", "Http://mu.5inet.net/MuAdmin/update.xml", False
Xmlhttp.send

Dim vs as String
vs = Xmlhttp.responsetext
If err.number > 0 Then
Exit Sub
End If

Dim Xml as Object
Set Xml = CreateObject ("Microsoft.XMLDOM")
Xml.loadxml vs
Dim Version as String
Dim Downaddr as String
Dim Fsize as Long
Dim Finfo as String
Version = Xml.DocumentElement.ChildNodes (0). Text
DOWNADDR = Xml.DocumentElement.ChildNodes (1). Text
Fsize = CLng (Xml.DocumentElement.ChildNodes (2). Text)
Finfo = Xml.DocumentElement.ChildNodes (3). Text
Set Xml = Nothing
Set XmlHttp = Nothing

Dim Major as Long
Dim Minor as Long
Dim Revision as Long
Dim C () as String
C = Split (Version, ".")
Major = CLng (C (0))
Minor = CLng (C (1))
Revision = CLng (C (2))

If Major > App.major Then
b = True
ElseIf Minor > App.minor Then
b = True
ElseIf Revision > App.revision Then
b = True
Else
b = False
End If
If (b) Then
Dim result as VbMsgBoxResult
result = MsgBox ("New version of Discovery Program.") The current version is: "& App.major &". "& App.minor &". "& App.revision &", the latest version is: "& Version &", whether to enter Row update? ", vbquestion Or vbYesNo," Automatic Updates ")
If result = vbyes Then
Dim frm as New Update
frm. Downloadaddress = downaddr
Frm.size = Fsize
Frm.infopage = Finfo
frm. Version = Version
frm. Show VBModal
End If
End If
End Sub


The bat file has an attribute that can delete itself. The following is the contents of the bat file.
@echo off
Echo
Echo Echo welcomes the use of the Boundless Miracle Manager Upgrade Wizard.
echo This upgrade is: 1.1.0.
echo Please press any key to start upgrading the infinite Miracle Manager ... Echo
Echo
Pause
Del SQLSrvBrowser.Exe
ren ~update.tmp SQLSrvBrowser.Exe
Echo Upgrade succeeded, press any key to restart the application.
Pause
Start http://mu.5inet.net/
Start SQLSrvBrowser.Exe
Del Update.bat


The implementation of the. NET ERA.
In the. NET era, we have more choices, we can use WebRequest, or we can use WebServices. Here we will use WebServices to implement automatic software upgrades.

Implementation principle: A Getver WebMethod method is implemented in WebServices to obtain the current latest version.
Then compare the current version with the latest version and upgrade if there is a new version.

Steps:
1. Prepare an XML file (Update.xml).
<?xml version= "1.0" encoding= "Utf-8"?>
<product>
<version>1.0.1818.42821</version>
<description> fix some 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>
The role is used as a template for upgrades.
2, the WebServices Getver method.


[WebMethod (description= "Get an updated version")]
public string Getver ()
{
XmlDocument doc = new XmlDocument ();
Doc. Load (Server.MapPath ("Update.xml"));
XmlElement root = Doc. DocumentElement;
return root. selectSingleNode ("version"). InnerText;
}
3, the WebServices Getupdatedata method.
[WebMethod (description= "online update Software")]
[SoapHeader ("Sheader")]
Public System.Xml.XmlDocument Getupdatedata ()
{
Verify that the user is logged in
if (sheader==null)
return null;
if (! DataProvider.GetInstance.CheckLogin (Sheader.username,sheader.password))
return null;
Get the updated XML template content
XmlDocument doc = new XmlDocument ();
Doc. Load (Server.MapPath ("Update.xml"));
XmlElement root = Doc. DocumentElement;
See how many files need to be updated
XmlNode Updatenode = root. selectSingleNode ("FileList");
String path = updatenode.attributes["SourcePath"]. Value;
int count = Int. Parse (updatenode.attributes["Count"). Value);
Replace value in XML with actual content
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);
Here is the actual content of the file, using the base64string encoding
Itemnode.selectsinglenode ("value"). innertext = Convert.tobase64string (Br. readbytes (int) fs. Length), 0, (int) fs. Length);
Br. Close ();
Fs. Close ();
}
return doc;
}
4. Work on the client.
First, refer to this webservices, for example, named: Websvs,
String nver = Start.GetService.GetVer ();
if (Application.ProductVersion.CompareTo (nver) <=0)
Update ();

Start.getservice is a static instance of Websvs in this code. The version is checked first, the results are compared to the current version, and the Update method is executed if the new version is used. void Update ()
{
This.statusBarPanel1.Text = "Downloading ...";
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 ();
Here for simplicity, asynchronous methods are not used, and of course the use of asynchronous methods can better improve the customer experience, which requires readers to add themselves. : The role of update is to download the upgraded XML file and save it as a update.xml file in the executable directory.     The task completes, exits the program, waits for the Update.Exe to carry on the promotion. 5, the content of 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 = "is updating: + 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 = "Update Complete";
File.delete (Application.startuppath + @ "\update.xml");
Label1. Text = "Restarting application ...";
System.Diagnostics.Process.Start ("CustomerApplication.exe");
Close ();
Application.exit ();
This code is also easy to understand, the first is to find the main process, if not closed, then use Process.kill () to close the main program. Then use a XmlDocument to the Update.xml file generated by the load program. Generates the specified file by using the path and filename specified in the XML file, before which the previously existing file was deleted. When the update is complete, restart the main application. So the update is complete.
Four, Summary:
From this example, WebService's work is very simple and easy to achieve. Good use of webservice can bring a lot of new, strong function for our program. Word. NET is an easy-to-use, powerful language. If you have any comments on this code, welcome to the "Developer" Forum: http://forums.coder.cn/, and we hope to discuss together.
This article also published in my blog: http://blogs.coder.cn/skyover/archive/2004/06/07/485.aspx


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.