Fake it until you make it: using custom HttpClientHandler to emulate a client server architecture

Fake it until you make it: using custom HttpClientHandler to emulate a client server architecture

Last week, I decided to create a playground for the SyncFramework to demonstrate how synchronization works. The sync framework itself is not designed in a client-server architecture, but as a set of APIs that you can use to synchronize data.

Synchronization scenarios usually involve a client-server architecture, but when I created the SyncFramework, I decided that network communication was something outside the scope and not directly related to data synchronization. So, instead of embedding the client-server concept in the SyncFramework, I decided to create a set of extensions to handle these scenarios. If you want to take a look at the network extensions, you can see them here.

Now, let’s return to the playground. The main requirement for me, besides showing how the synchronization process works, was not having to maintain an infrastructure for it. You know, a Sync Server and a few databases that I would have to constantly delete. So, I decided to use Blazor WebAssembly and SQLite databases running in the browser. If you want to know more about how SQLite databases can run in the browser, take a look at this article.

Now, there’s still a problem. How do I run a server on the browser? I know it’s somehow possible, but I did not have the time to do the research. So, I decided to create my own HttpClientHandler.

How the HttpClientHandler works

HttpClientHandler offers a number of attributes and methods for controlling HTTP requests and responses. It serves as the fundamental mechanism for HttpClient’s ability to send and receive HTTP requests and responses.

The HttpClientHandler manages aspects like the maximum number of redirects, redirection policies, handling cookies, and automated decompression of HTTP traffic. It can be set up and supplied to HttpClient to regulate the HTTP requests made by HttpClient.

HttpClientHandler might be helpful in testing situations when it’s necessary to imitate or mock HTTP requests and responses. The SendAsync method of HttpMessageHandler, from which HttpClientHandler also descended, can be overridden in a new class to deliver any response you require for your test.

here is a basic example

public class TestHandler : HttpMessageHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // You can check the request details and return different responses based on that.
        // For simplicity, we're always returning the same response here.
        var responseMessage = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent("Test response.")
        };
        return await Task.FromResult(responseMessage);
    }
}

And here’s how you’d use this handler in a test:

[Test]
public async Task TestHttpClient()
{
    var handler = new TestHandler();
    var client = new HttpClient(handler);

    var response = await client.GetAsync("http://example.com");
    var responseContent = await response.Content.ReadAsStringAsync();

    Assert.AreEqual("Test response.", responseContent);
}

The TestHandler in this illustration consistently sends back an HTTP 200 response with the body “Test response.” In a real test, you might use SendAsync with more sophisticated logic to return several responses depending on the specifics of the request. By doing so, you may properly test your code’s handling of different answers without actually sending HTTP queries.

Going back to our main story

Now that we know we can catch the HTTP request and handle it locally, we can write an HttpClientHandler that takes the request from the client nodes and processes them locally. Now, we have all the pieces to make the playground work without a real server. You can take a look at the implementation of the custom handler for the playground here

Until next time, happy coding )))))

 

 

 

 

 

 

 

Hosting SQLite databases in Blazor Web Assembly targeting net 6

Hosting SQLite databases in Blazor Web Assembly targeting net 6

Blazor is a framework for building interactive client-side web UI with .NET, developed by Microsoft. It allows developers to build full-stack web applications using C# instead of JavaScript.

Blazor comes in two different hosting models:

1. Blazor Server: In this model, the application runs on the server from within an ASP.NET Core app. UI updates, event handling, and JavaScript calls are handled over a SignalR connection.

2. Blazor Web Assembly: In this model, the application runs directly in the browser on a Web Assembly-based .NET runtime. Blazor Web Assembly includes a proper .NET runtime implemented in Web Assembly, a standard that defines a binary format for executable programs in web pages.

In both models, you can write your code in C#, compile it, and have it run in the browser. However, the way the code is executed differs significantly.

Blazor Web Assembly has a few key features:

– Runs in the browser: The app’s .NET assemblies and its runtime are downloaded into the browser and run locally. There’s no need for ongoing active server connection like in Blazor Server.
– Runs on Web Assembly: Web Assembly (wasm) is a binary instruction format for a stack-based virtual machine. It’s designed as a portable target for the compilation of high-level languages like C, C++, and Rust, allowing deployment on the web for client and server applications.
– Can be offline capable: Blazor Web Assembly apps can download the necessary resources to the client machine and run offline.
– Full .NET debugging support: Developers can debug their application using the tools they are accustomed to, like Visual Studio and Visual Studio Code.
– Sharing code between server and client: Since Blazor uses .NET for both server-side and client-side, code can easily be shared or moved, which is especially useful for data validation and model classes.

SQLite

As an alternative, Indexed DB, a low-level API for client-side storage of significant amounts of structured data, can be used as a backing store. However, using SQLite in a web browser through Web Assembly and Indexed DB is a rather advanced topic that may require additional libraries to manage the details.

Another way to use SQLite with Web Assembly is on the server side, particularly when using technologies like WASI (Web Assembly System Interface), which aims to extend the capabilities of Web Assembly beyond the browser. With WASI, Web Assembly modules could directly access system resources like the file system, and thus could interact with an SQLite database in a more traditional way.

Web Assembly and Native References

Applications built with Blazor Web Assembly (since net6) can incorporate native dependencies that are designed to function on Web Assembly. The .NET Web Assembly construction tools, which are also utilized for ahead-of-time (AOT) compilation of a Blazor application to Web Assembly and for relinking the runtime to eliminate unnecessary features, allow you to integrate these native dependencies into the .NET Web Assembly runtime statically.

This mean that if you are targeting net 6 in your Blazor Web Assembly application you can include the SQLite native Web Assembly reference and use all the power of a full SQL engine in your SPA application. If you want to learn more about native references here is the link for the official documentation

https://learn.microsoft.com/en-us/aspnet/core/blazor/webassembly-native-dependencies?view=aspnetcore-6.0

Including SQLite native reference in you Blazor Web Assembly project

The first thing that we need to do to use SQLite native reference in a web assembly application is to compile it from the source, you can do that in Linux or WSL

sudo apt-get install cmake default-jre git-core unzip

git clone https://github.com/emscripten-core/emsdk.git
cd emsdk
./emsdk install latest
./emsdk activate latest
source ./emsdk_env.sh

Command to compile SQLite as a web assembly reference

emcc sqlite3.h -shared -o e_sqlite3.o

Now that we have the native reference we need to refence it in the web assembly project

First we need to suppress the warnings we will get by adding native refences, so we need to include this lines in the project

<PropertyGroup>
    <!-- The following two are to suppress spurious build warnings from consuming Sqlite.  -->
    <!--These will become unnecessary when the Sqlite packages contain a dedicated WASM binary. -->
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
    <EmccExtraLDFlags>-s WARN_ON_UNDEFINED_SYMBOLS=0</EmccExtraLDFlags>
</PropertyGroup>

Now we are ready to include the reference

<ItemGroup>
    <PackageReference Include="Microsoft.Data.Sqlite" Version="6.0.3" />
    <NativeFileReference Include="e_sqlite3.o" />
</ItemGroup>

And voila, now we can use a SQLite database in web assembly

If you want to learn more about native references here are a few links that you might find interesting

Remember in this example we just talked about SQLite native reference but there is a world of native reference to explore, until next time, happy coding ))

 

 

 

 

 

Blazor: Use tag helpers to include java scripts and CSS in your html header

Blazor: Use tag helpers to include java scripts and CSS in your html header

Sometime we want to reuse our Blazor components in another apps, the best way to do this is to create a razor library, this process of create a razor library is not different from create a normal class library to share code. There is only one exception, razor components might need to reference JavaScript or CSS files. This problem can be easily solve in 2 steps as shown below.

1) Create a class that inherits from TagHelperComponent,,this class should include the tags that you want to include in the html header section of your app

using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace MyBlazorApp
{
  [HtmlTargetElement("head")]
  public class MyTagHelper: TagHelperComponent
  {
    private string Tags= 
@"
        <!-- ZXingBlazor -->
        <script src=""_content/ZXingBlazor/lib/barcodereader/zxing.js""></script>
        <script src = ""_content/ZXingBlazor/lib/barcodereader/barcode.js"" ></ script >
        < !--ZXingBlazor-- >
        < !--Signature Pad  -->
        <script src = ""_content/Mobsites.Blazor.SignaturePad/bundle.js"" ></ script >
        < link href=""_content/Mobsites.Blazor.SignaturePad/bundle.css"" rel=""stylesheet"" />
        < link href=""_content/Ultra.PropertyEditors.Module.Blazor/js/signaturepropertyeditor.js""/>
        <!-- Signature Pad  -->
        <!-- HTML Editor  -->
        <link href = ""//cdn.quilljs.com/1.3.6/quill.snow.css"" rel=""stylesheet"">
        <link href = ""//cdn.quilljs.com/1.3.6/quill.bubble.css"" rel=""stylesheet"">
        <script src = ""https://cdn.quilljs.com/1.3.6/quill.js"" ></ script >
        <script src=""_content/Blazored.TextEditor/quill-blot-formatter.min.js""></script>
        <script src = ""_content/Blazored.TextEditor/Blazored-BlazorQuill.js"" ></ script >
        < !--HTML Editor  -->
";
    public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
      if (string.Equals(context.TagName, "head", StringComparison.OrdinalIgnoreCase))
      {
        output.PostContent.AppendHtml(Tags).AppendLine();
      }
      return Task.CompletedTask;
    }
  }
}

*Note: to reference JavaScript or CSS from any razor library you can use the following syntax,please notice the doble quotes.

<script src=""_content/MyAssemblyName/PathToMyJavaScript/MyJavaScriptFile.js""></script>

 

2) Create an extension method in the “Microsoft.Extensions.DependencyInjection” namespace so you can easily add your tag helper to the service collection

 

using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Microsoft.Extensions.DependencyInjection
{
  public static class StartupExtensions
  {
    public static IServiceCollection AddMyHtmlTags(this IServiceCollection services)
    {
      services.AddTransient<ITagHelperComponent, MyTagHelper>();
      return services;
    }
  }
}

 

Here is an example on how to use your new extension in your startup class

 public void ConfigureServices(IServiceCollection services
 {
   services.AddMyHtmlTags();
 }