<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dejan Đenić on Medium]]></title>
        <description><![CDATA[Stories by Dejan Đenić on Medium]]></description>
        <link>https://medium.com/@dejandjenic?source=rss-14d32b373b09------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gODyGj280wqSeHYdIq6caQ.jpeg</url>
            <title>Stories by Dejan Đenić on Medium</title>
            <link>https://medium.com/@dejandjenic?source=rss-14d32b373b09------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 07:43:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dejandjenic/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Testing with JWT in .NET APIs]]></title>
            <link>https://medium.com/@dejandjenic/testing-with-jwt-in-net-apis-98c9587b9b33?source=rss-14d32b373b09------2</link>
            <guid isPermaLink="false">https://medium.com/p/98c9587b9b33</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Dejan Đenić]]></dc:creator>
            <pubDate>Wed, 22 Jan 2025 11:50:51 GMT</pubDate>
            <atom:updated>2025-01-22T11:50:51.486Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testing with JWT in .NET APIs</h3><p><strong>Introduction to JWT and Its Use in .NET APIs</strong></p><p><strong>JSON Web Tokens (JWT)</strong> are a compact, URL-safe means of representing claims between two parties. In the context of web APIs, JWT is commonly used for authentication and authorization. When a client logs in, a server generates a JWT containing user information and permissions (claims), which the client includes in subsequent requests.</p><p>In .NET APIs, JWT is integrated through middleware for authentication and authorization, allowing developers to enforce access rules based on claims and roles.</p><p><strong>Setting Up a Minimal API with JWT Authentication</strong></p><p>Let’s start by creating a .NET Minimal API project. This example will include two endpoints:</p><p>- /users: Returns a list of users and requires the “admin” claim.</p><p>- /me: Returns information about the currently authenticated user and requires only authentication without specific claims.</p><p><strong>Step 1*</strong></p><p>Update Project Dependencies</p><p>Update the csproj file to include the necessary packages for JWT handling, Swagger for API documentation, and OpenAPI integration.</p><pre>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;<br><br>    &lt;PropertyGroup&gt;<br>        &lt;TargetFramework&gt;net8.0&lt;/TargetFramework&gt;<br>        &lt;Nullable&gt;enable&lt;/Nullable&gt;<br>        &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;<br>    &lt;/PropertyGroup&gt;<br><br>    &lt;ItemGroup&gt;<br>        &lt;PackageReference Include=&quot;Microsoft.AspNetCore.OpenApi&quot; Version=&quot;8.0.11&quot;/&gt;<br>        &lt;PackageReference Include=&quot;Swashbuckle.AspNetCore&quot; Version=&quot;6.6.2&quot;/&gt;<br>        &lt;PackageReference Include=&quot;Microsoft.AspNetCore.Authentication.JwtBearer&quot; Version=&quot;8.0.11&quot; /&gt;<br>    &lt;/ItemGroup&gt;<br><br>&lt;/Project&gt;</pre><p><strong>Step 2</strong>: Implement API Logic in Program.cs</p><p>Add the following code to your Program.cs file. This configures the endpoints and sets up authentication and authorization.</p><pre>var builder = WebApplication.CreateBuilder(args);<br><br>// Add services to the container.<br>// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle<br>builder.Services.AddEndpointsApiExplorer();<br>builder.Services.AddSwaggerGen();<br><br>builder.Services.AddAuthentication();<br>builder.Services.AddAuthorization();<br><br>builder.Services.AddAuthentication(&quot;Bearer&quot;).AddJwtBearer();<br><br>var app = builder.Build();<br><br>// Configure the HTTP request pipeline.<br>if (app.Environment.IsDevelopment())<br>{<br>    app.UseSwagger();<br>    app.UseSwaggerUI();<br>}<br><br>app.UseHttpsRedirection();<br><br>app.MapGet(&quot;/users&quot;, () =&gt; new UserInfo[]<br>    {<br>        new()<br>        {<br>            Name = &quot;me&quot;<br>        },<br>        new()<br>        {<br>            Name = &quot;you&quot;<br>        }<br>    })<br>    .WithName(&quot;users&quot;)<br>    .WithOpenApi()<br>    .RequireAuthorization(p =&gt;<br>    {<br>        p.RequireRole(&quot;admin&quot;);<br>    });<br><br>app.MapGet(&quot;/me&quot;, (HttpContext context) =&gt; new UserInfo<br>    {<br>        Name = context.User.Identity.Name<br>    })<br>    .WithName(&quot;me&quot;)<br>    .WithOpenApi()<br>    .RequireAuthorization();<br><br>app.Run();<br><br>public class UserInfo<br>{<br>    public string Name { get; set; }<br>}</pre><p><strong>Step 3</strong>: Configure Authentication in appsettings.json</p><p>Add the following configuration to appsettings.json to define the JWT authentication settings.</p><pre>{<br>  &quot;Logging&quot;: {<br>    &quot;LogLevel&quot;: {<br>      &quot;Default&quot;: &quot;Information&quot;,<br>      &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;<br>    }<br>  },<br>  &quot;Authentication&quot;: {<br>    &quot;Schemes&quot;: {<br>      &quot;Bearer&quot;: {<br>        &quot;Authority&quot;: &quot;https://auth.example.com&quot;,<br>        &quot;ValidAudiences&quot;: [<br>          &quot;https://api.example.com&quot;<br>        ],<br>        &quot;ValidIssuer&quot;: &quot;https://auth.example.com&quot;<br>      }<br>    }<br>  }<br>}</pre><p><strong>Summary</strong>:</p><p>So far, we’ve created a minimal API with two endpoints secured using JWT authentication and authorization. The /users endpoint requires an “admin” role, while /me only requires the user to be authenticated.</p><p><strong>Adding Integration Tests with TestJWTLibrary</strong></p><p><strong>Step 1</strong>: Add a Test Project</p><p>Create a test project in the solution and reference the API project. For this example, we use xUnit. Add the TestJWTLibrary NuGet package to generate JWT tokens for testing purposes.</p><p><strong>Step 2</strong>: Implement a Test Server</p><p>The test server uses WebApplicationFactory to spin up the API for testing with a custom configuration.</p><pre>public class TestServer(TestJWTLibrary.Generator generator) : WebApplicationFactory&lt;Program&gt;<br>{<br>    protected override void ConfigureWebHost(IWebHostBuilder builder)<br>    {<br>        base.ConfigureWebHost(builder);<br>        generator.ConfigureAuthentication(builder);<br>        builder.UseEnvironment(&quot;Test&quot;);<br>    }<br>}</pre><p><strong>Step 3</strong>: Write Integration Tests</p><p>Here are some test examples:</p><pre><br>public class APITest<br>{<br>    TestJWTLibrary.Generator generator = new();<br>    <br>    [Fact]<br>    public async Task AuthorizedRoleTest()<br>    {<br>        await using var factory = new TestServer(generator);<br>        var client = factory.CreateDefaultClient();<br>        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(&quot;Bearer&quot;, generator.GenerateJwt(additionalClaims:new Claim(&quot;role&quot;,&quot;admin&quot;)));<br>        var response = await client.GetAsync(&quot;/users&quot;);<br>        response.StatusCode.Should().Be(HttpStatusCode.OK);<br>    }<br>    <br>    [Fact]<br>    public async Task ForbbidenRoleTest()<br>    {<br>        await using var factory = new TestServer(generator);<br>        var client = factory.CreateDefaultClient();<br>        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(&quot;Bearer&quot;, generator.GenerateJwt());<br>        var response = await client.GetAsync(&quot;/users&quot;);<br>        response.StatusCode.Should().Be(HttpStatusCode.Forbidden);<br>    }<br>    <br>    [Fact]<br>    public async Task UnAuthorizedRoleTest()<br>    {<br>        await using var factory = new TestServer(generator);<br>        var client = factory.CreateDefaultClient();<br>        var response = await client.GetAsync(&quot;/users&quot;);<br>        response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);<br>    }<br>    <br>    [Fact]<br>    public async Task MeTest()<br>    {<br>        await using var factory = new TestServer(generator);<br>        var client = factory.CreateDefaultClient();<br>        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(&quot;Bearer&quot;, generator.GenerateJwt());<br>        var response = await client.GetFromJsonAsync&lt;UserInfo&gt;(&quot;/me&quot;);<br>        response.Name.Should().Be(&quot;john.doe&quot;);<br>    }<br>    <br>    [Fact]<br>    public async Task MeSpecificNameTest()<br>    {<br>        await using var factory = new TestServer(generator);<br>        var client = factory.CreateDefaultClient();<br>        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(&quot;Bearer&quot;, generator.GenerateJwt(userId:&quot;test&quot;));<br>        var response = await client.GetFromJsonAsync&lt;UserInfo&gt;(&quot;/me&quot;);<br>        response.Name.Should().Be(&quot;test&quot;);<br>    }<br>    <br>    [Fact]<br>    public async Task MeUnAuthorizedTest()<br>    {<br>        await using var factory = new TestServer(generator);<br>        var client = factory.CreateDefaultClient();<br>        var response = await client.GetAsync(&quot;/me&quot;);<br>        response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);<br>    }<br>    <br>    [Fact]<br>    public async Task UnAuthorizedTest()<br>    {<br>        await using var factory = new TestServer(generator);<br>        var client = factory.CreateDefaultClient();<br>        var response = await client.GetAsync(&quot;/me&quot;);<br>        response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);<br>    } <br>}</pre><p><strong>Summary</strong></p><p>In this article, we covered how to set up a .NET Minimal API with JWT-based authentication and authorization. We implemented two secure endpoints and wrote integration tests using TestJWTLibrary. This library simplifies creating JWTs for test scenarios, eliminating the need for long-lived tokens or external authentication systems.</p><p>Explore the TestJWTLibrary on GitHub: <a href="https://github.com/dejandjenic/TestJWTLibrary">https://github.com/dejandjenic/TestJWTLibrary</a></p><p>Happy coding! 🎉</p><p>Originally published at <a href="https://www.dejandjenic.com/blogs/testing-with-jwt.html">https://www.dejandjenic.com/blogs/testing-with-jwt.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98c9587b9b33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a .NET Tool and Publishing it from GitHub]]></title>
            <link>https://medium.com/@dejandjenic/creating-a-net-tool-and-publishing-it-from-github-b0652fd28c2b?source=rss-14d32b373b09------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0652fd28c2b</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[dotnet-tool]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[Dejan Đenić]]></dc:creator>
            <pubDate>Wed, 01 Jan 2025 12:17:44 GMT</pubDate>
            <atom:updated>2025-01-01T12:17:44.508Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Creating a .NET Tool and Publishing it from GitHub</strong></h3><p><strong>Introduction</strong></p><p>In the world of software development, creating custom tools can significantly enhance your workflow and streamline repetitive tasks.</p><p>.NET tools offer a powerful and versatile approach to building cross-platform command-line utilities specifically designed for the .NET ecosystem.</p><p>This article guides you through the process of creating a simple .NET tool and publishing it to GitHub, making it readily available for other developers.</p><p><strong>Benefits of Creating .NET Tools</strong></p><p>- Multiplatform Compatibility: .NET tools can seamlessly run on Windows, macOS, and Linux environments, ensuring broader accessibility.</p><p>- Global Tooling: Once published, your tool becomes accessible through the global tool pool, allowing users to invoke it from any project directory using the designated command.</p><p>- Reusable Functionality: Encapsulate common tasks within a .NET tool, promoting code reusability and reducing redundancy across projects.</p><p>- Improved Developer Experience: Streamline workflows by automating repetitive tasks and providing a consistent command-line interface for interacting with your code.</p><p><strong>Step by step</strong></p><p>Let’s embark on creating a .NET tool named HelloTool that demonstrates a basic greeting functionality.</p><p><strong>Project Setup</strong></p><p>- Open your terminal and navigate to the desired directory for your project.</p><p>- Execute the following command to create a new console application:</p><pre>dotnet new console -o HelloTool</pre><p>Replace HelloTool with your preferred tool name.</p><p>- Next, create a solution file using this command:</p><pre>dotnet new sln --name HelloTool</pre><p>- Integrate the newly created console application project into the solution:</p><pre>dotnet sln add HelloTool</pre><p><strong>Tool Implementation</strong></p><p>- Open the Program.cs file within the HelloTool project directory.</p><p>- Modify the Main method to incorporate the greeting logic:</p><pre>Console.WriteLine($&quot;Hello, {(args.Length&gt;0?args[0]:&quot;World&quot;)}!&quot;);</pre><p>This code checks for any command-line arguments passed to the tool. If an argument exists, it’s used as the name in the greeting. Otherwise, it defaults to “World.”</p><p><strong>Project Configuration for Packaging</strong></p><p>-Prepare your tool for deployment to the NuGet package repository (nuget.org).</p><p>- Create a file named README.md within your solution directory. Provide a comprehensive description of your tool’s purpose, usage instructions, and any relevant information for potential users.</p><p>- Modify the HelloTool.csproj file to include the following configurations:</p><pre>&lt;Project Sdk=&quot;Microsoft.NET.Sdk&quot;&gt;<br><br>  &lt;PropertyGroup&gt;<br>    &lt;OutputType&gt;Exe&lt;/OutputType&gt;<br>    &lt;TargetFramework&gt;net8.0&lt;/TargetFramework&gt;<br>    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;<br>    &lt;Nullable&gt;enable&lt;/Nullable&gt;<br><br>    &lt;PackAsTool&gt;true&lt;/PackAsTool&gt;<br>    &lt;ToolCommandName&gt;hello&lt;/ToolCommandName&gt;<br>    &lt;PackageOutputPath&gt;./nupkg&lt;/PackageOutputPath&gt;<br><br><br>    &lt;GeneratePackageOnBuild&gt;true&lt;/GeneratePackageOnBuild&gt;<br>    &lt;PackageId&gt;HelloTool&lt;/PackageId&gt;<br>    &lt;Authors&gt;your name&lt;/Authors&gt;<br>    &lt;Company&gt;tour email&lt;/Company&gt;<br>    &lt;Product&gt;HelloTool&lt;/Product&gt;<br>    &lt;PackageReadmeFile&gt;README.md&lt;/PackageReadmeFile&gt;<br>    &lt;PackageProjectUrl&gt;https://github.com/dejandjenic/hello-tool&lt;/PackageProjectUrl&gt;<br>  &lt;/PropertyGroup&gt;<br><br><br>  &lt;ItemGroup&gt;<br><br>    &lt;None Include=&quot;README.md&quot; Pack=&quot;true&quot; PackagePath=&quot;\&quot; /&gt;<br><br>  &lt;/ItemGroup&gt;<br>&lt;/Project&gt;</pre><p>This configuration specifies:</p><p>* PackAsTool: Indicates that the project should be packaged as a .NET tool.</p><p>* ToolCommandName: Defines the command used to invoke the tool from the command line (e.g., hello).</p><p>* PackageOutputPath: Sets the directory where the generated NuGet package will be placed.</p><p>* GeneratePackageOnBuild: Ensures the NuGet package is automatically created during the build process.</p><p>* PackageId, Authors, Company, Product: Provide details about your tool.</p><p>* PackageReadmeFile: Specifies the README.md file for documentation inclusion in</p><p>create a file called GetBuildVersion.psm1 and paste the code bellow</p><pre>Function GetBuildVersion {<br>    Param (<br>        [string]$VersionString<br>    )<br><br>    # Process through regex<br>    $VersionString -match &quot;(?&lt;major&gt;\d+)(\.(?&lt;minor&gt;\d+))?(\.(?&lt;patch&gt;\d+))?(\-(?&lt;pre&gt;[0-9A-Za-z\-\.]+))?(\+(?&lt;build&gt;\d+))?&quot; | Out-Null<br><br>    if ($matches -eq $null) {<br>        return &quot;1.0.0-build&quot;<br>    }<br><br>    # Extract the build metadata<br>    $BuildRevision = [uint64]$matches[&#39;build&#39;]<br>    # Extract the pre-release tag<br>    $PreReleaseTag = [string]$matches[&#39;pre&#39;]<br>    # Extract the patch<br>    $Patch = [uint64]$matches[&#39;patch&#39;]<br>    # Extract the minor<br>    $Minor = [uint64]$matches[&#39;minor&#39;]<br>    # Extract the major<br>    $Major = [uint64]$matches[&#39;major&#39;]<br><br>    $Version = [string]$Major + &#39;.&#39; + [string]$Minor + &#39;.&#39; + [string]$Patch;<br>    if ($PreReleaseTag -ne [string]::Empty) {<br>        $Version = $Version + &#39;-&#39; + $PreReleaseTag<br>    }<br><br>    if ($BuildRevision -ne 0) {<br>        $Version = $Version + &#39;.&#39; + [string]$BuildRevision<br>    }<br><br>    return $Version<br>}</pre><p><strong>treamlined Release Management with GitHub Actions</strong></p><p>This section outlines how to leverage GitHub Actions for automated versioning and publishing of your .NET tool.</p><p>1. Release Branching:</p><p>* Implement a release branching strategy. Create a branch named like release/1.2.3 for each version you intend to publish.</p><p>2. GitHub Actions Workflow:</p><p>* Set up a GitHub Actions workflow to automate the build and publish process. The workflow will be triggered whenever a new branch is created under the release/* path.</p><p>3. Automatic Versioning:</p><p>* Within the workflow, utilize a script (like the provided GetBuildVersion.psm1) to extract the version number from the branch name (e.g., 1.2.3 from release/1.2.3). This extracted version will be used during the build process.</p><p>4. NuGet API Key:</p><p>* Obtain a NuGet API key from nuget.org. This key grants access to publish packages to the repository.</p><p>5. GitHub Repository Secret:</p><p>* In your GitHub repository’s settings, navigate to the Secrets section and create a new secret named NUGET_KEY. Store the obtained NuGet API key as the value for this secret.</p><p>By following these steps, your GitHub Actions workflow will automatically handle version extraction, build the tool with the appropriate version, and publish the resulting NuGet package whenever a new release branch is created. This streamlines the release process and ensures consistency.</p><p>Navigate to the ‘Actions’ tab in your GitHub repository. Create a new workflow file (e.g., .github/workflows/dotnet.yml) and paste the following code into it.</p><pre><br>name: .NET<br><br>on:<br>  create:<br>    branches: <br>      - release/**<br>  push:<br>    branches: [ &quot;main&quot; ]<br>  pull_request:<br>    branches: [ &quot;main&quot; ]<br><br>jobs:<br>  build:<br><br>    runs-on: ubuntu-latest<br><br>    steps:<br>    - uses: actions/checkout@v4<br>    - name: Get Build Version<br>      run: |<br>        Import-Module .\build\GetBuildVersion.psm1<br>        Write-Host $Env:GITHUB_REF<br>        $version = GetBuildVersion -VersionString $Env:GITHUB_REF<br>        echo &quot;BUILD_VERSION=$version&quot; | Out-File -FilePath $Env:GITHUB_ENV -Encoding utf-8 -Append<br>      shell: pwsh<br>    - name: Setup .NET<br>      uses: actions/setup-dotnet@v4<br>      with:<br>        dotnet-version: 8.0.x<br>    - name: Restore dependencies<br>      run: dotnet restore<br>    - name: Build<br>      run: dotnet build --no-restore -p:Version=$BUILD_VERSION <br>    - name: Push<br>      if: startsWith(github.ref, &#39;refs/heads/release&#39;)<br>      run: dotnet nuget push **\*.nupkg --api-key &quot;${{ secrets.NUGET_KEY }}&quot; --source https://api.nuget.org/v3/index.json --skip-duplicate</pre><p>Create a release branch and verify the build and deployment process.</p><p>Once your tool is published on nuget execute in terminal</p><pre>dotnet tool install -g HelloTool</pre><p>after installlation process is finished you can use your tool</p><pre>hello dejan</pre><p>should output “Hello dejan!”</p><p>github repo with this sample can be found <a href="https://github.com/dejandjenic/hello-tool">https://github.com/dejandjenic/hello-tool</a></p><p>Originally published at <a href="https://www.dejandjenic.com/blogs/creating-dotnet-tool-and-publishing-it-from-github.html">https://www.dejandjenic.com/blogs/creating-dotnet-tool-and-publishing-it-from-github.html</a></p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0652fd28c2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional testing with testcontainers]]></title>
            <link>https://medium.com/@dejandjenic/functional-testing-with-testcontainers-d146573d41c6?source=rss-14d32b373b09------2</link>
            <guid isPermaLink="false">https://medium.com/p/d146573d41c6</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[testcontainer]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[functional-testing]]></category>
            <dc:creator><![CDATA[Dejan Đenić]]></dc:creator>
            <pubDate>Thu, 21 Dec 2023 08:14:11 GMT</pubDate>
            <atom:updated>2023-12-21T08:16:02.263Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*kmFE--rqIn8vsDS37Jj8Xw.png" /></figure><h3>Introduction</h3><p>Functional testing is a crucial aspect of software development, ensuring that your application functions as expected in real-world scenarios. However, testing components with external dependencies, such as databases and message brokers, can be challenging. In this article, we explore how the TestContainers library simplifies functional testing by managing these dependencies effectively. We’ll focus on using TestContainers with Google Cloud Platform’s (GCP) Firestore and PubSub services in a .NET environment.</p><h3>Setting Up the API Project</h3><p>I recently contributed to the TestContainers open-source library, with two of my pull requests included in the <a href="https://github.com/testcontainers/testcontainers-dotnet/releases/tag/3.6.0">3.6.0</a> release. In this guide, we’ll delve into the usage of GCP Firestore and PubSub features with TestContainers.</p><p>Let’s assume we have a simple API for managing a to-do list. Our API uses Firestore as the operational database, storing only active to-dos, while PubSub is employed to publish messages for every API action. This allows us to build a reporting system without relying on the operational database.</p><p>Start by creating a .NET 8 API project and adding the necessary references:</p><pre>Google.Cloud.Firestore<br>Google.Cloud.Firestore.V1<br>Google.Cloud.PubSub.V1<br>Microsoft.AspNetCore.OpenApi<br>Swashbuckle.AspNetCore</pre><p>Next, add the required classes for your API:</p><pre>[FirestoreData]<br>public class Todo<br>{<br>    [FirestoreDocumentId]<br>    public string Id { get; set; }<br>    [FirestoreProperty]<br>    public string Text { get; set; }<br>}</pre><h3>Creating the Firestore and PubSub Services</h3><pre>public interface ITodoRepository<br>{<br>    Task&lt;List&lt;Todo&gt;&gt; List();<br>    Task Add(Todo item);<br>    Task Delete(string id);<br>}</pre><pre>public class TodoRepository(FirestoreDb db) : ITodoRepository<br>{<br>    public const string TodoCollectionName = &quot;Todo&quot;;<br>    public async Task&lt;List&lt;Todo&gt;&gt; List()<br>    {<br>        return (await db.Collection(TodoCollectionName).GetSnapshotAsync()).<br>        Documents.<br>        Select(x =&gt; <br>            x.ConvertTo&lt;Todo&gt;()).<br>        ToList();<br>    }</pre><pre>    public async Task Add(Todo item)<br>    {<br>        await db.<br>            Collection(TodoCollectionName)<br>            .Document().<br>            CreateAsync(item);<br>    } <br>    <br>    public async Task Delete(string id)<br>    {<br>        await db.<br>            Collection(TodoCollectionName)<br>            .Document(id).<br>            DeleteAsync();<br>    } <br>}</pre><pre>public class BaseEvent<br>{<br>    public DateTime Date { get; set; } = DateTime.UtcNow;</pre><pre>    public string? Type =&gt; this.GetType().FullName;<br>}</pre><pre>public class TodoCreated : BaseEvent<br>{<br>    <br>}</pre><pre>public class TodoDeleted : BaseEvent<br>{<br>    <br>}</pre><pre>public interface IEventPublisher<br>{<br>    Task Publish(BaseEvent eventData);<br>}</pre><pre>public class EventPublisher(PublisherClientImpl client) : IEventPublisher<br>{<br>    public async Task Publish(BaseEvent eventData)<br>    {<br>        await client.PublishAsync(System.Text.Json.JsonSerializer.Serialize(eventData));<br>    }<br>}</pre><pre>public interface ITodoService<br>{<br>    Task&lt;List&lt;Todo&gt;&gt; List();<br>    Task Add(Todo item);<br>    Task Delete(string id);<br>}</pre><pre>public class TodoService(ITodoRepository repository,IEventPublisher eventPublisher) : ITodoService<br>{<br>    public Task&lt;List&lt;Todo&gt;&gt; List()<br>    {<br>        return repository.List();<br>    }<br>    <br>    public async Task Add(Todo item)<br>    {<br>        await eventPublisher.Publish(new TodoCreated());<br>        await repository.Add(item);<br>    } <br>    <br>    public async Task Delete(string id)<br>    {<br>        await eventPublisher.Publish(new TodoDeleted());<br>        await repository.Delete(id);<br>    } <br>}</pre><p>For abbreviation purposes, our Todo class serves both as a model for requests and an entity for the database, though it’s not considered good practice.</p><pre>public class AppSettings<br>{<br>    public string ProjectId { get; set; }<br>    public string TopicName { get; set; }<br>}</pre><p>Additionally, include an app configuration class and the main program file:</p><pre>var builder = WebApplication.CreateBuilder(args);</pre><pre>builder.Services.AddEndpointsApiExplorer();<br>builder.Services.AddSwaggerGen();</pre><pre>var appSettings = builder.Configuration.GetSection(&quot;AppSettings&quot;).Get&lt;AppSettings&gt;();<br>builder.Services.AddSingleton(appSettings);</pre><pre>builder.Services.AddSingleton(FirestoreDb.Create(appSettings.ProjectId));<br>builder.Services.AddSingleton((PublisherClientImpl)PublisherClientImpl.Create(new TopicName(appSettings.ProjectId,appSettings.TopicName)));<br>builder.Services.AddScoped&lt;ITodoRepository,TodoRepository&gt;();<br>builder.Services.AddScoped&lt;ITodoService,TodoService&gt;();<br>builder.Services.AddScoped&lt;IEventPublisher,EventPublisher&gt;();</pre><pre>var app = builder.Build();</pre><pre>if (app.Environment.IsDevelopment())<br>{<br>    app.UseSwagger();<br>    app.UseSwaggerUI();<br>}</pre><pre>app.UseHttpsRedirection();<br></pre><pre>app.MapGet(&quot;/todo&quot;, (ITodoService service) =&gt;  service.List())<br>    .WithName(&quot;GetTodos&quot;)<br>    .WithOpenApi();</pre><pre>app.MapPost(&quot;/todo&quot;, (ITodoService service,[FromBody]Todo model) =&gt;  service.Add(model))<br>    .WithName(&quot;CreateTodo&quot;)<br>    .WithOpenApi();</pre><pre>app.MapDelete(&quot;/todo/{id}&quot;, (ITodoService service,[FromRoute]string id) =&gt;  service.Delete(id))<br>    .WithName(&quot;DeleteTodo&quot;)<br>    .WithOpenApi();</pre><pre>app.Run();</pre><pre>public partial class Program{}</pre><p>after starting our api and checking swagger we would see something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qSm7wLfrSUGL7SHZ.png" /></figure><p>we have 3 endpoints</p><ol><li>list todos</li><li>create todo</li><li>delete todo</li></ol><p>we store and retrieve this information from firestore database and we publish pubsub message after creating and deleting todo.</p><h3>Writing Functional Tests</h3><p>Now, let’s add a test project to our solution and include the necessary references:</p><pre>FluentAssertions<br>Microsoft.AspNetCore.Mvc.Testing<br>Testcontainers.Firestore<br>Testcontainers.PubSub<br>Microsoft.NET.Test.Sdk</pre><p>Reference your API project from the test project and add the following classes:</p><pre>public class CustomWebApplicationFactory&lt;TProgram&gt;<br>    : WebApplicationFactory&lt;TProgram&gt; where TProgram : class<br>{<br>    public Func&lt;IServiceCollection,Task&gt; OverideServices { get; set; }<br>	<br>    protected override void ConfigureWebHost(IWebHostBuilder builder)<br>    {<br>        builder.ConfigureServices(svc =&gt;<br>        {<br>            if (OverideServices != null)<br>            {<br>                OverideServices(svc).GetAwaiter().GetResult();<br>            }<br>        });<br>    }<br>}</pre><pre>public class TestBase <br>    : IClassFixture&lt;CustomWebApplicationFactory&lt;Program&gt;&gt;<br>{<br>	<br>    private readonly CustomWebApplicationFactory&lt;Program&gt; _factory;<br>    protected HttpClient client;<br>    private static FirestoreDb firestoreDb;<br>    private static PublisherServiceApiClient publisher;<br>    private static SubscriberServiceApiClient subscriber;<br>    private static SubscriptionName subscriptionName;<br>    <br>    private static  Func&lt;IServiceCollection,Task&gt; OverideServices = async (svc) =&gt;<br>    {<br>        var appSettings = svc.BuildServiceProvider().GetRequiredService&lt;AppSettings&gt;();<br>        await SetupFirestore(svc,appSettings);</pre><pre>        await SetupPubSub(svc,appSettings);<br>    };</pre><pre>    private static async Task SetupFirestore(IServiceCollection svc, AppSettings appSettings)<br>    {<br>        FirestoreContainer _firestoreContainer = new FirestoreBuilder().Build();<br>        await _firestoreContainer.StartAsync();<br>        <br>        <br>        var firestoreDbBuilder = new FirestoreDbBuilder();<br>        firestoreDbBuilder.ProjectId = appSettings.ProjectId;<br>        firestoreDbBuilder.Endpoint = _firestoreContainer.GetEmulatorEndpoint();<br>        firestoreDbBuilder.ChannelCredentials = ChannelCredentials.Insecure;</pre><pre>        firestoreDb = await firestoreDbBuilder.BuildAsync();</pre><pre>        svc.AddSingleton(firestoreDb);<br>    }</pre><pre>    private static async Task SetupPubSub(IServiceCollection svc, AppSettings appSettings)<br>    {<br>        PubSubContainer _pubSubContainer = new PubSubBuilder().Build();<br>        await _pubSubContainer.StartAsync();<br>        <br>        <br>        var projectId = appSettings.ProjectId;<br>        var topicId = appSettings.TopicName;<br>        var subscriptionId = $&quot;{appSettings.TopicName}-sub&quot;;<br>		<br>        var topicName = new TopicName(projectId, topicId);<br>        subscriptionName = new SubscriptionName(projectId, subscriptionId);<br>		<br>        var publisherClientBuilder = new PublisherServiceApiClientBuilder();<br>        publisherClientBuilder.Endpoint = _pubSubContainer.GetEmulatorEndpoint();<br>        publisherClientBuilder.ChannelCredentials = ChannelCredentials.Insecure;<br>        <br>        var subscriberClientBuilder = new SubscriberServiceApiClientBuilder();<br>        subscriberClientBuilder.Endpoint = _pubSubContainer.GetEmulatorEndpoint();<br>        subscriberClientBuilder.ChannelCredentials = ChannelCredentials.Insecure;</pre><pre>	   <br>        publisher = await publisherClientBuilder.BuildAsync();<br>        subscriber = await subscriberClientBuilder.BuildAsync();<br>        <br>        publisher.CreateTopic(topicName);<br>        await subscriber.CreateSubscriptionAsync(subscriptionName, topicName, null, 60);<br>            <br>        svc.AddSingleton(<br>            new PublisherClientImpl(<br>                topicName, <br>                new List&lt;PublisherServiceApiClient&gt;() { publisher },<br>                new PublisherClient.Settings(), <br>                async () =&gt; { }));<br>    }</pre><pre>    public TestBase(CustomWebApplicationFactory&lt;Program&gt; factory)<br>    {<br>        _factory = factory;<br>        _factory.OverideServices = OverideServices;<br>        client = _factory.CreateClient();<br>    }</pre><pre>    public async Task ClearTodoCollection()<br>    {<br>        var collection = firestoreDb.Collection(TodoRepository.TodoCollectionName);<br>        foreach (var item in (await collection.GetSnapshotAsync()).Documents.Select(x=&gt; x.ConvertTo&lt;Todo&gt;()))<br>        {<br>            await collection.Document(item.Id).DeleteAsync();<br>        }<br>    }</pre><pre>    public async Task&lt;int&gt; CheckSubscription()<br>    {<br>        var messages = await subscriber.PullAsync(subscriptionName, 5);<br>        await subscriber.AcknowledgeAsync(subscriptionName,messages.ReceivedMessages.Select(x=&gt;x.AckId));<br>        return messages.ReceivedMessages.Count;<br>    }<br>	<br>}</pre><p>the code above is used as a test base class, when invoked it starts docker container for pubsub and firestore (by using TestContainers library) and sets up environment for it.</p><p>now we have to add some tests</p><pre>public class TodoTests : TestBase<br>{</pre><pre>    async Task&lt;List&lt;Todo&gt;&gt; GetTodos()<br>    {<br>        return (await client.GetFromJsonAsync&lt;List&lt;Todo&gt;&gt;(&quot;/todo&quot;))!;<br>    }<br>    <br>    private async Task&lt;string&gt; AddTodo()<br>    {<br>        var todoText = Guid.NewGuid().ToString();<br>        await client.PostAsJsonAsync(&quot;/todo&quot;, new Todo()<br>        {<br>            Text = todoText<br>        });<br>        return todoText;<br>    }<br>    <br>    private async Task DeleteTodo(string id)<br>    {<br>        await client.DeleteAsync($&quot;/todo/{id}&quot;);<br>    }<br>    <br>    [Fact]<br>    public async Task Should_Return_Empty_List()<br>    {<br>        var response = await GetTodos();<br>        response.Count.Should().Be(0);<br>    }<br>    <br>    [Fact]<br>    public async Task Should_Add_Todo()<br>    {<br>        var todos = await GetTodos();<br>        todos.Count.Should().Be(0);</pre><pre>        var todoText = await AddTodo();</pre><pre>        todos = await GetTodos();<br>        todos.Count.Should().Be(1);<br>        todos.FirstOrDefault()!.Text.Should().Be(todoText);</pre><pre>        await ClearTodoCollection();<br>        (await CheckSubscription()).Should().Be(1);<br>    }</pre><pre>    [Fact]<br>    public async Task Should_Delete_Todo()<br>    {<br>        var todos = await GetTodos();<br>        todos.Count.Should().Be(0);</pre><pre>        var todoText = await AddTodo();<br>        <br>        todos = await GetTodos();<br>        todos.Count.Should().Be(1);<br>        todos.FirstOrDefault()!.Text.Should().Be(todoText);<br>        <br>        await DeleteTodo(todos.FirstOrDefault()!.Id);<br>        <br>        todos = await GetTodos();<br>        todos.Count.Should().Be(0);<br>        <br>        await ClearTodoCollection();<br>        (await CheckSubscription()).Should().Be(2);<br>    }</pre><pre>    public TodoTests(CustomWebApplicationFactory&lt;Program&gt; factory) : base(factory)<br>    {<br>        <br>    }<br>}</pre><h3>Running the Tests and Analyzing Results</h3><p>test server will be started and will execute api project, we did setup and registered with api project DI a special version for our services that we want to use with emulator, no code is changed in api project to achieve this.</p><p>we created test for our api, we ensured that when we create a todo it will appear in the list of all todos, we ensured that when we delete a todo it will not be shown on the list. We tested that api produces pubsub messages.</p><p>if we run tests now we see similar output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2QWsoX8JrKRXZC9l.png" /></figure><p>all tests have passed and out code coverage is 98%.</p><h3>Conclusion</h3><p>In conclusion, using TestContainers simplifies functional testing by managing external dependencies effectively. In this guide, we explored its integration with GCP Firestore and PubSub, demonstrating how to set up an API project, write functional tests, and analyze the results. By following these practices, developers can ensure their applications are robust and reliable in real-world scenarios.</p><p>code used in this article can be found <a href="https://github.com/dejandjenic/GCPTestContainers">here</a></p><p>Originally published at <a href="https://www.dejandjenic.com/blogs/functional-testing-with-testcontainers.html">https://www.dejandjenic.com/blogs/functional-testing-with-testcontainers.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d146573d41c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Responsive Apps, A Guide to SignalR Integration with Azure]]></title>
            <link>https://medium.com/@dejandjenic/building-responsive-apps-a-guide-to-signalr-integration-with-azure-1aa2759257f7?source=rss-14d32b373b09------2</link>
            <guid isPermaLink="false">https://medium.com/p/1aa2759257f7</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[signalr]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Dejan Đenić]]></dc:creator>
            <pubDate>Thu, 30 Nov 2023 13:35:39 GMT</pubDate>
            <atom:updated>2023-11-30T13:35:39.673Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>SignalR is an impressive library and service from Microsoft designed for real-time applications.</p><p>In this example, we’ll explore how the SignalR library can be integrated with Azure’s hosted SignalR service. To begin, create a .NET 8 Web API project using the .NET 8 SDK.</p><p>When using Azure-hosted SignalR, the workflow should follow these steps:</p><ol><li>The client connects to the server application to obtain the SignalR endpoint (hosted on Azure) and an access token.</li><li>The SignalR library connects to the Azure Negotiate endpoint using the provided access token.</li><li>Once connected, communication between the client and server is enabled.</li></ol><h3>Code</h3><p>Let’s dive into the coding process.</p><p>First, create a configuration class named AppSettings to hold our configuration details:</p><pre>public class AppSettings<br>{<br>    public string AzureSignalREndpoint { get; set; }<br>}</pre><p>Next, define an interface for IHubContextStore:</p><pre>public interface IHubContextStore<br>{<br>    public ServiceHubContext ChatHubContext { get; }<br>}</pre><p>Now, implement the SignalRService class:</p><pre>using AzureSignalR;<br>using Microsoft.Azure.SignalR.Management;</pre><pre>public class SignalRService(AppSettings configuration, ILoggerFactory loggerFactory) : IHostedService, IHubContextStore<br>{<br>    private const string ChatHub = &quot;Chat&quot;;<br>    public ServiceHubContext ChatHubContext { get; private set; }</pre><pre>    async Task IHostedService.StartAsync(CancellationToken cancellationToken)<br>    {<br>        using var serviceManager = new ServiceManagerBuilder()<br>            .WithOptions(o=&gt;o.ConnectionString = configuration.AzureSignalREndpoint)<br>            .WithLoggerFactory(loggerFactory)<br>            .BuildServiceManager();<br>        ChatHubContext = await serviceManager.CreateHubContextAsync(ChatHub, cancellationToken);<br>    }</pre><pre>    Task IHostedService.StopAsync(CancellationToken cancellationToken)<br>    {<br>        return Task.WhenAll(Dispose(ChatHubContext));<br>    }</pre><pre>    private static Task Dispose(ServiceHubContext hubContext)<br>    {<br>        if (hubContext == null)<br>        {<br>            return Task.CompletedTask;<br>        }<br>        return hubContext.DisposeAsync();<br>    }<br>}</pre><p>and finally our Program.cs</p><pre>using AzureSignalR;<br>using Microsoft.AspNetCore.Mvc;</pre><pre>var builder = WebApplication.CreateBuilder(args);</pre><pre>var config = builder.Configuration.GetSection(&quot;AppSettings&quot;).Get&lt;AppSettings&gt;();<br>builder.Services.AddSingleton(config);</pre><pre>builder.Services.AddEndpointsApiExplorer();<br>builder.Services.AddSwaggerGen();</pre><pre>builder.Services.AddCors(x =&gt; <br>    x.AddDefaultPolicy(p=&gt;<br>        p.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin()<br>    )<br>);</pre><pre>builder.Services.AddSignalR().AddAzureSignalR(options =&gt;<br>{<br>    options.ConnectionString = config.AzureSignalREndpoint;<br>});</pre><pre>builder.Services<br>    .AddSingleton&lt;SignalRService&gt;()<br>    .AddHostedService(sp =&gt; sp.GetService&lt;SignalRService&gt;())<br>    .AddSingleton&lt;IHubContextStore&gt;(sp =&gt; sp.GetService&lt;SignalRService&gt;());</pre><pre>var app = builder.Build();</pre><pre>app.UseCors();</pre><pre>if (app.Environment.IsDevelopment())<br>{<br>    app.UseSwagger();<br>    app.UseSwaggerUI();<br>}</pre><pre>app.UseHttpsRedirection();</pre><pre>app.MapGet(&quot;/login&quot;, async ([FromServices]IHubContextStore store) =&gt;<br>{<br>    var negotiateResponse = await store.ChatHubContext.NegotiateAsync();<br>    return negotiateResponse;<br>});</pre><pre>app.UseAzureSignalR(routes =&gt;<br>{<br>    routes.MapHub&lt;Chat&gt;(&quot;/chat&quot;);<br>});</pre><pre>app.Run();</pre><p>This Program.cs file performs the following key tasks:</p><ol><li>Configuration Setup: Retrieves the configuration settings from the AppSettings class.</li><li>Swagger Support: Adds support for Swagger to document and test the API endpoints.</li><li>CORS Configuration: Enables Cross-Origin Resource Sharing (CORS) to allow communication between different origins.</li><li>SignalR Registration: Registers SignalR services and configures them to use the Azure SignalR endpoint.</li><li>SignalR Service Registration: Registers the SignalRService class as a singleton and hosted service, making it available for the application’s lifetime.</li><li>Azure SignalR Usage: Configures the application to use Azure SignalR with specified hub routes.</li><li>/login Endpoint: Defines an endpoint to negotiate and obtain the SignalR configuration (URL and access token) for the client.</li><li>Application Run: Starts the application.</li></ol><p>This Program.cs file acts as the entry point for the application, orchestrating the setup and configuration of various services, including SignalR integration with Azure.</p><p>For the client side, create an HTML file with the following content:</p><pre>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;style&gt;<br>        #messages {<br>            list-style: none<br>        }</pre><pre>        #messages li {<br>            margin-top: 10px;<br>        }</pre><pre>        #messages .user {<br>            background-color: #e1fce8;<br>            border-radius: 10px;<br>            padding: 10px;<br>        }</pre><pre>        #messages .system {<br>            text-align: right;<br>            background-color: #e1f0fc;<br>            border-radius: 10px;<br>            padding: 10px;<br>        }<br>    &lt;/style&gt;<br>    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.1/signalr.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;./index.js&quot;&gt;&lt;/script&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;ul id=&quot;messages&quot;&gt;&lt;/ul&gt;<br>    &lt;textarea id=&quot;text&quot; rows=&quot;10&quot; cols=&quot;50&quot;&gt;&lt;/textarea&gt;<br>    &lt;br&gt;<br>    &lt;button id=&quot;btn&quot;&gt;<br>        Send<br>    &lt;/button&gt;</pre><pre>    &lt;script&gt;<br>        init();<br>    &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Create a JavaScript file named index.js with the following content:</p><pre>function ajax(method, url, cb) {<br>  var xmlhttp = new XMLHttpRequest();</pre><pre>  xmlhttp.onreadystatechange = function () {<br>    if (xmlhttp.readyState == XMLHttpRequest.DONE) {<br>      if (xmlhttp.status == 200) {<br>        return cb(null, JSON.parse(xmlhttp.responseText));<br>      }<br>      cb(xmlhttp.status + &quot; error&quot;);<br>    }<br>  };</pre><pre>  xmlhttp.open(method, url, true);<br>  xmlhttp.send();<br>}</pre><pre>function addtext(message, cls) {<br>  var li = document.createElement(&quot;li&quot;);<br>  var text = document.createTextNode(message);<br>  li.appendChild(text);<br>  li.classList = [cls];<br>  document.getElementById(&quot;messages&quot;).appendChild(li);<br>}</pre><pre>function bindConnectionMessage(connection) {<br>  var messageCallback = function (name, message) {<br>    if (!message) return;<br>    addtext(message, &quot;system&quot;);<br>  };  <br>  connection.on(&quot;echo&quot;, messageCallback);<br>}<br></pre><pre>var connection;<br></pre><pre>function connect(url, token) {<br>  connection = new signalR.HubConnectionBuilder()<br>    .withUrl(url, { accessTokenFactory: () =&gt; token })<br>    .build();</pre><pre>  bindConnectionMessage(connection);<br>  connection<br>    .start()<br>    .catch(function (error) {<br>      console.error(error.message);<br>    });<br>}</pre><pre>ajax(&quot;GET&quot;, &quot;http://localhost:5065/login&quot;, function (err, data) {<br>  connect(data.url, data.accessToken);<br>});</pre><pre>function init() {<br>  document.getElementById(&quot;btn&quot;).addEventListener(&quot;click&quot;, async (e) =&gt; {<br>    try {<br>      var message = document.getElementById(&quot;text&quot;).value;<br>      addtext(message, &quot;user&quot;);<br>      document.getElementById(&quot;text&quot;).value = &quot;&quot;;<br>      await connection.invoke(&quot;echo&quot;, &quot;user&quot;, message);<br>    } catch (err) {<br>      console.error(err);<br>    }<br>  });<br>}</pre><p>This simple client is sufficient for testing our Azure SignalR instance. When both the server and client are running, the result should resemble the image below:</p><h3>Conclusion:</h3><p>In conclusion, leveraging SignalR in conjunction with Azure’s hosted SignalR service empowers developers to create dynamic, real-time applications with ease. The seamless integration of SignalR into the Azure environment streamlines the process of building responsive and interactive applications that can handle communication between clients and servers in real-time.</p><p>Throughout this article, we’ve covered the essential steps, from project setup and configuration to the implementation of SignalR services. The code examples provided demonstrate how to connect clients to the Azure SignalR service, facilitating instant communication and collaboration.</p><p>By adopting this approach, developers can harness the power of SignalR to enhance user experiences, making applications more engaging and responsive. Whether you’re building a chat application, live updates for a dashboard, or any other real-time feature, SignalR on Azure proves to be a robust solution.</p><p>As you embark on your real-time application development journey, keep in mind the flexibility and scalability that Azure SignalR brings to the table. Consider exploring additional Azure services to complement your real-time solutions and meet the specific needs of your application.</p><p>In summary, SignalR on Azure opens up a realm of possibilities for developers looking to create modern, responsive applications that thrive in the world of real-time communication.</p><p>sample code can be found here: <a href="https://github.com/dejandjenic/AzureSignalR">https://github.com/dejandjenic/AzureSignalR</a></p><p>Originally published at <a href="https://www.dejandjenic.com/blogs/azure-signalr.html">https://www.dejandjenic.com/blogs/azure-signalr.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1aa2759257f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Workflow Management with the XWorkflows Library]]></title>
            <link>https://medium.com/@dejandjenic/simplifying-workflow-management-with-the-xworkflows-library-a8c1787c756a?source=rss-14d32b373b09------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8c1787c756a</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[workflow]]></category>
            <dc:creator><![CDATA[Dejan Đenić]]></dc:creator>
            <pubDate>Sun, 19 Nov 2023 12:58:29 GMT</pubDate>
            <atom:updated>2023-11-19T12:58:29.972Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*Q7yGI22jv-jaeGsgcisH0Q.png" /></figure><h3>Introduction</h3><p>Managing complex workflows within software applications can quickly become a challenge, especially when dealing with multiple states, actions, and entities. Navigating the intricacies of transitioning between these states while ensuring data integrity can lead to spaghetti code and maintenance headaches. Fortunately, the XWorkflows library emerges as a powerful tool to address these concerns, offering an elegant and efficient solution for managing workflow behavior.</p><h3>Installation</h3><p>Before we dive into the details, let’s get started with the installation process. The XWorkflows library is conveniently available on NuGet, making it effortless to integrate into your projects. To install the library, follow these simple steps:</p><p>Open your NuGet Package Manager Console.</p><p>Run the following command:</p><pre>Install-Package XWorkflows</pre><p>The library and its dependencies will be fetched and installed into your project.</p><p>With the XWorkflows library in your toolkit, you’re ready to explore how it simplifies and enhances workflow management within your software applications.</p><h3>Basic Concepts</h3><p>At the heart of the XWorkflows library lie several fundamental concepts that form the building blocks of effective workflow management. Let’s briefly explore these concepts before diving into practical implementation:</p><p>Workflow Entities: These are the subjects of your workflows, entities that undergo state transitions based on actions. The library provides a framework to manage the state changes of these entities gracefully.</p><p>Workflow Actions: Actions encapsulate specific tasks that can be executed on entities. They define the logic associated with each transition and can lead to changes in the entity’s state.</p><p>Workflow Events: Events are triggered upon successful action execution. They allow for additional tasks such as logging, notifications, and post-action execution logic.</p><p>Workflow States: States represent the various stages an entity can go through. Each state defines the actions that can be performed from it, encapsulating the logic for transitioning.</p><p>Workflow: A workflow brings all these pieces together, organizing and orchestrating the execution of actions and managing the state transitions of entities.</p><p>With these core concepts in mind, let’s delve into how to implement and utilize the XWorkflows library to achieve effective workflow management in your applications.</p><p>In the following sections, we’ll guide you through the process of setting up workflows, defining actions and states, handling errors, and exploring advanced features that allow for tailored customization and efficient workflow management. Let’s get started!</p><h3>Getting Started</h3><p>Now that we have a foundational understanding of the core concepts of the XWorkflows library, let’s dive into getting started with practical implementation.</p><h3>Defining Entities</h3><p>Entities are at the center of your workflow management. They represent the objects that undergo state transitions as actions are executed. To define an entity that can be managed by XWorkflows, you’ll need to create a class that implements the IWorkflowStateEntity interface. This interface provides the necessary methods to retrieve and update the entity’s state.</p><pre>public class OrderEntity : IWorkflowStateEntity&lt;State&gt;<br>{<br>    public string Identifier { get; set; }<br>    public State State { get; set; }<br><br>    public async Task&lt;string&gt; GetIdentifier()<br>    {<br>        return Identifier;<br>    }<br><br>    public async Task&lt;State&gt; GetState()<br>    {<br>        return State;<br>    }<br><br>    public async Task SetState(State state, string identifier)<br>    {<br>        State = state;<br>    }<br>}</pre><h3>Creating Actions</h3><p>Actions define the specific tasks that can be executed within a workflow. They encapsulate the logic associated with state transitions and can be triggered by external events or triggers. To create a custom action, you’ll need to inherit from the WorkflowAction class provided by the library.</p><pre>public class SubmitOrderAction : WorkflowAction&lt;OrderWorkflow, SubmitOrderEvent, CreatedState, OrderEntity, State, SubmitOrderActionRequest, SubmitOrderActionRequest, bool&gt;<br>{<br>    public SubmitOrderAction(CreatedState state, SubmitOrderEvent e) : base(state, e)<br>    {<br>    }<br><br>    public override async Task&lt;(WorkflowActionResult&lt;bool&gt;, SubmitOrderActionRequest)&gt; Execute(OrderEntity data, SubmitOrderActionRequest p, CancellationToken cancellationToken)<br>    {<br>        // Custom logic for submitting an order<br>        // Transition the entity&#39;s state and perform necessary tasks<br><br>        return (WorkflowActionResult&lt;bool&gt;.Succeeded(true), p);<br>    }<br>}</pre><h3>Creating Events</h3><p>Events provide the opportunity to perform tasks after an action is successfully executed. They can include tasks such as logging, sending notifications, or updating related data. To create an event, implement the IWorkflowEvent interface or derive from the WorkflowEvent class.</p><pre>public class SubmitOrderEvent : WorkflowEvent&lt;OrderWorkflow, CreatedState, OrderEntity, State&gt;<br>{<br>    public override async Task Execute(OrderEntity data, CancellationToken cancellationToken)<br>    {<br>        // Perform post-action tasks like logging or notifications<br>    }<br>}</pre><p>In the next sections of this article, we will cover more advanced topics such as error handling, managing multiple workflows, and customizing action/event execution. We will also provide practical examples showcasing how the XWorkflows library can be applied to real-world scenarios to simplify workflow management.</p><p>Stay tuned for Part 2 of this article where we dive deeper into these concepts and demonstrate their implementation with comprehensive code examples.</p><h3>Conclusion</h3><p>The XWorkflows library offers a powerful solution to the complexities of workflow management within software applications. By embracing its core concepts of entities, actions, events, states, and workflows, developers can create well-organized and efficient workflow systems that ensure data integrity and simplify maintenance. In Part 2 of this article, we’ll explore more advanced features and dive into practical examples, enabling you to harness the full potential of the XWorkflows library for your projects.</p><h3>Advanced Features and Practical Examples</h3><p>Welcome to Part 2 of our article on simplifying workflow management with the XWorkflows library. In this section, we will explore more advanced features and delve into practical examples to demonstrate the versatility and power of the library.</p><h3>Error Handling</h3><p>As any software system grows, handling errors becomes crucial. In the XWorkflows library, error handling is well-integrated to ensure smooth workflow execution even in the face of unexpected situations. The library provides mechanisms to handle invalid state transitions and exceptions during action execution.</p><pre>try<br>{<br>    // Execute an action within a workflow<br>    var actionRequest = new CustomActionRequest { /* Request data */ };<br>    var (result, response) = await workflow.ExecuteAction(entity, actionRequest);<br>}<br>catch (WorkflowException ex)<br>{<br>    // Handle the exception<br>    Console.WriteLine($&quot;Workflow Error: {ex.Message}&quot;);<br>}</pre><h3>Managing Multiple Workflows</h3><p>In real-world applications, managing workflows for different entities is common. The XWorkflows library excels in this area, allowing you to define and manage separate workflows with their own states and actions.</p><pre>var orderWorkflow = new OrderWorkflow(actionsForOrder);<br>var taskWorkflow = new TaskWorkflow(actionsForTask);<br><br>// Execute actions within respective workflows<br>await orderWorkflow.ExecuteAction(orderEntity, submitOrderRequest);<br>await taskWorkflow.ExecuteAction(taskEntity, updateStatusRequest);</pre><h3>Customizing Action and Event Execution</h3><p>The flexibility of the XWorkflows library extends to customizing the execution of actions and events. You can override methods within action and event classes to inject custom logic before and after execution.</p><pre>public class CustomAction : WorkflowAction&lt;MyWorkflow, MyEvent, MyState, MyEntity, State, CustomRequest, CustomRequest, bool&gt;<br>{<br>    protected CustomAction(MyState state, MyEvent e) : base(state, e)<br>    {<br>    }<br><br>    public override async Task&lt;(WorkflowActionResult&lt;bool&gt;, CustomRequest)&gt; Execute(MyEntity data, CustomRequest p, CancellationToken cancellationToken)<br>    {<br>        // Custom pre-execution logic<br>        Log(&quot;Executing CustomAction...&quot;);<br><br>        var result = await base.Execute(data, p, cancellationToken);<br><br>        // Custom post-execution logic<br>        Log(&quot;CustomAction executed successfully!&quot;);<br><br>        return result;<br>    }<br>}</pre><h3>Practical Examples</h3><p>In this part of the article, we’ll provide practical examples showcasing the XWorkflows library in action:</p><p>Order Processing Workflow: We’ll demonstrate how to implement a complete order processing workflow using XWorkflows. This example will cover the submission, cancellation, and delivery of orders, each with their respective actions and events.</p><p>Task Management Workflow: We’ll dive into creating a workflow for managing tasks. This example will guide you through the definition of states, actions, and events to handle task status updates, completions, and cancellations.</p><p>Approval Workflow: This example will showcase an approval workflow for managing document approval processes. We’ll cover submitting documents for approval, approving/rejecting them, and leveraging events for notifications.</p><h3>Conclusion</h3><p>In this section, we’ve explored advanced features of the XWorkflows library that empower developers to handle error scenarios, manage multiple workflows, and customize action/event execution. We’ve also introduced practical examples that highlight the versatility and practicality of the library in real-world scenarios.</p><p>By harnessing the power of the XWorkflows library, developers can simplify and streamline complex workflow management, leading to more maintainable, organized, and efficient software applications.</p><p>Stay tuned for the upcoming examples, where we’ll walk you through the implementation details of the order processing, task management, and approval workflows.</p><h3>Practical Examples</h3><p>Welcome to Part 3 of our article on simplifying workflow management with the XWorkflows library. In this section, we will dive into practical examples that demonstrate the library’s capabilities in real-world scenarios.</p><h3>Example 1: Order Processing Workflow</h3><p>In this example, we’ll walk you through the implementation of an order processing workflow using the XWorkflows library.</p><p>Scenario Consider an e-commerce platform where orders transition through different states: “Created,” “Submitted,” “Delivered,” and “Canceled.” We will create actions for submitting, canceling, and delivering orders, along with events for logging and notifications.</p><p>Implementation Define the Order Entity:</p><p>Create a class OrderEntity that implements IWorkflowStateEntity. This class will hold the order’s identifier and state.</p><pre>// Define the OrderEntity class<br>// https://github.com/dejandjenic/XWorkflows.Examples</pre><p>Create Actions and Events:</p><p>Define actions for submitting, canceling, and delivering orders. Create corresponding events for each action to handle post-action tasks.</p><pre>// Define actions and events<br>// https://github.com/dejandjenic/XWorkflows.Examples</pre><p>Define States:</p><p>Create classes for each order state, inheriting from WorkflowStateBase&lt;OrderEntity, State, OrderWorkflow&gt;. Define the allowed transitions for each state.</p><pre>// Define states<br>// https://github.com/dejandjenic/XWorkflows.Examples</pre><p>Create the OrderWorkflow:</p><p>Define the OrderWorkflow class, registering the actions and states.</p><pre>// Create the OrderWorkflow class<br>// https://github.com/dejandjenic/XWorkflows.Examples</pre><p>Execute Workflow Actions:</p><p>Instantiate the OrderEntity and execute actions within the workflow.</p><pre>// Instantiate OrderEntity<br>var order = new OrderEntity { /* Initialize properties */ };<br><br>// Execute actions within the workflow<br>var submitRequest = new SubmitOrderActionRequest { /* Request data */ };<br>var (submitResult, submitResponse) = await orderWorkflow.ExecuteAction(order, submitRequest);</pre><h3>Example 2: Task Management Workflow</h3><p>In this example, we&#39;ll guide you through the implementation of a task management workflow using the XWorkflows library.</p><p>Scenario Imagine a task management application where tasks transition through states: &quot;Open,&quot; &quot;In Progress,&quot; &quot;Completed,&quot; and &quot;Canceled.&quot; We&#39;ll define actions for updating task status, marking tasks as completed, and canceling tasks.</p><p>Implementation Define the Task Entity:</p><p>Create a class TaskEntity that implements IWorkflowStateEntity. This class will store the task&#39;s identifier and state.</p><pre>// Define the TaskEntity class<br>// https://github.com/dejandjenic/XWorkflows.Examples</pre><p>Create Actions and Events:</p><p>Define actions for updating task status, completing tasks, and canceling tasks. Implement corresponding events for post-action tasks.</p><pre>// Define actions and events<br>// https://github.com/dejandjenic/XWorkflows.Examples</pre><p>Define States:</p><p>Create classes for each task state, inheriting from WorkflowStateBase&lt;TaskEntity, State, TaskWorkflow&gt;. Specify allowed transitions for each state.</p><pre>// Define states<br>// https://github.com/dejandjenic/XWorkflows.Examples</pre><p>Create the TaskWorkflow:</p><p>Define the TaskWorkflow class, registering actions and states.</p><pre>// Create the TaskWorkflow class<br>// https://github.com/dejandjenic/XWorkflows.Examples</pre><p>Execute Workflow Actions:</p><p>Instantiate the TaskEntity and execute actions within the workflow.</p><pre>// Instantiate TaskEntity<br>var task = new TaskEntity { /* Initialize properties */ };<br><br>// Execute actions within the workflow<br>var updateStatusRequest = new UpdateTaskStatusActionRequest { /* Request data */ };<br>var (updateStatusResult, updateStatusResponse) = await taskWorkflow.ExecuteAction(task, updateStatusRequest);</pre><h3>Example 3: Approval Workflow</h3><p>In our final example, we&#39;ll showcase the XWorkflows library&#39;s application in an approval workflow scenario.</p><p>Scenario Consider a document approval process with states: &quot;Draft,&quot; &quot;Pending Approval,&quot; &quot;Approved,&quot; and &quot;Rejected.&quot; We&#39;ll create actions for submitting documents, approving/rejecting them, and events for notifications.</p><p>Implementation Define the Document Entity:</p><p>Create a class DocumentEntity implementing IWorkflowStateEntity. This class will hold the document&#39;s identifier and state.</p><pre>// Define the DocumentEntity class<br>// https://github.com/dejandjenic/XWorkflows.Examples</pre><p>Create Actions and Events:</p><p>Define actions for submitting documents, approving them, and rejecting them. Create corresponding events for notifications.</p><pre>// Define actions and events<br>// https://github.com/dejandjenic/XWorkflows.Examples</pre><p>Define States:</p><p>Create classes for each document state, inheriting from WorkflowStateBase&lt;DocumentEntity, State, ApprovalWorkflow&gt;. Specify allowed transitions.</p><pre>// Define states<br>// https://github.com/dejandjenic/XWorkflows.Examples</pre><p>Create the ApprovalWorkflow:</p><p>Define the ApprovalWorkflow class, registering actions and states.</p><pre>// Create the ApprovalWorkflow class<br>// https://github.com/dejandjenic/XWorkflows.Examples</pre><p>Execute Workflow Actions:</p><p>Instantiate the DocumentEntity and execute actions within the workflow.</p><pre>// Instantiate DocumentEntity<br>var document = new DocumentEntity { /* Initialize properties */ };<br><br>// Execute actions within the workflow<br>var submitRequest = new SubmitForApprovalActionRequest { /* Request data */ };<br>var (submitResult, submitResponse) = await approvalWorkflow.ExecuteAction(document, submitRequest);</pre><h3>Conclusion</h3><p>In this section, we&#39;ve explored practical examples that demonstrate how the XWorkflows library can be applied to real-world scenarios. Through the order processing, task management, and approval workflow examples, we&#39;ve showcased the library&#39;s versatility and power in simplifying workflow management within software applications.</p><p>By following these examples and harnessing the capabilities of the XWorkflows library, developers can efficiently manage complex workflows, ensure data integrity, and achieve organized and maintainable software systems.</p><p>XWorkflows Examples GitHub Repository: <a href="https://github.com/dejandjenic/XWorkflows.Examples">https://github.com/dejandjenic/XWorkflows.Examples</a></p><p>NuGet Package: XWorkflows</p><p>Originally published at <a href="https://www.dejandjenic.com/blogs/workflow-management.html">https://www.dejandjenic.com/blogs/workflow-management.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8c1787c756a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Cross-Platform Deployment: Blazor WASM Applications with Electron.js]]></title>
            <link>https://medium.com/@dejandjenic/mastering-cross-platform-deployment-blazor-wasm-applications-with-electron-js-509dc4338450?source=rss-14d32b373b09------2</link>
            <guid isPermaLink="false">https://medium.com/p/509dc4338450</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[blazor]]></category>
            <category><![CDATA[electron]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Dejan Đenić]]></dc:creator>
            <pubDate>Thu, 31 Aug 2023 08:24:35 GMT</pubDate>
            <atom:updated>2023-08-31T08:24:35.215Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Cross-Platform Deployment: Blazor WASM Applications with Electron.js and Auto-Updates via GitHub Actions</h3><p><strong>Introduction</strong></p><p>In the dynamic landscape of web application development, the need to bring web technologies closer to the desktop experience has led to innovative solutions. In this tutorial, we will explore the fusion of Blazor WebAssembly (WASM) with Electron.js — a framework for building cross-platform desktop applications using web technologies. By combining these two technologies, we can deliver the power of Blazor WASM applications in a standalone desktop environment.</p><p><strong>Prerequisites</strong></p><p>Before we dive into the deployment process, make sure you have the following prerequisites set up:</p><p>A functional Blazor application (You can refer to my previous article on <a href="https://medium.com/@dejandjenic/exploring-blazor-and-deployment-options-da81c2c301aa">https://medium.com/@dejandjenic/exploring-blazor-and-deployment-options-da81c2c301aa</a> for guidance on setting up a Blazor project).</p><p><strong>Project Setup</strong></p><p>To embark on this journey, we’ll create a new repository and structure our project accordingly:</p><ul><li>Create a new repository for your project.</li><li>Inside this repository, create a directory named “blazor” to hold your existing Blazor application files.</li><li>Copy all the Blazor application files from your previous repository to the “blazor” directory.</li><li>Additionally, create an “electron-app” directory at the root of your repository.</li></ul><p><strong>Initializing Electron.js</strong></p><p>Our next step involves setting up Electron.js to create the bridge between our Blazor application and the desktop environment:</p><ul><li>Navigate to the “electron-app” directory and execute the following commands:</li></ul><pre>npm init<br>npm install electron --save-dev</pre><ul><li>These commands will initialize a new project and add Electron as a development dependency.</li></ul><pre>// main.js<br><br>// Modules to control application life and create native browser window<br>const { app, BrowserWindow } = require(&#39;electron&#39;)<br>const path = require(&#39;path&#39;)<br>require(&#39;update-electron-app&#39;)(<br><br>)<br><br>const createWindow = () =&gt; {<br>  console.log(__dirname)<br>  // Create the browser window.<br>  const mainWindow = new BrowserWindow({<br>    width: 800,<br>    height: 600,<br>    webPreferences: {<br>      preload: path.join(__dirname, &#39;preload.js&#39;),      <br>    }<br>  })<br><br>  // and load the index.html of the app.<br>  mainWindow.loadFile(&#39;index.html&#39;)  <br>  <br>  // Open the DevTools.<br>  // mainWindow.webContents.openDevTools()<br>}<br><br>// This method will be called when Electron has finished<br>// initialization and is ready to create browser windows.<br>// Some APIs can only be used after this event occurs.<br>app.whenReady().then(() =&gt; {<br>  createWindow()<br><br>  app.on(&#39;activate&#39;, () =&gt; {<br>    // On macOS it&#39;s common to re-create a window in the app when the<br>    // dock icon is clicked and there are no other windows open.<br>    if (BrowserWindow.getAllWindows().length === 0) createWindow()<br>  })<br>})<br><br>// Quit when all windows are closed, except on macOS. There, it&#39;s common<br>// for applications and their menu bar to stay active until the user quits<br>// explicitly with Cmd + Q.<br>app.on(&#39;window-all-closed&#39;, () =&gt; {<br>  if (process.platform !== &#39;darwin&#39;) app.quit()<br>})<br><br>// In this file you can include the rest of your app&#39;s specific main process<br>// code. You can also put them in separate files and require them here.</pre><p><strong>Loading the Blazor Application</strong></p><p>To integrate our Blazor application, we’ll create a script named loadBlazor.js. This script adjusts the base URL and loads the Blazor scripts:</p><pre><br>function addScript(value, element, prop){<br>    var el = document.createElement(element);<br>    el[prop] = value;<br>    document.getElementsByTagName(&#39;head&#39;)[0].appendChild(el);<br>    return el;<br>}<br><br>let url = document.baseURI.replace(&quot;index.html&quot;,&quot;&quot;)<br><br>addScript(url, &quot;base&quot;, &quot;href&quot;)<br>addScript(url + &quot;_framework/blazor.webassembly.js&quot;, &quot;script&quot;, &quot;src&quot;)<br><br>setTimeout(()=&gt;{<br>    addScript(url, &quot;a&quot;, &quot;href&quot;).click()<br>},1000)</pre><p><strong>Electron Forge for Packaging and Publishing</strong></p><p>Electron Forge simplifies packaging and publishing our Electron application. Let’s add necessary dependencies and create configuration files:</p><ul><li>Install Electron Forge:</li></ul><pre>npm install --save-dev @electron-forge/cli @electron-forge/publisher-github</pre><ul><li>Create a forge.config.js configuration file:</li></ul><pre>module.exports = {<br>  packagerConfig: {<br>    asar: true,<br>  },<br>  rebuildConfig: {},<br>  makers: [<br>    {<br>      name: &#39;@electron-forge/maker-squirrel&#39;,<br>      config: {},<br>    },<br>    {<br>      name: &#39;@electron-forge/maker-zip&#39;,<br>      platforms: [&#39;darwin&#39;],<br>    },<br>    {<br>      name: &#39;@electron-forge/maker-deb&#39;,<br>      config: {},<br>    },<br>    {<br>      name: &#39;@electron-forge/maker-rpm&#39;,<br>      config: {},<br>    },<br>  ],<br>  plugins: [<br>    {<br>      name: &#39;@electron-forge/plugin-auto-unpack-natives&#39;,<br>      config: {},<br>    },<br>  ],<br>  publishers: [<br>    {<br>      name: &#39;@electron-forge/publisher-github&#39;,<br>      config: {<br>        repository: {<br>          owner: &#39;dejandjenic&#39;,<br>          name: &#39;BlazorPlaygroundElectron&#39;<br>        },<br>        prerelease: false<br>      }<br>    }<br>  ]<br>};</pre><p>This configuration demonstrates that you’re generating application packages for different platforms like Windows, macOS, Debian-based (Linux), and RPM-based (Linux) distributions.</p><p>Additionally, in your GitHub Actions workflow configuration, you could highlight that the pipeline runs on different operating systems:</p><pre>name: Blazor Playground<br><br>on:<br>  push:<br>    tags:<br>      - &#39;*&#39;<br><br>jobs:  <br>  release:<br>    runs-on: ${{ matrix.os }}<br><br>    strategy:<br>      matrix:<br>        os: [windows-latest, ubuntu-latest, macos-latest]<br><br>    steps:<br>      - name: Check out Git repository<br>        uses: actions/checkout@v1<br><br>      - name: Setup .NET Core<br>        uses: actions/setup-dotnet@v2<br>        with:<br>          dotnet-version: &#39;7.0&#39;<br><br>    <br>      - name: Publish<br>        run: dotnet publish blazor/BlazorPlayground.csproj -c Release -o release<br>      - name: Install ReplaceInFile<br>        run: dotnet tool install --tool-path . ReplaceInFile<br>      - name: Modify original file index.html<br>        run: ./replaceinfile &quot;release/wwwroot/index.html&quot; &#39;&lt;base href=\&quot;/\&quot; /&gt;&#39; &quot;&quot;<br>      - name: Modify original file index.html<br>        run: ./replaceinfile &quot;release/wwwroot/index.html&quot; &#39;&lt;script src=\&quot;_framework/blazor.webassembly.js\&quot;&gt;&lt;/script&gt;&#39; &quot;&quot;<br>      - name: Modify original file index.html<br>        run: ./replaceinfile &quot;release/wwwroot/index.html&quot; &quot;&lt;/body&gt;&quot; &#39;&lt;script src=\&quot;loadBlazor.js\&quot;&gt;&lt;/script&gt;&lt;/body&gt;&#39;<br>      - name: Copy blazor output<br>        run: cp -r ./release/wwwroot/* ./electron-app/<br>        <br>      - name: Install Node.js, NPM and Yarn<br>        uses: actions/setup-node@v3<br>        with:<br>          node-version: 20<br><br>      - name: Restore npm dependencies<br>        run: npm ci<br>        working-directory: ./electron-app/<br><br>      - name: Publish app<br>        run: npm run publish<br>        working-directory: ./electron-app/<br>        if: github.ref_type == &#39;tag&#39;<br>        env:<br>          GITHUB_TOKEN: ${{ github.token }}</pre><p>By specifying different operating systems like Windows, Ubuntu (Linux), and macOS in the workflow, you’re implicitly indicating that the application is being built and tested for these platforms.</p><p>Remember, you can adjust these sections to provide clearer details about your application’s cross-platform compatibility and the role of Electron Forge in generating packages for different operating systems.</p><p><strong>Images</strong></p><p>Setting required permissions for GitHub actions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*6BGjAms_4doeE--zxw6gCw.png" /></figure><p>Draft release created by publishing electron app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zJ9EWX_JODv1RPHT2gtPwA.png" /></figure><p>Released version</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QNmgMxse79iirIZpF2fYlQ.png" /></figure><p>Running application on windows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1U34j3u7kEcl6Fq2JBSUQ.png" /></figure><p>Application is being updated</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*Pxe79tbGsndqosKd2nE_PA.png" /></figure><p><strong>Conclusion: Elevating Your Application with Auto-Updates and CI/CD</strong></p><p>In the realm of application deployment, the marriage of Blazor WASM and Electron.js brings forth an integration that bridges web experiences and desktop functionality. Throughout this tutorial, we’ve traversed the complete journey, from establishing a project structure to deploying your application via Electron Forge. However, the story doesn’t end here — two integral factors deserve special attention: Auto-Updates and Continuous Integration and Continuous Deployment (CI/CD) through GitHub Actions.</p><p><strong>Empowering User Experience with Auto-Updates</strong></p><p>Introducing an invaluable feature, Electron.js brings automatic updates to the forefront. This game-changing capability ensures that your application remains current, delivering bug fixes, feature enhancements, and security patches seamlessly, without requiring manual user interventions. The result is an elevated user experience, an aspect pivotal to the success of any Electron application.</p><p><strong>Exemplifying Auto-Update in Our Project</strong></p><p>Within our project, the auto-update functionality is seamlessly integrated using the update-electron-app package. When a new version is released, users are prompted to update, ensuring they continually benefit from the latest improvements. This feature not only improves the user experience but also streamlines the maintenance process for developers.</p><p><strong>Effortless Releases with CI/CD through GitHub Actions</strong></p><p>The journey doesn’t stop with auto-updates; we’ve also embraced the prowess of GitHub Actions for CI/CD. By leveraging this automation tool, the deployment process transforms into an orchestrated symphony of tasks. Each release, when tagged, triggers a cascade of actions: building, packaging, and publishing. GitHub Actions introduces consistency and reliability to your deployment pipeline, significantly reducing manual intervention and potential errors.</p><p><strong>Unleash Your Application’s Potential</strong></p><p>With your Blazor WASM application now elegantly fused with Electron.js, empowered by auto-updates, and fortified by CI/CD through GitHub Actions, the horizon of possibilities is vast. Delve into advanced Electron.js features, optimize performance, and craft an immersive user experience that resonates with both web and desktop enthusiasts.</p><p><strong>Embark on Your Development Odyssey</strong></p><p>Ready to embark on your own development journey? The complete codebase and resources employed in this tutorial are at your fingertips in the <a href="https://github.com/dejandjenic/BlazorPlaygroundElectron">https://github.com/dejandjenic/BlazorPlaygroundElectron</a>. Feel free to explore, experiment, and shape the code to fit your unique projects.</p><p>As we conclude, remember that the fusion of Blazor WASM and Electron.js, accentuated by auto-updates and fortified by GitHub Actions, redefines the landscape of desktop applications. With every release cycle smoothly orchestrated, your application evolves seamlessly, delivering the latest features and enhancements to your audience with unparalleled convenience.</p><p>Originally published at <a href="https://dejandjenic.github.io/blogs/publishing-blazor-wasm-with-electron-js.html">https://dejandjenic.github.io/blogs/publishing-blazor-wasm-with-electron-js.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=509dc4338450" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Blazor and Deployment Options]]></title>
            <link>https://medium.com/@dejandjenic/exploring-blazor-and-deployment-options-da81c2c301aa?source=rss-14d32b373b09------2</link>
            <guid isPermaLink="false">https://medium.com/p/da81c2c301aa</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[blazor-webassembly]]></category>
            <category><![CDATA[blazor]]></category>
            <dc:creator><![CDATA[Dejan Đenić]]></dc:creator>
            <pubDate>Mon, 14 Aug 2023 06:46:28 GMT</pubDate>
            <atom:updated>2023-08-14T06:46:28.782Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>In this article, I’m excited to delve into the world of Blazor, Microsoft’s innovative web framework that enables developers to build interactive and dynamic web applications using C# and .NET instead of traditional web languages. In this article, I’ll walk you through the process of creating a Blazor application that provides various useful functionalities like base64 encoding/decoding, URL encoding/decoding, JWT decoding, string escaping, HTML encoding/decoding, hash generation, and even GUID generation. As we progress, I’ll also touch upon the deployment options, specifically focusing on hosting the application on GitHub Pages and containerizing it using Docker.</p><p><strong>Solution Overview</strong></p><p>To make our exploration practical and hands-on, we’ll implement a set of simple yet powerful tools every developer frequently uses. These tools include functionalities such as base64 encoding/decoding, URL encoding/decoding, JWT decoding, string escaping, HTML encoding/decoding, hash generation, and even GUID generation. And we’re going to build all of these into a Blazor WebAssembly application.</p><p><strong>Development</strong></p><p><strong>Reusable Control: Editor.razor</strong></p><p>We start by designing a reusable control, Editor, which provides input and output text fields, action buttons for encoding/decoding, and a swap button to easily switch between input and output. This control simplifies the process of creating pages with different functionalities by eliminating repetitive UI code.</p><pre>@using System.Web<br><br>&lt;textarea  rows=&quot;15&quot; cols=&quot;40&quot; style=&quot;width:100%&quot; @bind=&quot;ModelObject.Source&quot;&gt;&lt;/textarea&gt;<br>&lt;button class=&quot;btn btn-primary&quot; @onclick=&quot;Action1Handler&quot;&gt;@Action1Text&lt;/button&gt;<br>@if (Action2Enabled)<br>{<br>    &lt;button class=&quot;btn btn-primary&quot; @onclick=&quot;Action2Handler&quot;&gt;@Action2Text&lt;/button&gt;<br>}<br>@if (SwapEnabled)<br>{<br>    &lt;button class=&quot;btn btn-primary&quot; @onclick=&quot;Swap&quot;&gt;&lt;i class=&quot;bi bi-arrow-down-up&quot;&gt;&lt;/i&gt; Swap&lt;/button&gt;<br>}<br>&lt;textarea  rows=&quot;15&quot; cols=&quot;40&quot; style=&quot;width:100%&quot; @bind=&quot;ModelObject.Destination&quot;&gt;&lt;/textarea&gt;<br><br><br><br>@code {<br><br>    class Model<br>    {<br>        public string Source { get; set; }<br>        public string Destination { get; set; }<br>    }<br><br>    private Model ModelObject = new();<br><br>    [Parameter]<br>    public string Action1Text { get; set; }<br>    [Parameter]<br>    public string Action2Text { get; set; }<br><br>    [Parameter]<br>    public Func&lt;string, string&gt; Action1 { get; set; }<br><br>    [Parameter]<br>    public Func&lt;string, string&gt; Action2 { get; set; }<br><br>    [Parameter]<br>    public bool Action2Enabled { get; set; } = true;<br>    [Parameter]<br>    public bool SwapEnabled { get; set; } = true;<br><br>    [Parameter]<br>    public string DefaultText { get; set; }<br><br>    private void Action1Handler()<br>    {<br>        ModelObject.Destination = Action1(ModelObject.Source);<br>    }<br><br>    private void Action2Handler()<br>    {<br>        ModelObject.Destination = Action2(ModelObject.Source);<br>    }<br><br>    private void Swap()<br>    {<br>        (ModelObject.Destination, ModelObject.Source) = (ModelObject.Source, ModelObject.Destination);<br>    }<br><br>    protected override void OnParametersSet()<br>    {<br>        base.OnParametersSet();<br>        ModelObject = new Model()<br>        {<br>                Source = DefaultText<br>        };<br>    }<br>}</pre><p><strong>Base64 Encoding: Base64.razor</strong></p><p>In the Base64.razor page, we showcase base64 encoding and decoding. Users can input text, click the “Encode” button to see the base64 encoded result, and click the “Decode” button to revert the encoded text back to its original form.</p><pre>@page &quot;/base64&quot;<br>@using System.Web<br><br>&lt;PageTitleWithH1&gt;Base64 Encode&lt;/PageTitleWithH1&gt;<br><br>&lt;Editor<br>    Action1Text=&quot;Encode&quot;<br>    Action2Text=&quot;Decode&quot;<br>    Action1=@(s =&gt; Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(s)))<br>    Action2=@(s =&gt; System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(s)))&gt;<br>&lt;/Editor&gt;</pre><p><strong>Escape String: Escape.razor</strong></p><p>The Escape.razor page illustrates how to escape and unescape strings using regular expressions. Users can input text, click the “Escape” button to escape special characters, and click the “Unescape” button to revert the process.</p><pre>@page &quot;/escape&quot;<br><br>&lt;PageTitleWithH1&gt;Escape&lt;/PageTitleWithH1&gt;<br><br>&lt;Editor<br>    Action1Text=&quot;Escape&quot;<br>    Action2Text=&quot;Unescape&quot;<br>    Action1=@(s =&gt;  System.Text.RegularExpressions.Regex.Escape(s))<br>    Action2=@(s =&gt; System.Text.RegularExpressions.Regex.Unescape(s))&gt;<br>&lt;/Editor&gt;</pre><p><strong>Guid Generation: Guid.razor</strong></p><p>In the Guid.razor page, we demonstrate the generation of GUIDs (Globally Unique Identifiers). Users can specify the number of GUIDs they want to generate, and the application will produce a list of randomly generated GUIDs.</p><pre>@page &quot;/guid&quot;<br><br>&lt;PageTitleWithH1&gt;Guid&lt;/PageTitleWithH1&gt;<br><br>&lt;Editor<br>    Action1Text=&quot;Generate&quot;<br>    Action2Enabled=false<br>    SwapEnabled=false<br>    DefaultText=&quot;10&quot;<br>    Action1=@(s =&gt;  <br>    {<br>        var count = int.TryParse(s,out var i)?i:10;<br>        count=Math.Max(1,count);<br>        count=Math.Min(100,count);<br>        return string.Join(&quot;\r\n&quot;,Enumerable.Range(1,count).Select(x=&gt; System.Guid.NewGuid().ToString()));<br>    })&gt;<br>&lt;/Editor&gt;</pre><p><strong>Hash Generation: Hash.razor</strong></p><p>The Hash.razor page showcases the creation of SHA256 hashes. Users can input text, and the application will display the SHA256 hash of the input text.</p><pre>@page &quot;/hash&quot;<br>@using System.Security.Cryptography<br><br>&lt;PageTitleWithH1&gt;Hash&lt;/PageTitleWithH1&gt;<br><br>&lt;Editor<br>    Action1Text=&quot;SHA256 hash&quot;<br>    Action2Enabled=false<br>    SwapEnabled=false<br>    Action1=@(s =&gt;  CreateHash(s))&gt;<br>&lt;/Editor&gt;<br><br>@code<br>{<br>    public static string CreateHash(ReadOnlySpan&lt;char&gt; input)<br>    {<br>        var encoding = System.Text.Encoding.UTF8;<br>        var inputByteCount = encoding.GetByteCount(input);<br>        using var sha256 = new SHA256Managed();<br><br>        Span&lt;byte&gt; bytes = inputByteCount &lt; 1024<br>            ? stackalloc byte[inputByteCount]<br>            : new byte[inputByteCount];<br>        Span&lt;byte&gt; destination = stackalloc byte[sha256.HashSize / 8];<br><br>        encoding.GetBytes(input, bytes);<br><br>        sha256.TryComputeHash(bytes, destination, out int _bytesWritten);<br><br>        return BitConverter.ToString(destination.ToArray()).ToLower().Replace(&quot;-&quot;,&quot;&quot;);<br>    }<br>}</pre><p><strong>HTML Encoding: Html.razor</strong></p><p>With the Html.razor page, we demonstrate HTML encoding and decoding. Users can input text, click the “Encode” button to encode special characters, and click the “Decode” button to revert the encoding.</p><pre>@page &quot;/html&quot;<br>@using System.Web<br><br>&lt;PageTitleWithH1&gt;Html Encode&lt;/PageTitleWithH1&gt;<br><br>&lt;Editor<br>    Action1Text=&quot;Encode&quot;<br>    Action2Text=&quot;Decode&quot;<br>    Action1=@(s =&gt; HttpUtility.HtmlEncode(s))<br>    Action2=@(s =&gt; HttpUtility.HtmlDecode(s))&gt;<br>&lt;/Editor&gt;</pre><p><strong>JSON Formatting: Json.razor</strong></p><p>The Json.razor page focuses on JSON formatting. Users can input JSON data, click the “Beautify” button to format it with proper indentation, and click the “Uglify” button to remove extra whitespace.</p><pre>@page &quot;/json&quot;<br>@using System.Web<br>@using System.Text.Json<br>@using System.Dynamic<br><br>&lt;PageTitleWithH1&gt;Json beautify&lt;/PageTitleWithH1&gt;<br><br>&lt;Editor<br>    Action1Text=&quot;Beautify&quot;<br>    Action2Text=&quot;Uglify&quot;<br>    Action1=@(json =&gt; {<br>                       var parsedJson = JsonSerializer.Deserialize&lt;ExpandoObject&gt;(json);<br>                       var options = new JsonSerializerOptions() { WriteIndented = true };<br>                       return JsonSerializer.Serialize(parsedJson, options);<br>            })<br>    Action2=@(json =&gt; {<br>                          var parsedJson = JsonSerializer.Deserialize&lt;ExpandoObject&gt;(json);<br>                          var options = new JsonSerializerOptions() { WriteIndented = false };<br>                          return JsonSerializer.Serialize(parsedJson, options);<br>            })&gt;<br>&lt;/Editor&gt;</pre><p><strong>JWT Parsing: Jwt.razor</strong></p><p>In the Jwt.razor page, we explore JSON Web Tokens (JWT) by providing a token for parsing. The application will display the claims contained in the JWT payload.</p><pre>@page &quot;/jwt&quot;<br>@using System.Text.Json;<br><br>&lt;PageTitleWithH1&gt;JWT&lt;/PageTitleWithH1&gt;<br><br>&lt;Editor Action1Text=&quot;Parse&quot;<br>        Action2Enabled=false<br>        SwapEnabled=false<br>        Action1=@(s =&gt;<br>        {<br>        try{<br>            var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler().ReadJwtToken(s);<br>            var options = new JsonSerializerOptions() { WriteIndented = true };<br>            return JsonSerializer.Serialize( token.Payload.Claims,options);<br>        }<br>        catch(Exception ex){<br>            return ex.Message;<br>        }<br>        })<br>        Action2=@(s =&gt; System.Text.RegularExpressions.Regex.Unescape(s))&gt;<br>&lt;/Editor&gt;</pre><p><strong>URL Encoding: Url.razor</strong></p><p>Lastly, the Url.razor page demonstrates URL encoding and decoding. Users can input a URL, click the “Encode” button to encode special characters, and click the “Decode” button to revert the encoding.</p><pre>@page &quot;/url&quot;<br>@using System.Web<br><br>&lt;PageTitleWithH1&gt;Url Encode&lt;/PageTitleWithH1&gt;<br><br>&lt;Editor<br>    Action1Text=&quot;Encode&quot;<br>    Action2Text=&quot;Decode&quot;<br>    Action1=@(s =&gt; HttpUtility.UrlEncode(s))<br>    Action2=@(s =&gt; HttpUtility.UrlDecode(s))&gt;<br>&lt;/Editor&gt;</pre><p><strong>Navigation Menu Enhancement</strong></p><p>To improve the user experience, we’ve also enhanced the navigation menu. It now lists each functionality, making it easier for users to jump to the desired page.</p><pre>&lt;div class=&quot;top-row ps-3 navbar navbar-dark&quot;&gt;<br>    &lt;div class=&quot;container-fluid&quot;&gt;<br>        &lt;a class=&quot;navbar-brand&quot; href=&quot;&quot;&gt;Blazor Playground&lt;/a&gt;<br>        &lt;button title=&quot;Navigation menu&quot; class=&quot;navbar-toggler&quot; @onclick=&quot;ToggleNavMenu&quot;&gt;<br>            &lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt;<br>        &lt;/button&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;<br><br>&lt;div class=&quot;@NavMenuCssClass nav-scrollable&quot; @onclick=&quot;ToggleNavMenu&quot;&gt;<br>    &lt;nav class=&quot;flex-column&quot;&gt;<br>        &lt;div class=&quot;nav-item px-3&quot;&gt;<br>            &lt;NavLink class=&quot;nav-link&quot; href=&quot;&quot; Match=&quot;NavLinkMatch.All&quot;&gt;<br>                &lt;span class=&quot;oi oi-home&quot; aria-hidden=&quot;true&quot;&gt;&lt;/span&gt; Home<br>            &lt;/NavLink&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;nav-item px-3&quot;&gt;<br>            &lt;NavLink class=&quot;nav-link&quot; href=&quot;html&quot;&gt;<br>                &lt;span class=&quot;oi oi-plus&quot; aria-hidden=&quot;true&quot;&gt;&lt;/span&gt; Html encode<br>            &lt;/NavLink&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;nav-item px-3&quot;&gt;<br>            &lt;NavLink class=&quot;nav-link&quot; href=&quot;url&quot;&gt;<br>                &lt;span class=&quot;oi oi-list-rich&quot; aria-hidden=&quot;true&quot;&gt;&lt;/span&gt; Url encode<br>            &lt;/NavLink&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;nav-item px-3&quot;&gt;<br>            &lt;NavLink class=&quot;nav-link&quot; href=&quot;base64&quot;&gt;<br>                &lt;span class=&quot;oi oi-flash&quot; aria-hidden=&quot;true&quot;&gt;&lt;/span&gt; Base64<br>            &lt;/NavLink&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;nav-item px-3&quot;&gt;<br>            &lt;NavLink class=&quot;nav-link&quot; href=&quot;json&quot;&gt;<br>                &lt;span class=&quot;oi oi-fork&quot; aria-hidden=&quot;true&quot;&gt;&lt;/span&gt; Json<br>            &lt;/NavLink&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;nav-item px-3&quot;&gt;<br>            &lt;NavLink class=&quot;nav-link&quot; href=&quot;hash&quot;&gt;<br>                &lt;span class=&quot;oi oi-layers&quot; aria-hidden=&quot;true&quot;&gt;&lt;/span&gt; Hash<br>            &lt;/NavLink&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;nav-item px-3&quot;&gt;<br>            &lt;NavLink class=&quot;nav-link&quot; href=&quot;guid&quot;&gt;<br>                &lt;span class=&quot;oi oi-globe&quot; aria-hidden=&quot;true&quot;&gt;&lt;/span&gt; Guid<br>            &lt;/NavLink&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;nav-item px-3&quot;&gt;<br>            &lt;NavLink class=&quot;nav-link&quot; href=&quot;escape&quot;&gt;<br>                &lt;span class=&quot;oi oi-lock-locked&quot; aria-hidden=&quot;true&quot;&gt;&lt;/span&gt; Escape<br>            &lt;/NavLink&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;nav-item px-3&quot;&gt;<br>            &lt;NavLink class=&quot;nav-link&quot; href=&quot;jwt&quot;&gt;<br>                &lt;span class=&quot;oi oi-key&quot; aria-hidden=&quot;true&quot;&gt;&lt;/span&gt; JWT<br>            &lt;/NavLink&gt;<br>        &lt;/div&gt;<br>    &lt;/nav&gt;<br>&lt;/div&gt;<br><br>@code {<br>    private bool collapseNavMenu = true;<br><br>    private string? NavMenuCssClass =&gt; collapseNavMenu ? &quot;collapse&quot; : null;<br><br>    private void ToggleNavMenu()<br>    {<br>        collapseNavMenu = !collapseNavMenu;<br>    }<br>}</pre><p><strong>Deployment: GitHub Pages and Docker</strong></p><p>For deployment, we’ve covered two options: GitHub Pages and Docker.</p><p><strong>GitHub Pages Deployment</strong></p><p>To host our application on GitHub Pages, we’ve set up a GitHub Action workflow. This workflow builds the application, modifies the base address for subdirectory hosting, copies the index.html to a 404.html file, and deploys the output to the gh-pages branch. This enables us to access our Blazor application using a public URL.</p><pre>name: Blazor Playground<br><br>on:<br>  push:<br>    branches:<br>    - main  # default branch<br><br>jobs:<br>  build:<br><br>    runs-on: ubuntu-latest<br><br>    steps:<br>    - uses: actions/checkout@v1<br>    - name: Setup .NET Core<br>      uses: actions/setup-dotnet@v2<br>      with:<br>        dotnet-version: &#39;7.0&#39;<br>    - name: Publish<br>      run: dotnet publish -c Release -o release<br>    - name: Set base<br>      run: sed -i &#39;s/&lt;base href=&quot;\/&quot;/&lt;base href=&quot;\/BlazorPlayground\/&quot;/g&#39; release/wwwroot/index.html &gt;&gt; release/wwwroot/index.html<br>    - name: No Jekyll<br>      run: touch release/wwwroot/.nojekyll<br>    - name: copy index.html to 404.html<br>      run: cp release/wwwroot/index.html release/wwwroot/404.html<br>    - name: Deploy<br>      uses: peaceiris/actions-gh-pages@v2.5.0<br>      env:<br>        ACTIONS_DEPLOY_KEY: ${{ secrets.ACTIONS_DEPLOY_KEY }}<br>        PUBLISH_BRANCH: gh-pages  # deploying branch<br>        PUBLISH_DIR: ./release/wwwroot</pre><p><strong>Docker Deployment</strong></p><p>Alternatively, we’ve containerized our Blazor application using Docker. The Dockerfile builds the application, copies the output to an Nginx-based image, and configures Nginx to serve the static files. This containerized application can be deployed to any environment that supports Docker containers.</p><pre>FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build<br> <br>WORKDIR /src<br><br><br><br>COPY [&quot;BlazorPlayground.csproj&quot;, &quot;BlazorPlayground.csproj&quot;]<br><br>RUN dotnet restore &quot;BlazorPlayground.csproj&quot;<br><br><br><br>COPY [&quot;/&quot;, &quot;/&quot;]<br>RUN sed -i &#39;s/&lt;base href=&quot;\/&quot;/&lt;base href=&quot;\/BlazorPlayground\/&quot;/g&#39; release/wwwroot/index.html &gt;&gt; release/wwwroot/index.html<br><br>RUN dotnet build &quot;BlazorPlayground.csproj&quot; --no-restore -c Release -o /app<br><br><br><br>FROM build AS publish<br>RUN dotnet publish &quot;BlazorPlayground.csproj&quot; --no-restore -c Release -o /app<br><br><br><br><br>FROM nginx:alpine AS final<br>WORKDIR /usr/share/nginx/html<br><br>COPY --from=publish /app/wwwroot .<br>COPY [&quot;nginx.conf&quot;, &quot;/etc/nginx/nginx.conf&quot;]</pre><pre>events { }<br>http {<br>    include mime.types;<br><br>    server {<br>        listen 80;<br><br>        location / {<br>            root /usr/share/nginx/html;<br>            try_files $uri $uri/ /index.html =404;<br>        }<br>    }<br>}</pre><p><strong>Conclusion</strong></p><p>In this article, we’ve journeyed through the exciting world of Blazor, building a versatile web application that offers a range of essential tools. We’ve explored encoding, decoding, hashing, and more, showcasing Blazor’s capabilities in a practical and engaging manner. Moreover, we’ve discussed deployment options, making our application accessible through GitHub Pages and containerization. This hands-on experience with Blazor and deployment strategies equips developers with valuable insights for their future projects.</p><p>For the complete code and the deployed version of the application, check out the <a href="https://github.com/dejandjenic/BlazorPlayground/">GitHub repository </a>and the <a href="https://dejandjenic.github.io/BlazorPlayground/">live application</a>.</p><p>Originally published at <a href="https://dejandjenic.github.io/blogs/blazor-playground.html">https://dejandjenic.github.io/blogs/blazor-playground.html</a></p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da81c2c301aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Scalable Serverless Applications: Hosting .NET Minimal APIs with Google Cloud Functions]]></title>
            <link>https://medium.com/@dejandjenic/building-scalable-serverless-applications-hosting-net-minimal-apis-with-google-cloud-functions-56b8ae938f24?source=rss-14d32b373b09------2</link>
            <guid isPermaLink="false">https://medium.com/p/56b8ae938f24</guid>
            <category><![CDATA[minimal-api]]></category>
            <category><![CDATA[net-7]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[google-cloud-functions]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Dejan Đenić]]></dc:creator>
            <pubDate>Tue, 01 Aug 2023 15:32:30 GMT</pubDate>
            <atom:updated>2023-08-01T15:32:30.957Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Building Scalable Serverless Applications: Hosting .NET Minimal APIs with Google Cloud Functions</strong></h3><p><strong>Introduction</strong></p><p>In today’s fast-paced digital landscape, developers are constantly seeking efficient ways to build and deploy applications that are scalable, cost-effective, and require minimal maintenance. The combination of .NET Minimal APIs and Google Cloud Functions presents a compelling solution to meet these demands. By leveraging the simplicity and performance of .NET Minimal APIs with the serverless architecture of Google Cloud Functions, developers can create robust applications that scale seamlessly with incoming traffic while enjoying the benefits of a pay-as-you-go billing model.</p><p>In this article, we will delve into the process of hosting a .NET Minimal API on Google Cloud Functions, unlocking the power of serverless computing for your .NET applications. We will walk you through the necessary steps to set up and deploy your .NET Minimal API, as well as explore the unique advantages that both technologies offer. Whether you are a seasoned .NET developer or just starting your journey into serverless computing, this guide will equip you with the knowledge and tools needed to build modern, scalable, and responsive applications with ease.</p><p>Let’s get started on this exciting journey of hosting a .NET Minimal API with Google Cloud Functions and unlock the full potential of serverless computing for your projects!</p><p>Hosting a .NET Minimal API with Google Cloud Functions can be a powerful combination to create scalable, serverless applications. In this article, we’ll walk through the steps to set up and deploy a .NET Minimal API on Google Cloud Functions. Before we begin, ensure you have basic knowledge of .NET Minimal APIs, Google Cloud Functions, and the Google Cloud Platform (GCP).</p><p><strong>Benefits of Google Cloud Functions:</strong></p><p>Serverless Architecture: Google Cloud Functions is a serverless computing platform, which means you don’t need to worry about managing servers or infrastructure. Google takes care of server provisioning, scaling, and maintenance, allowing you to focus on writing code and building applications.</p><p>Auto-scaling: Google Cloud Functions automatically scales your application in response to incoming traffic. It provisions and scales resources as needed, ensuring optimal performance during peak times while saving costs during periods of low or no traffic.</p><p>Pay-per-Use Billing: With serverless computing, you only pay for the actual compute resources used during the execution of your functions. This fine-grained billing model allows you to optimize costs and eliminate the need to pay for idle resources.</p><p>Easy Integration: Google Cloud Functions integrates seamlessly with other Google Cloud services, enabling you to build powerful and interconnected applications. You can easily trigger functions based on events from Cloud Storage, Pub/Sub, Firestore, HTTP requests, and more.</p><p>Fast Deployment: Deploying functions is quick and straightforward. Google Cloud Functions abstracts away the complexity of infrastructure setup and configuration, allowing you to deploy and update functions with ease.</p><p>Global Reach: Google Cloud Functions provides the option to deploy functions across multiple regions, ensuring low-latency access to your applications for users around the world.</p><p><strong>Benefits of .NET Minimal APIs:</strong></p><p>Simplified Code: .NET Minimal APIs offer a simplified and more concise syntax compared to traditional ASP.NET Web APIs. This leads to cleaner and more readable code, making it easier for developers to understand and maintain the application.</p><p>Improved Performance: The lightweight nature of .NET Minimal APIs results in faster startup times and reduced memory consumption. This is especially beneficial for serverless architectures where fast startup is crucial to handle incoming requests efficiently.</p><p>Built-in Dependency Injection: .NET Minimal APIs come with built-in support for dependency injection, making it easier to manage and inject services into your application components. This promotes better code organization and testability.</p><p>Rapid Development: With a minimalist approach, .NET Minimal APIs eliminate boilerplate code, allowing developers to focus on building the core business logic of their application without unnecessary distractions.</p><p>Versatility: .NET Minimal APIs are versatile and can be hosted on various platforms, including traditional web servers, containerized environments, and, as demonstrated in this article, serverless platforms like Google Cloud Functions.</p><p>Cross-platform Compatibility: .NET Core provide cross-platform support, enabling developers to build and deploy .NET Minimal APIs on Windows, macOS, and Linux systems.</p><p>By combining the benefits of Google Cloud Functions and .NET Minimal APIs, developers can create highly scalable, cost-efficient, and easily maintainable serverless applications that respond quickly to user requests and adapt to varying workloads. Whether you’re building microservices, APIs, or event-driven applications, this combination empowers developers to focus on application logic rather than infrastructure management.</p><p><strong>1. Prerequisites</strong></p><p>Before you start, make sure you have the following prerequisites in place:</p><p>A Google Cloud Platform (GCP) account.</p><p>The Google Cloud SDK (gcloud) installed on your local machine.</p><p>.NET 7 SDK or later installed on your local machine.</p><p>Basic knowledge of C# and .NET Minimal APIs.</p><p><strong>2. Create a .NET Minimal API</strong></p><p>First, let’s create a simple .NET Minimal API project:</p><p>Open a terminal or command prompt and run the following command to install project template</p><pre>dotnet new install Google.Cloud.Functions.Templates</pre><p>Open a terminal or command prompt and run the following command to create a new .NET Minimal API project:</p><pre>dotnet new gcf-http -n MyMinimalApiProject</pre><p>Navigate to the project directory:</p><pre>cd MyMinimalApiProject</pre><p>Open the project in your preferred code editor.</p><p>In the Function.cs file, you’ll find a GCP cloud function template.</p><pre>using Google.Cloud.Functions.Framework;<br>using Microsoft.AspNetCore.Http;<br>using System.Threading.Tasks;<br><br>namespace MyMinimalApiProject;<br><br>public class Function : IHttpFunction<br>{<br>    /// &lt;summary&gt;<br>    /// Logic for your function goes here.<br>    /// &lt;/summary&gt;<br>    /// &lt;param name=&quot;context&quot;&gt;The HTTP context, containing the request and the response.&lt;/param&gt;<br>    /// &lt;returns&gt;A task representing the asynchronous operation.&lt;/returns&gt;<br>    public async Task HandleAsync(HttpContext context)<br>    {<br>        await context.Response.WriteAsync(&quot;Hello, Functions Framework.&quot;);<br>    }<br>}</pre><p>Employing Swagger proves highly beneficial as it facilitates seamless integration with your API and offers a user-friendly UI tool for testing purposes. With Swagger, developers can effortlessly interact with your API, making it easier to explore and validate its functionalities.</p><p>In your preferred code editor, open the MyMinimalApiProject.csproj file and add the necessary packages to include Swagger support in your project:</p><pre>&lt;Project Sdk=&quot;Microsoft.NET.Sdk&quot;&gt;<br> &lt;PropertyGroup&gt;<br>  &lt;OutputType&gt;Exe&lt;/OutputType&gt;<br>  &lt;TargetFramework&gt;net7.0&lt;/TargetFramework&gt;<br> &lt;/PropertyGroup&gt;<br><br> &lt;ItemGroup&gt;<br>  &lt;PackageReference Include=&quot;Microsoft.AspNetCore.OpenApi&quot; Version=&quot;7.0.8&quot; /&gt;<br>  &lt;PackageReference Include=&quot;Swashbuckle.AspNetCore&quot; Version=&quot;6.5.0&quot; /&gt;<br>  &lt;PackageReference Include=&quot;Google.Cloud.Functions.Hosting&quot; Version=&quot;2.1.0&quot; /&gt;<br>  &lt;None Include=&quot;appsettings*.json&quot; CopyToOutputDirectory=&quot;PreserveNewest&quot; /&gt;<br> &lt;/ItemGroup&gt;<br>&lt;/Project&gt;</pre><p>Create a new file named MathService.cs with the following content:</p><pre>using System;<br><br>namespace MyMinimalApiProject<br>{<br>    public interface IMathService<br>    {<br>        double Pow(int baseNum, int pow);<br>        double Sqrt(long baseNum);<br>    }<br><br>    public class MathService : IMathService<br>    {<br>        public double Pow(int baseNum, int pow)<br>        {<br>            return Math.Pow(baseNum, pow);<br>        }<br><br>        public double Sqrt(long baseNum)<br>        {<br>            return Math.Sqrt(baseNum);<br>        }<br>    }<br><br>}</pre><p>Create a new file named Startup.cs with the following content:</p><pre>public class Startup : FunctionsStartup<br>{<br><br>    public override void Configure(WebHostBuilderContext context, IApplicationBuilder app)<br>    {<br>        base.Configure(context, app);<br><br>        app.UseSwagger();<br>        app.UseSwaggerUI();<br><br><br>        app.UseRouting();<br>        app.UseEndpoints(endpoints =&gt;<br>        {<br>            endpoints.MapGet(&quot;/pow/{baseNum}/{pow}&quot;, (IMathService service, int baseNum, int pow) =&gt; service.Pow(baseNum, pow))<br>            .WithName(&quot;Pow&quot;)<br>            .WithOpenApi();<br><br>            endpoints.MapGet(&quot;/sqrt/{baseNum}&quot;, (IMathService service, long baseNum) =&gt; service.Sqrt(baseNum))<br>            .WithName(&quot;Sqrt&quot;)<br>            .WithOpenApi();<br>        }<br>        );<br>        <br>    }<br><br><br>    public override void ConfigureServices(WebHostBuilderContext context, IServiceCollection services)<br>    {<br>        base.ConfigureServices(context, services);<br><br>        services.AddScoped&lt;IMathService, MathService&gt;();<br><br>        services.AddEndpointsApiExplorer();<br>        services.AddSwaggerGen();<br><br>    }<br>}</pre><p>In the Function.cs file, modify it to register the Startup class and respond with a 404 response for unhandled requests:</p><pre>[FunctionsStartup(typeof(Startup))]<br><br>public class Function : IHttpFunction<br>{<br>    public async Task HandleAsync(HttpContext context)<br>    {<br>        context.Response.StatusCode = 404;<br>        await context.Response.WriteAsync(&quot;Notfound&quot;);<br>    }<br>}</pre><p>With these modifications, your .NET Minimal API project is now equipped with Swagger support, providing interactive documentation for your API. It includes two endpoints for calculating the power and square root of numbers using the IMathService interface. By using Swagger, developers can seamlessly interact with your API, making it easier to explore and test its functionalities. Now, let’s proceed to test the API locally and deploy it to Google Cloud Functions to unlock the power of serverless computing for your application.</p><p><strong>3. Test the .NET Minimal API Locally</strong></p><p>Before deploying to Google Cloud Functions, ensure your .NET Minimal API works as expected locally:</p><p>Run the following command to build and run the project:</p><pre>dotnet run</pre><p>By default, the API will be available at <a href="http://localhost:8080.">http://localhost:8080.</a></p><p>Use a tool like curl, Postman, or a web browser to test your API endpoints or you can use swagger ui that we added in previous step by navigating to <a href="http://localhost:8080/swagger/index.html">http://localhost:8080/swagger/index.html</a></p><p><strong>4. Set Up Google Cloud Functions</strong></p><p>Now, let’s set up Google Cloud Functions for deployment:</p><p>Open a terminal or command prompt.</p><p>Authenticate with your Google Cloud account using the following command and follow the instructions on-screen:</p><pre>gcloud auth login</pre><p>Set your Google Cloud project as the default project for deployment:</p><pre>gcloud config set project YOUR_PROJECT_ID</pre><p>Replace YOUR_PROJECT_ID with the actual ID of your Google Cloud project.</p><p><strong>5. Deploy the .NET Minimal API to Google Cloud Functions</strong></p><p>With everything set up, it’s time to deploy the .NET Minimal API to Google Cloud Functions:</p><p>Open a terminal or command prompt.</p><p>Run the following command to deploy the function:</p><pre>gcloud functions deploy myFunctionName --runtime dotnet7 --trigger-http --allow-unauthenticated</pre><p>Replace myFunctionName with a name of your choice.</p><p>Wait for the deployment process to finish.</p><p>Once deployed, the command will provide you with the URL of the deployed function.</p><p><strong>6. Test the Deployed .NET Minimal API</strong></p><p>Now that your .NET Minimal API is deployed as a Google Cloud Function, test it using the provided URL:</p><p>Use a tool like curl, Postman, or a web browser to access the API using the provided URL.</p><p>Ensure that the API behaves as expected and returns the desired responses.</p><p>Congratulations! You have successfully hosted a .NET Minimal API with Google Cloud Functions. You now have a scalable and serverless solution that automatically scales based on the incoming traffic, making it cost-effective and efficient.</p><p>code created for this article is available at <a href="https://github.com/dejandjenic/MyMinimalApiProject">https://github.com/dejandjenic/MyMinimalApiProject</a></p><p>originally published at <a href="https://dejandjenic.github.io/blogs/dotnet-minimal-api-on-gcp-cloud-function.html">https://dejandjenic.github.io/blogs/dotnet-minimal-api-on-gcp-cloud-function.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56b8ae938f24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Test Visualization on GitLab with .NET Projects]]></title>
            <link>https://medium.com/@dejandjenic/enhancing-test-visualization-on-gitlab-with-net-projects-47f65a90c19?source=rss-14d32b373b09------2</link>
            <guid isPermaLink="false">https://medium.com/p/47f65a90c19</guid>
            <category><![CDATA[xunit]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Dejan Đenić]]></dc:creator>
            <pubDate>Mon, 24 Jul 2023 06:16:58 GMT</pubDate>
            <atom:updated>2023-07-24T06:16:58.377Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Enhancing Test Visualization on GitLab with .NET Projects</strong></h3><p><strong>Introduction</strong></p><p>In modern software development, efficient testing is crucial to ensure the stability and quality of applications. GitLab, a popular web-based Git repository management tool, offers a wide range of features to support the testing process. One such feature is test visualization, which provides developers with valuable insights into the test execution and results. This article explores how test visualization can be leveraged within GitLab for .NET projects, empowering teams to optimize their testing workflows and improve overall project quality.</p><p><strong>Understanding Test Visualization in GitLab</strong></p><p><strong>Overview of GitLab’s test visualization capabilities</strong></p><p>GitLab provides a dedicated section within its user interface for visualizing test results and metrics. It offers a comprehensive overview of test execution, allowing developers to track the progress and outcomes of their tests.</p><p><strong>Key benefits of using test visualization in software development</strong></p><p>Test visualization in GitLab brings several advantages to the software development process</p><p>1. Enhanced visibility: Developers can easily monitor the status and trends of their tests, gaining insights into test coverage, pass rates, and failure patterns.</p><ul><li>Early bug detection: Test visualization helps identify failing tests early in the development cycle, enabling prompt bug fixes and preventing issues from reaching production.</li><li>Test prioritization: By analyzing test results, teams can prioritize their efforts and allocate resources to fix critical or frequently failing tests.</li><li>Performance monitoring: Test visualization allows for tracking the performance of tests over time, highlighting any degradation or improvements in test execution</li></ul><p><strong>Integration with Continuous Integration/Continuous Deployment (CI/CD) pipelines</strong></p><p>GitLab seamlessly integrates test visualization into its CI/CD pipelines. Developers can configure test stages and jobs within the pipeline to automatically trigger test execution and generate visualized reports. This integration ensures that testing becomes an integral part of the development workflow.</p><p><strong>Setting Up .Net Project</strong></p><p>To create a new project and include the sample code provided by Microsoft <a href="https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage?tabs=windows,">https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage?tabs=windows,</a> follow these steps:</p><p>Inside the project directory, create a file named PrimeService.cs and add the following code</p><pre>public class PrimeService<br>    {<br>        public bool IsPrime(int candidate)<br>        {<br>            if (candidate &lt; 2)<br>            {<br>                return false;<br>            }<br><br>            for (int divisor = 2; divisor &lt;= Math.Sqrt(candidate); ++divisor)<br>            {<br>                if (candidate % divisor == 0)<br>                {<br>                    return false;<br>                }<br>            }<br>            return true;<br>        }<br>    }</pre><p>Create a test project within the same project directory. You can name it anything you prefer.</p><p>Add a reference to the project that contains PrimeService.cs. In your test project, add a reference to the project containing the PrimeService class.</p><p>Inside the test project, create a file named PrimeServiceTests.cs and add the following code:</p><pre>public class PrimeServiceTests<br>    {<br>        readonly PrimeService _primeService;<br><br>        public PrimeServiceTests() =&gt; _primeService = new PrimeService();<br><br>        [Theory]<br>        [InlineData(-1), InlineData(0), InlineData(1)]<br>        public void IsPrime_ValuesLessThan2_ReturnFalse(int value) =&gt;<br>            Assert.False(_primeService.IsPrime(value), $&quot;{value} should not be prime&quot;);<br><br>        [Theory]<br>        [InlineData(2), InlineData(3), InlineData(5), InlineData(7)]<br>        public void IsPrime_PrimesLessThan10_ReturnTrue(int value) =&gt;<br>            Assert.True(_primeService.IsPrime(value), $&quot;{value} should be prime&quot;);<br>    }</pre><p>Now you have a project with the PrimeService class and corresponding unit tests. You can proceed with configuring your CI/CD pipeline in GitLab and visualizing the test results using the test visualization capabilities.</p><p><strong>Setting Up GitLab for .NET Project Testing</strong></p><ul><li>Configuring GitLab CI/CD pipelines for .NET projects</li><li>Defining test stages and jobs within the pipeline</li><li>Installing necessary dependencies and tools for testing</li></ul><p>In the root directory of your project, create a .gitlab-ci.yml file and add the following content</p><pre>image:<br>  name: mcr.microsoft.com/dotnet/sdk:7.0<br><br>stages:<br>  - build<br>  - test<br><br>build_job:<br>  stage: build<br>  only:<br>    - pushes  <br>  script:<br>    - dotnet build<br><br>test_job:<br>  stage: test<br>  only:<br>    - pushes<br>  script:<br>    - dotnet test --results-directory $CI_PROJECT_DIR/cobertura --collect:&quot;XPlat Code Coverage&quot; --test-adapter-path:. --logger:&quot;junit;LogFilePath=..\artifacts\{assembly}-test.xml;MethodFormat=Class;FailureBodyFormat=Verbose&quot;<br>    - cp $CI_PROJECT_DIR/cobertura/*/coverage.cobertura.xml $CI_PROJECT_DIR/cobertura/coverage.cobertura.xml<br>    - dotnet tool install -g dotnet-reportgenerator-globaltool<br>    - dotnet tool install -g CodeCoverageExtractor<br>    - /root/.dotnet/tools/reportgenerator -reports:&quot;$CI_PROJECT_DIR/cobertura/coverage.cobertura.xml&quot; -targetdir:&quot;coveragereport&quot; -reporttypes:&quot;Html&quot;<br>    - /root/.dotnet/tools/codecoverageextractor $CI_PROJECT_DIR/cobertura/coverage.cobertura.xml<br>    - tar -cvf coveragereport.tar coveragereport/<br>  artifacts:<br>    when: always<br>    expire_in: 1 week<br>    paths:<br>      - ./**/*test.xml<br>      - $CI_PROJECT_DIR/cobertura/coverage.cobertura.xml<br>      - coveragereport.tar<br>    reports:<br>      junit:<br>        - ./**/*test.xml<br>      coverage_report:<br>        coverage_format: cobertura<br>        path: $CI_PROJECT_DIR/cobertura/coverage.cobertura.xml<br>        <br>  dependencies:<br>    - build_job<br>  coverage: /total_coverage=(\d+.?\d?)/</pre><p>The .gitlab-ci.yml file defines two stages: build and test. The build_job stage builds the project, and the test_job stage runs the tests.</p><p>The pipeline script installs the dotnet-reportgenerator-globaltool and CodeCoverageExtractor tools for generating test reports and extracting code coverage information.</p><p>By configuring GitLab CI/CD pipelines, defining test stages and jobs, and installing the required dependencies and tools, you can automate the build and test process for your .NET projects on GitLab. The pipeline script generates test reports, including code coverage, and provides valuable artifacts and reports for further analysis.</p><p><strong>Action</strong></p><p>Perform the following actions after setting up GitLab for .NET project testing</p><ul><li>Create a new merge request with the code you just created. This will trigger the pipeline to run</li><li>Once the pipeline is executed, it should display a status similar to the following:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*pNQv0dKb2YpBXqbAWs3IYg.png" /></figure><p>The image shows the pipeline status, a link to the full test report, and information about the code coverage percentage (83.30%).</p><p>Navigate to the test report page to view detailed information about the test jobs that were executed, including the duration of each job, final results, and details about each test executed, such as input parameters, duration, result, and logs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cJSHhQF89OQ26kgn9x-aEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d3jA7YJL52Rgdly_7de-YQ.png" /></figure><p>From the test report, you can observe that not all of the code is covered by tests; it is currently at 83.30% coverage.</p><p>Append the following test to your test project</p><pre>[Theory]<br>        [InlineData(4), InlineData(6), InlineData(8), InlineData(9)]<br>        public void IsPrime_NonPrimesLessThan10_ReturnFalse(int value) =&gt;<br>            Assert.False(_primeService.IsPrime(value), $&quot;{value} should not be prime&quot;);</pre><p>Commit and push your changes to the merge request and wait for the pipeline to finish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*lKinzYK68sKJfmHaOJBLjQ.png" /></figure><p>The results will show that your code now has 100% coverage.</p><p>Configure additional useful settings for your GitLab project:</p><ul><li>Navigate to Settings -&gt; General page and expand “Badges.”</li><li>Add the following entries:</li></ul><pre>https://gitlab.com/djenka79/test-coverage-gitlab/badges/main/pipeline.svg<br>https://gitlab.com/djenka79/test-coverage-gitlab/badges/main/coverage.svg</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o56Qa2ThqrWcYOzC5327MQ.png" /></figure><p>Merge your merge request, and once the pipeline is finished, your project’s overview page should display information about running pipelines and code coverage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DeOeam5v0W41qxPAQQEMKw.png" /></figure><p>The overview page will show information about the running pipelines and the code coverage percentage.</p><p>By following these actions, you can leverage the GitLab pipeline and test visualization features to monitor the progress of your tests, track code coverage, and ensure the quality of your .NET projects.</p><p><strong>Conclusion</strong></p><p>With GitLab’s robust test visualization capabilities, .NET project teams can gain valuable insights into the testing process, leading to improved software quality and accelerated development cycles. By leveraging test visualization, developers can identify bottlenecks, enhance collaboration, and optimize their testing strategies. Incorporating test visualization into the GitLab workflow empowers teams to make informed decisions and continuously improve their software testing practices.</p><p>code used to create this article can be found <a href="https://gitlab.com/djenka79/test-coverage-gitlab">https://gitlab.com/djenka79/test-coverage-gitlab</a></p><p>originally published at <a href="https://dejandjenic.github.io/blogs/test-report-visualization-with-gitlab-and-dotnet.html">https://dejandjenic.github.io/blogs/test-report-visualization-with-gitlab-and-dotnet.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47f65a90c19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Layered Caching in .NET Microservices]]></title>
            <link>https://medium.com/@dejandjenic/multi-layered-caching-in-net-microservices-500578ca6e28?source=rss-14d32b373b09------2</link>
            <guid isPermaLink="false">https://medium.com/p/500578ca6e28</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[in-memory-cache]]></category>
            <dc:creator><![CDATA[Dejan Đenić]]></dc:creator>
            <pubDate>Thu, 13 Jul 2023 17:42:17 GMT</pubDate>
            <atom:updated>2023-07-13T17:42:17.794Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Multi-Layered Caching in .NET Microservices</strong></h3><p>Caching plays a crucial role in optimizing the performance and scalability of .NET microservices. It allows frequently accessed data to be stored in memory or fast storage mediums, reducing the need to repeatedly retrieve data from original sources. In this blog post, we will explore the concept of multi-layered caching in .NET microservices and its significance in building highly performant and scalable applications.</p><p><strong>Introduction</strong></p><p>Caching offers several benefits in modern .NET applications:</p><p>- <strong>**Reduced Latency**</strong>: Caching minimizes the latency associated with fetching data from databases or external services, resulting in faster response times and improved user experience.</p><p>- <strong>**Enhanced Scalability**</strong>: By reducing the computational and network resources required to serve requests, caching improves the scalability of microservices, enabling them to handle higher loads efficiently.</p><p>- <strong>**Improved Resilience**</strong>: Caching mitigates the impact of external service failures or outages by providing access to previously cached data, ensuring that the application remains functional even when external dependencies are unavailable.</p><p><strong>The Need for Caching in .NET Applications</strong></p><p>To demonstrate the need for caching in .NET applications, let’s create a sample .NET API project using the Minimal API approach. We will use the GenFu library for generating fake data.</p><p>First, let’s define a data model that will be returned by the search endpoint:</p><pre><br>public class DataEntity<br>{<br>    public string Name { get; set; }<br>    public string LastName { get; set; }<br>    public int Age { get; set; }<br>}</pre><p>Next, we need to create repository and service classes to be used by the endpoint. Here’s an example of the IDataRepository interface and its implementation, DataRepository:</p><pre>public interface IDataRepository<br>{<br>    Task&lt;IList&lt;DataEntity&gt;&gt; SearchEntities(string name);<br>    Task Add(string name);<br>}<br><br> public class DataRepository : IDataRepository<br>{<br>    public async Task Add(string name)<br>    {<br>        <br>    }<br><br>    public async Task&lt;IList&lt;DataEntity&gt;&gt; SearchEntities(string name)<br>    {<br>        await Task.Delay(1500);<br>        return GenFu.GenFu.ListOf&lt;DataEntity&gt;();<br>    }<br>}</pre><p>Similarly, let’s define the IDataService interface and its implementation, DataService:</p><pre>public interface IDataService<br>{<br>    Task&lt;IList&lt;DataEntity&gt;&gt; SearchEntities(string name);<br>    Task Add(string name);<br>}<br><br><br> public class DataService : IDataService<br>{<br>    readonly IDataRepository repository;<br>    public DataService(IDataRepository repository)<br>    {<br>        this.repository = repository;<br>    }<br><br>    public async Task Add(string name)<br>    {<br>        await repository.Add(name);<br>    }<br><br>    public async Task&lt;IList&lt;DataEntity&gt;&gt; SearchEntities(string name)<br>    {<br>        return await repository.SearchEntities(name);<br>    }<br>}</pre><p>In the above code, we simulate the database read operation by introducing a delay of 1.5 seconds. The implementation for adding data is left empty for now. This setup allows us to simulate the load and reading latency without actually implementing it.</p><p>To wire up the dependencies, modify your Program.cs file as follows:</p><pre>using CachingDemo.Cache;<br>using CachingDemo.Repository;<br>using CachingDemo.Service;<br>using Microsoft.AspNetCore.Mvc;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br><br>builder.Services.AddScoped&lt;IDataRepository, DataRepository&gt;();<br>builder.Services.AddScoped&lt;IDataService, DataService&gt;();<br><br><br>var app = builder.Build();<br><br>app.MapGet(&quot;/search&quot;, async ([FromQuery] string name, IDataService service) =&gt; await service.SearchEntities(name));<br>app.MapGet(&quot;/add&quot;, async ([FromQuery] string name, IDataService service) =&gt; await service.Add(name));<br><br>app.Run();</pre><p>By running the application, you will have two endpoints: /search for searching entities and /add for adding entities. Note that the /add endpoint should ideally be a POST request, but for simplicity, we are using a GET request in this example.</p><p>To test the search endpoint, you can use a URL like the following:</p><pre>https://localhost:7220/search?name=test</pre><p>This will return a JSON array of fake data similar to the following:</p><pre>[<br>  {<br>    &quot;name&quot;: &quot;John&quot;,<br>    &quot;lastName&quot;: &quot;Doe&quot;,<br>    &quot;age&quot;: 25<br>  },<br>  {<br>    &quot;name&quot;: &quot;Jane&quot;,<br>    &quot;lastName&quot;: &quot;Smith&quot;,<br>    &quot;age&quot;: 30<br>  },<br>  ...<br>]</pre><p>Please note that the data is randomly generated and may not match exactly.</p><p>In a real-world scenario, the application would be hosted behind a load balancer with multiple instances running simultaneously. In a Kubernetes environment, these instances would be represented as pods within a deployment. To simulate this environment on your local machine, you can use Docker Compose.</p><p>Let’s add some additional components to our project.</p><p><strong>Adding YARP for Load Balancing and Docker Compose</strong></p><p>We can enhance our project by adding the YARP (Yet Another Reverse Proxy) project for load balancing. Additionally, we’ll use Docker Compose to spin up multiple instances of our API.</p><p>Create a new project and configure it as follows:</p><pre>var builder = WebApplication.CreateBuilder(args);<br>builder.Services.AddReverseProxy()<br>    .LoadFromConfig(builder.Configuration.GetSection(&quot;ReverseProxy&quot;));<br>var app = builder.Build();<br>app.MapReverseProxy();<br>app.Run();</pre><p>Add the following configuration to your appsettings.json file:</p><pre>{<br>  &quot;Logging&quot;: {<br>    &quot;LogLevel&quot;: {<br>      &quot;Default&quot;: &quot;Information&quot;,<br>      &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;<br>    }<br>  },<br>  &quot;AllowedHosts&quot;: &quot;*&quot;,<br><br><br>  &quot;ReverseProxy&quot;: {<br>    &quot;Routes&quot;: {<br>      &quot;minimumroute&quot;: {<br>        &quot;ClusterId&quot;: &quot;minimumcluster&quot;,<br>        &quot;Match&quot;: {<br>          &quot;Path&quot;: &quot;{**catch-all}&quot;<br>        }<br>      }<br>    },<br>    &quot;Clusters&quot;: {<br>      &quot;minimumcluster&quot;: {<br>        &quot;Destinations&quot;: {<br>          &quot;api1&quot;: {<br>            &quot;Address&quot;: &quot;http://api/&quot;<br>          },<br>          &quot;api2&quot;: {<br>            &quot;Address&quot;: &quot;http://api2/&quot;<br>          }<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>we added routing of content to any of 2 instances of our app that are going to be used in our docker compose.</p><p>lets create some Dockerfile</p><p>first for our app, name this file Dockerfile</p><pre>FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base<br>WORKDIR /app<br>EXPOSE 80<br>EXPOSE 443<br><br>FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build<br>WORKDIR /src<br>COPY [&quot;CachingDemo/CachingDemoApi.csproj&quot;, &quot;CachingDemo/&quot;]<br>RUN dotnet restore &quot;CachingDemo/CachingDemoApi.csproj&quot;<br>COPY . .<br>WORKDIR &quot;/src/CachingDemo&quot;<br>RUN dotnet build &quot;CachingDemoApi.csproj&quot; -c Release -o /app/build<br><br>FROM build AS publish<br>RUN dotnet publish &quot;CachingDemoApi.csproj&quot; -c Release -o /app/publish /p:UseAppHost=false<br><br>FROM base AS final<br>WORKDIR /app<br>COPY --from=publish /app/publish .<br>ENTRYPOINT [&quot;dotnet&quot;, &quot;CachingDemoApi.dll&quot;]</pre><p>then for YARP project, name this file Dockerfile.YARP</p><pre><br>FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base<br>WORKDIR /app<br>EXPOSE 80<br>EXPOSE 443<br><br>FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build<br>WORKDIR /src<br>COPY [&quot;YARP/YARP.csproj&quot;, &quot;YARP/&quot;]<br>RUN dotnet restore &quot;YARP/YARP.csproj&quot;<br>COPY . .<br>WORKDIR &quot;/src/YARP&quot;<br>RUN dotnet build &quot;YARP.csproj&quot; -c Release -o /app/build<br><br>FROM build AS publish<br>RUN dotnet publish &quot;YARP.csproj&quot; -c Release -o /app/publish /p:UseAppHost=false<br><br>FROM base AS final<br>WORKDIR /app<br>COPY --from=publish /app/publish .<br>ENTRYPOINT [&quot;dotnet&quot;, &quot;YARP.dll&quot;]</pre><p>Build the Docker images for the API project and YARP project:</p><pre>docker build . -t api<br>docker build . -f .\Dockerfile.YARP -t yarp</pre><p>Create a docker-compose.yml file with the following contents:</p><pre>version: &#39;2.1&#39;<br>services:<br>  api:<br>    image: api<br>  api2:<br>    image: api<br>  yarp:<br>    image: yarp<br>    ports:<br>      - &quot;8002:80&quot;</pre><p>Run Docker Compose to start the instances:</p><pre>docker compose up</pre><p>With this setup, Docker Compose will spin up two instances of your API project and one instance of the YARP project, which will forward requests to the API instances.</p><p>Now, let’s move on to load testing using NBomber.</p><p><strong>Load Testing with NBomber</strong></p><p>To perform load testing, we’ll use the NBomber library. Make sure to add the required NuGet packages for NBomber, GenFu, and any other dependencies.</p><p>Create a new load testing project and add references to YARP and GenFu.</p><p>Configure NBomber in your load testing project as shown below:</p><pre><br>using NBomber.CSharp;<br><br>var httpClient=new HttpClient();<br><br><br>var users = GenFu.GenFu.ListOf&lt;User&gt;();<br><br>var scenario = Scenario.Create(&quot;test_api_scenario&quot;, async context =&gt;<br>{<br>    var name = users[GenFu.GenFu.Random.Next(25)].Name;<br>    await httpClient.GetAsync($&quot;http://localhost:8002/search?name={name}&quot;);<br><br>    if(GenFu.GenFu.Random.Next(30) % 29 == 0)<br>        await httpClient.GetAsync($&quot;http://localhost:8002/add?name={name}&quot;);<br><br>    return Response.Ok();<br>})<br>.WithLoadSimulations(<br>    Simulation.Inject(rate: 10,<br>                      interval: TimeSpan.FromSeconds(1),<br>                      during: TimeSpan.FromSeconds(30)),<br>    Simulation.Pause(during: TimeSpan.FromSeconds(5))<br>)<br><br>;<br><br>NBomberRunner<br>    .RegisterScenarios(scenario)    <br>    .Run();<br><br>class User<br>{<br>    public string Name { get; set; }<br>}</pre><p>In the above code, we define a scenario named “test_api_scenario” that sends HTTP requests to the search endpoint with random names. We also include a conditional request to the add endpoint for every 30th request. The scenario is configured to have an injection rate of 10 requests per second for 30 seconds, followed by a 5-second pause.</p><p>Running this load testing project will generate load on your API instances and test their performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*KVjrv0k2jGCnEvxcwT3TNg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tq3FdiOcTsRVyLTGZaL3zw.png" /></figure><p>our load test creates 10 request per second and usual duration is slightly over 1.5 seconds.</p><p><strong>Implementing Caching</strong></p><p>Now, let’s add caching to our project using Redis and in-memory caching.</p><p>Create the following interfaces and classes for caching:</p><pre>public interface IGenericCache<br>{<br>    public Task&lt;T&gt; GetOrSet&lt;T&gt;(string key, Func&lt;Task&lt;T&gt;&gt; getData);<br>    public Task RemoveItem(string key);<br>}<br><br>public class RedisGenericCache : IGenericCache<br>{<br>    readonly IDatabase db;<br><br>    public RedisGenericCache(ConnectionMultiplexer redis)<br>    {            <br>        db = redis.GetDatabase();<br>    }<br><br>    public async Task&lt;T&gt; GetOrSet&lt;T&gt;(string key, Func&lt;Task&lt;T&gt;&gt; getData)<br>    {<br>        var cacheData = await db.StringGetAsync(key);<br><br>        if (!cacheData.HasValue)<br>        {<br>            var data = await getData();<br>            var cacheString = System.Text.Json.JsonSerializer.Serialize(data);<br>            await db.StringSetAsync(key, cacheString);<br>            cacheData = cacheString;<br>        }<br>        return System.Text.Json.JsonSerializer.Deserialize&lt;T&gt;(cacheData);<br>    }<br><br>    public async Task RemoveItem(string key)<br>    {<br>        await db.StringGetDeleteAsync(key);<br>    }<br>}</pre><p>Modify your Program.cs to incorporate the Redis caching:</p><pre>using CachingDemo.Cache;<br>using CachingDemo.Repository;<br>using CachingDemo.Service;<br>using Microsoft.AspNetCore.Mvc;<br>using Microsoft.Extensions.Caching.Memory;<br>using StackExchange.Redis;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br><br>builder.Services.AddScoped&lt;IDataRepository, DataRepository&gt;();<br>builder.Services.AddScoped&lt;IDataService, DataService&gt;();<br><br><br><br>builder.Services.AddSingleton(sp =&gt; ConnectionMultiplexer.Connect(&quot;redis&quot;));<br>builder.Services.AddSingleton&lt;RedisGenericCache&gt;();<br>builder.Services.Decorate&lt;IDataRepository, RedisDataRepository&gt;();<br><br>var app = builder.Build();<br><br>app.MapGet(&quot;/search&quot;, async ([FromQuery] string name, IDataService service) =&gt; await service.SearchEntities(name));<br>app.MapGet(&quot;/add&quot;, async ([FromQuery] string name, IDataService service) =&gt; await service.Add(name));<br><br>app.Run();</pre><p>In the above code, we register the RedisGenericCache and RedisDataRepository classes as singleton services. We then decorate the IDataRepository service with RedisDataRepository , which provide caching capabilities.</p><p>lets shutdown docker compose and build enw version of our api.</p><pre>docker compose down<br>docker build . -t api</pre><p>create file called redis.conf with content (it will be used later) and in file Dockerfile.redis add</p><pre>notify-keyspace-events AKE</pre><pre>FROM redis<br>COPY redis.conf /usr/local/etc/redis/redis.conf<br>CMD [ &quot;redis-server&quot;, &quot;/usr/local/etc/redis/redis.conf&quot; ]</pre><p>build redis docker file and lets add redis container to our docker compose file</p><pre>docker build . -f .\Dockerfile.redis -t myredis</pre><pre>version: &#39;2.1&#39;<br>services:<br>  redis:<br>    image: myredis<br>  api:<br>    image: api<br>    depends_on:<br>      - redis<br>  api2:<br>    image: api<br>    depends_on:<br>      - redis<br>  yarp:<br>    image: yarp<br>    ports:<br>      - &quot;8002:80&quot;</pre><p>start our instances and restart the test</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*_bQRPyqHiQLh4Lydl8b1Gg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WbVwGFl_aspqxPWDzG1hRA.png" /></figure><p>wow, but really nobody is surprised that adding caching improves performance greatly.</p><p>However using redis (or any other distributed caching mechanism) in real world scenario would add some network latency and some delay. Can we improve this? Can we add some in memory caching to this existing model?</p><p><strong>Adding in memory caching</strong></p><p>add file InMemoryGenericCache.cs</p><pre>public class InMemoryGenericCache : IGenericCache<br>{<br>    readonly IMemoryCache cache;<br>    public InMemoryGenericCache(IMemoryCache cache)<br>    {<br>        this.cache = cache;<br>    }<br><br>    public async Task&lt;T&gt; GetOrSet&lt;T&gt;(string key, Func&lt;Task&lt;T&gt;&gt; getData)<br>    {<br>        return await cache.GetOrCreateAsync(key, async (e) =&gt; await getData());<br>    }<br><br>    public async Task RemoveItem(string key)<br>    {<br>        cache.Remove(key);<br>    }<br>}</pre><p>and file InMemoryDataRepository.cs</p><pre>public class InMemoryDataRepository : InMemoryGenericCache, IDataRepository<br>{<br>    readonly IDataRepository repository;<br>    public InMemoryDataRepository(IDataRepository repository, IMemoryCache cache) : base(cache)<br>    {<br>        this.repository = repository;<br>    }<br><br>    public async Task Add(string name)<br>    {<br>        await RemoveItem($&quot;SearchEntities_{name}&quot;);<br>        await repository.Add(name);<br>    }<br><br>    public async Task&lt;IList&lt;DataEntity&gt;&gt; SearchEntities(string name)<br>    {<br>        return await GetOrSet($&quot;SearchEntities_{name}&quot;, () =&gt; repository.SearchEntities(name));<br>    }<br>}</pre><p>but wait, what will happen if data in redis cache is invalidated and in memory data is not cleared (on second pod or instance)?</p><p>lets use redis subscription to notify subscribers about deleting keys from redis.</p><p>add</p><pre>public interface IRedisSubscriber<br>{<br>    Task OnItemRemoved(string key);<br>}<br><br><br>public class RedisSubscriber : IRedisSubscriber<br>{<br>    readonly InMemoryGenericCache inMemoryGenericCache;<br>    readonly ILogger&lt;RedisSubscriber&gt; logger;<br>    public RedisSubscriber(InMemoryGenericCache inMemoryGenericCache,ILogger&lt;RedisSubscriber&gt; logger)<br>    {<br>        this.logger = logger;<br>        this.inMemoryGenericCache = inMemoryGenericCache;<br>    }<br>    public async Task OnItemRemoved(string key)<br>    {<br>        logger.LogInformation($&quot;redis key deleted {key}&quot;);<br>        await inMemoryGenericCache.RemoveItem(key);<br>    }<br>}<br><br>public class RedisSubscriberNotificationService : BackgroundService<br>{<br>    readonly IEnumerable&lt;IRedisSubscriber&gt; subscribers;<br>    readonly ConnectionMultiplexer redis;<br>    public RedisSubscriberNotificationService(IEnumerable&lt;IRedisSubscriber&gt; subscribers, ConnectionMultiplexer redis)<br>    {<br>        this.redis = redis;<br>        this.subscribers = subscribers;<br>    }<br><br>    protected async override Task ExecuteAsync(CancellationToken stoppingToken)<br>    {<br><br>        if (subscribers.Any())<br>        {<br>            var sub = redis.GetSubscriber();<br>            sub.Subscribe(&quot;__keyevent@0__:del&quot;, async (c, m) =&gt;<br>            {<br>                await Task.WhenAll(subscribers.Select(async subscriber =&gt; await subscriber.OnItemRemoved(m)));<br>            });<br>        }<br>    }<br>}</pre><p>by doing this we will be notified when redis key is removed and we can use this moment to clear same value from in memory cache.</p><p>modify Program.cs to incorporate new in memory caching</p><pre>using CachingDemo.Cache;<br>using CachingDemo.Repository;<br>using CachingDemo.Service;<br>using Microsoft.AspNetCore.Mvc;<br>using Microsoft.Extensions.Caching.Memory;<br>using StackExchange.Redis;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br><br>builder.Services.AddScoped&lt;IDataRepository, DataRepository&gt;();<br>builder.Services.AddScoped&lt;IDataService, DataService&gt;();<br><br><br><br>builder.Services.AddSingleton(sp =&gt; ConnectionMultiplexer.Connect(&quot;redis&quot;));<br>builder.Services.AddSingleton&lt;RedisGenericCache&gt;();<br>builder.Services.Decorate&lt;IDataRepository, RedisDataRepository&gt;();<br><br><br><br><br>builder.Services.AddSingleton&lt;IMemoryCache, MemoryCache&gt;();<br>builder.Services.AddSingleton&lt;InMemoryGenericCache&gt;();<br>builder.Services.Decorate&lt;IDataRepository, InMemoryDataRepository&gt;();<br><br>builder.Services.AddHostedService&lt;RedisSubscriberNotificationService&gt;();<br>builder.Services.AddSingleton&lt;IRedisSubscriber, RedisSubscriber&gt;();<br><br><br>var app = builder.Build();<br><br>app.MapGet(&quot;/search&quot;, async ([FromQuery] string name, IDataService service) =&gt; await service.SearchEntities(name));<br>app.MapGet(&quot;/add&quot;, async ([FromQuery] string name, IDataService service) =&gt; await service.Add(name));<br><br>app.Run();</pre><p>lets build our api image again and run the tests</p><pre>docker compose down<br>docker build . -t api<br>docker compose up</pre><p>lets review results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*UmihFnB-y5Ihvr3zMMq4Bw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4X8-4qLzYBaec_uSSWWeuA.png" /></figure><p>wow, we have great results , using both of caching mechanisms, in memory for speed, redis for durability and distribution and we are still able to return correct results.</p><p>entire code shown here can be found <a href="https://github.com/dejandjenic/CachingDemo">https://github.com/dejandjenic/CachingDemo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=500578ca6e28" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>