Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 64 additions & 37 deletions docs/content/samples/todoapp/wpf.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,44 +2,71 @@
title = "WPF"
+++

You can find [our sample TodoApp for WPF](https://github.com/CommunityToolkit/Datasync/tree/main/samples/todoapp/TodoApp.WPF) on our GitHub repository. All of our logic has been placed in the `Database/AppDbContext.cs` file:

{{< highlight lineNos="true" type="csharp" wrap="true" title="AppDbContext.cs" >}}
public class AppDbContext(DbContextOptions<AppDbContext> options) : OfflineDbContext(options)
{
public DbSet<TodoItem> TodoItems => Set<TodoItem>();

protected override void OnDatasyncInitialization(DatasyncOfflineOptionsBuilder optionsBuilder)
{
HttpClientOptions clientOptions = new()
{
Endpoint = new Uri("https://YOURSITEHERE.azurewebsites.net/"),
HttpPipeline = [new LoggingHandler()]
};
_ = optionsBuilder.UseHttpClientOptions(clientOptions);
}
## Run the application first

public async Task SynchronizeAsync(CancellationToken cancellationToken = default)
{
PushResult pushResult = await this.PushAsync(cancellationToken);
if (!pushResult.IsSuccessful)
{
throw new ApplicationException($"Push failed: {pushResult.FailedRequests.FirstOrDefault().Value.ReasonPhrase}");
}

PullResult pullResult = await this.PullAsync(cancellationToken);
if (!pullResult.IsSuccessful)
{
throw new ApplicationException($"Pull failed: {pullResult.FailedRequests.FirstOrDefault().Value.ReasonPhrase}");
}
}
}
{{< /highlight >}}
The WPF sample uses an in-memory Sqlite store for storing its data. To run the application locally:

* [Configure Visual Studio for WPF development](https://learn.microsoft.com/visualstudio/get-started/csharp/tutorial-wpf).
* Open `samples/todoapp/Samples.TodoApp.sln` in Visual Studio.
* In the Solution Explorer, right-click the `TodoApp.WPF` project, then select **Set as Startup Project**.
* Select a target (in the top bar), then press F5 to run the application.

If you bump into issues at this point, ensure you can properly develop and run WPF applications outside of the datasync service.

## Deploy a datasync server to Azure

Before you begin adjusting the application for offline usage, you must [deploy a datasync service](../server.md). Make a note of the URI of the service before continuing.

## Update the application for datasync operations

All the changes are isolated to the `Database/AppDbContext.cs` file.

1. Change the definition of the class so that it inherits from `OfflineDbContext`:

To enable offline synchronization:
```csharp
public class AppDbContext(DbContextOptions<AppDbContext> options) : OfflineDbContext(options)
{
// Rest of the class
}
```

2. Add the `OnDatasyncInitialization()` method:

```csharp
protected override void OnDatasyncInitialization(DatasyncOfflineOptionsBuilder optionsBuilder)
{
HttpClientOptions clientOptions = new()
{
Endpoint = new Uri("https://YOURSITEHERE.azurewebsites.net/"),
HttpPipeline = [new LoggingHandler()]
};
_ = optionsBuilder.UseHttpClientOptions(clientOptions);
}
```

Replace the Endpoint with the URI of your datasync service.

3. Update the `SynchronizeAsync()` method.

The `SynchronizeAsync()` method is used by the application to synchronize data to and from the datasync service. It is called primarily from the `MainViewModel` which drives the UI interactions for the main list.

```csharp
public async Task SynchronizeAsync(CancellationToken cancellationToken = default)
{
PushResult pushResult = await this.PushAsync(cancellationToken);
if (!pushResult.IsSuccessful)
{
throw new ApplicationException($"Push failed: {pushResult.FailedRequests.FirstOrDefault().Value.ReasonPhrase}");
}

PullResult pullResult = await this.PullAsync(cancellationToken);
if (!pullResult.IsSuccessful)
{
throw new ApplicationException($"Pull failed: {pullResult.FailedRequests.FirstOrDefault().Value.ReasonPhrase}");
}
}
```

* Switch from `DbContext` to `OfflineDbContext`.
* Define your `OnDatasyncInitialization()` method (don't forget to change the URL to the URL of your datasync server).
* Where appropriate, use `PushAsync()` and `PullAsync()` to communicate with the server.
You can now re-run your application. Watch the console logs to show the interactions with the datasync service. Press the refresh button to synchronize data with the cloud. When you restart the application, your changes will automatically populate the database again.

We have placed a `SynchronizeAsync()` method on the database context, which is used in the view model for the single page we have.
Obviously, you will want to do much more in a "real world" application, including proper error handling, authentication, and using a Sqlite file instead of an in-memory database. This example shows off the minimum required to add datasync services to an application.
38 changes: 19 additions & 19 deletions samples/todoapp/Samples.TodoApp.sln
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TodoApp.WinUI3", "TodoApp.W
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CommunityToolkit.Datasync.Client", "..\..\src\CommunityToolkit.Datasync.Client\CommunityToolkit.Datasync.Client.csproj", "{2AC73FBE-9E76-4702-B551-B5884383CC68}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TodoApp.WPF", "TodoApp.WPF\TodoApp.WPF.csproj", "{410D4BBD-5ED7-4BC0-A2CF-547A4784732F}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sample.Datasync.Server", "..\datasync-server\src\Sample.Datasync.Server\Sample.Datasync.Server.csproj", "{E67734DD-B397-4A65-AA50-D62F37EF05DD}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TodoApp.MAUI", "TodoApp.MAUI\TodoApp.MAUI.csproj", "{00430043-04C5-4F8F-87A9-98ECC0051808}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TodoApp.MAUI", "TodoApp.MAUI\TodoApp.MAUI.csproj", "{00430043-04C5-4F8F-87A9-98ECC0051808}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TodoApp.WPF", "TodoApp.WPF\TodoApp.WPF.csproj", "{A0996FB8-890D-4E90-A881-01F9EF709711}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down Expand Up @@ -67,22 +67,6 @@ Global
{2AC73FBE-9E76-4702-B551-B5884383CC68}.Release|x64.Build.0 = Release|Any CPU
{2AC73FBE-9E76-4702-B551-B5884383CC68}.Release|x86.ActiveCfg = Release|Any CPU
{2AC73FBE-9E76-4702-B551-B5884383CC68}.Release|x86.Build.0 = Release|Any CPU
{410D4BBD-5ED7-4BC0-A2CF-547A4784732F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{410D4BBD-5ED7-4BC0-A2CF-547A4784732F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{410D4BBD-5ED7-4BC0-A2CF-547A4784732F}.Debug|ARM64.ActiveCfg = Debug|Any CPU
{410D4BBD-5ED7-4BC0-A2CF-547A4784732F}.Debug|ARM64.Build.0 = Debug|Any CPU
{410D4BBD-5ED7-4BC0-A2CF-547A4784732F}.Debug|x64.ActiveCfg = Debug|Any CPU
{410D4BBD-5ED7-4BC0-A2CF-547A4784732F}.Debug|x64.Build.0 = Debug|Any CPU
{410D4BBD-5ED7-4BC0-A2CF-547A4784732F}.Debug|x86.ActiveCfg = Debug|Any CPU
{410D4BBD-5ED7-4BC0-A2CF-547A4784732F}.Debug|x86.Build.0 = Debug|Any CPU
{410D4BBD-5ED7-4BC0-A2CF-547A4784732F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{410D4BBD-5ED7-4BC0-A2CF-547A4784732F}.Release|Any CPU.Build.0 = Release|Any CPU
{410D4BBD-5ED7-4BC0-A2CF-547A4784732F}.Release|ARM64.ActiveCfg = Release|Any CPU
{410D4BBD-5ED7-4BC0-A2CF-547A4784732F}.Release|ARM64.Build.0 = Release|Any CPU
{410D4BBD-5ED7-4BC0-A2CF-547A4784732F}.Release|x64.ActiveCfg = Release|Any CPU
{410D4BBD-5ED7-4BC0-A2CF-547A4784732F}.Release|x64.Build.0 = Release|Any CPU
{410D4BBD-5ED7-4BC0-A2CF-547A4784732F}.Release|x86.ActiveCfg = Release|Any CPU
{410D4BBD-5ED7-4BC0-A2CF-547A4784732F}.Release|x86.Build.0 = Release|Any CPU
{E67734DD-B397-4A65-AA50-D62F37EF05DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E67734DD-B397-4A65-AA50-D62F37EF05DD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E67734DD-B397-4A65-AA50-D62F37EF05DD}.Debug|ARM64.ActiveCfg = Debug|Any CPU
Expand Down Expand Up @@ -123,6 +107,22 @@ Global
{00430043-04C5-4F8F-87A9-98ECC0051808}.Release|x86.ActiveCfg = Release|Any CPU
{00430043-04C5-4F8F-87A9-98ECC0051808}.Release|x86.Build.0 = Release|Any CPU
{00430043-04C5-4F8F-87A9-98ECC0051808}.Release|x86.Deploy.0 = Release|Any CPU
{A0996FB8-890D-4E90-A881-01F9EF709711}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A0996FB8-890D-4E90-A881-01F9EF709711}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A0996FB8-890D-4E90-A881-01F9EF709711}.Debug|ARM64.ActiveCfg = Debug|Any CPU
{A0996FB8-890D-4E90-A881-01F9EF709711}.Debug|ARM64.Build.0 = Debug|Any CPU
{A0996FB8-890D-4E90-A881-01F9EF709711}.Debug|x64.ActiveCfg = Debug|Any CPU
{A0996FB8-890D-4E90-A881-01F9EF709711}.Debug|x64.Build.0 = Debug|Any CPU
{A0996FB8-890D-4E90-A881-01F9EF709711}.Debug|x86.ActiveCfg = Debug|Any CPU
{A0996FB8-890D-4E90-A881-01F9EF709711}.Debug|x86.Build.0 = Debug|Any CPU
{A0996FB8-890D-4E90-A881-01F9EF709711}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A0996FB8-890D-4E90-A881-01F9EF709711}.Release|Any CPU.Build.0 = Release|Any CPU
{A0996FB8-890D-4E90-A881-01F9EF709711}.Release|ARM64.ActiveCfg = Release|Any CPU
{A0996FB8-890D-4E90-A881-01F9EF709711}.Release|ARM64.Build.0 = Release|Any CPU
{A0996FB8-890D-4E90-A881-01F9EF709711}.Release|x64.ActiveCfg = Release|Any CPU
{A0996FB8-890D-4E90-A881-01F9EF709711}.Release|x64.Build.0 = Release|Any CPU
{A0996FB8-890D-4E90-A881-01F9EF709711}.Release|x86.ActiveCfg = Release|Any CPU
{A0996FB8-890D-4E90-A881-01F9EF709711}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
1 change: 0 additions & 1 deletion samples/todoapp/TodoApp.MAUI/MainPage.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ public void OnListItemTapped(object sender, ItemTappedEventArgs e)
{
if (e.Item is TodoItem item)
{
Debug.WriteLine($"[UI] >>> Item clicked: {item.Id}");
this._viewModel.SelectItemCommand.Execute(item);
}

Expand Down
3 changes: 1 addition & 2 deletions samples/todoapp/TodoApp.WPF/App.xaml
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
<Application x:Class="TodoApp.WPF.App"
<Application x:Class="TodoApp.WPF.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TodoApp.WPF"
StartupUri="MainWindow.xaml">
<Application.Resources>

</Application.Resources>
</Application>
8 changes: 2 additions & 6 deletions samples/todoapp/TodoApp.WPF/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using Microsoft.Extensions.DependencyInjection;
using System.Windows;
using TodoApp.WPF.Database;
using TodoApp.WPF.Services;
using TodoApp.WPF.ViewModels;

namespace TodoApp.WPF;
Expand All @@ -17,22 +18,18 @@ namespace TodoApp.WPF;
public partial class App : Application, IDisposable
{
private readonly SqliteConnection dbConnection;

/// <summary>
/// The IoC service provider
/// </summary>
public IServiceProvider Services { get; }

public App()
{
// Create the connection to the SQLite database
this.dbConnection = new SqliteConnection("Data Source=:memory:");
this.dbConnection.Open();

// Create the IoC Services provider.
Services = new ServiceCollection()
.AddTransient<TodoListViewModel>()
.AddScoped<IDbInitializer, DbContextInitializer>()
.AddScoped<IAlertService, AlertService>()
.AddDbContext<AppDbContext>(options => options.UseSqlite(this.dbConnection))
.BuildServiceProvider();

Expand All @@ -42,7 +39,6 @@ public App()

private void InitializeDatabase()
{
// using IServiceScope scope = Ioc.Default.CreateScope();
using IServiceScope scope = Services.CreateScope();
IDbInitializer initializer = scope.ServiceProvider.GetRequiredService<IDbInitializer>();
initializer.Initialize();
Expand Down
32 changes: 32 additions & 0 deletions samples/todoapp/TodoApp.WPF/Converters/BooleanToImageConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Globalization;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace TodoApp.WPF.Converters;

/// <summary>
/// A converter to convert the boolean for IsComplete into one of two images.
/// </summary>
public class BooleanToImageConverter : IValueConverter
{
private const string baseUri = "pack://application:,,,/Images";

public object? Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool booleanValue)
{
return new BitmapImage(new Uri(booleanValue ? $"{baseUri}/completed.png" : $"{baseUri}/incomplete.png"));
}

return null;
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
46 changes: 24 additions & 22 deletions samples/todoapp/TodoApp.WPF/Database/AppDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,37 +5,36 @@
using CommunityToolkit.Datasync.Client.Http;
using CommunityToolkit.Datasync.Client.Offline;
using Microsoft.EntityFrameworkCore;
using TodoApp.WPF.Services;

namespace TodoApp.WPF.Database;

public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public DbSet<TodoItem> TodoItems => Set<TodoItem>();

// protected override void OnDatasyncInitialization(DatasyncOfflineOptionsBuilder optionsBuilder)
// {
// HttpClientOptions clientOptions = new()
// {
// Endpoint = new Uri("https://Y.azurewebsites.net/"),
// HttpPipeline = [new LoggingHandler()]
// };
// _ = optionsBuilder.UseHttpClientOptions(clientOptions);
// }
//protected override void OnDatasyncInitialization(DatasyncOfflineOptionsBuilder optionsBuilder)
//{
// HttpClientOptions clientOptions = new()
// {
// Endpoint = new Uri("https://YOURSITEHERE.azurewebsites.net/"),
// HttpPipeline = [new LoggingHandler()]
// };
// _ = optionsBuilder.UseHttpClientOptions(clientOptions);
//}

public async Task SynchronizeAsync(CancellationToken cancellationToken = default)
{
// PushResult pushResult = await this.PushAsync(cancellationToken);
// if (!pushResult.IsSuccessful)
// {
// throw new ApplicationException($"Push failed: {pushResult.FailedRequests.FirstOrDefault().Value.ReasonPhrase}");
// }

// PullResult pullResult = await this.PullAsync(cancellationToken);
// if (!pullResult.IsSuccessful)
// {
// throw new ApplicationException($"Pull failed: {pullResult.FailedRequests.FirstOrDefault().Value.ReasonPhrase}");
// }
//PushResult pushResult = await this.PushAsync(cancellationToken);
//if (!pushResult.IsSuccessful)
//{
// throw new ApplicationException($"Push failed: {pushResult.FailedRequests.FirstOrDefault().Value.ReasonPhrase}");
//}

//PullResult pullResult = await this.PullAsync(cancellationToken);
//if (!pullResult.IsSuccessful)
//{
// throw new ApplicationException($"Pull failed: {pullResult.FailedRequests.FirstOrDefault().Value.ReasonPhrase}");
//}
}
}

Expand All @@ -49,7 +48,10 @@ public class DbContextInitializer(AppDbContext context) : IDbInitializer
{
/// <inheritdoc />
public void Initialize()
=> context.Database.EnsureCreated();
{
_ = context.Database.EnsureCreated();
// Task.Run(async () => await context.SynchronizeAsync());
}

/// <inheritdoc />
public Task InitializeAsync(CancellationToken cancellationToken = default)
Expand Down
8 changes: 1 addition & 7 deletions samples/todoapp/TodoApp.WPF/Database/TodoItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,9 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Text.Json;

namespace TodoApp.WPF.Database;

public class TodoItem : OfflineClientEntity
{
public string Title { get; set; } = string.Empty;
public bool IsComplete { get; set; } = false;

public override string ToString()
=> JsonSerializer.Serialize(this);
}
}
Binary file removed samples/todoapp/TodoApp.WPF/Images/AddItem.png
Binary file not shown.
Binary file removed samples/todoapp/TodoApp.WPF/Images/RefreshItems.png
Binary file not shown.
Binary file added samples/todoapp/TodoApp.WPF/Images/completed.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added samples/todoapp/TodoApp.WPF/Images/incomplete.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading