Fix dev-integrated samples and remove MemoryLogger

This commit is contained in:
Caelan Sayler
2025-03-03 21:57:57 +00:00
committed by Caelan
parent 373b218dad
commit 3ba3ad4d7b
9 changed files with 35 additions and 141 deletions

View File

@@ -19,8 +19,7 @@
</ItemGroup>
<ItemGroup>
<!--Condition below is only needed to test this sample project against the local projects instead of the NuGet package. Remove it in your app.-->
<PackageReference Include="Velopack" Version="0.*" Condition="$(UseLocalVelopack) == ''" />
<ProjectReference Include="..\..\src\lib-csharp\Velopack.csproj" />
</ItemGroup>
</Project>

View File

@@ -3,7 +3,6 @@ using System.Text;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Threading;
using Microsoft.Extensions.Logging;
using Velopack;
namespace CSharpAvalonia;
@@ -18,10 +17,8 @@ public partial class MainWindow : Window
InitializeComponent();
var updateUrl = SampleHelper.GetReleasesDir(); // replace with your update path/url
_um = new UpdateManager(updateUrl, logger: Program.Log);
_um = new UpdateManager(updateUrl);
TextLog.Text = Program.Log.ToString();
Program.Log.LogUpdated += LogUpdated;
UpdateStatus();
}
@@ -32,8 +29,9 @@ public partial class MainWindow : Window
// ConfigureAwait(true) so that UpdateStatus() is called on the UI thread
_update = await _um.CheckForUpdatesAsync().ConfigureAwait(true);
} catch (Exception ex) {
Program.Log.LogError(ex, "Error checking for updates");
LogMessage("Error checking for updates", ex);
}
UpdateStatus();
}
@@ -44,8 +42,9 @@ public partial class MainWindow : Window
// ConfigureAwait(true) so that UpdateStatus() is called on the UI thread
await _um.DownloadUpdatesAsync(_update, Progress).ConfigureAwait(true);
} catch (Exception ex) {
Program.Log.LogError(ex, "Error downloading updates");
LogMessage("Error downloading updates", ex);
}
UpdateStatus();
}
@@ -54,26 +53,32 @@ public partial class MainWindow : Window
_um.ApplyUpdatesAndRestart(_update);
}
private void LogUpdated(object sender, LogUpdatedEventArgs e)
private void LogMessage(string text, Exception e = null)
{
// logs can be sent from other threads
Dispatcher.UIThread.InvokeAsync(() => {
TextLog.Text = e.Text;
ScrollLog.ScrollToEnd();
});
Dispatcher.UIThread.InvokeAsync(
() => {
TextLog.Text += text + Environment.NewLine;
if (e != null) {
TextLog.Text += e.ToString() + Environment.NewLine;
}
ScrollLog.ScrollToEnd();
});
}
private void Progress(int percent)
{
// progress can be sent from other threads
Dispatcher.UIThread.InvokeAsync(() => {
TextStatus.Text = $"Downloading ({percent}%)...";
});
Dispatcher.UIThread.InvokeAsync(
() => {
TextStatus.Text = $"Downloading ({percent}%)...";
});
}
private void Working()
{
Program.Log.LogInformation("");
LogMessage("");
BtnCheckUpdate.IsEnabled = false;
BtnDownloadUpdate.IsEnabled = false;
BtnRestartApply.IsEnabled = false;

View File

@@ -1,44 +0,0 @@
using System;
using System.Text;
using Microsoft.Extensions.Logging;
namespace CSharpAvalonia;
public class LogUpdatedEventArgs : EventArgs
{
public string Text { get; set; }
}
public class MemoryLogger : ILogger
{
public event EventHandler<LogUpdatedEventArgs> LogUpdated;
private readonly StringBuilder _sb = new StringBuilder();
public IDisposable BeginScope<TState>(TState state)
{
return null;
}
public bool IsEnabled(LogLevel logLevel)
{
return true;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
lock (_sb) {
var message = formatter(state, exception);
if (exception != null) message += "\n" + exception.ToString();
Console.WriteLine("log: " + message);
_sb.AppendLine(message);
LogUpdated?.Invoke(this, new LogUpdatedEventArgs { Text = _sb.ToString() });
}
}
public override string ToString()
{
lock (_sb) {
return _sb.ToString();
}
}
}

View File

@@ -6,8 +6,6 @@ namespace CSharpAvalonia;
class Program
{
public static MemoryLogger Log { get; private set; }
// Initialization code. Don't use any Avalonia, third-party APIs or any
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized
// yet and stuff might break.
@@ -15,13 +13,10 @@ class Program
public static void Main(string[] args)
{
try {
// Logging is essential for debugging! Ideally you should write it to a file.
Log = new MemoryLogger();
// It's important to Run() the VelopackApp as early as possible in app startup.
VelopackApp.Build()
.WithFirstRun((v) => { /* Your first run code here */ })
.Run(Log);
.OnFirstRun((v) => { /* Your first run code here */ })
.Run();
// Now it's time to run Avalonia
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);

View File

@@ -5,8 +5,6 @@ namespace CSharpWpf
{
public partial class App : Application
{
public static MemoryLogger Log { get; private set; }
// Since WPF has an "automatic" Program.Main, we need to create our own.
// In order for this to work, you must also add the following to your .csproj:
// <StartupObject>CSharpWpf.App</StartupObject>
@@ -14,13 +12,10 @@ namespace CSharpWpf
private static void Main(string[] args)
{
try {
// Logging is essential for debugging! Ideally you should write it to a file.
Log = new MemoryLogger();
// It's important to Run() the VelopackApp as early as possible in app startup.
VelopackApp.Build()
.WithFirstRun((v) => { /* Your first run code here */ })
.Run(Log);
.OnFirstRun((v) => { /* Your first run code here */ })
.Run();
// We can now launch the WPF application as normal.
var app = new App();

View File

@@ -19,8 +19,7 @@
</ItemGroup>
<ItemGroup>
<!--Condition below is only needed to test this sample project against the local projects instead of the NuGet package. Remove it in your app.-->
<PackageReference Include="Velopack" Version="0.*" Condition="$(UseLocalVelopack) == ''" />
<ProjectReference Include="..\..\src\lib-csharp\Velopack.csproj" />
</ItemGroup>
</Project>

View File

@@ -1,6 +1,5 @@
using System.Text;
using System.Windows;
using Microsoft.Extensions.Logging;
using Velopack;
namespace CSharpWpf
@@ -15,10 +14,8 @@ namespace CSharpWpf
InitializeComponent();
string updateUrl = SampleHelper.GetReleasesDir(); // replace with your update url
_um = new UpdateManager(updateUrl, logger: App.Log);
_um = new UpdateManager(updateUrl);
TextLog.Text = App.Log.ToString();
App.Log.LogUpdated += LogUpdated;
UpdateStatus();
}
@@ -29,7 +26,7 @@ namespace CSharpWpf
// ConfigureAwait(true) so that UpdateStatus() is called on the UI thread
_update = await _um.CheckForUpdatesAsync().ConfigureAwait(true);
} catch (Exception ex) {
App.Log.LogError(ex, "Error checking for updates");
LogMessage("Error checking for updates", ex);
}
UpdateStatus();
}
@@ -41,7 +38,7 @@ namespace CSharpWpf
// ConfigureAwait(true) so that UpdateStatus() is called on the UI thread
await _um.DownloadUpdatesAsync(_update, Progress).ConfigureAwait(true);
} catch (Exception ex) {
App.Log.LogError(ex, "Error downloading updates");
LogMessage("Error downloading updates", ex);
}
UpdateStatus();
}
@@ -51,11 +48,14 @@ namespace CSharpWpf
_um.ApplyUpdatesAndRestart(_update);
}
private void LogUpdated(object sender, LogUpdatedEventArgs e)
private void LogMessage(string text, Exception e = null)
{
// logs can be sent from other threads
this.Dispatcher.InvokeAsync(() => {
TextLog.Text = e.Text;
TextLog.Text += text + Environment.NewLine;
if (e != null) {
TextLog.Text += e.ToString() + Environment.NewLine;
}
ScrollLog.ScrollToEnd();
});
}
@@ -70,7 +70,7 @@ namespace CSharpWpf
private void Working()
{
App.Log.LogInformation("");
LogMessage("");
BtnCheckUpdate.IsEnabled = false;
BtnDownloadUpdate.IsEnabled = false;
BtnRestartApply.IsEnabled = false;

View File

@@ -1,44 +0,0 @@
using System.Text;
using Microsoft.Extensions.Logging;
namespace CSharpWpf
{
public class LogUpdatedEventArgs : EventArgs
{
public string Text { get; set; }
}
public class MemoryLogger : ILogger
{
public event EventHandler<LogUpdatedEventArgs> LogUpdated;
private readonly StringBuilder _sb = new StringBuilder();
public IDisposable BeginScope<TState>(TState state)
{
return null;
}
public bool IsEnabled(LogLevel logLevel)
{
return true;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
lock (_sb) {
var message = formatter(state, exception);
if (exception != null) message += "\n" + exception.ToString();
Console.WriteLine("log: " + message);
_sb.AppendLine(message);
LogUpdated?.Invoke(this, new LogUpdatedEventArgs { Text = _sb.ToString() });
}
}
public override string ToString()
{
lock (_sb) {
return _sb.ToString();
}
}
}
}

View File

@@ -17,16 +17,5 @@
<ItemGroup>
<Compile Include="..\SampleHelper.cs" Link="SampleHelper.cs" Visible="false" />
</ItemGroup>
<PropertyGroup Condition="$(UseLocalVelopack) != ''">
<RestoreSources>https://api.nuget.org/v3/index.json;$(RestoreSources)</RestoreSources>
<RestoreSources Condition="Exists('$(MSBuildThisFileDirectory)..\build\$(Configuration)')">
$([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)..\build\$(Configuration)'));$(RestoreSources)
</RestoreSources>
</PropertyGroup>
<ItemGroup Condition="$(UseLocalVelopack) != ''">
<ProjectReference Include="..\..\src\lib-csharp\Velopack.csproj" />
</ItemGroup>
</Project>