65.9K
CodeProject is changing. Read more.
Home

UpdaterApp - a Library for Easy Update

starIconstarIconstarIconstarIconstarIcon

5.00/5 (7 votes)

Sep 27, 2019

CPOL

4 min read

viewsIcon

9814

downloadIcon

326

This article explains an easy method to download and update your WinForms application

Introduction

Whenever we develop software, we need automatic updating. This allows the developer to take advantage of automatic resources through an open source library developed 100% in VB.NET and can be used in C # and other languages.
So in this article, I propose a library (.dll), which is based on the AntSoft Systems On Demand (ASUpdater) library (I am licensed to distribute this code because I am the author of it and CEO of the company).

Requirements

  • .NET Framework 4.5 or higher
  • System.Windows.Forms
  • System.Reflection
  • System.Xml
  • System.Security.Cryptography
  • System.ComponentModel
  • System.Drawing

Code of the Library

Module

The module has basic and common library functions, as well as application information such as Path, Title, and Versions.

In this module, we have the variables, which will receive the application data and the functions UrlExist, GotInternet, CreateHashPure, GetMd5Hash and sub MainLib.

  • Public Function UrlExist (ByVal sUrl As String): Check if the URL exists and return a boolean. You must also enter the path with the file to be downloaded.
  • GotInternet(): Checks if computer is connected to the network. The function returns a Boolean response.
  • CreateHashPure(ByVal sString As String, Optional iSize As Integer = 32): Create MD5 Hash.
    • sString. Enter the variable you want to encrypt in MD5.
    • iSize: Enter the size you want to return encryption in MD5, maximum size is 32.

    The function returns a String response.

  • GetMd5Hash(ByVal md5Hash As MD5, ByVal input As String): The function return a String response.
  • MainLib(). Load the information of the Application on Start.

In module mMain, we have the following code:

Imports System.Windows.Forms
Imports System.Net
Imports System.Xml
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Security.Cryptography
Imports System.ComponentModel
Imports System.Drawing
Module mMain
    Public sPath As String 'Application Path 
    Public sTitle As String 'Application Title
    Public sVerActual As String 'Actual Application Major Version with format 1
    Public sVerActualSimp As String 'Actual Application Version with simple format 1.0
    'Sets the Update Version to the Application version, 
    'but in the future, the version will receive information from the configuration file, 
    'which is on the server hosting the new version installation file.
    Public sVerUpdate As FileVersionInfo = _
           FileVersionInfo.GetVersionInfo(Application.ExecutablePath)
    Public sVersion As String
    Public PicUpdateImg As System.Drawing.Image
    Public PicAboutImg As System.Drawing.Image
    Public LibUpdate As New Updater

    Public Sub MainLib()
        'Check if Application path is Root Drive e has or not
        If Application.StartupPath.EndsWith("\") Then
            sPath = Application.StartupPath
        Else
            sPath = Application.StartupPath & "\"
        End If
        'Load to PicUpdateImg (Image Object) the resource image file
        PicUpdateImg = My.Resources.ASSUpdater
        'Load to PicAboutImg (Image Object) the resource image file
        PicAboutImg = My.Resources.ASSUpdaterAbout
        'Load the necessary info to run this application
        With My.Application.Info
            sTitle = .ProductName.ToString & " v" & .Version.Major & "." & .Version.Minor
            sVerActual = .Version.Major.ToString
            sVerActualSimp = String.Format("{0}.{1}", _
                             .Version.Major.ToString, .Version.Minor.ToString)
            sVersion = String.Format("Versão {0}", My.Application.Info.Version.ToString)
        End With
    End Sub
    ''' <summary>
    ''' Check if URL exists and return a boolean 
    ''' </summary>
    ''' <param name="sUrl">Enter the URL you want to check for. 
    ''' The URL must be complete, including the name of the file to download.</param>
    ''' <returns>A boolean response</returns>
    ''' <remarks></remarks>
    Public Function UrlExist(ByVal sUrl As String) As Boolean
        Dim fileUrl As Uri = New Uri(sUrl)
        Dim req As System.Net.WebRequest
        req = System.Net.WebRequest.Create(sUrl)
        Dim resp As System.Net.WebResponse
        Try
            resp = req.GetResponse()
            resp.Close()
            req = Nothing
            Return (True)
        Catch ex As Exception
            req = Nothing
            Return False
        End Try
    End Function
    ''' <summary>
    ''' Checks if computer is connected to network
    ''' </summary>
    ''' <returns>Boolean Response</returns>
    ''' <remarks></remarks>
    Public Function GotInternet() As Boolean
        Try
            Return My.Computer.Network.IsAvailable
        Catch weberrt As WebException
            Return False
        Catch except As Exception
            Return False
        End Try
    End Function
    ''' <summary>
    ''' Create MD5 Hash
    ''' </summary>
    ''' <param name="sString">Enter the variable you want to encrypt in MD5</param>
    ''' <param name="iSize">Enter the size you want to return encryption in MD5, 
    ''' maximum size is 32</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function CreateHashPure(ByVal sString As String, _
                    Optional iSize As Integer = 32) As String
        Using md5Hash As MD5 = MD5.Create()
            Dim hash As String = GetMd5Hash(md5Hash, sString)
            hash = Left(hash, iSize)
            Return LCase(hash)
        End Using
    End Function
    ''' <summary>
    ''' Function to Create MD5 Hash, with base the set information
    ''' </summary>
    ''' <param name="md5Hash">A MD5 Hash created</param>
    ''' <param name="input">Input string</param>
    ''' <returns>Return string response</returns>
    ''' <remarks></remarks>
    Public Function GetMd5Hash(ByVal md5Hash As MD5, ByVal input As String) As String

        ' Convert the input string to a byte array and compute the hash.
        Dim data As Byte() = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input))

        ' Create a new Stringbuilder to collect the bytes
        ' and create a string.
        Dim sBuilder As New StringBuilder()

        ' Loop through each byte of the hashed data 
        ' and format each one as a hexadecimal string.
        Dim i As Integer
        For i = 0 To data.Length - 1
            sBuilder.Append(data(i).ToString("x2"))
        Next i

        ' Return the hexadecimal string.
        Return sBuilder.ToString()

    End Function 'GetMd5Hash

End Module

Class

The library has a class named Updater.vb. In this module class, many functions are implemented. This is the heart of the Library, with Functions, Subs and Property. The most important function, which the other, maybe is CheckNewVersion(), which checks if there is a new version to download and returns a boolean response. With base in this response, it's possible to know if the application needs the update.

Other functions and property, as well as Subs, are important because they are part of the library, but they complement other Functions or even Subs. Below is the commented and complete code of the Class, so that the developer can better understand it.

Imports System.Windows.Forms
Imports System.Reflection
Imports System.Xml
Imports System.IO

Public Class Updater
    'Define the variables that received values to use by Application
    Private _versionapp As String
    Private _codeapp As String
    Private _nameapp As String
    Private _urlconfig As String
    Private sNewVersion As String, sDescUpdate As String, sDateUpdate As String
    'Create a Check Update Response for decision making
    Public Enum CheckResponse
        res_empty = 0
        res_noupdate = 1
        res_update = 2
        res_erro = 3
    End Enum

    Public Sub New()
        MainLib()
    End Sub
    ''' <summary>
    ''' After check if has a new version to download, the Library showing a message
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub AppUpdate()
        Dim frm As New frmUpdateDesc 'create a new instance of frmUpdateDesc
        'Show the information about 
        frm.wbDescription.DocumentText = My.Resources.HTMLStart & _
            "<h4>A new version is available for download.</h4>" &
            "<p>Version: " & sNewVersion & "<br/>" &
            "Date: " & sDateUpdate & "</p>" &
            "<div>Description: " & sDescUpdate & "</div>" &
            "<p>You want to get the new version now?<br/>" &
            "To start the download, click the Download button.!</p>" & My.Resources.HTMLEnd
        frm.ShowDialog()
    End Sub
    ''' <summary>
    ''' Displays information obtained in the CheckNewVersion function.
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub CheckUpdate()
        'check new update
        Dim CheckUpdataRes As CheckResponse = CheckNewVersion()
        If CheckUpdataRes = CheckResponse.res_update Then 'check new update
            AppUpdate() 'show update form
        ElseIf CheckUpdataRes = CheckResponse.res_noupdate Then
            MessageBox.Show("Your software has the latest version and is up to date!", _
            sTitle, MessageBoxButtons.OK, MessageBoxIcon.Information)
        ElseIf CheckUpdataRes = CheckResponse.res_empty Then 'check new update
            Exit Sub
        ElseIf CheckUpdataRes = CheckResponse.res_erro Then 'check new update
            MessageBox.Show("Could not check for update!", sTitle, _
                             MessageBoxButtons.OK, MessageBoxIcon.Error)
        Else
            MessageBox.Show("Error!", sTitle, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End If
    End Sub
    ''' <summary>
    ''' Check Online Version
    ''' </summary>
    ''' <returns>Return A Enum a CheckResponse Value</returns>
    ''' <remarks></remarks>
    Public Function CheckNewVersion() As CheckResponse
        Dim PathTemp As String
        PathTemp = System.IO.Path.GetTempPath()
        Try
            'Allows you to verify that all required Properties have been set 
            'so that the library can check for a new update version.
            'Check ULRConfig
            If String.IsNullOrWhiteSpace(URLConfig) Then
                MessageBox.Show("You must specify the configuration file path to check _
                for update!", sTitle, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Return CheckResponse.res_empty
            End If
            'Check VersionApp
            If String.IsNullOrWhiteSpace(VersionApp) Then
                MessageBox.Show("Application version must be specified to check _
                for update!", sTitle, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Return CheckResponse.res_empty
            End If
            'Check NameApp
            If String.IsNullOrWhiteSpace(NameApp) Then
                MessageBox.Show("You must specify the application name to check _
                for updates.!", sTitle, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Return CheckResponse.res_empty
            End If
            'Check if computer is connected a Network
            If GotInternet() = False Then
                MessageBox.Show("Unable to check software update. _
                                 No Internet connection verified!", sTitle, _
                                 MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                Return False
            End If
            'Allows you to check if the given URL is true or if the given file exists 
            'on the server
            If UrlExist(URLConfig) = True Then
                'Checks if Config file exists
                If File.Exists(PathTemp & My.Application.Info.AssemblyName & ".xml") _
                   Then File.Delete(PathTemp & My.Application.Info.AssemblyName & ".xml")
                'Starts configuration file download by saving to computer Temp folder
                My.Computer.Network.DownloadFile(URLConfig, PathTemp & _
                              My.Application.Info.AssemblyName & ".xml")
                'Start reading configuration information
                GoTo InitialDld
            Else

                Return CheckResponse.res_erro
            End If
InitialDld:
            Clipboard.SetText(PathTemp & My.Application.Info.AssemblyName & ".xml")
            'Checks if the configuration file was successfully obtained
            If System.IO.File.Exists(PathTemp & My.Application.Info.AssemblyName & ".xml") Then
                Dim dom As New XmlDocument()
                'Read information from the configuration file to pass to variables, 
                'allowing the library to tell if there is a need to update
                dom.Load(PathTemp & My.Application.Info.AssemblyName & ".xml")
                'Load Version Info
                Dim sVer As String = dom.SelectSingleNode("//Info/Version").InnerText
                'Load Date Info
                Dim sDate As String = dom.SelectSingleNode("//Info/Date").InnerText
                'Load File download (Install file) Info
                Dim sFileDld As String = dom.SelectSingleNode("//Info/Filename").InnerText
                'Load Description Info
                Dim sDescription As String = _
                        dom.SelectSingleNode("//Info//Description").InnerText
                'Compares the current version of the application 
                'to the obtained version through the configuration file. 
                'If the server version is larger then upgrade is enabled, 
                'if false reports no need for upgrade
                If sVerUpdate.FileVersion.ToString < sVer Then
                    sNewVersion = sVer
                    sDescUpdate = sDescription
                    sDateUpdate = sDate
                    LibUpdate.NameApp = NameApp
                    LibUpdate.VersionApp = VersionApp
                    LibUpdate.URLConfig = URLConfig
                    Return CheckResponse.res_update
                Else
                    Return CheckResponse.res_noupdate
                End If
            Else
                Return CheckResponse.res_erro
            End If
        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message & vbNewLine & vbNewLine & _
                            "StackTrace: " & ex.StackTrace, sTitle, MessageBoxButtons.OK, _
                             MessageBoxIcon.Stop)

            Return CheckResponse.res_erro
        Finally

        End Try
    End Function
    ''' <summary>
    ''' Get Library Assembly Version
    ''' </summary>
    ''' <returns>Return String Value</returns>
    ''' <remarks></remarks>
    Public Function LibVersion() As String
        Dim assy As System.Reflection.Assembly = GetType(Updater).Assembly
        Dim assyName As String = assy.GetName().Name
        'AssemblyTitle
        Dim attr As Attribute = Attribute.GetCustomAttribute( _
              assy, GetType(AssemblyTitleAttribute))
        Dim adAttr As AssemblyTitleAttribute = _
                    CType(attr, AssemblyTitleAttribute)
        Return String.Format("{0}", GetType(Updater).Assembly.GetName().Version)
    End Function
    ''' <summary>
    ''' Get Library Assembly Name (Title) and Version
    ''' </summary>
    ''' <returns>Return String Value</returns>
    ''' <remarks></remarks>
    Public Function LibNameVersion() As String
        Dim assy As System.Reflection.Assembly = GetType(Updater).Assembly
        Dim assyName As String = assy.GetName().Name
        'AssemblyTitle And AssemblyVersion
        Dim attr As Attribute = Attribute.GetCustomAttribute( _
              assy, GetType(AssemblyTitleAttribute))
        Dim adAttr As AssemblyTitleAttribute = _
                    CType(attr, AssemblyTitleAttribute)
        Return String.Format("{0} v{1}", adAttr.Title, _
               GetType(Updater).Assembly.GetName().Version)
    End Function
    ''' <summary>
    ''' Get Library Assembly Description
    ''' </summary>
    ''' <returns>Return String Value</returns>
    ''' <remarks></remarks>
    Public Function LibDescription() As String
        Dim assy As System.Reflection.Assembly = GetType(Updater).Assembly
        Dim assyName As String = assy.GetName().Name
        'AssemblyDescriptionAttribute
        Dim attr As Attribute = Attribute.GetCustomAttribute( _
              assy, GetType(AssemblyDescriptionAttribute))
        Dim adAttr As AssemblyDescriptionAttribute = _
                    CType(attr, AssemblyDescriptionAttribute)
        Return String.Format("{0}", adAttr.Description)
    End Function
    ''' <summary>
    ''' Get Library Assembly Name (Title)
    ''' </summary>
    ''' <returns>Return String Value</returns>
    ''' <remarks></remarks>
    Public Function LibName() As String
        Dim assy As System.Reflection.Assembly = GetType(Updater).Assembly
        Dim assyName As String = assy.GetName().Name
        'AssemblyTitleAttribute
        Dim attr As Attribute = Attribute.GetCustomAttribute( _
              assy, GetType(AssemblyTitleAttribute))
        Dim adAttr As AssemblyTitleAttribute = _
                    CType(attr, AssemblyTitleAttribute)
        Return String.Format("{0}", adAttr.Title)
    End Function
    ''' <summary>
    ''' Get Library Assembly Copyright
    ''' </summary>
    ''' <returns>Return String Value</returns>
    ''' <remarks></remarks>
    Public Function LibCopyright() As String
        Dim assy As System.Reflection.Assembly = GetType(Updater).Assembly
        Dim assyName As String = assy.GetName().Name
        'AssemblyCopyrightAttribute
        Dim attr As Attribute = Attribute.GetCustomAttribute( _
              assy, GetType(AssemblyCopyrightAttribute))
        Dim adAttr As AssemblyCopyrightAttribute = _
                    CType(attr, AssemblyCopyrightAttribute)
        Return String.Format("{0}", adAttr.Copyright)
    End Function
    ''' <summary>
    ''' Set and Get Application Version
    ''' </summary>
    ''' <returns>Return string Value</returns>
    Public Property VersionApp() As String
        Get
            Return _versionapp
        End Get
        Set(value As String)
            _versionapp = value
        End Set
    End Property
    ''' <summary>
    ''' Set and Get Application Name
    ''' </summary>
    ''' <returns>Return string Value</returns>
    Public Property NameApp() As String
        Get
            Return _nameapp
        End Get
        Set(value As String)
            _nameapp = value
        End Set
    End Property
    ''' <summary>
    ''' Set and Get URL of the XML File configuration and information
    ''' </summary>
    ''' <returns>Return string Value</returns>
    Public Property URLConfig() As String
        Get
            Return _urlconfig
        End Get
        Set(value As String)
            _urlconfig = value
        End Set
    End Property
End Class

Configuration XML File Structure

The structure of the XML file is important so that the library and its CheckNewVersion () function can read the information correctly and then pass the library variables, which will process the information and decide whether or not to update the software.

Below, we provide the structure of XML, which may have the name the developer wants, but it is recommended to be the same as AssemblyName, to facilitate the update management process if this library is used in multiple projects.

<?xml version="1.0" encoding="utf-8"?>
<!--Arquivo de Atualização do Software Appsetup v1.0-->
<!--Date in US Format or in Your Region Format-->
<Application>
<Info>
  <Version>1.1.1.0321</Version>
  <Date>27/09/2019</Date>
  <Filename>http://antsoft.com.br/appsetup.exe</Filename>
  <Description>
    System Update Tool Improvement.
  </Description>
  <copyright>Copyright © 2019, AntSoft Systems On Demand</copyright>
</Info>
</Application>

Forms

The three forms in the library project are in the code available for download and will not be discussed in the article, since it is simple to understand because the code is all commented. Just note that in the form, there is a sub named UpdateService(), which is the core of the form, because this Sub is that, after checking the need for update, the library will download the configuration file in XML and after the installation file, which should preferably be exe or msi extension.

The following are the images of the two library forms. The first image is the Update Description Form, the second image is the Update Form, where the installation file will be obtained and then run to install the new version. In the example, the update file is not found because it is a demo.

In the frmUpdater Form, the Sub UpdateService() has an important point to explain, as it allows a better understanding of the developer:

 Public Sub UpdateService()
        'Clear All items on Listview
        lvwUpdate.Items.Clear()
        'Add new item on ListView
        lvwUpdate.Items.Add("Starting the upgrade", 3)
        Try
            'Allows you to add two new Handles to allow you to generate file 
            'download progress and completion
            AddHandler wc.DownloadProgressChanged, AddressOf OnDownloadProgressChanged
            AddHandler wc.DownloadFileCompleted, AddressOf OnFileDownloadCompleted
            'Add new item on ListView
            AddTextlvw("Checking for new version online...")
            'Checks if Config file exists
            If File.Exists(PathTemp & My.Application.Info.AssemblyName & ".xml") _
               Then File.Delete(PathTemp & My.Application.Info.AssemblyName & ".xml")
            'Get Config File
            My.Computer.Network.DownloadFile(UpdaterApp.LibUpdate.URLConfig, _
                PathTemp & My.Application.Info.AssemblyName & ".xml")

            If File.Exists(PathTemp & My.Application.Info.AssemblyName & ".xml") Then
                'Add new item on ListView
                AddTextlvw("Valid update found ...", 2)
            Else
                'Add new item on ListView
                AddTextlvw("Update not verified or process failed!", 1)
                'Add new item on ListView
                AddTextlvw("Try again!", 1)
                Exit Sub
                pBar.Visible = False
            End If
            'Add new item on ListView
            AddTextlvw("Starting version checking ...")
            Dim dom As New XmlDocument()
            'Read information from the configuration file to pass to variables, 
            'allowing the library to tell if there is a need to update
            dom.Load(PathTemp & My.Application.Info.AssemblyName & ".xml")

            'Load Version Info
            sNewVersion = dom.SelectSingleNode("//Info/Version").InnerText
            'Load Date Info
            Dim sDate As String = dom.SelectSingleNode("//Info/Date").InnerText
            'Load File download (Install file) Info
            Dim sFileDld As String = dom.SelectSingleNode("//Info/Filename").InnerText
            'Get only filename of the URL Path
            Dim sFileTmp As String = System.IO.Path.GetFileName(sFileDld)
            sFileExec = System.IO.Path.GetFileName(sFileDld)
            'Add new item on ListView
            AddTextlvw("Current version: " & sVerUpdate.FileVersion, 5)
            'Add new item on ListView
            AddTextlvw("Downloadable Version: " & sNewVersion, 5)
            If sVerUpdate.FileVersion.ToString < sNewVersion Then
                'Add new item on ListView
                AddTextlvw("Starting the update file download.", 3)
                'Checks if Install File exists, if true Delete
                If System.IO.File.Exists(PathTemp & "\" & sFileTmp) Then _
                    Kill(PathTemp & "\" & sFileTmp)
                If UrlExist(sFileDld) = True Then
                    'Add new item on ListView
                    AddTextlvw("Downloading the installation file...")
                    'Start download of the Install file setup
                    wc.DownloadFileAsync(New Uri(sFileDld), PathTemp & "\" & sFileTmp)
                Else
                    'Add new item on ListView
                    AddTextlvw("Setup file not found!", 1)
                    pBar.Visible = False
                    Exit Sub
                End If
            Else
                'Add new item on ListView
                AddTextlvw("No need to update.", 4)
                pBar.Visible = False
                btnAbout.Enabled = True

            End If
        Catch ex As Exception
            'Add new item on ListView
            MessageBox.Show("Unable to update software. Error: " & vbNewLine & _
                            ex.Message, sTitle, _
                            MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            AddTextlvw("Error trying to verify update.", 1)
            pBar.Visible = False

        End Try
    End Sub

Call UpdateApp Library

To call the new version, check function and then start the download if there is a new version available. It is very simple and done in a few command lines. You must reference the UpdateApp Library in the project references.

In a form, you need to enter the following command lines:

Public Class Form1
    Dim LibUpdater As New UpdaterApp.Updater
    Private Sub Button1_Click(sender As Object, e As EventArgs) _
            Handles Button1.Click, LinkLabel1.Click
        With LibUpdater
            'Change this URL to the path where your configuration file is hosted in XML format.
            .URLConfig = "http://www.antsoft.com.br/CPTests/UpdateApp/" & _
              My.Application.Info.AssemblyName & ".xml"
            'Application Name
            .NameApp = My.Application.Info.ProductName
            'Application Version in String Format
            .VersionApp = My.Application.Info.Version.ToString
            'Call the CheckUpdate Function
            .CheckUpdate()
        End With
    End Sub
End Class

Points of Interest

With the above code, it is possible to check a simple, yet efficient way to check for new updates of your application and it can make it easy for all your customers to get news and make it easy to maintain your software, thus optimizing time and allowing more time to devote to developing new versions.

History

This code is the release version.