Skip to content
This repository was archived by the owner on Dec 22, 2019. It is now read-only.

Commit d08161c

Browse files
committed
Bugfixing/optimizations/refactoring
1 parent 616dab6 commit d08161c

14 files changed

Lines changed: 156 additions & 80 deletions

File tree

UpdateLib/TestApp/Form1.cs

Lines changed: 28 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -28,39 +28,40 @@ private void Instance_CheckForUpdatesCompleted(object sender, CheckForUpdatesCom
2828
{
2929
this.InvokeOnUI(() => checkForUpdatesToolStripMenuItem.Enabled = true);
3030

31-
if (e.Cancelled || e.Error != null)
32-
{
33-
this.InvokeOnUI(() => MessageDialog.Show(
34-
this,
35-
"Updater",
36-
e.Cancelled ? "Cancelled" : "Error",
37-
e.Cancelled ? "Update got cancelled" : "Please check the logs for more information.",
38-
e.Cancelled ? SystemIcons.Warning : SystemIcons.Error,
39-
MessageBoxButtons.OK));
40-
41-
return;
42-
}
43-
44-
if (!e.UpdateAvailable)
45-
{
46-
this.InvokeOnUI(() =>
47-
MessageDialog.Show(
48-
this,
49-
"Updater",
50-
"No update available!",
51-
$"You already have the latest version ({e.LatestVersion}).",
52-
SystemIcons.Information,
53-
MessageBoxButtons.OK));
54-
55-
return;
56-
}
31+
//if (e.Cancelled || e.Error != null)
32+
//{
33+
// this.InvokeOnUI(() => MessageDialog.Show(
34+
// this,
35+
// "Updater",
36+
// e.Cancelled ? "Cancelled" : "Error",
37+
// e.Cancelled ? "Update got cancelled" : "Please check the logs for more information.",
38+
// e.Cancelled ? SystemIcons.Warning : SystemIcons.Error,
39+
// MessageBoxButtons.OK));
40+
41+
// return;
42+
//}
43+
44+
//if (!e.UpdateAvailable)
45+
//{
46+
// this.InvokeOnUI(() =>
47+
// MessageDialog.Show(
48+
// this,
49+
// "Updater",
50+
// "No update available!",
51+
// $"You already have the latest version ({e.LatestVersion}).",
52+
// SystemIcons.Information,
53+
// MessageBoxButtons.OK));
54+
55+
// return;
56+
//}
5757
}
5858

5959
private void checkForUpdatesToolStripMenuItem_Click(object sender, EventArgs e)
6060
{
6161
checkForUpdatesToolStripMenuItem.Enabled = false;
6262

63-
Updater.Instance.CheckForUpdatesAsync();
63+
AsyncTask task = Updater.Instance.CheckForUpdatesAsync();
64+
task.Cancel();
6465
}
6566

6667
private void Form1_Load(object sender, EventArgs e)

UpdateLib/TestApp/Program.cs

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -16,23 +16,33 @@ static class Program
1616
[STAThread]
1717
static void Main()
1818
{
19-
// we still want our updater to have visual styles in case of update cmd argument switch
20-
Application.EnableVisualStyles();
21-
Application.SetCompatibleTextRenderingDefault(false);
19+
try
20+
{
2221

23-
Updater.Instance
24-
//.ConfigureUpdateUrl("https://raw.githubusercontent.com/MatthiWare/UpdateLib.TestApp.UpdateExample/master/Dev/updatefile.xml")
25-
.ConfigureUpdateUrl("http://matthiware.dev/UpdateLib/Dev/updatefile.xml")
26-
.ConfigureLogger((logger) => logger.LogLevel = LoggingLevel.Debug)
27-
.ConfigureLogger((logger) => logger.Writers.Add(new ConsoleLogWriter()))
28-
.ConfigureLogger((logger) => logger.Writers.Add(new FileLogWriter()))
29-
.ConfigureUnsafeConnections(true)
30-
.ConfigureCacheInvalidation(TimeSpan.FromSeconds(30))
31-
.ConfigureUpdateNeedsAdmin(false)
32-
.ConfigureInstallationMode(InstallationMode.Shared)
33-
.Initialize();
22+
// we still want our updater to have visual styles in case of update cmd argument switch
23+
Application.EnableVisualStyles();
24+
Application.SetCompatibleTextRenderingDefault(false);
3425

35-
Application.Run(new Form1());
26+
Updater.Instance
27+
//.ConfigureUpdateUrl("https://raw.githubusercontent.com/MatthiWare/UpdateLib.TestApp.UpdateExample/master/Dev/updatefile.xml")
28+
.ConfigureUpdateUrl("http://matthiware.dev/UpdateLib/Dev/updatefile.xml")
29+
.ConfigureLogger((logger) => logger.LogLevel = LoggingLevel.Debug)
30+
.ConfigureLogger((logger) => logger.Writers.Add(new ConsoleLogWriter()))
31+
.ConfigureLogger((logger) => logger.Writers.Add(new FileLogWriter()))
32+
.ConfigureUnsafeConnections(true)
33+
.ConfigureCacheInvalidation(TimeSpan.FromSeconds(30))
34+
.ConfigureUpdateNeedsAdmin(false)
35+
.ConfigureInstallationMode(InstallationMode.Shared)
36+
.Initialize();
37+
38+
Application.Run(new Form1());
39+
}
40+
catch (Exception e)
41+
{
42+
Console.WriteLine(e.ToString());
43+
MessageBox.Show(e.ToString());
44+
}
45+
3646
}
3747
}
3848
}

UpdateLib/UpdateLib.Tests/Files/HashCacheEntryTest.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ public void TestHashing()
4242

4343
EditTempFile();
4444

45-
entry.Recalculate(File.GetLastWriteTime(temp_file).Ticks);
45+
entry.Recalculate();
4646

4747
Assert.AreNotEqual(ticks, entry.Ticks);
4848
Assert.AreNotEqual(hash, entry.Hash);

UpdateLib/UpdateLib/Files/HashCacheEntry.cs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ public class HashCacheEntry
1616
public string FilePath { get; set; }
1717

1818
[XmlAttribute("Time")]
19-
public long Ticks { get; set; }
19+
public long Ticks { get; set; } = -1;
2020

2121
public HashCacheEntry() { }
2222

@@ -35,11 +35,13 @@ public HashCacheEntry(string file)
3535
Ticks = File.GetLastWriteTime(FilePath).Ticks;
3636
}
3737

38-
public void Recalculate(long tick)
38+
public void Recalculate()
3939
{
4040
try
4141
{
42-
if (tick != Ticks)
42+
long tick = File.GetLastWriteTime(FilePath).Ticks;
43+
44+
if (Ticks == -1 || tick != Ticks)
4345
{
4446
Hash = HashUtil.GetHash(FilePath);
4547
Ticks = tick;

UpdateLib/UpdateLib/Files/HashCacheFile.cs

Lines changed: 35 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1-
using MatthiWare.UpdateLib.Utils;
1+
using MatthiWare.UpdateLib.Security;
2+
using MatthiWare.UpdateLib.Utils;
23
using System;
34
using System.Collections.Generic;
45
using System.IO;
56
using System.Reflection;
67
using System.Xml.Serialization;
8+
using System.Linq;
79

810
namespace MatthiWare.UpdateLib.Files
911
{
@@ -17,29 +19,53 @@ public class HashCacheFile
1719
[XmlArrayItem("Entry")]
1820
public List<HashCacheEntry> Items { get; set; }
1921

20-
private static Lazy<string> storagePath = new Lazy<string>(GetStoragePath);
22+
private readonly object sync = new object();
2123

2224
public HashCacheFile()
2325
{
2426
Items = new List<HashCacheEntry>();
2527
}
2628

29+
public void AddOrUpdateEntry(string fullPath, string hash = "")
30+
{
31+
lock (sync)
32+
{
33+
long ticks = File.GetLastWriteTime(fullPath).Ticks;
34+
hash = string.IsNullOrEmpty(hash) ? HashUtil.GetHash(fullPath) : hash;
35+
36+
HashCacheEntry entry = Items.FirstOrDefault(f => f.FilePath == fullPath);
37+
38+
if (entry == null)
39+
{
40+
entry = new HashCacheEntry();
41+
entry.FilePath = fullPath;
42+
entry.Hash = hash;
43+
entry.Ticks = ticks;
44+
45+
Items.Add(entry);
46+
}
47+
else
48+
{
49+
entry.Ticks = ticks;
50+
entry.Hash = hash;
51+
}
52+
}
53+
}
54+
2755
#region Save/Load
2856
private static string GetStoragePath()
2957
{
30-
string path = IOUtils.GetAppDataPath();
31-
string productName = Updater.ProductName;
32-
string name = Assembly.GetEntryAssembly().GetName().Name;
58+
string path = IOUtils.AppDataPath;
3359

34-
return $@"{path}\{name}\{productName}\{CACHE_FOLDER_NAME}\{FILE_NAME}";
60+
return $@"{path}\{CACHE_FOLDER_NAME}\{FILE_NAME}";
3561
}
3662

3763
public static HashCacheFile Load()
3864
{
39-
if (!File.Exists(storagePath.Value))
65+
if (!File.Exists(GetStoragePath()))
4066
return null;
4167

42-
using (Stream stream = File.Open(storagePath.Value, FileMode.Open, FileAccess.Read))
68+
using (Stream stream = File.Open(GetStoragePath(), FileMode.Open, FileAccess.Read))
4369
{
4470
XmlSerializer serializer = new XmlSerializer(typeof(HashCacheFile));
4571
return (HashCacheFile)serializer.Deserialize(stream);
@@ -48,7 +74,7 @@ public static HashCacheFile Load()
4874

4975
public void Save()
5076
{
51-
FileInfo fi = new FileInfo(storagePath.Value);
77+
FileInfo fi = new FileInfo(GetStoragePath());
5278

5379
if (!fi.Directory.Exists)
5480
fi.Directory.Create();

UpdateLib/UpdateLib/Logging/Writers/FileLogWriter.cs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,10 @@ public class FileLogWriter : ILogWriter
2020

2121
private static FileInfo GetLogFile()
2222
{
23-
string path = IOUtils.GetAppDataPath();
24-
string productName = Updater.ProductName;
23+
string path = IOUtils.AppDataPath;
2524
string name = Assembly.GetEntryAssembly().GetName().Name;
2625

27-
FileInfo m_logFile = new FileInfo($@"{path}\{name}\{productName}\{LOG_FOLDER_NAME}\log_{DateTime.Now.ToString("yyyyMMdd")}.log");
26+
FileInfo m_logFile = new FileInfo($@"{path}\{LOG_FOLDER_NAME}\log_{DateTime.Now.ToString("yyyyMMdd")}.log");
2827

2928
if (!m_logFile.Directory.Exists)
3029
m_logFile.Directory.Create();

UpdateLib/UpdateLib/Tasks/CheckForUpdatesTask.cs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
using static MatthiWare.UpdateLib.Tasks.CheckForUpdatesTask;
88
using MatthiWare.UpdateLib.Logging;
99
using System.IO;
10+
using MatthiWare.UpdateLib.Utils;
1011

1112
namespace MatthiWare.UpdateLib.Tasks
1213
{
@@ -34,11 +35,14 @@ protected override void DoWork()
3435
Updater updater = Updater.Instance;
3536

3637
// Getting the file name from the url
37-
string localFile = GetLocalFileName();
38+
string localFile = $@"{IOUtils.AppDataPath}\Update.xml";
39+
40+
if (IsCancelled)
41+
return;
3842

3943
if (IsUpdateFileInvalid(localFile))
4044
wcDownloader.DownloadFile(Url, localFile);
41-
45+
4246
// load the updatefile from disk
4347
Result.UpdateFile = UpdateFile.Load(localFile);
4448
Result.Version = Result.UpdateFile.VersionString;
@@ -49,6 +53,9 @@ protected override void DoWork()
4953
// Wait for the clean up to complete
5054
updater.CleanUpTask.AwaitTask();
5155

56+
if (IsCancelled)
57+
return;
58+
5259
/*
5360
* Start a task to get all the files that need to be updated
5461
* Returns if there is anything to update
@@ -76,13 +83,6 @@ private CheckForUpdatedFilesTask CheckForUpdatedFiles(UpdateFile file, HashCache
7683
return task;
7784
}
7885

79-
private string GetLocalFileName()
80-
{
81-
const char slash = '/';
82-
string[] tokens = Url.Split(slash);
83-
return string.Concat(".", slash, tokens[tokens.Length - 1]);
84-
}
85-
8686
public class Data
8787
{
8888
public string Version { get; set; } = string.Empty;

UpdateLib/UpdateLib/Tasks/DownloadManager.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,11 @@ private void Task_TaskCompleted(object sender, System.ComponentModel.AsyncComple
6262
}
6363

6464
if (amountToDownload.Decrement() == 0)
65+
{
66+
Updater.Instance.GetCache().Save();
6567
Updater.Instance.RestartApp();
68+
}
69+
6670
}
6771

6872
private void CancelOtherTasks()
@@ -71,6 +75,5 @@ private void CancelOtherTasks()
7175
task.Cancel();
7276
}
7377

74-
7578
}
7679
}

UpdateLib/UpdateLib/Tasks/DownloadTask.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ public DownloadTask(FileEntry entry)
3434

3535
protected override void DoWork()
3636
{
37+
if (IsCancelled)
38+
return;
39+
3740
wait = new ManualResetEvent(false);
3841

3942
string localFile = Updater.Instance.Converter.Replace(Entry.DestinationLocation);
@@ -55,6 +58,8 @@ protected override void DoWork()
5558

5659
if (hash.Length != Entry.Hash.Length || hash != Entry.Hash)
5760
throw new InvalidHashException($"Calculated hash doesn't match provided hash for file: {localFile}");
61+
62+
Updater.Instance.GetCache().AddOrUpdateEntry(localFile, hash);
5863
}
5964

6065
public override void Cancel()

UpdateLib/UpdateLib/Tasks/UpdateCacheTask.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ protected override void DoWork()
6969
}
7070

7171
// check to see if the file has been modified since last cache check
72-
entry.Recalculate(f.LastWriteTime.Ticks);
72+
entry.Recalculate();
7373
}
7474

7575
Result.Save();

0 commit comments

Comments
 (0)