 |
|
 |
Oi Eduardo,
tudo bem? (portuguese for how are you )
thanks for the code.
i updated it a bit by adding a comparefiles function when infoParam = "?" so it becomes 'updated only if it doesn't exist or file changed
regards,
Jason
|
|
|
|
 |
|
 |
G'day All,
First off, thanks for the code as I have been using this Auto Update functionality for over 6 months now and it's worked perfectly!
Now to the issue! This code has worked for me when the "client" part of my system is installed on Server or XP operating system and needs to auto upgrade. However, it won't auto update when it is installed on a VISTA operating system - in all three OS scenarios the "server" part of my system is installed on a Server 2003 OS.
I am in the process of setting up a development environment on a VISTA Enterprise system so I can step through my code but just wondering if anyone may know why the VISTA scenario fails? The user on the VISTA OS is an Administrator so it should not be a permissions thing. Also I have tried with a local Administrator and Domain Administrator account on the VISTA OS.
Any advise would be nice!
Cheers Brendan
|
|
|
|
 |
|
 |
I'm not sure if anyone else has had problems using Application.Exit or Application.Restart but I could not get my application to work correctly until I used Environment.Exit(0)
Without using that method, my application would restart after the update but then get to a point and just close. I have yet to figure out why.
As an after thought, it may have something to do with my Shutdown mode and/or the fact that I have the application set to a single instance app.
Just thought I would spread this information.
Tim
|
|
|
|
 |
|
 |
Hey,
First of all when I download the Testprogram and DLL, when i try to open them in Visual Studios 2010 it tries to convert it and when it finishes there are errors while converting the program. Then the program does not run.
Second, I am still lost on how to apply this to my program. I need like a step by step procedure on what to do with this.
Someone PLEASE HELP
Thanks
|
|
|
|
 |
|
 |
Imports System.IO Imports System.Net Imports System.Diagnostics Imports System.Threading
Public Module AutoUpdate Private m_RemotePath As String Private m_UpdateFileName As String = "Update.txt" Private m_ErrorMessage As String = "There was a problem runing the Auto Update." ' <File Name>;<Version> [' comments ] ' <File Name>[;<Version>] [' comments ] ' <File Name>[;?] [' comments ] ' <File Name>[;delete] [' comments ] ' ... ' Blank lines and comments are ignored ' The first line should be the current program/version ' from the second line to the end the second parameter is optional ' if the second parameter is not specified the file is updated. ' if the version is specified the update checks the version ' if the second parameter is an interrogation mark (?) the update checks if the ' file alredy exists and "don't" upgrade if exists. ' if the second parameter is "delete" the system try to delete the file ' "'" (chr(39)) start a line comment (like vb)
' Function Return Value ' True means that the program needs to exit because: the autoupdate did the update ' or there was an error during the update ' False - nothing was done
Public Sub CheckForUpdate() Try Dim b As Boolean = UpdateFiles(RemotePath) If b Then Application.Exit() Else MsgBox("You have the latest version of " + My.Application.Info.ProductName, MsgBoxStyle.OkOnly + MsgBoxStyle.Information) End If Catch ex As Exception End Try End Sub
Public Function UpdateFiles(Optional ByVal RemotePath As String = "") As Boolean If RemotePath = "" Then RemotePath = m_RemotePath Else m_RemotePath = RemotePath
Dim Ret As Boolean = False Dim AssemblyName As String = System.Reflection.Assembly.GetEntryAssembly.GetName.Name Dim ToDeleteExtension As String = ".ToDelete" Dim RemoteUri As String = RemotePath & AssemblyName & "/" Dim MyWebClient As New WebClient Try ' try to delete old files if exist Dim s As String = Dir(My.Application.Info.DirectoryPath & "\*" & ToDeleteExtension) Do While s <> "" Try File.Delete(My.Application.Info.DirectoryPath & "\" & s) Catch ex As Exception End Try s = Dir() Loop ' get the update file content Dim Contents As String = MyWebClient.DownloadString(RemoteUri & UpdateFileName) ' Process the autoupdate ' get rid of the line feeds if exists Contents = Replace(Contents, Chr(Keys.LineFeed), "") Dim FileList() As String = Split(Contents, Chr(Keys.Return)) Contents = "" ' Remove all comments and blank lines For Each F As String In FileList If InStr(F, "'") <> 0 Then F = Strings.Left(F, InStr(F, "'") - 1) If F.Trim <> "" Then If Contents <> "" Then Contents += Chr(Keys.Return) Contents += F.Trim End If Next ' rebuild the file list FileList = Split(Contents, Chr(Keys.Return)) Dim Info() As String = Split(FileList(0), ";") ' if the name is correct and it is a new version If My.Application.Info.DirectoryPath.ToLower & "\" & Info(0).ToLower = My.Application.Info.DirectoryPath.ToLower + "\" + My.Application.Info.ProductName.ToLower + ".exe" AndAlso _ GetVersion(Info(1)) > GetVersion(My.Application.Info.Version.ToString) Then ' process files in the list For Each F As String In FileList Info = Split(F, ";") Dim isToDelete As Boolean = False Dim isToUpgrade As Boolean = False Dim TempFileName As String = My.Application.Info.DirectoryPath & "\" & Now.TimeOfDay.TotalMilliseconds Dim FileName As String = My.Application.Info.DirectoryPath & "\" & Info(0).Trim Dim FileExists As Boolean = File.Exists(FileName) If Info.Length = 1 Then ' Just the file as parameter always upgrade isToUpgrade = True isToDelete = FileExists ElseIf Info(1).Trim = "delete" Then ' second parameter is "delete" isToDelete = FileExists ElseIf Info(1).Trim = "?" Then ' second parameter is "?" (check if file exists and don't upgrade if exists) isToUpgrade = Not FileExists ElseIf FileExists Then ' verify the file version Dim fv As FileVersionInfo = FileVersionInfo.GetVersionInfo(FileName) isToUpgrade = (GetVersion(Info(1).Trim) > GetVersion(fv.FileMajorPart & "." & fv.FileMinorPart & "." & fv.FileBuildPart & "." & fv.FilePrivatePart)) isToDelete = isToUpgrade Else ' the second parameter exists as version number and the file doesn't exists isToUpgrade = True End If 'Debug.Print(TempFileName) ' download the new file 'If isToUpgrade Then MyWebClient.DownloadFile(RemoteUri & Info(0), TempFileName) ' If isToUpgrade Then Dim fDownload As New frmDownload(RemoteUri & Info(0), TempFileName) If fDownload.ShowDialog() = DialogResult.Abort Then ' rename the existent file to be deleted in the future If isToDelete Then File.Move(FileName, TempFileName & ToDeleteExtension) ' rename the downloaded file to the real name If isToUpgrade Then File.Move(TempFileName, FileName) ' try to delete the file End If End If
Next ' call the new version System.Diagnostics.Process.Start(Application.ExecutablePath, Microsoft.VisualBasic.Command()) Ret = True End If Catch ex As Exception Ret = True MsgBox(m_ErrorMessage & vbCr & ex.Message & vbCr & "Assembly: " & AssemblyName, MsgBoxStyle.Critical, Application.ProductName) End Try Return Ret End Function Private Sub FileDownloadComplete()
End Sub Public Property RemotePath() As String Get Return m_RemotePath End Get Set(ByVal value As String) m_RemotePath = value End Set End Property
Public Property UpdateFileName() As String Get Return m_UpdateFileName End Get Set(ByVal value As String) m_UpdateFileName = value End Set End Property
Public Property ErrorMessage() As String Get Return m_ErrorMessage End Get Set(ByVal value As String) m_ErrorMessage = value End Set End Property
Private Function GetVersion(ByVal Version As String) As String Dim x() As String = Split(Version, ".") Return String.Format("{0:00000}{1:00000}{2:00000}{3:00000}", Int(x(0)), Int(x(1)), Int(x(2)), Int(x(3))) End Function
Public Sub MakeFolderToUpload() Try Dim fn As String = My.Application.Info.DirectoryPath + "\" + My.Application.Info.AssemblyName + ".exe" Dim fnNew As String = "C:\" + My.Application.Info.ProductName + "\" + My.Application.Info.AssemblyName + ".exe"
If IO.Directory.Exists("C:\" + My.Application.Info.ProductName) Then Try IO.Directory.Delete("C:\" + My.Application.Info.ProductName, True) Catch ex As Exception If IO.File.Exists(fnNew) Then IO.File.Delete(fnNew) End Try End If Application.DoEvents() IO.Directory.CreateDirectory("C:\" + My.Application.Info.ProductName) IO.File.Copy(fn, fnNew, True) Dim rtb As New RichTextBox rtb.AppendText(My.Application.Info.AssemblyName + ".exe;" + My.Application.Info.Version.ToString) rtb.SaveFile("C:\" + My.Application.Info.ProductName + "\update.txt", RichTextBoxStreamType.PlainText) Catch ex As Exception End Try End Sub End Module
Public Class frmDownload Inherits System.Windows.Forms.Form
Private WithEvents tmrDownload As System.Windows.Forms.Timer Private WithEvents tmrNext As System.Windows.Forms.Timer
#Region " Windows Form Designer generated code "
'Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub
'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. Friend WithEvents ProgressBar1 As System.Windows.Forms.ProgressBar Friend WithEvents Label1 As System.Windows.Forms.Label Friend WithEvents st2Speed As System.Windows.Forms.Label Friend WithEvents st2Downloded As System.Windows.Forms.Label Friend WithEvents st2DownloadURL As System.Windows.Forms.Label Friend WithEvents st2LocalFile As System.Windows.Forms.Label Friend WithEvents lblCent As System.Windows.Forms.Label <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() Me.ProgressBar1 = New System.Windows.Forms.ProgressBar Me.Label1 = New System.Windows.Forms.Label Me.st2Speed = New System.Windows.Forms.Label Me.st2Downloded = New System.Windows.Forms.Label Me.st2DownloadURL = New System.Windows.Forms.Label Me.st2LocalFile = New System.Windows.Forms.Label Me.lblCent = New System.Windows.Forms.Label Me.SuspendLayout() ' 'ProgressBar1 ' Me.ProgressBar1.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _ Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.ProgressBar1.Location = New System.Drawing.Point(117, 73) Me.ProgressBar1.Name = "ProgressBar1" Me.ProgressBar1.Size = New System.Drawing.Size(315, 24) Me.ProgressBar1.TabIndex = 10 ' 'Label1 ' Me.Label1.Location = New System.Drawing.Point(24, 73) Me.Label1.Name = "Label1" Me.Label1.Size = New System.Drawing.Size(53, 24) Me.Label1.TabIndex = 8 Me.Label1.Text = "Progress:" Me.Label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft ' 'st2Speed ' Me.st2Speed.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.st2Speed.Location = New System.Drawing.Point(280, 105) Me.st2Speed.Name = "st2Speed" Me.st2Speed.Size = New System.Drawing.Size(152, 16) Me.st2Speed.TabIndex = 12 Me.st2Speed.Text = "Transfer Rate: KB/Sec" Me.st2Speed.TextAlign = System.Drawing.ContentAlignment.MiddleRight ' 'st2Downloded ' Me.st2Downloded.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _ Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.st2Downloded.Location = New System.Drawing.Point(24, 105) Me.st2Downloded.Name = "st2Downloded" Me.st2Downloded.Size = New System.Drawing.Size(240, 16) Me.st2Downloded.TabIndex = 11 Me.st2Downloded.Text = "Downloaded" Me.st2Downloded.TextAlign = System.Drawing.ContentAlignment.MiddleLeft ' 'st2DownloadURL ' Me.st2DownloadURL.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _ Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.st2DownloadURL.Location = New System.Drawing.Point(24, 9) Me.st2DownloadURL.Name = "st2DownloadURL" Me.st2DownloadURL.Size = New System.Drawing.Size(408, 32) Me.st2DownloadURL.TabIndex = 6 Me.st2DownloadURL.Text = "Download URL" ' 'st2LocalFile ' Me.st2LocalFile.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _ Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.st2LocalFile.Location = New System.Drawing.Point(24, 41) Me.st2LocalFile.Name = "st2LocalFile" Me.st2LocalFile.Size = New System.Drawing.Size(408, 32) Me.st2LocalFile.TabIndex = 7 Me.st2LocalFile.Text = "Local File Name" ' 'lblCent ' Me.lblCent.Font = New System.Drawing.Font("Microsoft Sans Serif", 10.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblCent.Location = New System.Drawing.Point(64, 73) Me.lblCent.Name = "lblCent" Me.lblCent.Size = New System.Drawing.Size(48, 24) Me.lblCent.TabIndex = 9 Me.lblCent.Text = "%" Me.lblCent.TextAlign = System.Drawing.ContentAlignment.MiddleRight ' 'frmDownload ' Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13) Me.ClientSize = New System.Drawing.Size(456, 130) Me.ControlBox = False Me.Controls.Add(Me.Label1) Me.Controls.Add(Me.ProgressBar1) Me.Controls.Add(Me.st2Speed) Me.Controls.Add(Me.st2Downloded) Me.Controls.Add(Me.st2DownloadURL) Me.Controls.Add(Me.st2LocalFile) Me.Controls.Add(Me.lblCent) Me.MaximizeBox = False Me.Name = "frmDownload" Me.ShowIcon = False Me.ShowInTaskbar = False Me.Text = "Download" Me.ResumeLayout(False)
End Sub
#End Region #Region " Declarations " Dim UrlOfFile As String Dim LocOfFile As String Dim MainForm As Form Dim bPaused As Boolean Public Sub New(ByVal f As Form, ByVal sURL2Download As String, ByVal sLocalFilename As String) MyBase.New()
'This call is required by the Windows Form Designer. InitializeComponent()
Me.Text = Application.ProductName + " Update" 'Add any initialization after the InitializeComponent() call Me.UrlOfFile = sURL2Download Me.LocOfFile = sLocalFilename 'Me.SizeOfFile = FileSize Me.MainForm = f 'Me.ProgressBar1 'Me._NumberOfDownload = NumberOfDownload.MoreDownload End Sub Public Sub New(ByVal sURL2Download As String, ByVal sLocalFilename As String) MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() Me.Text = Application.ProductName + " Update"
Me.UrlOfFile = sURL2Download Me.LocOfFile = sLocalFilename End Sub Private Sub WaitMinimize() Thread.Sleep(100) 'Me.ShowHide() End Sub #End Region #Region " Menus " Private Sub mnuShowHide_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 'Me.ShowHide() End Sub Private Sub mnuExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Me.Close() End Sub Private Sub NotifyIcon1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) 'Me.ShowHide() End Sub Private Sub ShowHide1() If Me.Visible = True Then Me.WindowState = FormWindowState.Minimized Me.Hide() Else Me.Show() Me.Focus() Me.WindowState = FormWindowState.Normal End If End Sub Dim DownloadedTemp As Double Dim Downloaded As Double Private Sub tmrDownload_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrDownload.Tick Application.DoEvents() DownloadedTemp = Downloaded / 1000 Downloaded = 0 'bitsec.Text = Format(DownloadedTemp, "#,###,###,###0.00") & " KB/sec" Me.st2Speed.Text = "Transfer Rate: " & Format(DownloadedTemp, "#,###,###,###0.00") & " KB/sec" End Sub #End Region Dim iDownloadCount As Integer = 0
Private Sub frmDownload_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim t As New Threading.Thread(AddressOf Me.WaitMinimize) t.Start()
If Me.UrlOfFile.Trim.Length < 7 Then Me.Close() End If Me.tmrNext.Start() End Sub Private Sub tmrNext_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrNext.Tick Try If My.Computer.Network.IsAvailable Then Me.tmrNext.Stop() If Me.iDownloadCount >= 3 Then
Me.Close() Exit Try End If Me.iDownloadCount += 1 Dim StartTime As DateTime = Now Dim fn As String = Me.DownloadFile(Me.UrlOfFile, Me.LocOfFile) If IO.File.Exists(fn) Then Me.DialogResult = Windows.Forms.DialogResult.Abort Me.Close() Else Me.Timer(10) Me.tmrNext.Start() End If End If Catch ex As Exception Me.Timer(10) Me.tmrNext.Start() End Try End Sub Private Function Timer(ByVal i As Integer) As Integer Return i * 1000 End Function Private Function DownloadFile(ByVal sURL As String, ByVal sDownloadLocation As String) As String If Not IO.Directory.Exists(My.Computer.FileSystem.SpecialDirectories.Temp) Then IO.Directory.CreateDirectory(My.Computer.FileSystem.SpecialDirectories.Temp) End If Dim sLocalTempFile As String = Me.LocOfFile
Try Me.st2DownloadURL.Text = "Downloading from: " & sURL Me.st2LocalFile.Text = "Saving to: " & sLocalTempFile
Dim URLReq As Net.HttpWebRequest Dim URLRes As Net.HttpWebResponse
Dim bBuffer(999) As Byte Dim iBytesRead As Integer
Application.DoEvents()
URLReq = System.Net.WebRequest.Create(sURL) URLRes = URLReq.GetResponse Dim sChunks As IO.Stream = URLReq.GetResponse.GetResponseStream
Me.ProgressBar1.Value = 0 Me.ProgressBar1.Maximum = URLRes.ContentLength
Dim FileStreamer As New IO.FileStream(sLocalTempFile, IO.FileMode.Create)
tmrDownload.Start()
Do If My.Computer.Network.IsAvailable Then Try If Me.bPaused = True Then Do Application.DoEvents() If Me.bPaused = False Then Exit Do End If Loop End If iBytesRead = sChunks.Read(bBuffer, 0, 1000)
Downloaded += iBytesRead Me.st2Downloded.Text = "Downloaded " & Format(Me.ProgressBar1.Value / 1024, "#,###,###,###0.00") & " KB of " & Format(Me.ProgressBar1.Maximum / 1024, "#,###,###,###0.00") & " KB" Application.DoEvents() If Me.ProgressBar1.Value + iBytesRead <= Me.ProgressBar1.Maximum Then Me.ProgressBar1.Value += iBytesRead Else Me.ProgressBar1.Value = Me.ProgressBar1.Maximum End If Try Me.lblCent.Text = ((Me.ProgressBar1.Value / Me.ProgressBar1.Maximum) * 100).ToString("##") & "%" Catch ex As Exception End Try
FileStreamer.Write(bBuffer, 0, iBytesRead) Catch ex As Exception Exit Do End Try Else Exit Do End If Loop Until iBytesRead = 0
Downloaded = 0 Me.tmrDownload.Stop()
sChunks.Close() FileStreamer.Close()
Return sLocalTempFile Catch ex1 As Net.WebException Catch ex As Exception End Try Me.tmrDownload.Stop() Return "" End Function End Class
|
|
|
|
 |
|
 |
The code in AutoUpdate is working up to the line
System.Diagnostics.Process.Start(Application.ExecutablePath, Microsoft.VisualBasic.Command())
then I'm getting this error message guys,
"The process cannot access the file because it is being used by another process"
How can i solve this, ideas ???
|
|
|
|
 |
|
 |
Got it, never mind Maybe to help others who might face same prob
Now, The zip file with the source code, has 2 projects, one for the AutoUpdate dll project, and another for the AutoUpdateTest project.
Now the AutoUpdate dll is simply referenced in the AutoUpdateTest project which means in essence we have one project, which is the AutoUpdateTest project which is the one we are trying to update. Now if you run that project, you will get an error
“The process cannot access the file because it is being used by another process “
Whats happening here is we were trying to update the same process that is currently running, this obviously doesn’t make sense or is not possible coz windows locks a running process !!!!!, My solution was simple, since we can’t modify a running process why not let this process do the job of downloading a replacing another projects .exe file, i.e. just create a separate project which will be the one we want to update, create say a third project there called ProjectToAutoUpdate project, compile it and copy the ProjectToAutoUpdate.exe to AutoUpdateTest Bin folder, set AutoUpdateTest as Main project so it runs first and checks updates etc, then downloads updates then delete the actual .exe we want updated(ProjectToAutoUpdate.exe), and then start this new ProjectToAutoUpdate.exe from AutoUpdateTest .
Man !!!
Well corret me if i'm wrong somewhere, but my solution works
|
|
|
|
 |
|
 |
what version of windows are you using?
|
|
|
|
 |
|
 |
Hi all How do i do this line in C# if I am using the DLL! If AutoUpdate.UpdateFiles() Then Exit Sub
|
|
|
|
 |
|
|
 |
|
 |
Hi is there a c# version available?
Qaisar
|
|
|
|
 |
|
|
 |
|
|
 |
|
 |
I'm receiving the following error when adding the autoupdate.dll file to my project:
"Could not load file or assembly 'AutoUpdate, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies.
Not sure what gives.
|
|
|
|
 |
|
 |
NOw when I add the code as a module for AutoUpdate.vb it gives me this error:
Starting a second message loop on a single thread is not a valid operation. Use Form.ShowDialog instead
Any ideas?
|
|
|
|
 |
|
 |
hi friends,
how can i save and retrieve word file into sql database using vb.net 2005.
thanx Naresh Rajput
|
|
|
|
 |
|
 |
hi friends,
how can i save and retrieve word file into sql database.
thanx Naresh Rajput
|
|
|
|
 |
|
 |
Hi there,
First of all, compliments for the usefull article. I was developing something similiar to this for a huge project long time before. The software I'm working on now is a software that contains a lot of logic builded inside class libraries (DLL files). Compiling the new version of the software will generate new references to the libraries by using keys on the .exe file side.
If the developer team distributes a new release of a single class library (dll file), we do not need to update the whole software package. We would like to update only the single class library file (dll file). By reading a central update file on a webserver we would like to download/update only the files needed to be updated and not the whole software package.
The problem I'm facing now are the references/codes compiled in the binary executable .exe file of the software. The new updated class library will not always be accepted, because the .exe file has in my opinion a reference key to each .dll file inculded in the project.
Is there a way to solve this problem? How can I update only the files that need to be updated (dll files) without having the issue with the reference keys. The class libraries should stay protected as they are. Am I missing something here? Any suggestions?
Regards,
Sead
|
|
|
|
 |
|
 |
this blog suggests it won't work for those of us using MSI installers, as the installer will simply revert the application files back automatically. true?
|
|
|
|
 |
|
 |
Is it not a little dangerous to remove the ability of updating the AutoUpdate program itself?
What happens when a patch/fix is required for the AutoUpdate program, how do you see this scenario being performed ?
|
|
|
|
 |
|
 |
1. Create a project - click File -> New -> Project -> Class Library 1.1. Name it whatever you want (as long as its name is AutoUpdate ) 1.2. Rename Class1.cs to AutoUpdate.cs (accepting to rename all references) 1.2. Double click AutoUpdate.cs and paste (replace whatever is in there) the following listing
Project: AutoUpdate
File: AutoUpdate.cs
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Diagnostics; using System.Windows.Forms;
public class AutoUpdate {
private const string ToDeleteExtension = ".ToDelete"; private const string UpdateFileName = "Update.txt"; private const string ErrorMessageCheck = "There was a problem checking the update config file."; private const string ErrorMessageUpdate = "There was a problem runing the Auto Update."; private const string ErrorMessageDelete = "There was a problem deleting files.";
#region "CleanUp"
public static bool CleanUp() { try
{ string file;
DirectoryInfo dir = new DirectoryInfo(Application.StartupPath); FileInfo[] infos = dir.GetFiles("*" + ToDeleteExtension, SearchOption.AllDirectories); foreach (FileInfo info in infos) { file = info.FullName; File.SetAttributes(file, FileAttributes.Normal); File.Delete(file); } return true; } catch (Exception ex) { MessageBox.Show(ErrorMessageDelete + "\r" + ex.Message); return false; } }
#endregion
#region "UpdateFiles"
public static bool UpdateFiles(string remotePath, bool DoUpdate) { if (remotePath == string.Empty) return false;
if (DoUpdate) { CleanUp(); }
System.Collections.Generic.List<AutoUpdateRollback> rollBackList = new System.Collections.Generic.List<AutoUpdateRollback>();
string remoteUri = remotePath; WebClient myWebClient = new WebClient();
bool retValue = false; try
{ string contents = myWebClient.DownloadString(remoteUri + UpdateFileName); contents = contents.Replace("\n", ""); string[] fileList = contents.Split(Convert.ToChar("\r"));
contents = string.Empty; foreach (string file in fileList) { string fileAux; if ((file.IndexOf("\'") + 1 != 0)) fileAux = file.Substring(0, ((file.IndexOf("\'") + 1) - 1)); else
fileAux = file; if (fileAux.Trim() != string.Empty) { if (!string.IsNullOrEmpty(contents)) contents = contents + (char) (Keys.Return); contents = contents + fileAux.Trim(); } }
fileList = contents.Split((char) (Keys.Return)); string[] info; string infoFilePath; String infoParam; List<string> fileNameList = new List<string>(); Version Version1, Version2; FileVersionInfo fv; bool IsToDelete; bool IsToUpgrade; foreach (string file in fileList) { info = file.Split(Convert.ToChar(";")); infoFilePath = info[0].Trim(); infoParam = info[1].Trim(); while (infoFilePath[0] == '.' || infoFilePath[0] == '\\') { infoFilePath = infoFilePath.Substring(1, infoFilePath.Length-1); }
if (fileNameList.Contains(infoFilePath.ToLowerInvariant())) { continue; }
fileNameList.Add(infoFilePath.ToLowerInvariant()); IsToDelete = false; IsToUpgrade = false; string fileName = Application.StartupPath + @"\" + infoFilePath; string tempFileName = Application.StartupPath + @"\" + infoFilePath + DateTime.Now.TimeOfDay.TotalMilliseconds; bool FileExists = File.Exists(fileName); if ((infoParam == "delete")) { IsToDelete = FileExists; if (DoUpdate) if (IsToDelete) rollBackList.Add(new AutoUpdateRollback(fileName, tempFileName + ToDeleteExtension, "Delete")); } else if ((infoParam == "?")) { IsToUpgrade = !FileExists; } else if (infoParam != string.Empty && (infoParam[0] == '=' && FileExists)) { fv = FileVersionInfo.GetVersionInfo(fileName); Version1 = new Version(infoParam.Substring(1, infoParam.Length - 1)); Version2 = new Version(fv.FileVersion); IsToUpgrade = Version1 != Version2; IsToDelete = IsToUpgrade; if (DoUpdate) if (IsToUpgrade) rollBackList.Add( new AutoUpdateRollback(fileName, tempFileName + ToDeleteExtension, "Upgrade")); } else if (FileExists) { fv = FileVersionInfo.GetVersionInfo(fileName); if (infoParam != string.Empty) { Version1 = new Version(infoParam); Version2 = new Version(fv.FileVersion); IsToUpgrade = Version1 > Version2; IsToDelete = IsToUpgrade; if (DoUpdate) if (IsToUpgrade) rollBackList.Add( new AutoUpdateRollback(fileName, tempFileName + ToDeleteExtension, "Upgrade")); } } else
{ IsToUpgrade = true; }
if (DoUpdate) { if (IsToUpgrade) myWebClient.DownloadFile(remoteUri + infoFilePath, tempFileName); if (IsToDelete) File.Move(fileName, tempFileName + ToDeleteExtension); if (IsToUpgrade) File.Move(tempFileName, fileName); }
if (IsToUpgrade || IsToDelete) retValue = true; }
} catch (Exception ex) { MessageBox.Show("There was an error. Trying to roll back"); if (DoUpdate) { foreach (AutoUpdateRollback rollBack in rollBackList) { if (rollBack.Operation == "Delete" || rollBack.Operation == "Upgrade") { if (File.Exists(rollBack.Renamed)) File.Move(rollBack.Renamed, rollBack.Original); } } MessageBox.Show(ErrorMessageUpdate + "\r" + ex.Message + "\r" + "Remote URI: " + remoteUri); } else
MessageBox.Show(ErrorMessageCheck + "\r" + ex.Message + "\r" + "Remote URI: " + remoteUri);
retValue = false; } finally
{ myWebClient.Dispose(); rollBackList.Clear(); }
return retValue; }
#endregion
}
public class AutoUpdateRollback { #region Properties
private string _renamed, _original, _operation;
public string Operation { get { return _operation; } set { _operation = value; } }
public string Original { get { return _original; } set { _original = value; } }
public string Renamed { get { return _renamed; } set { _renamed = value; } }
#endregion
#region Constructor
public AutoUpdateRollback(string Original, string Renamed, string Operation) { _original = Original; _renamed = Renamed; _operation = Operation; }
#endregion
}
2. Add a new project of type Windows Application named "Updated" 2.1. Rename Form1.cs to ShowVersionForm.cs 2.2. Click View Code and paste (replace whatever is in there) the following listing;
Project: Updated
File: ShowVersionForm.cs
using System; using System.Diagnostics; using System.Reflection; using System.Windows.Forms;
namespace Updated { public partial class ShowVersionForm : Form { public ShowVersionForm() { InitializeComponent(); label2.Text = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion; }
private void button1_Click(object sender, EventArgs e) { Close(); } } }
3. Add a new project of type Windows Application named "AutoUpdateTest" 3.1. Add a reference to the AutoUpdate and to Updated projects 3.2. Rename Form1.cs to Startup.cs 3.3. Click View Code and paste (replace whatever is in there) the following listing
Project: AutoUpdateTest
File: Startup.cs
using System; using System.Diagnostics; using System.Windows.Forms;
namespace AutoUpdateTest { public partial class Startup : Form { public Startup() { InitializeComponent(); }
private void Startup_Load(object sender, EventArgs e) { Show();
string RemotePath = "http://localhost/AutoUpdateTest/"; label1.Text = RemotePath; Form helper = new Updated.ShowVersionForm(); helper.Show(); MessageBox.Show("Checking if update is needed..."); if (AutoUpdate.UpdateFiles(RemotePath, false)) { MessageBox.Show("Update is needed."); if (AutoUpdate.UpdateFiles(RemotePath, true)) { MessageBox.Show("Auto Update succedeed!"); Dispose(); Process.Start(Application.ExecutablePath); Application.Exit(); } } else
{ MessageBox.Show("No update is available."); AutoUpdate.CleanUp(); } }
private void button1_Click(object sender, EventArgs e) { Close(); } } }
4. On IIS create a virtual directory named "AutoUpdateTest" 4.1. Put your sample files in there. 4.2. Put there an Update.txt like this one
\Updated2.exe ; 'Get Updated2.exe if it doesn't exist (ignore "\") .\Updated3.exe ; ? 'Get Updated3.exe if it doesn't exist (ignore ".\") .\Updated3.exe ; delete 'This line is ignored as it's the second instance of the same file path ..\Updated4.exe ; =1.0.0.3 'If actual Updated4.exe isn't this version, get it (ignore "..\") Updated5.exe ; delete 'Delete Updated5.exe Updated.exe ; 1.0.0.3 'If actual Updated.exe version is smaller than 1.0.0.3, get it 'Update2.exe ; delete 'ignore this line 'the lines below just test the same features on sub-directories TST\TSTUpdated.dll ; 1.0.0.1 TST\SubSub\SUBUpdated.dll ; 1.0.0.1 \TST\SubSub\Slash.dll ; 1.0.0.1 .\TST\SubSub\DotSlash.dll ; 1.0.0.1 .\TST\SubSub\Trash.dll ; delete
5. Build all projects in the solution and execute AutoUpdateTest.exe
NB 1 - If you have questions, just reply to this message. I'll receive a notification and will answer. NB 2 - Part 2 was added as an answer to a message from "Member 6038196"
modified on Thursday, November 12, 2009 4:10 PM
|
|
|
|
 |
|
|
 |
|
 |
yes,it can update while single folder,but how can i update with sub folder? any advise?
God helps those who help themselves
|
|
|
|
 |
|
 |
yeah,i got how to update subfolder, i had made a mistaken when i updated! thank you!
God helps those who help themselves
|
|
|
|
 |
|
 |
what is the content of the form/GUI?
I need your help regarding this:
I need an automatic updater for created applications (Tool_A, Tool_B) in the client's PC. I will create a tool that will reside in the memory of the client's PC and server's PC. Whenever I created an update and put in the server, the tool in the server PC will contact the tool in the client's PC and display an option if the user wants to upgrade to a new version of Tool_A/Tool_B.
I hope ypu can give me some advise.
|
|
|
|
 |
|