Adding new WinForms sample application (#452)

This commit is contained in:
Kevin B
2025-01-09 23:37:12 -08:00
committed by GitHub
parent 28c475284f
commit d462ed5479
8 changed files with 469 additions and 0 deletions

View File

@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<AssemblyName>VelopackCSharpWinForms</AssemblyName>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<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) == ''" />
</ItemGroup>
</Project>

114
samples/CSharpWinForms/Form1.Designer.cs generated Normal file
View File

@@ -0,0 +1,114 @@
namespace CSharpWinForms;
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
btnCheckUpdate = new Button();
btnDownloadUpdate = new Button();
btnRestartApply = new Button();
txtTextLog = new TextBox();
lblStatus = new Label();
SuspendLayout();
//
// btnCheckUpdate
//
btnCheckUpdate.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
btnCheckUpdate.Location = new Point(12, 96);
btnCheckUpdate.Name = "btnCheckUpdate";
btnCheckUpdate.Size = new Size(520, 23);
btnCheckUpdate.TabIndex = 0;
btnCheckUpdate.Text = "Check for Updates";
btnCheckUpdate.UseVisualStyleBackColor = true;
btnCheckUpdate.Click += btnCheckUpdate_Click;
//
// btnDownloadUpdate
//
btnDownloadUpdate.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
btnDownloadUpdate.Enabled = false;
btnDownloadUpdate.Location = new Point(12, 125);
btnDownloadUpdate.Name = "btnDownloadUpdate";
btnDownloadUpdate.Size = new Size(520, 23);
btnDownloadUpdate.TabIndex = 1;
btnDownloadUpdate.Text = "Download";
btnDownloadUpdate.UseVisualStyleBackColor = true;
btnDownloadUpdate.Click += btnDownloadUpdate_Click;
//
// btnRestartApply
//
btnRestartApply.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
btnRestartApply.Enabled = false;
btnRestartApply.Location = new Point(12, 154);
btnRestartApply.Name = "btnRestartApply";
btnRestartApply.Size = new Size(520, 23);
btnRestartApply.TabIndex = 2;
btnRestartApply.Text = "Restart && Apply";
btnRestartApply.UseVisualStyleBackColor = true;
btnRestartApply.Click += btnRestartApply_Click;
//
// txtTextLog
//
txtTextLog.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
txtTextLog.Location = new Point(12, 183);
txtTextLog.Multiline = true;
txtTextLog.Name = "txtTextLog";
txtTextLog.ScrollBars = ScrollBars.Vertical;
txtTextLog.Size = new Size(520, 167);
txtTextLog.TabIndex = 3;
//
// lblStatus
//
lblStatus.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
lblStatus.AutoSize = true;
lblStatus.Location = new Point(12, 9);
lblStatus.Name = "lblStatus";
lblStatus.Size = new Size(0, 15);
lblStatus.TabIndex = 4;
//
// Form1
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(544, 368);
Controls.Add(lblStatus);
Controls.Add(txtTextLog);
Controls.Add(btnRestartApply);
Controls.Add(btnDownloadUpdate);
Controls.Add(btnCheckUpdate);
Name = "Form1";
Text = "Velopack Sample";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button btnCheckUpdate;
private Button btnDownloadUpdate;
private Button btnRestartApply;
private TextBox txtTextLog;
private Label lblStatus;
}

View File

@@ -0,0 +1,107 @@
using System.Text;
using Microsoft.Extensions.Logging;
using Velopack;
namespace CSharpWinForms;
public partial class Form1 : Form
{
private readonly UpdateManager _um;
private UpdateInfo? _update;
public Form1()
{
InitializeComponent();
string updateUrl = SampleHelper.GetReleasesDir(); // replace with your update url
_um = new UpdateManager(updateUrl, logger: Program.Log);
txtTextLog.Text = Program.Log.ToString();
Program.Log.LogUpdated += LogUpdated;
UpdateStatus();
}
private void LogUpdated(object? sender, LogUpdatedEventArgs e)
{
// logs can be sent from other threads
if (InvokeRequired) {
Invoke(() => LogUpdated(sender, e));
return;
}
txtTextLog.Text = e.Text;
txtTextLog.SelectionStart = txtTextLog.Text.Length;
txtTextLog.ScrollToCaret();
}
private void Progress(int percent)
{
// progress can be sent from other threads
if (InvokeRequired) {
Invoke(() => Progress(percent));
return;
}
lblStatus.Text = $"Downloading ({percent}%)...";
}
private void Working()
{
Program.Log.LogInformation("");
btnCheckUpdate.Enabled = false;
btnDownloadUpdate.Enabled = false;
btnRestartApply.Enabled = false;
lblStatus.Text = "Working...";
}
private void UpdateStatus()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine($"Velopack version: {VelopackRuntimeInfo.VelopackNugetVersion}");
sb.AppendLine($"This app version: {(_um.IsInstalled ? _um.CurrentVersion : "(n/a - not installed)")}");
if (_update != null) {
sb.AppendLine($"Update available: {_update.TargetFullRelease.Version}");
btnDownloadUpdate.Enabled = true;
} else {
btnDownloadUpdate.Enabled = false;
}
if (_um.UpdatePendingRestart != null) {
sb.AppendLine("Update ready, pending restart to install");
btnRestartApply.Enabled = true;
} else {
btnRestartApply.Enabled = false;
}
lblStatus.Text = sb.ToString();
btnCheckUpdate.Enabled = true;
}
private async void btnCheckUpdate_Click(object sender, EventArgs e)
{
Working();
try {
// 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");
}
UpdateStatus();
}
private async void btnDownloadUpdate_Click(object sender, EventArgs e)
{
Working();
try {
// 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");
}
UpdateStatus();
}
private void btnRestartApply_Click(object sender, EventArgs e)
{
_um.ApplyUpdatesAndRestart(_update!);
}
}

View File

@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -0,0 +1,43 @@
using System.Text;
using Microsoft.Extensions.Logging;
namespace CSharpWinForms;
public class LogUpdatedEventArgs : EventArgs
{
public string? Text { get; set; }
}
public class MemoryLogger : ILogger
{
public event EventHandler<LogUpdatedEventArgs>? LogUpdated;
private readonly StringBuilder _sb = new();
public IDisposable? BeginScope<TState>(TState state) where TState : notnull
{
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

@@ -0,0 +1,31 @@
using Velopack;
namespace CSharpWinForms;
internal static class Program
{
// Logging is essential for debugging! Ideally you should write it to a file.
public static MemoryLogger Log { get; } = new MemoryLogger();
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
try {
// 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);
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
} catch (Exception ex) {
MessageBox.Show("Unhandled exception: " + ex.ToString());
}
}
}

View File

@@ -0,0 +1,19 @@
# VeloWinFormsSample
_Prerequisites: vpk command line tool installed_
This app demonstrates how to use WinForms to provide a desktop UI, installer, and updates for Windows only.
You can run this sample by executing the build script with a version number: `build.bat 1.0.0`. Once built, you can install the app - build more updates, and then test updates and so forth. The sample app will check the local release dir for new update packages.
In your production apps, you should deploy your updates to some kind of update server instead.
## WinForms Implementation Notes
The Velopack startup bootstrapping should be placed as early as possible in the Main method.
```csharp
VelopackApp.Build()
.WithFirstRun((v) => { /* Your first run code here */ })
.Run(Log);
```
This sample explicitly sets the AssemblyName in the csproj file to match the Velpoack packId (`-u` option). This is not required, but demonstrates handling the case where the app name and the packId are different.

View File

@@ -0,0 +1,18 @@
@echo off
setlocal enabledelayedexpansion
if "%~1"=="" (
echo Version number is required.
echo Usage: build.bat [version]
exit /b 1
)
set "version=%~1"
echo.
echo Compiling VelopackCSharpWinForms with dotnet...
dotnet publish -c Release -o %~dp0publish
echo.
echo Building Velopack Release v%version%
vpk pack -u VelopackCSharpWinForms -v %version% -o %~dp0releases -p %~dp0publish -f net8-x64-desktop