Skip to content

Commit

Permalink
Added preprocessor directives for two build configs
Browse files Browse the repository at this point in the history
TAP isn't compulsory anymore and there are two configurations, one
providing TAP and one only using EAP. This won't require an installation
of Microsoft.Bcl anymore.
  • Loading branch information
ProgTrade committed Apr 17, 2015
1 parent 8e9c735 commit 4781efc
Show file tree
Hide file tree
Showing 3 changed files with 235 additions and 113 deletions.
9 changes: 0 additions & 9 deletions nUpdate/Core/ImplementationPattern.cs

This file was deleted.

207 changes: 125 additions & 82 deletions nUpdate/Updating/UpdateManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ public class UpdateManager : IDisposable
Dispose(true);
}

public SynchronizationContext Context { get; set; }

/// <summary>
/// Gets or sets the URI of the configuration file.
/// </summary>
Expand Down Expand Up @@ -238,16 +240,12 @@ private void ResetTokens()
public bool SearchForUpdates()
{
ResetTokens();
_searchCancellationTokenSource.Token.ThrowIfCancellationRequested();
if (!ConnectionChecker.IsConnectionAvailable())
return false;

_searchCancellationTokenSource.Token.ThrowIfCancellationRequested();

// Check for SSL and ignore it
ServicePointManager.ServerCertificateValidationCallback += delegate { return (true); };
var configurations = UpdateConfiguration.Download(UpdateConfigurationFileUri, Proxy);
_searchCancellationTokenSource.Token.ThrowIfCancellationRequested();

var result = new UpdateResult(configurations, CurrentVersion,
IncludeAlpha, IncludeBeta);
Expand All @@ -269,7 +267,8 @@ public bool SearchForUpdates()
}

TotalSize = updatePackageSize;
_searchCancellationTokenSource.Token.ThrowIfCancellationRequested();
if (_searchCancellationTokenSource.Token.IsCancellationRequested)
throw new OperationCanceledException();

return true;
}
Expand All @@ -279,10 +278,9 @@ public bool SearchForUpdates()
/// </summary>
public void SearchForUpdatesAsync()
{
TaskEx.Run(() => SearchForUpdates()).ContinueWith(SearchTaskCompleted,
Task.Factory.StartNew(() => SearchForUpdates()).ContinueWith(SearchTaskCompleted,
_searchCancellationTokenSource.Token,
TaskContinuationOptions.None,
TaskScheduler.FromCurrentSynchronizationContext());
TaskContinuationOptions.None, TaskScheduler.Default);
}

private void SearchTaskCompleted(Task<bool> task)
Expand All @@ -296,17 +294,23 @@ private void SearchTaskCompleted(Task<bool> task)
OnUpdateSearchFinished(task.Result);
}

#if PROVIDE_TAP

/// <summary>
/// Provides a task that searches for updates and can be wrapped asynchronously.
/// </summary>
/// <returns>Returns <c>true</c> if updates are available; otherwise, <c>false</c>.</returns>
/// <exception cref="SizeCalculationException">The calculation of total size of the packages has failed.</exception>
/// <exception cref="OperationCanceledException">The update search was canceled.</exception>
#pragma warning disable 1998
public async Task<bool> SearchForUpdatesTask()
#pragma warning restore 1998
{
return SearchForUpdates();
}

#endif

/// <summary>
/// Cancels the active update search.
/// </summary>
Expand All @@ -328,7 +332,93 @@ public void CancelSearch()
/// <seealso cref="DownloadPackagesTask"/>
public void DownloadPackages()
{
InternalDownloadPackage(ImplementationPattern.Synchronous, null);
ResetTokens();
int received = 0;
double total = _updateConfigurations.Select(config => GetUpdatePackageSize(config.UpdatePackageUri))
.Where(updatePackageSize => updatePackageSize != null)
.Sum(updatePackageSize => updatePackageSize.Value);

if (!Directory.Exists(_applicationUpdateDirectory))
Directory.CreateDirectory(_applicationUpdateDirectory);

foreach (var updateConfiguration in _updateConfigurations)
{
WebResponse webResponse = null;
try
{
if (_downloadCancellationTokenSource.Token.IsCancellationRequested)
{
DeletePackages();
throw new OperationCanceledException();
}

var webRequest = WebRequest.Create(updateConfiguration.UpdatePackageUri);
webResponse = webRequest.GetResponse();

var buffer = new byte[1024];
_packageFilePaths.Add(new UpdateVersion(updateConfiguration.LiteralVersion),
Path.Combine(_applicationUpdateDirectory,
String.Format("{0}.zip", updateConfiguration.LiteralVersion)));
using (FileStream fileStream = File.Create(Path.Combine(_applicationUpdateDirectory,
String.Format("{0}.zip", updateConfiguration.LiteralVersion))))
{
using (Stream input = webResponse.GetResponseStream())
{
if (input == null)
throw new Exception("The response stream couldn't be read.");

if (_downloadCancellationTokenSource.Token.IsCancellationRequested)
{
DeletePackages();
throw new OperationCanceledException();
}

int size = input.Read(buffer, 0, buffer.Length);
while (size > 0)
{
if (_downloadCancellationTokenSource.Token.IsCancellationRequested)
{
fileStream.Flush();
fileStream.Close();
DeletePackages();
throw new OperationCanceledException();
}

fileStream.Write(buffer, 0, size);
received += size;
OnUpdateDownloadProgressChanged(received,
(long)total, (float)(received / total) * 100);
size = input.Read(buffer, 0, buffer.Length);
}

if (!updateConfiguration.UseStatistics || !_includeCurrentPcIntoStatistics)
continue;

try
{
string response =
new WebClient().DownloadString(String.Format("{0}?versionid={1}&os={2}",
updateConfiguration.UpdatePhpFileUri, updateConfiguration.VersionId,
SystemInformation.OperatingSystemName)); // Only for calling it
if (!String.IsNullOrEmpty(response))
{
throw new StatisticsException(String.Format(
_lp.StatisticsScriptExceptionText, response));
}
}
catch (Exception ex)
{
throw new StatisticsException(ex.Message);
}
}
}
}
catch (Exception)
{
if (webResponse != null)
webResponse.Close();
}
}
}

/// <summary>
Expand All @@ -338,10 +428,10 @@ public void DownloadPackages()
/// <seealso cref="DownloadPackages"/>
public void DownloadPackagesAsync()
{
TaskEx.Run(() => InternalDownloadPackage(ImplementationPattern.EventBasedAsynchronous, null)).ContinueWith(DownloadTaskCompleted,
_searchCancellationTokenSource.Token,
Task.Factory.StartNew(DownloadPackages).ContinueWith(DownloadTaskCompleted,
_downloadCancellationTokenSource.Token,
TaskContinuationOptions.None,
TaskScheduler.FromCurrentSynchronizationContext());
TaskScheduler.Default);
}

private void DownloadTaskCompleted(Task task)
Expand All @@ -355,6 +445,8 @@ private void DownloadTaskCompleted(Task task)
OnUpdateDownloadFinished(this, EventArgs.Empty);
}

#if PROVIDE_TAP

/// <summary>
/// Provides a task that downloads the available update packages from the server and can be wrapped asynchronously.
/// </summary>
Expand All @@ -366,16 +458,12 @@ private void DownloadTaskCompleted(Task task)
/// <seealso cref="DownloadPackagesAsync"/>
/// <seealso cref="DownloadPackages"/>
public async Task DownloadPackagesTask(IProgress<UpdateDownloadProgressChangedEventArgs> progress)
{
await InternalDownloadPackage(ImplementationPattern.TaskBasedAsynchronous, progress);
}

private async Task InternalDownloadPackage(ImplementationPattern pattern,
IProgress<UpdateDownloadProgressChangedEventArgs> progress)
{
ResetTokens();
int received = 0;
double total = _updateConfigurations.Select(config => GetUpdatePackageSize(config.UpdatePackageUri)).Where(updatePackageSize => updatePackageSize != null).Sum(updatePackageSize => updatePackageSize.Value);
double total = _updateConfigurations.Select(config => GetUpdatePackageSize(config.UpdatePackageUri))
.Where(updatePackageSize => updatePackageSize != null)
.Sum(updatePackageSize => updatePackageSize.Value);

if (!Directory.Exists(_applicationUpdateDirectory))
Directory.CreateDirectory(_applicationUpdateDirectory);
Expand All @@ -392,15 +480,7 @@ public async Task DownloadPackagesTask(IProgress<UpdateDownloadProgressChangedEv
}

var webRequest = WebRequest.Create(updateConfiguration.UpdatePackageUri);
switch (pattern)
{
case ImplementationPattern.TaskBasedAsynchronous:
webResponse = await webRequest.GetResponseAsync();
break;
default:
webResponse = webRequest.GetResponse();
break;
}
webResponse = await webRequest.GetResponseAsync();

var buffer = new byte[1024];
_packageFilePaths.Add(new UpdateVersion(updateConfiguration.LiteralVersion),
Expand All @@ -419,45 +499,23 @@ public async Task DownloadPackagesTask(IProgress<UpdateDownloadProgressChangedEv
DeletePackages();
throw new OperationCanceledException();
}
int size;
switch (pattern)
{
case ImplementationPattern.TaskBasedAsynchronous:
size = await input.ReadAsync(buffer, 0, buffer.Length);
break;
default:
size = input.Read(buffer, 0, buffer.Length);
break;
}

int size = await input.ReadAsync(buffer, 0, buffer.Length);
while (size > 0)
{
if (_downloadCancellationTokenSource.Token.IsCancellationRequested)
{
fileStream.Flush();
fileStream.Close();
DeletePackages();
throw new OperationCanceledException();
}

switch (pattern)
{
case ImplementationPattern.TaskBasedAsynchronous:
await fileStream.WriteAsync(buffer, 0, size);
received += size;
progress.Report(new UpdateDownloadProgressChangedEventArgs(received,
(long)total,
(float)(received / total) * 100));
size = await input.ReadAsync(buffer, 0, buffer.Length);
break;
default:
fileStream.Write(buffer, 0, size);
received += size;
if (pattern == ImplementationPattern.EventBasedAsynchronous)
OnUpdateDownloadProgressChanged(received,
(long) total,
(float) (received/total)*100);
size = input.Read(buffer, 0, buffer.Length);
break;
}
await fileStream.WriteAsync(buffer, 0, size);
received += size;
progress.Report(new UpdateDownloadProgressChangedEventArgs(received,
(long) total, (float) (received/total)*100));
size = await input.ReadAsync(buffer, 0, buffer.Length);
}

if (!updateConfiguration.UseStatistics || !_includeCurrentPcIntoStatistics)
Expand All @@ -471,40 +529,25 @@ public async Task DownloadPackagesTask(IProgress<UpdateDownloadProgressChangedEv
SystemInformation.OperatingSystemName)); // Only for calling it
if (!String.IsNullOrEmpty(response))
{
switch (pattern)
{
case ImplementationPattern.TaskBasedAsynchronous:
throw new StatisticsException(String.Format(
_lp.StatisticsScriptExceptionText, response));
default:
OnStatisticsEntryFailed(new Exception(String.Format(
_lp.StatisticsScriptExceptionText, response)));
break;
}

throw new StatisticsException(String.Format(
_lp.StatisticsScriptExceptionText, response));
}
}
catch (Exception ex)
{
switch (pattern)
{
case ImplementationPattern.TaskBasedAsynchronous:
throw new StatisticsException(ex.Message);
default:
OnStatisticsEntryFailed(ex);
break;
}
throw new StatisticsException(ex.Message);
}
}
}
}
finally
catch (Exception)
{
if (webResponse != null)
if (webResponse != null)
webResponse.Close();
}
}
}
#endif

/// <summary>
/// Cancels the active download.
Expand All @@ -516,12 +559,12 @@ public void CancelDownload()
}

/// <summary>
/// Returns a value indicating whether the package is valid or not. If it contains an invalid signature, it will be deleted directly.
/// Returns a value indicating whether the signature of each package is valid, or not. If a package contains an invalid signature, it will be deleted directly.
/// </summary>
/// <returns>Returns <c>true</c>' if the package is valid; otherwise <c>false</c>.</returns>
/// <returns>Returns <c>true</c> if the package is valid; otherwise <c>false</c>.</returns>
/// <exception cref="FileNotFoundException">The update package to check could not be found.</exception>
/// <exception cref="ArgumentException">The signature of the update package is null or empty.</exception>
public bool CheckPackageValidity()
public bool ValidatePackages()
{
foreach (var filePathItem in _packageFilePaths)
{
Expand Down

0 comments on commit 4781efc

Please sign in to comment.