Automatic online software upgrade in C/S mode using C #

Source: Internet
Author: User

Http://www.chenjiliang.com/Article/View.aspx? ArticleID = 14833

Abstract:

In view of the poor maintainability of applications written in C/S mode, this paper proposes a set of automatic online upgrade solutions, and analyzes the difficulties and implementation principles of online upgrade, and provides
Some code at the level, which has practical reference value and practical significance. The program code in this article is tested and passed in. NET Framework 1.1 and Windows2000.

Keywords: C #; online upgrade; automatic upgrade; download; XML document

1 Preface

For a long time, the majority of programmers have been arguing over whether to use Client/Server or Browser/Server structure. Among these arguments, the C/S structure
The maintenance cost is a very important factor. Many enterprise users give up using C/S for this reason. However, when an application must
How can we solve the problem of client deployment and automatic upgrade when the C/S structure is used to achieve its functions well? The deployment is simple. You just need to click the installer. The difficulty is that when a new version is released,
Automatic Upgrade [3]. Now, our goal is simple. We hope to develop a reusable automatic upgrade system that is irrelevant to specific applications. Below I provide you with a set of reusable C #
Automatically update the system.

2. Difficulties in implementing automatic software upgrade

First, in order to find updates on the remote server, the application must have a way to query the network, which requires network programming and simple protocol for communications between the application and the server.

The second is download. It seems that you do not need to consider the Internet of Things, but you need to consider downloading the files requested by the user and downloading large files without the user's consent. The friendly automatic update application will use the remaining bandwidth to download updates. This sounds simple, but it is a technical problem. Fortunately, there is a solution.

The third factor is the process of replacing the original application with the new application. This problem is interesting because it requires that you delete yourself from the system during code runtime. There are multiple ways to implement this function [5], in this article, we mainly use the date number of the new and old versions to replace the new version of the application.

3. Principle of automatic online software upgrade

Write two programs, one is the main program; the other is the Upgrade Program; all the upgrade tasks are completed by the Upgrade Program.

1. Start the Upgrade Program, connect the Upgrade Program to the website, and download the new main program (including the supported library files and xml configuration documents) to the Temporary Folder;

2. the Upgrade Program obtains the update date, version number, or file size of the new version program in the XML configuration file on the server;

3. the Upgrade Program obtains the latest update date, version number, or file size of the original client application, and compares the two. if the date of the Upgrade Program is found to be later than the latest date of the original program
Indicates whether the user is upgrading or compares the existing version with the latest version. If the latest version is found, the user is prompted to upgrade or not. Other attributes, such as the file size, are also used for comparison, it is found that the file size of the Upgrade Program is large.
The user is prompted to upgrade the size of the earlier version of the program. This article mainly uses the updated date number of the new and old versions to prompt users to upgrade.

4. If the user chooses to upgrade, the system obtains the list of downloaded files and starts to download documents in batches;

5. the Upgrade Program checks whether the old master program is active. if the activity is active, the old master program is closed;

6. Delete the old main program and copy the files in the Temporary Folder to the corresponding location;

7. Check the status of the main program. If the status is active, start the new main program;

8. Close the upgrade process and complete the upgrade [4].

4. Key Steps for online upgrade using C #

Here, I mainly use date information to check whether the upgraded version needs to be downloaded.

4.1 prepare an xml configuration file

The name is autoupdater. xml. It serves as an upgrade template and displays the information to be upgraded.

Copy and save
<?XML Version ="1.0"?><! -- XML version --><Autoupdater>    <Urladdres Url ="Http: // 192.168.198.113/vbroker/log /"/>    <! -- Upgrade the website of the server where the file is located -->    <Updateinfo>        <Updatetime Date ="2005-02-02"/>        <! -- Update date of the Update file -->        <Version Num ="1.0.0.1"/>        <! -- Upgrade the file version -->    </Updateinfo>    <Updatefilelist>        <! -- Upgrade file list -->        <Updatefile Filename ="Aa.txt"/>        <! -- A total of three files need to be upgraded -->        <Updatefile Filename ="Vb40.rar"/>        <Updatefile Filename =VB4-1.CAB"/>    </Updatefilelist>    <Restartapp>        <Restart Allow ="Yes"/>        <! -- Allow restarting the application -->        <Appname Name ="Tims.exe"/>        <! -- Name of the started Application -->    </Restartapp></Autoupdater>

From the above XML document you can know that the upgrade document server address, upgrade document update date, the list of files to be upgraded, a total of three files need to be upgraded: aa.txt0000vb40.rar, VB4-1.CAB. And whether the application can be restarted and the name of the application to be restarted.

4.2 obtain the last update date of the client application and server upgrade Program

It is implemented through the getthelastupdatetime () function.
Copy and save

Private StringGetthelastupdatetime (StringDIR ){StringLastupdatetime ="";StringAutoupdaterfilename = dir +@ "\ Autoupdater. xml";If(! File. exists (autoupdaterfilename ))ReturnLastupdatetime;// Open the XML fileFilestream myfile =NewFilestream (autoupdaterfilename, filemode. Open );// XML file ReaderXmltextreader xml =NewXmltextreader (myfile );While(XML. Read ()){If(XML. Name ="Updatetime"){// Obtain the last update date of the upgrade documentLastupdatetime = xml. getattribute ("Date");Break;}} XML. Close (); myfile. Close ();ReturnLastupdatetime ;}

Use xmltextreader to open the XML document and read the update time to obtain the value corresponding to the date, that is, the last update time of the server-side Update file.

Function call implementation:
Copy and save

// Obtain the Last Update Time of the application in the specified path of the client.StringThepreupdatedate = getthelastupdatetime (application. startuppath );// Application. startuppath indicates the path of the client application.// Obtain the last update date of the downloaded documents from the serverStringThelastsupdatedate = getthelastupdatetime (thefolder. fullname );// Thefolder. fullname indicates the path of the Temporary Folder downloaded from the upgrade document to the client.

4.3 comparison date

The last update date of the client application is compared with the last update date of the server upgrade program.
Copy and save

// Obtain the latest update date of the downloaded documentStringThelastsupdatedate = getthelastupdatetime (thefolder. fullname );If(Thepreupdatedate! =""){// If the client updates the upgraded application on a date greater than the update date of the application on the server    If(Convert. todatetime (thepreupdatedate)> = convert. todatetime (thelastsupdatedate) {MessageBox. Show ("The current software is already up-to-date. No updates are required! ","System prompt", Messageboxbuttons. OK, messageboxicon. information );This. Close ();}}This. Labdownfile. Text ="Download an Update file";This. Labfilename. Refresh ();This. Btncancel. Enabled =True;This. Progressbar. Position = 0;This. Progressbartotal. Position = 0;This. Progressbartotal. Refresh ();This. Progressbar. Refresh ();// Obtain the list of downloaded files through dynamic arrayArraylist list = getdownfilelist (gettheupdateurl (), thefolder. fullname );String[] URLs =New String[List. Count]; List. copyto (URLs, 0 );

Compare the date of the client-upgraded application with the date of the application downloaded from the server. If the former is greater than the latter, the application is not updated. If the former is smaller than the latter, you can use a dynamic array to obtain the list of downloaded files and start downloading the files.

Implemented through the batchdownload () function. The upgrade program checks whether the old master program is active. If it is active, it closes the old master program. It deletes the old master program and copies the files in the Temporary Folder to the corresponding location; check the status of the main program. If the status is active, start the new main program.
Copy and save

Private VoidBatchdownload (ObjectData ){This. Invoke (This. Activestatechanger,New Object[] {True,False});Try{Downloadinstructions instructions = (downloadinstructions) data;// Batch download        Using(Batchdownloader BDL =NewBatchdownloader () {BDL. currentprogresschanged + =NewDownloadprogresshandler (This. Singleprogresschanged); BDL. statechanged + =NewDownloadprogresshandler (This. Statechanged); BDL. filechanged + =NewDownloadprogresshandler (bdl_filechanged); BDL. totalprogresschanged + =NewDownloadprogresshandler (bdl_totalprogresschanged); BDL. Download (instructions. URLs, instructions. Destination, (manualresetevent)This. Cancelevent );}}Catch(Exception ex) {showerrormessage (Ex );}This. Invoke (This. Activestatechanger,New Object[] {False,False});This. Labfilename. Text ="";// Update the program    If(This. _ Update ){// Close the original application        This. Labdownfile. Text ="Closing Program ...."; System. Diagnostics. Process [] Proc = system. Diagnostics. process. getprocessesbyname ("TIMS");// Close all processes of the original application        Foreach(System. Diagnostics. Process proInProc) {pro. Kill ();} directoryinfo thefolder =NewDirectoryinfo (path. gettemppath () +"Jurassicupdate");If(Thefolder. exists ){Foreach(Fileinfo thefileInThefolder. getfiles ()){// If the Temporary Folder contains a file with the same name as the file in the application directory, delete the file in the application directory.                If(File. exists (application. startuppath +"\\"+ Path. getfilename (thefile. fullname) file. Delete (application. startuppath +"\\"+ Path. getfilename (thefile. fullname ));// Move the files in the Temporary Folder to the directory where the application is locatedFile. Move (thefile. fullname, application. startuppath +"\\"+ Path. getfilename (thefile. fullname ));}}// Start the installer        This. Labdownfile. Text ="Starting the program ...."; System. Diagnostics. process. Start (application. startuppath +"\\"+"Tims.exe");This. Close ();}}

This program is the key code for online upgrade. The steps are a bit complicated: first, use the invoke method to synchronously call the process to change the status, and then call the dynamic link library for batch download.
(Batchdownloader. CS) class starts batch download, and then judges whether the original main application is closed. If not, use process. Kill () to close the master
Program. Next, check whether there is a file with the same name as the file in the Temporary Folder (that is, the directory where the update program is downloaded). If there is a file with the same name, delete
File, and then move the files in the Temporary Folder to the directory where the application is located. Restart the main application. This completes the update.

References

[1] Pang lan. 8051 SCM online upgrade software method. http://www.mcublog.com/more.asp? Name = mcublog & id = 3111 China Electronic Engineer blog site

[2] using Web Services in winform to implement auto update (C #). Http://www.cnblogs.com/x#/articles/105656.htmlblog

[3] reusable automatic upgrade system implementation. Http://www.cnblogs.com/cdo/archive/2005/09/06/231229.html blog

[4] use VB6.0 to compile a self-Upgrade Program. Http://www.enet.com.cn/article/2004/0525/A20040525311583.shtml

[5]. Net Background Intelligent Transmission Service to achieve automatic update (on). http://www.itonline.gd.cn/news/detail.asp? News_id = 4071 it online

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.