C # software Automatic Update upgrade

Source: Internet
Author: User
Tags httpcontext unpack visibility
C # software automatic Update upgrade

principle

The structure of the server side is this:

Its working principle is as follows:

Update.asmx only provides a feature that detects whether an update is needed, returns an updated address when an update is needed, and typically returns an address that is download.ashx and, in some exceptional cases, modifies the server to provide an updated download from other URLs. The specific way to detect whether an update is needed is to get the main program version number in the Updata directory, and then get the latest version number in the database, in contrast. If the same is directly relative to the version number provided by the client and returns the result, if different, the main program version number is written to the database, then a new update package is generated, and the update address is returned directly to the client.

The DOWNLOAD.ASHX function is simply to update the package output with the latest version.

While the client part contains the main program, Update.exe and other ancillary files, updated by the main program to detect and download updates, when the main program exits, if there is an update and has been successfully downloaded, then call Update.exe complete unpack and update coverage work. Note that Update.exe can never be updated because it cannot update itself, so do not include Update.exe in the update package when the server is updated.

Here's how to actually write an automatic update solution: server-side

First set up a Web service project, the project name is "Automatic Update Service":

Add a database named Database.mdf:

Create a new database diagram in the database and design the database table as follows:

Create a ado.net Entity Data Model named MODEL.EDMX:

Build the model from the database that you just created:

Add two nodes to the Web.config appsettings node to set the update's main file name and update package download address:

C#

<appSettings>

<add key= "Main program file name" value= "MyApp.exe"/>

<add key= "update package download Address" value= "Download.ashx"/>

</appSettings>

Introduce a Gzip class to package (the source code for this class will be provided at the end of the article with the sample source in this article):

Add a new Web service named Update.asmx:

Write the following code:

C#

[WebMethod]

public string GetUpdate (string Clientverison)

{

if (Get Latest version ()!= Clientverison)

{

return system.web.configuration.webconfigurationmanager.appsettings["update package download Address"];

}

return null;

}


Static string Gets the latest version ()

{

String v = Gets the file version (HttpContext.Current.Server.MapPath (string). Format ("~/app_data/update/{0}", system.web.configuration.webconfigurationmanager.appsettings["main program file name"));

using (var c = new Databaseentities ())

{

Get the latest version information from the database

var q = c.updateversion.orderbydescending (f => f.publictime). FirstOrDefault ();

if (q = = NULL | | v!= q.version)

{

When the version in the database is inconsistent with the current main program version, write to the database and generate a new update package, whichever is the main program version

var d = new Updateversion () {Version = V, publictime = DateTime.Now};

C.addtoupdateversion (d);

C.savechanges ();

Package Update files (HttpContext.Current.Server.MapPath ("~/app_data/update/"), HttpContext.Current.Server.MapPath ("~/app_data /update.gzip "));

}

}

return v;

}


public static void Package update file (String package directory, string output file)

{

GZip. Compress (output file, Directory.GetFiles (packaged directory). Concat (directory.getdirectories (packaged directory)). ToArray ());

}


public static string Get file version (string file path)

{

FileVersionInfo f = fileversioninfo.getversioninfo (file path);

return f.fileversion;

}

create download.ashx to output update packages:

Code:

C#

public void ProcessRequest (HttpContext context)

{

Context. Response.ContentType = "Application/zip";

Context. Response.WriteFile (context. Server.MapPath ("~/app_data/update.gzip"));

}

The service is ready to write. Client

Create a new WinForm application project named Update:

After the establishment of a direct delete Form1.cs bar, this program does not require an interface, in the Program.cs to write code on it.

You also need to introduce the Gzip class for unpack:

Then write the code:

C#

[STAThread]

static void Main ()

{

Try

{

var d = DateTime.Now;

while (DateTime.Now.Subtract (d). TotalSeconds <) application.doevents ();

GZip. Decompress (Path.Combine (Application.startuppath, "Update.data"), Application.startuppath);

}

Catch {}

}

The function here is to wait 10 seconds, then unpack the Update.data file and overwrite it in the current directory.

Now to build the main program, the main program is WinForm, command line, WPF all can, we create a new WPF application, named MyApp:

To add a service reference to a program:

The address used here is the local debug address.

To detect the version number of the main program itself, you also need to add a reference to the System.Windows.Forms.

Then start the design interface, only to demonstrate the update operation, so the interface is simply designed to update the relevant prompts, action controls:

The code is:

<window x:class= "Myapp.window1"

Xmlns= "Http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml"

Title= "Window1" height= "377" loaded= "window_loaded" closed= "window_closed" >

<Grid>

<Grid.RowDefinitions>

<rowdefinition height= "1*"/>

<rowdefinition height= "1*"/>

<rowdefinition height= "1*"/>

</Grid.RowDefinitions>

<label margin= "0" name= "Label1" horizontalalignment= "center" verticalalignment= "center" visibility= "Hidden" > A new version is detected and is downloaded. </Label>

<button grid.row= "1" height= "Name=" button1 "verticalalignment=" Center "visibility=" Hidden "click=" button1_ Click > Start Download </Button>

<label grid.row= "2" margin= "0" name= "label2" verticalalignment= "center" horizontalalignment= "center" visibility= " Hidden > Update package has been downloaded and the update operation will be performed automatically after the program is closed. </Label>

</Grid>

</Window>

Note that the controls are set to Visibility= "Hidden", and we'll show them when we need them.

Writing background code:

C#

Public Uri Downloaduri

{

Get

{

return _downloaduri;

}

Set

{

_downloaduri = value;

}

}

Private Uri _downloaduri;


public bool Updateready

{

Get

{

return _updateready;

}

Set

{

_updateready = value;

}

}

private bool _updateready;


private void Window_Loaded (object sender, RoutedEventArgs e)

{

var u = new MyApp.ServiceReference.UpdateSoapClient ();

var s=u.getupdate (System.Windows.Forms.Application.ProductVersion);

if (!string. IsNullOrEmpty (s))

{

Gets the URI relative to the URI of the Web service

Downloaduri = new Uri (U.endpoint.listenuri, s);

Label1. Visibility = button1. Visibility = visibility.visible;

}

}


private void Button1_Click (object sender, RoutedEventArgs e)

{

var c = new WebClient ();

C.downloadfile (Downloaduri, System.IO.Path.Combine (System.Windows.Forms.Application.StartupPath, "Update.data")) ;

Updateready = true;

Label2. Visibility = visibility.visible;

}


private void Window_closed (object sender, EventArgs e)

{

if (Updateready)

{

Process.Start (System.IO.Path.Combine (System.Windows.Forms.Application.StartupPath, "Update.exe"));

}

}

Test

Now put the main program, the subordinate files and the Update.exe together, and copy the main program and the subordinate files to the app_data/update/directory on the server side and add a "update note. txt":

Then start the client program to test, you should see nothing in the program interface, because the client and server-side program version is consistent.

Now we modify the client version Number 1.0.0.1:

Then recompile the program.

Because the server is only to determine whether the version number is different, not which is higher, so not only upgrade, downgrade update is also possible, we have to test:

Find the so-called new version of ^ ^, point start Download:

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.