<?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"><channel><title><![CDATA[Dave K's Blog]]></title><description><![CDATA[Dave K's Blog]]></description><link>https://davek.dev</link><generator>RSS for Node</generator><lastBuildDate>Sun, 08 Nov 2026 14:44:41 GMT</lastBuildDate><atom:link href="https://davek.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Beginner's Guide to Semantic Kernel with Dapper, PostgreSQL, and PGVector in C#]]></title><description><![CDATA[Getting started with Microsoft Semantic Kernel using Dapper, PostgreSQL, and PGVector in C#]]></description><link>https://davek.dev/beginners-guide-to-semantic-kernel-with-dapper-postgresql-and-pgvector-in-c</link><guid isPermaLink="true">https://davek.dev/beginners-guide-to-semantic-kernel-with-dapper-postgresql-and-pgvector-in-c</guid><category><![CDATA[C#]]></category><category><![CDATA[AI]]></category><category><![CDATA[llm]]></category><category><![CDATA[PostgreSQL]]></category><category><![CDATA[openai]]></category><category><![CDATA[.NET]]></category><category><![CDATA[chatgpt]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Dave K]]></dc:creator><pubDate>Wed, 02 Oct 2024 18:14:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/UF3vfhV04SA/upload/461b66caa0e55154429ff1535f2857d2.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Semantic Kernel is an open-source framework by Microsoft that integrates machine learning and natural language processing to build AI applications.</p>
<p>It offers tools for tasks like language understanding, text generation, and semantic search, emphasizing modularity and easy customization.</p>
<p>The tutorial guides through setting up a C# Web API for uploading and querying text files using PostgreSQL with PGVector for vector database, configuring database services and dependencies, creating embeddings with AzureOpenAI, and utilizing the Semantic Kernel Memory plugin for persistent storage and intelligent querying. The example demonstrates the practical steps needed to implement and interact with these technologies in a seamless manner.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<ul>
<li><p>A C# compatible IDE, such as Visual Studio, Rider, or VS Code</p>
</li>
<li><p>An account with a compatible AI service (for this tutorial, I am using Azure Open AI)</p>
</li>
<li><p>Docker</p>
</li>
</ul>
<h2 id="heading-setting-up-postgres-with-pgvector">Setting up Postgres with PGVector</h2>
<p>To use Semantic Kernel, we need a vector database. Vector databases are specialized databases designed to store, index, and query high-dimensional vectors, enabling efficient similarity search and retrieval for tasks like machine learning and natural language processing.</p>
<p>For this tutorial, I’m going to use PostgreSQL. PostgreSQL is an open-source relational database management system known for its robustness, extensibility, and support for advanced data types and complex queries. Through the use of the PGVector extension, it is also very capable of handling vector embeddings. The easiest way to get started with this is to set up Docker and deploy the pgvector container with the following command:</p>
<pre><code class="lang-powershell">docker run -<span class="hljs-literal">-name</span> postgres <span class="hljs-literal">-e</span> POSTGRES_PASSWORD=mysecretpassword <span class="hljs-literal">-p</span> <span class="hljs-number">5432</span>:<span class="hljs-number">5432</span> <span class="hljs-literal">-d</span> pgvector/pgvector:pg16
</code></pre>
<h2 id="heading-creating-the-application">Creating the Application</h2>
<p>For this tutorial I’m going to set up a new C# Web API, that allows us to simply upload and query a text file.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">The full code for this example is available on github at <a target="_blank" href="https://github.com/davek-dev/semantic-kernel-demo">https://github.com/davek-dev/semantic-kernel-demo</a></div>
</div>

<p>Open up the IDE and start a new web project.</p>
<h3 id="heading-installing-the-dependencies">Installing the Dependencies</h3>
<p>Before we start, we’re going to need to install the following packages form Nuget into our project:</p>
<ul>
<li><p>Dapper</p>
</li>
<li><p>Pgvector.Dapper</p>
</li>
</ul>
<p>And if you’re using Azure Open AI then the following:</p>
<ul>
<li><p>Microsoft.AspNetCore.OpenApI</p>
</li>
<li><p>Microsoft.KernelMemory.Core</p>
</li>
<li><p>Microsoft.KernelMemory.MemoryDb.Postgres</p>
</li>
<li><p>Microsoft.KernelMemory.SemanticKernelPlugin</p>
</li>
<li><p>Microsoft.SemanticKernel</p>
</li>
<li><p>Microsoft.SemanticKernel.Connectors.OpenAI</p>
</li>
</ul>
<p>For different AI providers different packages will be required to some of those above.</p>
<h3 id="heading-configuring-the-database">Configuring the Database</h3>
<p>The first thing we need to do is set up our database to enable the PGVector extension. The full <a target="_blank" href="https://github.com/davek-dev/semantic-kernel-demo/blob/main/SemanticKernelDemo/Database/DbContext.cs">DbContext.cs is here</a>, but in summary, we have an <code>Init()</code> function that is called during the program start-up to create the database:</p>
<pre><code class="lang-csharp">    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">CreateDatabase</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-comment">// create database if it doesn't exist</span>
        <span class="hljs-keyword">await</span> <span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> connection = <span class="hljs-keyword">new</span> NpgsqlConnection(DbConstants.ConnectionString.Replace(DbConstants.DatabaseName, <span class="hljs-string">"postgres"</span>));
        <span class="hljs-keyword">var</span> sqlDbCount = <span class="hljs-string">$"SELECT EXISTS(SELECT datname FROM pg_catalog.pg_database WHERE datname = '<span class="hljs-subst">{DbConstants.DatabaseName}</span>');"</span>;
        <span class="hljs-keyword">var</span> dbCount = <span class="hljs-keyword">await</span> connection.ExecuteScalarAsync&lt;<span class="hljs-keyword">int</span>&gt;(sqlDbCount);
        <span class="hljs-keyword">if</span> (dbCount == <span class="hljs-number">0</span>)
        {
            <span class="hljs-keyword">var</span> sql = <span class="hljs-string">$"CREATE DATABASE \"<span class="hljs-subst">{DbConstants.DatabaseName}</span>\""</span>;
            <span class="hljs-keyword">await</span> connection.ExecuteAsync(sql);
        }
    }
</code></pre>
<p>and then enable the PGVector extension:</p>
<pre><code class="lang-csharp">    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">ConfigureVectors</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">await</span> <span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> connection =  CreateConnection() <span class="hljs-keyword">as</span> NpgsqlConnection;
        <span class="hljs-keyword">await</span> <span class="hljs-keyword">using</span> (<span class="hljs-keyword">var</span> cmd = <span class="hljs-keyword">new</span> NpgsqlCommand(<span class="hljs-string">"CREATE EXTENSION IF NOT EXISTS vector"</span>, connection))
        {
            <span class="hljs-keyword">await</span> cmd.ExecuteNonQueryAsync();
        }
        <span class="hljs-keyword">await</span> connection.ReloadTypesAsync();
    }
</code></pre>
<p>It is important to call <code>ReloadTypesAsync()</code> on the connection to ensure vector types are loaded into our application.</p>
<p>In our <code>CreateConnection()</code> function, we also configure our data source to use vectors:</p>
<pre><code class="lang-csharp">    <span class="hljs-function"><span class="hljs-keyword">public</span> IDbConnection <span class="hljs-title">CreateConnection</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">var</span> dataSourceBuilder = <span class="hljs-keyword">new</span> NpgsqlDataSourceBuilder(DbConstants.ConnectionString);
        dataSourceBuilder.UseVector();
        <span class="hljs-keyword">var</span> dataSource = dataSourceBuilder.Build();
        <span class="hljs-keyword">return</span> dataSource.OpenConnection();
    }
</code></pre>
<p>We also need to configure Dapper to handle vector types. We can do this by calling <code>SqlMapper.AddTypeHandler(new VectorTypeHandler());</code> in our startup code. In this example, I have moved our startup code to create and configure our database into an <a target="_blank" href="https://github.com/davek-dev/semantic-kernel-demo/blob/main/SemanticKernelDemo/Database/DatabaseExtensions.cs">extension method</a> that is called when the program starts.</p>
<pre><code class="lang-csharp">    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">ConfigureDatabaseServices</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> WebApplication app</span>)</span>
    {
        SqlMapper.AddTypeHandler(<span class="hljs-keyword">new</span> VectorTypeHandler());

        <span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> scope = app.Services.CreateScope();
        <span class="hljs-keyword">var</span> context = scope.ServiceProvider.GetRequiredService&lt;DbContext&gt;();
        Task.Run(() =&gt; context.Init()).Wait();
    }
</code></pre>
<h3 id="heading-adding-ai">Adding AI</h3>
<p>To use AI in our applications, we basically need to split our process into 2 parts. Loading the data which involves creating embeddings from our data, and querying the embeddings once we have loaded it.</p>
<h3 id="heading-embeddings">Embeddings</h3>
<p>Embeddings are dense vector representations of data, like words or images, that capture relationships and similarities. This makes processing and analysis in machine learning and natural language processing tasks more efficient.</p>
<p>In our example, we use <code>AzureOpenAITextEmbeddingGeneration</code> to create embeddings.</p>
<p>After creating the embeddings, we store them in our database for querying.</p>
<h3 id="heading-adding-the-memory">Adding the Memory</h3>
<p>To store the vectors in our PostgreSQL database, we can use the Semantic Kernel Memory plugin.</p>
<p>The Semantic Kernel Memory plugin enhances the Semantic Kernel framework by enabling persistent memory storage for embeddings and other data. This allows applications to remember context and improve their ability to retrieve relevant information over time. It helps in tasks like conversational AI and recommendation systems by facilitating more intelligent interactions and better performance.</p>
<p>Again, we set up the Kernel and Memory at startup through an extension method. The full code for setting up Semantic Kernel and Memory is available <a target="_blank" href="https://github.com/davek-dev/semantic-kernel-demo/blob/main/SemanticKernelDemo/SemanticKernel/SemanticKernelExtensions.cs">here</a>, but to summarise:</p>
<p>Firstly, I had to specify the embedding dimensions as 1536 (<code>EmbeddingDimensions = 1536</code>), since PGVector has a limit on vector dimensions, which the newest OpenAI models exceed. 1536 should be sufficient for most use cases.</p>
<p>You can also see some other configurations around partition size and tokens. You can adjust these to best suit your use case or leave them as they are.</p>
<p>Then, we add the PostgreSQL connection string and build the kernel memory.</p>
<p>Finally we build the Kernel Memory, build the KErnel then add the memory to the Kernel through the plugin:</p>
<pre><code class="lang-csharp">    <span class="hljs-comment">//...ommited for brevity    </span>
    <span class="hljs-keyword">var</span> kernelBuilder = Kernel.CreateBuilder();

    kernelBuilder.Services.AddAzureOpenAIChatCompletion(AzureOpenAiChatCompletionDeployment, AzureOpenAiEndpoint,
        AzureOpenAiApiKey);

    <span class="hljs-keyword">var</span> kernel = kernelBuilder.Build();

    <span class="hljs-keyword">var</span> plugin = <span class="hljs-keyword">new</span> MemoryPlugin(memory, <span class="hljs-string">"kernelMemory"</span>);
    kernel.ImportPluginFromObject(plugin, <span class="hljs-string">"memory"</span>);
</code></pre>
<h3 id="heading-consuming-the-kernel">Consuming the Kernel</h3>
<p>To use the Kernel we have just built, for this tutorial I have created a simple service that can simply import test into memory or query the memory to produce a response:</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> class <span class="hljs-title">SemanticKernelService</span>(<span class="hljs-params">Kernel kernel, IKernelMemory memory</span>) : ISemanticKernelService</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">ImportText</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> text</span>)</span>
    {
        <span class="hljs-keyword">await</span> memory.ImportTextAsync(text);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;<span class="hljs-keyword">string</span>&gt; <span class="hljs-title">Query</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> query</span>)</span>
    {
        <span class="hljs-keyword">var</span> result = <span class="hljs-keyword">await</span> memory.AskAsync(query);
        <span class="hljs-keyword">return</span> result.Result;
    }
}
</code></pre>
<p>And created a couple of Endpoints in our <a target="_blank" href="https://github.com/davek-dev/semantic-kernel-demo/blob/main/SemanticKernelDemo/Program.cs">Program.cs</a> to allow us to upload a text file to create embeddings, and then query the data:</p>
<pre><code class="lang-csharp"><span class="hljs-comment">//...ommited for brevity  </span>
app.MapPost(<span class="hljs-string">"Query"</span>,
        <span class="hljs-keyword">async</span> (ISemanticKernelService semanticKernelService, <span class="hljs-keyword">string</span> query) =&gt;
        {
            <span class="hljs-keyword">var</span> result = <span class="hljs-keyword">await</span> semanticKernelService.Query(query);
            <span class="hljs-keyword">return</span> TypedResults.Ok(result);
        })
    .WithOpenApi(operation =&gt;
    {
        operation.Summary = <span class="hljs-string">"Query Transcriptions"</span>;
        operation.Description = <span class="hljs-string">"Query Transcriptions"</span>;
        operation.Tags = <span class="hljs-keyword">new</span> List&lt;OpenApiTag&gt; { <span class="hljs-keyword">new</span>() { Name = <span class="hljs-string">"AI"</span> } };

        <span class="hljs-keyword">return</span> operation;
    });

app.MapPost(<span class="hljs-string">"/upload"</span>,
        <span class="hljs-keyword">async</span> (IFormFile file) =&gt;
        {
            <span class="hljs-keyword">await</span> <span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> stream = file.OpenReadStream();
            <span class="hljs-keyword">var</span> buffer = <span class="hljs-keyword">new</span> <span class="hljs-keyword">byte</span>[stream.Length];
            <span class="hljs-keyword">await</span> stream.ReadAsync(buffer);
            <span class="hljs-keyword">var</span> text = Encoding.UTF8.GetString(buffer);

            <span class="hljs-keyword">var</span> semanticKernelService = app.Services.GetRequiredService&lt;ISemanticKernelService&gt;();
            <span class="hljs-keyword">await</span> semanticKernelService.ImportText(text);

            <span class="hljs-keyword">return</span> TypedResults.Ok();
        })
    .DisableAntiforgery();

app.Run();
</code></pre>
<h3 id="heading-running-our-application">Running Our Application</h3>
<p>We can run our application, upload a text file and query it through the build in Swagger page.</p>
<p>In the below example I simply uploaded this text file and then asked a question to the query endpoint:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1727877165148/c99fa965-9003-4953-b4d2-ecab03600971.jpeg" alt class="image--center mx-auto" /></p>
<p>I hope you enjoyed this tutorial and found it useful. If you did please give me a shout out.</p>
]]></content:encoded></item><item><title><![CDATA[.NET MAUI - Saving PDF Files with ITextSharp]]></title><description><![CDATA[In the earlier articles in my PDF Splitter series, we have relied on the inbuild .NET libraries to handle working with PDF files in MAUI, but these only…]]></description><link>https://davek.dev/net-maui-saving-pdf-files-with-itextsharp</link><guid isPermaLink="true">https://davek.dev/net-maui-saving-pdf-files-with-itextsharp</guid><category><![CDATA[.NET]]></category><category><![CDATA[#dotnet-maui]]></category><category><![CDATA[C#]]></category><category><![CDATA[software development]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Dave K]]></dc:creator><pubDate>Thu, 03 Aug 2023 13:56:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/zwKoA_0CWgg/upload/b13ba612e5444575c77625b16704c1f1.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>In the earlier articles in my <a target="_blank" href="https://davek.dev/series/pdf-splitter">PDF Splitter series</a>, we have relied on the inbuild .NET libraries to handle working with PDF files in MAUI, but these only support opening and displaying of PDF files. Now that we are looking to save our newly splitwe have to look eslewhere and in this article we will be using the <a target="_blank" href="https://github.com/VahidN/iTextSharp.LGPLv2.Core">LGPLv2 net core version of ITextSharp</a> and the MAUI FileSaveViewer to write a PDF file to disk.</p>
<h3 id="heading-add-the-reference">Add the Reference</h3>
<p>The first thing we need to do is install the iTextSharp LGPLv2 package from nuget:</p>
<pre><code class="lang-bash">Install-Package iTextSharp.LGPLv2.Core
</code></pre>
<h3 id="heading-creating-a-save-file-service">Creating a Save File Service</h3>
<p>Then we add a new SavePdfService.cs file to our services directory.</p>
<p>To create our new PDF we need our service save function to accept three inputs:</p>
<ul>
<li><p>The original PDF file path - As we are now working with a different library, we will need to open the original PDF file using that library.</p>
</li>
<li><p>A StorageFile - A StorgateFile object is what's returned from the inbuilt MAUI FileSavePicker and provides a stream for us to write our file to.</p>
</li>
<li><p>A list of page numbers to extract into our output file.</p>
</li>
</ul>
<p>We can then open the original pdf using iTextSharps PdfReader and select the pages we would like to extract from the file.</p>
<p>We then use the pdfStamper to write those pages into a new MemoryStream, before resetting the position of the stream to the start, and copying the contents of our memory stream into our StorageFile stream:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">SavePdfService</span> : <span class="hljs-title">ISavePdfService</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">SavePdf</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> inputFile, StorageFile outputFile, IEnumerable&lt;<span class="hljs-keyword">int</span>&gt; pages</span>)</span>
    {
        <span class="hljs-keyword">var</span> stream = <span class="hljs-keyword">await</span> outputFile.OpenAsync(FileAccessMode.ReadWrite);
        <span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> outputStream = stream.GetOutputStreamAt(<span class="hljs-number">0</span>);

        <span class="hljs-keyword">var</span> pdfStream = <span class="hljs-keyword">new</span> MemoryStream();

        <span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> reader = <span class="hljs-keyword">new</span> PdfReader(inputFile);
        reader.SelectPages(pages.ToArray());

        PdfStamper stamper = <span class="hljs-keyword">new</span> PdfStamper(reader, pdfStream);
        stamper.Close();

        pdfStream.Position = <span class="hljs-number">0</span>;

        <span class="hljs-keyword">await</span> pdfStream.CopyToAsync(outputStream.AsStreamForWrite((<span class="hljs-keyword">int</span>)pdfStream.Length));

        stream.Dispose();            
    }
}
</code></pre>
<p>We then need to ensure we extract an interface of our service and register it in our MauiProgram.cs file alongside our existing PdfService:</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> MauiAppBuilder <span class="hljs-title">RegisterAppServices</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> MauiAppBuilder builder</span>)</span>
{
    builder.Services.AddSingleton&lt;IPdfService, PdfService&gt;();
    builder.Services.AddSingleton&lt;ISavePdfService, SavePdfService&gt;();

    <span class="hljs-keyword">return</span> builder;
}
</code></pre>
<h3 id="heading-updating-our-views">Updating Our Views</h3>
<p>Finally, we can hook up our save functionality by adding the OnSaveFileCommand and associated handler to our PdfViewPageViewModel:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">PdfViewPageViewModel</span> : <span class="hljs-title">BindableModelBase</span>
{
    <span class="hljs-keyword">private</span> IPdfService _pdfService;
    <span class="hljs-keyword">private</span> ISavePdfService _savePdfService;
    <span class="hljs-keyword">private</span> PdfPageItem _selectedPageItem;
    <span class="hljs-keyword">public</span> ICommand OnItemSelectedCommand { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">private</span> <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> ICommand OnItemRemovedCommand { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">private</span> <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> ICommand OnSaveFileCommand { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">private</span> <span class="hljs-keyword">set</span>; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">PdfViewPageViewModel</span>(<span class="hljs-params">IPdfService pdfService, ISavePdfService savePdfService</span>)</span>
    {
        _pdfService = pdfService;
        _savePdfService = savePdfService;
        OnItemSelectedCommand = <span class="hljs-keyword">new</span> Command(SelectPage);
        OnItemRemovedCommand = <span class="hljs-keyword">new</span> Command&lt;<span class="hljs-keyword">string</span>&gt;(RemovePage);
        OnSaveFileCommand =  <span class="hljs-keyword">new</span> Command&lt;<span class="hljs-keyword">string</span>&gt;(<span class="hljs-keyword">async</span> (s) =&gt; <span class="hljs-keyword">await</span> OnSaveClicked(s));
    }

    <span class="hljs-comment">//.. Code ommited for brevity</span>

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">OnSaveClicked</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> s</span>)</span>
    {
        <span class="hljs-keyword">var</span> window = <span class="hljs-keyword">new</span> Microsoft.UI.Xaml.Window();
        <span class="hljs-keyword">var</span> hwnd = WinRT.Interop.WindowNative.GetWindowHandle(window);

        FileSavePicker savePicker = <span class="hljs-keyword">new</span> FileSavePicker();
        savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
        savePicker.FileTypeChoices.Add(<span class="hljs-string">"PDF Document"</span>, <span class="hljs-keyword">new</span> List&lt;<span class="hljs-keyword">string</span>&gt;() { <span class="hljs-string">".pdf"</span> });
        savePicker.SuggestedFileName = <span class="hljs-string">$"New_Document_<span class="hljs-subst">{DateTime.Now:ddMMyyyy_HHmmss}</span>"</span>;

        WinRT.Interop.InitializeWithWindow.Initialize(savePicker, hwnd);
        <span class="hljs-keyword">var</span> file = <span class="hljs-keyword">await</span> savePicker.PickSaveFileAsync();

        <span class="hljs-keyword">await</span> _savePdfService.SavePdf(_pdfService.PdfFilePath, file, _pdfService.SelectedItems.Select(x =&gt; x.PageNumber).ToList());

        <span class="hljs-keyword">await</span> App.Current.MainPage.DisplayAlert(<span class="hljs-string">"Success"</span>, <span class="hljs-string">"File has been saved"</span>, <span class="hljs-string">"OK"</span>);
        _pdfService.SelectedItems.Clear();
        NotifyPropertyChanged(() =&gt; DisplaySaveButton);
    }


    <span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> DisplaySaveButton =&gt; _pdfService.SelectedItems.Any();
}
</code></pre>
<p>And adding our 'Save' button to our view by creating a PdfSaveControl:</p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;?xml version="1.0" encoding="utf-8" ?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">ContentView</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://schemas.microsoft.com/dotnet/2021/maui"</span>
             <span class="hljs-attr">xmlns:x</span>=<span class="hljs-string">"http://schemas.microsoft.com/winfx/2009/xaml"</span>
             <span class="hljs-attr">xmlns:fonts</span>=<span class="hljs-string">"clr-namespace:PdfSplitter.Fonts"</span>
             <span class="hljs-attr">x:Name</span>=<span class="hljs-string">"this"</span>
             <span class="hljs-attr">x:Class</span>=<span class="hljs-string">"PdfSplitter.Controls.PdfSaveControl"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">VerticalStackLayout</span> <span class="hljs-attr">BindingContext</span>=<span class="hljs-string">"{x:Reference this}"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Button</span>  
            <span class="hljs-attr">x:Name</span>=<span class="hljs-string">"Save"</span>
            <span class="hljs-attr">Margin</span>=<span class="hljs-string">"5"</span>
            <span class="hljs-attr">CornerRadius</span>=<span class="hljs-string">"10"</span>
            <span class="hljs-attr">BackgroundColor</span>=<span class="hljs-string">"DarkGreen"</span>
            <span class="hljs-attr">TextColor</span>=<span class="hljs-string">"White"</span>
            <span class="hljs-attr">FontFamily</span>=<span class="hljs-string">"Icons"</span> 
            <span class="hljs-attr">FontAttributes</span>=<span class="hljs-string">"Bold"</span>
            <span class="hljs-attr">FontSize</span>=<span class="hljs-string">"20"</span>
            <span class="hljs-attr">Text</span>=<span class="hljs-string">"{x:Static fonts:MaterialDesignRegular.Save}"</span>
            <span class="hljs-attr">Command</span>=<span class="hljs-string">"{Binding SaveCommand}"</span>
            <span class="hljs-attr">SemanticProperties.Hint</span>=<span class="hljs-string">"Save selected pages to new document."</span>
            <span class="hljs-attr">HorizontalOptions</span>=<span class="hljs-string">"End"</span>
            <span class="hljs-attr">VerticalOptions</span>=<span class="hljs-string">"End"</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">VerticalStackLayout</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">ContentView</span>&gt;</span>
</code></pre>
<p>Inserting the new control into the main PdfViewPage view in our final grid space:</p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;?xml version="1.0" encoding="utf-8" ?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">ContentPage</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://schemas.microsoft.com/dotnet/2021/maui"</span>
             <span class="hljs-attr">xmlns:x</span>=<span class="hljs-string">"http://schemas.microsoft.com/winfx/2009/xaml"</span>
             <span class="hljs-attr">xmlns:Controls</span>=<span class="hljs-string">"clr-namespace:PdfSplitter.Controls"</span>
             <span class="hljs-attr">x:Class</span>=<span class="hljs-string">"PdfSplitter.Views.PdfViewPage"</span>             
             <span class="hljs-attr">x:Name</span>=<span class="hljs-string">"pdfExtractorViewPage"</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">Grid</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Grid.RowDefinitions</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">RowDefinition</span> <span class="hljs-attr">Height</span>=<span class="hljs-string">"4*"</span> /&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">RowDefinition</span> <span class="hljs-attr">Height</span>=<span class="hljs-string">"auto"</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Grid.RowDefinitions</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Grid.ColumnDefinitions</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">ColumnDefinition</span> <span class="hljs-attr">Width</span>=<span class="hljs-string">"5*"</span> /&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">ColumnDefinition</span> <span class="hljs-attr">Width</span>=<span class="hljs-string">"*"</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Grid.ColumnDefinitions</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Controls:PdfPageContent</span> <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">Grid.Column</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">Page</span>=<span class="hljs-string">"{Binding SelectedPageItem}"</span> <span class="hljs-attr">SelectPageCommand</span>=<span class="hljs-string">"{Binding OnItemSelectedCommand}"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Controls:PdfPages</span> <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">Grid.Column</span>=<span class="hljs-string">"1"</span> <span class="hljs-attr">Grid.RowSpan</span>=<span class="hljs-string">"2"</span> <span class="hljs-attr">Pages</span>=<span class="hljs-string">"{Binding Items}"</span> <span class="hljs-attr">SelectedPage</span>=<span class="hljs-string">"{Binding SelectedPageItem, Mode=TwoWay}"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Controls:PdfSelectedPages</span>  <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"1"</span> <span class="hljs-attr">Grid.Column</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">SelectedPages</span>=<span class="hljs-string">"{Binding SelectedItems}"</span> <span class="hljs-attr">RemovePageCommand</span>=<span class="hljs-string">"{Binding OnItemRemovedCommand}"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Controls:PdfSaveControl</span>  <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"1"</span> <span class="hljs-attr">Grid.Column</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">SaveCommand</span>=<span class="hljs-string">"{Binding OnSaveFileCommand}"</span> <span class="hljs-attr">IsVisible</span>=<span class="hljs-string">"{Binding DisplaySaveButton}"</span> <span class="hljs-attr">VerticalOptions</span>=<span class="hljs-string">"End"</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Grid</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">ContentPage</span>&gt;</span>
</code></pre>
<h3 id="heading-conclusion">Conclusion</h3>
<p>This concludes my series for creating a PDF Splitter application from scratch in .NET MAUI.</p>
<p>The full code is available on my <a target="_blank" href="https://github.com/davek-dev/PdfSplitter">GitHub here</a> and may receive further updates and improvements as I continue to develop and enhance the application.</p>
<p>Thanks for reading!</p>
]]></content:encoded></item><item><title><![CDATA[.NET MAUI - Working with PDF Files Pt. 2]]></title><description><![CDATA[In the previous article, we created a PDF model and service to allow us to work with and track PDF pages. The next step is to build the UI to allow us to…]]></description><link>https://davek.dev/net-maui-working-with-pdf-files-pt-2</link><guid isPermaLink="true">https://davek.dev/net-maui-working-with-pdf-files-pt-2</guid><category><![CDATA[C#]]></category><category><![CDATA[.NET]]></category><category><![CDATA[Blogging]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[#dotnet-maui]]></category><dc:creator><![CDATA[Dave K]]></dc:creator><pubDate>Wed, 02 Aug 2023 13:58:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/gcHFXsdcmJE/upload/a748787f9385d3a08244eb7acfd6056b.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>In the <a target="_blank" href="https://davek.dev/net-maui-working-with-pdf-files-pt-1">previous article</a>, we created a PDF model and service to allow us to work with and track PDF pages. The next step is to build the UI to allow us to interact with the service.</p>
<p>To do this we will create a single 'view' and a 'view model' (see article on MVVM for more detail on the design patterns), and controls for displaying the list of pages, page content and any selected pages.</p>
<h3 id="heading-updating-the-file-menu">Updating the File Menu</h3>
<p>Before we can do any of the above, we should first update our <a target="_blank" href="https://davek.dev/net-maui-creating-a-xaml-file-menu">file menu</a> to allow us to select a PDF file to load and display.</p>
<p>Add the following to our AppShellViewModel.cs to inject out pdf service and use the inbuilt MAUI FilePicker control to allow us to select and load a PDF file.</p>
<p>Note: The code also includes navigation to route to our PDF View page that we <a target="_blank" href="https://davek.dev/net-maui-basic-navigation">previously created</a>. We'll be adding code to this during this article so we should start to see everything come together.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">AppShellViewModel</span>
{
    <span class="hljs-keyword">private</span> IPdfService _pdfService;

    <span class="hljs-keyword">public</span> ICommand OnMenuItemClickedCommand { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">private</span> <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> ICommand OnMenuItemClosePdfClickedCommand { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">private</span> <span class="hljs-keyword">set</span>; }

    <span class="hljs-keyword">public</span> ICommand OnMenuItemAboutClickedCommand { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">private</span> <span class="hljs-keyword">set</span>; }

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">bool</span> PdfOpen = <span class="hljs-literal">false</span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">AppShellViewModel</span>(<span class="hljs-params">IPdfService pdfService</span>)</span>
    {
        _pdfService= pdfService;

        OnMenuItemClickedCommand = <span class="hljs-keyword">new</span> Command&lt;<span class="hljs-keyword">string</span>&gt;(<span class="hljs-keyword">async</span> (s) =&gt; <span class="hljs-keyword">await</span> OnMenuItemClicked(s));
        OnMenuItemClosePdfClickedCommand = <span class="hljs-keyword">new</span> Command&lt;<span class="hljs-keyword">string</span>&gt;(<span class="hljs-keyword">async</span> (s) =&gt; <span class="hljs-keyword">await</span> OnMenuItemClicked(s), (s) =&gt; PdfOpen);

        OnMenuItemAboutClickedCommand = <span class="hljs-keyword">new</span> Command(DisplayAbout);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">OnMenuItemClicked</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> item</span>)</span>
    {
        <span class="hljs-keyword">switch</span> (item) {
            <span class="hljs-keyword">case</span> <span class="hljs-string">"Exit"</span>:
                Application.Current.Quit();
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">"Open"</span>:
                <span class="hljs-keyword">await</span> SelectFile();
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">"Close"</span>:
                <span class="hljs-keyword">await</span> CloseFile();
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">default</span>:
                <span class="hljs-keyword">break</span>;
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">SelectFile</span>(<span class="hljs-params"></span>)</span>
    {        
        <span class="hljs-keyword">var</span> options = <span class="hljs-keyword">new</span> PickOptions()
        {
            FileTypes = FilePickerFileType.Pdf
        };

        <span class="hljs-keyword">var</span> fileResult = <span class="hljs-keyword">await</span> FilePicker.PickAsync(options);

        <span class="hljs-keyword">if</span> (fileResult != <span class="hljs-literal">null</span>)
        {
            <span class="hljs-keyword">await</span> _pdfService.LoadPdf(fileResult.FullPath);

            PdfOpen = <span class="hljs-literal">true</span>;
            (OnMenuItemClosePdfClickedCommand <span class="hljs-keyword">as</span> Command).ChangeCanExecute();
            <span class="hljs-keyword">await</span> Shell.Current.GoToAsync(<span class="hljs-keyword">nameof</span>(PdfViewPage));
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">CloseFile</span>(<span class="hljs-params"></span>)</span>
    {
        _pdfService.UnloadPdf();
        PdfOpen = <span class="hljs-literal">false</span>;
        (OnMenuItemClosePdfClickedCommand <span class="hljs-keyword">as</span> Command).ChangeCanExecute();
        <span class="hljs-keyword">await</span> Shell.Current.GoToAsync(<span class="hljs-string">$"//<span class="hljs-subst">{<span class="hljs-keyword">nameof</span>(MainPage)}</span>"</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DisplayAbout</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">var</span> about = <span class="hljs-keyword">new</span> Window(<span class="hljs-keyword">new</span> About(<span class="hljs-keyword">new</span> AboutViewModel()));
        about.Width = <span class="hljs-number">650</span>;
        about.Height = <span class="hljs-number">300</span>;
        Application.Current.OpenWindow(about);
    }
}
</code></pre>
<h3 id="heading-creating-the-page-list-control">Creating the Page List Control</h3>
<p>The first thing we need to do is create a control to display the preview of pages from within our PDF File.</p>
<p>By breaking our page down into controls we can build quite complex UI's with simple building blocks. Our page list control is simply a list view nested in a scroll view, within which we provide a custom data template that is repeated for each page.</p>
<p>The list view is bound to our pages list, and we will also provide a function to allow an item to be selected, in this case, we've limited it to a single item. These bindings will come from our PdfViewPage xaml view and PdfViewPageViewModel which we will complete at the end of this article.</p>
<p>The template itself is just a grid with the image control to bind to our page item preview and a label that binds to the page item name.</p>
<p>It is important to mention how the binding context of controls is set to match the x:Name in the ContentView (usually just set to 'this') to handle the scope of the bindings.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">ContentView</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://schemas.microsoft.com/dotnet/2021/maui"</span>
             <span class="hljs-attr">xmlns:x</span>=<span class="hljs-string">"http://schemas.microsoft.com/winfx/2009/xaml"</span>
             <span class="hljs-attr">x:Class</span>=<span class="hljs-string">"PdfSplitter.Controls.PdfPages"</span>
             <span class="hljs-attr">x:Name</span>=<span class="hljs-string">"this"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">ScrollView</span> <span class="hljs-attr">BindingContext</span>=<span class="hljs-string">"{x:Reference this}"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">ListView</span> <span class="hljs-attr">ItemsSource</span>=<span class="hljs-string">"{Binding Pages}"</span> <span class="hljs-attr">SelectionMode</span>=<span class="hljs-string">"Single"</span> <span class="hljs-attr">SelectedItem</span>=<span class="hljs-string">"{Binding SelectedPage}"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">ListView.ItemTemplate</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">DataTemplate</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">ViewCell</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">Grid</span> <span class="hljs-attr">Padding</span>=<span class="hljs-string">"10"</span> <span class="hljs-attr">MaximumWidthRequest</span>=<span class="hljs-string">"120"</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">Grid.RowDefinitions</span>&gt;</span>
                                <span class="hljs-tag">&lt;<span class="hljs-name">RowDefinition</span> <span class="hljs-attr">Height</span>=<span class="hljs-string">"6*"</span> /&gt;</span>
                                <span class="hljs-tag">&lt;<span class="hljs-name">RowDefinition</span> <span class="hljs-attr">Height</span>=<span class="hljs-string">"auto"</span> /&gt;</span>
                            <span class="hljs-tag">&lt;/<span class="hljs-name">Grid.RowDefinitions</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">Grid.ColumnDefinitions</span>&gt;</span>
                                <span class="hljs-tag">&lt;<span class="hljs-name">ColumnDefinition</span> <span class="hljs-attr">Width</span>=<span class="hljs-string">"*"</span> /&gt;</span>
                            <span class="hljs-tag">&lt;/<span class="hljs-name">Grid.ColumnDefinitions</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">Image</span> <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">Grid.Column</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">Margin</span>=<span class="hljs-string">"0, 5, 0, 0"</span> <span class="hljs-attr">Source</span>=<span class="hljs-string">"{Binding Preview}"</span> /&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">Label</span> <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"1"</span>  <span class="hljs-attr">Grid.Column</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">Text</span>=<span class="hljs-string">"{Binding PageName}"</span> <span class="hljs-attr">HorizontalOptions</span>=<span class="hljs-string">"Center"</span> <span class="hljs-attr">Margin</span>=<span class="hljs-string">"0"</span> /&gt;</span>
                        <span class="hljs-tag">&lt;/<span class="hljs-name">Grid</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">ViewCell</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">DataTemplate</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">ListView.ItemTemplate</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">ListView</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">ScrollView</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">ContentView</span>&gt;</span>
</code></pre>
<h3 id="heading-creating-the-page-view-component">Creating the Page View Component</h3>
<p>In a similar fashion to the page list control for displaying the preview, we can create another control for displaying the 'selected' page. In this control, we simply create a 2-row grid, as want to display an image control which we bind to our page 'PageView' ImageSource function created in the <a target="_blank" href="https://davek.dev/net-maui-working-with-pdf-files-pt-1">previous article</a> and add a button to allow us to select and add the page to our 'extracted' pdf.</p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;?xml version="1.0" encoding="utf-8" ?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">ContentView</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://schemas.microsoft.com/dotnet/2021/maui"</span>
             <span class="hljs-attr">xmlns:x</span>=<span class="hljs-string">"http://schemas.microsoft.com/winfx/2009/xaml"</span>
             <span class="hljs-attr">x:Name</span>=<span class="hljs-string">"this"</span>
             <span class="hljs-attr">x:Class</span>=<span class="hljs-string">"PdfSplitter.Controls.PdfPageContent"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Grid</span> <span class="hljs-attr">BindingContext</span>=<span class="hljs-string">"{x:Reference this}"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Grid.RowDefinitions</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">RowDefinition</span> <span class="hljs-attr">Height</span>=<span class="hljs-string">"1*"</span> /&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">RowDefinition</span> <span class="hljs-attr">Height</span>=<span class="hljs-string">"auto"</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Grid.RowDefinitions</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Image</span> <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">Margin</span>=<span class="hljs-string">"0, 10, 0, 0"</span> <span class="hljs-attr">Source</span>=<span class="hljs-string">"{Binding Page.PageView}"</span>  /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Button</span> 
            <span class="hljs-attr">x:Name</span>=<span class="hljs-string">"SelectPage"</span>
            <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"1"</span> 
            <span class="hljs-attr">Margin</span>=<span class="hljs-string">"5"</span>
            <span class="hljs-attr">Text</span>=<span class="hljs-string">"Add to Extracted File"</span> 
            <span class="hljs-attr">Command</span>=<span class="hljs-string">"{Binding SelectPageCommand}"</span>
            <span class="hljs-attr">SemanticProperties.Hint</span>=<span class="hljs-string">"Add page to extracted document."</span>
            <span class="hljs-attr">HorizontalOptions</span>=<span class="hljs-string">"Center"</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Grid</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">ContentView</span>&gt;</span>
</code></pre>
<h3 id="heading-creating-the-selected-items-control">Creating the Selected Items Control</h3>
<p>Finally, we need a control to display our selected pages. This is very similar to our preview control in that it will display the preview image and the page name of selected pages. However, in this instance, we will display the pages horizontally rather than vertically, and also add a button to allow us to remove a selected page and return it to our original document page list, in case we select a page incorrectly.</p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;?xml version="1.0" encoding="utf-8" ?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">ContentView</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://schemas.microsoft.com/dotnet/2021/maui"</span>
             <span class="hljs-attr">xmlns:x</span>=<span class="hljs-string">"http://schemas.microsoft.com/winfx/2009/xaml"</span>
             <span class="hljs-attr">xmlns:fonts</span>=<span class="hljs-string">"clr-namespace:PdfSplitter.Fonts"</span>
             <span class="hljs-attr">x:Name</span>=<span class="hljs-string">"this"</span>
             <span class="hljs-attr">x:Class</span>=<span class="hljs-string">"PdfSplitter.Controls.PdfSelectedPages"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">ScrollView</span> <span class="hljs-attr">Orientation</span>=<span class="hljs-string">"Horizontal"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">StackLayout</span> <span class="hljs-attr">BindingContext</span>=<span class="hljs-string">"{x:Reference this}"</span> <span class="hljs-attr">BindableLayout.ItemsSource</span>=<span class="hljs-string">"{Binding SelectedPages}"</span> <span class="hljs-attr">Orientation</span>=<span class="hljs-string">"Horizontal"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">BindableLayout.ItemTemplate</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">DataTemplate</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">Grid</span> <span class="hljs-attr">Padding</span>=<span class="hljs-string">"5,2,0,2"</span> <span class="hljs-attr">MaximumHeightRequest</span>=<span class="hljs-string">"180"</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">Grid.RowDefinitions</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">RowDefinition</span> <span class="hljs-attr">Height</span>=<span class="hljs-string">"1*"</span> /&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">RowDefinition</span> <span class="hljs-attr">Height</span>=<span class="hljs-string">"auto"</span> /&gt;</span>
                        <span class="hljs-tag">&lt;/<span class="hljs-name">Grid.RowDefinitions</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">Grid.ColumnDefinitions</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">ColumnDefinition</span> <span class="hljs-attr">Width</span>=<span class="hljs-string">"*"</span> /&gt;</span>
                        <span class="hljs-tag">&lt;/<span class="hljs-name">Grid.ColumnDefinitions</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">Image</span> <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">Grid.Column</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">Margin</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">Source</span>=<span class="hljs-string">"{Binding Preview}"</span> <span class="hljs-attr">ZIndex</span>=<span class="hljs-string">"0"</span> /&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">Label</span> <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"1"</span>  <span class="hljs-attr">Grid.Column</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">Text</span>=<span class="hljs-string">"{Binding PageName}"</span> <span class="hljs-attr">HorizontalOptions</span>=<span class="hljs-string">"Center"</span> <span class="hljs-attr">Margin</span>=<span class="hljs-string">"0"</span> /&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">Button</span> 
                            <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"0"</span> 
                            <span class="hljs-attr">Grid.Column</span>=<span class="hljs-string">"0"</span> 
                            <span class="hljs-attr">Margin</span>=<span class="hljs-string">"2"</span>
                            <span class="hljs-attr">Padding</span>=<span class="hljs-string">"0"</span>
                            <span class="hljs-attr">CornerRadius</span>=<span class="hljs-string">"10"</span>
                            <span class="hljs-attr">BackgroundColor</span>=<span class="hljs-string">"DarkRed"</span>
                            <span class="hljs-attr">BorderColor</span>=<span class="hljs-string">"Black"</span>
                            <span class="hljs-attr">BorderWidth</span>=<span class="hljs-string">"1"</span>                            
                            <span class="hljs-attr">TextColor</span>=<span class="hljs-string">"White"</span>                               
                            <span class="hljs-attr">FontAttributes</span>=<span class="hljs-string">"Bold"</span>
                            <span class="hljs-attr">Text</span>=<span class="hljs-string">"{x:Static fonts:MaterialDesignRegular.Delete}"</span>
                            <span class="hljs-attr">FontFamily</span>=<span class="hljs-string">"Icons"</span>
                            <span class="hljs-attr">FontSize</span>=<span class="hljs-string">"20"</span>
                            <span class="hljs-attr">WidthRequest</span>=<span class="hljs-string">"10"</span>
                            <span class="hljs-attr">HeightRequest</span>=<span class="hljs-string">"10"</span>
                            <span class="hljs-attr">HorizontalOptions</span>=<span class="hljs-string">"End"</span>
                            <span class="hljs-attr">VerticalOptions</span>=<span class="hljs-string">"Start"</span>
                            <span class="hljs-attr">ZIndex</span>=<span class="hljs-string">"1"</span>
                            <span class="hljs-attr">SemanticProperties.Hint</span>=<span class="hljs-string">"Remove page from document to extract."</span>
                            <span class="hljs-attr">Command</span>=<span class="hljs-string">"{Binding Source={RelativeSource AncestorType={x:Type StackLayout}}, Path=BindingContext.RemovePageCommand}"</span> 
                            <span class="hljs-attr">CommandParameter</span>=<span class="hljs-string">"{Binding PageName}"</span>/&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">Grid</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">DataTemplate</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">BindableLayout.ItemTemplate</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">StackLayout</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">ScrollView</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">ContentView</span>&gt;</span>
</code></pre>
<h3 id="heading-the-problem-with-maui-collectionview">The Problem with MAUI CollectionView</h3>
<p>When originally building this application the plan was to use the <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/maui/user-interface/controls/collectionview/?view=net-maui-7.0">CollectionView</a> component for the display of the collection of the selected pages above, as this is more powerful than the list view. However, at the time of writing, there is a <a target="_blank" href="https://github.com/dotnet/maui/issues/7967">well-documented</a> error in this component which means it does not redraw correctly in the display when the underlying observable collection is updated.</p>
<h3 id="heading-the-horizontal-stacklayout-workaround">The Horizontal StackLayout Workaround</h3>
<p>Thankfully, we can work around the issue by using a StackLayout component as an alternative, setting the orientation to Horizontal as shown in the above control.</p>
<p>I have decided to call this a workaround, rather than a solution because the above is a bug rather than a feature, and as such may at some point be fixed, although for now, that <a target="_blank" href="https://github.com/dotnet/maui/issues/7967#issuecomment-1231769370">does not seem to be a priority</a>.</p>
<h3 id="heading-adding-the-controls-to-our-page-view">Adding the Controls to Our Page View</h3>
<p>All that remains to do to display our PDF is to add our newly created controls to our PdfViewPage xaml:</p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;?xml version="1.0" encoding="utf-8" ?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">ContentPage</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://schemas.microsoft.com/dotnet/2021/maui"</span>
             <span class="hljs-attr">xmlns:x</span>=<span class="hljs-string">"http://schemas.microsoft.com/winfx/2009/xaml"</span>
             <span class="hljs-attr">xmlns:Controls</span>=<span class="hljs-string">"clr-namespace:PdfSplitter.Controls"</span>
             <span class="hljs-attr">x:Class</span>=<span class="hljs-string">"PdfSplitter.Views.PdfViewPage"</span>             
             <span class="hljs-attr">x:Name</span>=<span class="hljs-string">"pdfExtractorViewPage"</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">Grid</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Grid.RowDefinitions</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">RowDefinition</span> <span class="hljs-attr">Height</span>=<span class="hljs-string">"4*"</span> /&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">RowDefinition</span> <span class="hljs-attr">Height</span>=<span class="hljs-string">"auto"</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Grid.RowDefinitions</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Grid.ColumnDefinitions</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">ColumnDefinition</span> <span class="hljs-attr">Width</span>=<span class="hljs-string">"5*"</span> /&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">ColumnDefinition</span> <span class="hljs-attr">Width</span>=<span class="hljs-string">"*"</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Grid.ColumnDefinitions</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Controls:PdfPageContent</span> <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">Grid.Column</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">Page</span>=<span class="hljs-string">"{Binding SelectedPageItem}"</span> <span class="hljs-attr">SelectPageCommand</span>=<span class="hljs-string">"{Binding OnItemSelectedCommand}"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Controls:PdfPages</span> <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">Grid.Column</span>=<span class="hljs-string">"1"</span> <span class="hljs-attr">Grid.RowSpan</span>=<span class="hljs-string">"2"</span> <span class="hljs-attr">Pages</span>=<span class="hljs-string">"{Binding Items}"</span> <span class="hljs-attr">SelectedPage</span>=<span class="hljs-string">"{Binding SelectedPageItem, Mode=TwoWay}"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Controls:PdfSelectedPages</span>  <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"1"</span> <span class="hljs-attr">Grid.Column</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">SelectedPages</span>=<span class="hljs-string">"{Binding SelectedItems}"</span> <span class="hljs-attr">RemovePageCommand</span>=<span class="hljs-string">"{Binding OnItemRemovedCommand}"</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Grid</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">ContentPage</span>&gt;</span>
</code></pre>
<p>And to update our view model to include the properties and methods that our controls will bind to:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">PdfViewPageViewModel</span> : <span class="hljs-title">BindableModelBase</span>
{
    <span class="hljs-keyword">private</span> IPdfService _pdfService;
    <span class="hljs-keyword">private</span> PdfPageItem _selectedPageItem;
    <span class="hljs-keyword">public</span> ICommand OnItemSelectedCommand { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">private</span> <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> ICommand OnItemRemovedCommand { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">private</span> <span class="hljs-keyword">set</span>; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">PdfViewPageViewModel</span>(<span class="hljs-params">IPdfService pdfService, ISavePdfService savePdfService</span>)</span>
    {
        _pdfService = pdfService;
        _savePdfService = savePdfService;
        OnItemSelectedCommand = <span class="hljs-keyword">new</span> Command(SelectPage);
        OnItemRemovedCommand = <span class="hljs-keyword">new</span> Command&lt;<span class="hljs-keyword">string</span>&gt;(RemovePage);
    }

    <span class="hljs-keyword">public</span> ObservableCollection&lt;PdfPageItem&gt; Items =&gt; _pdfService.Items;

    <span class="hljs-keyword">public</span> ObservableCollection&lt;PdfPageItem&gt; SelectedItems =&gt; _pdfService.SelectedItems;

    <span class="hljs-keyword">public</span> PdfPageItem SelectedPageItem 
    {
        <span class="hljs-keyword">get</span> 
        {     
            <span class="hljs-keyword">if</span>(_selectedPageItem == <span class="hljs-literal">null</span> &amp;&amp; _pdfService.Items.Count &gt; <span class="hljs-number">0</span>)
            {
                _selectedPageItem = _pdfService.Items[<span class="hljs-number">0</span>];
            }
            <span class="hljs-keyword">return</span> _selectedPageItem;
        }
        <span class="hljs-keyword">set</span> 
        { 
            _selectedPageItem = <span class="hljs-keyword">value</span>;
            NotifyPropertyChanged(() =&gt; SelectedPageItem);
        }
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> PdfOpen { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">private</span> <span class="hljs-keyword">set</span>; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">SelectPage</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">if</span>(_selectedPageItem != <span class="hljs-literal">null</span>)
        {
            _pdfService.SelectItem(_selectedPageItem);

            <span class="hljs-keyword">int</span> selectedItemPageNo = _selectedPageItem.PageNumber;

            SelectedPageItem = _pdfService.Items.FirstOrDefault(x =&gt; x.PageNumber &gt; selectedItemPageNo);

            NotifyPropertyChanged(() =&gt; DisplaySaveButton);
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">RemovePage</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> pageName</span>)</span>
    {
        <span class="hljs-keyword">var</span> pageToRemove = SelectedItems.FirstOrDefault(x =&gt; x.PageName == pageName);

        <span class="hljs-keyword">if</span> (pageToRemove != <span class="hljs-literal">null</span>)
        {
            _pdfService.UnselectItem(pageToRemove);
            NotifyPropertyChanged(() =&gt; Items);
        }
    }
}
</code></pre>
<h3 id="heading-finishing-up">Finishing Up</h3>
<p>We should now be able to launch our application and it should look similar to the below. I have added some UI tweaks and changed the background image, implementation can be obtained from the GitHub repository.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691066973064/74b7c8ac-7297-4e64-9a6b-f0a779cd6501.png" alt class="image--center mx-auto" /></p>
<p>And after opening a PDF file:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691066918955/5010f1f5-adb3-4ddc-b6cc-a783f87b2ca2.png" alt class="image--center mx-auto" /></p>
<p>The final step is to implement the 'save' PDF functionality, which can be triggered as in the above image by way of clicking the green button. This will be the topic of my next article.</p>
]]></content:encoded></item><item><title><![CDATA[.NET MAUI - Working with PDF Files Pt. 1]]></title><description><![CDATA[For the fourth article in my PDF Splitter series, we will start working with PDF files in .NET MAUI. Helpfully, MAUI contains a lot of useful PDF tools for…]]></description><link>https://davek.dev/net-maui-working-with-pdf-files-pt-1</link><guid isPermaLink="true">https://davek.dev/net-maui-working-with-pdf-files-pt-1</guid><category><![CDATA[#dotnet-maui]]></category><category><![CDATA[Blogging]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[C#]]></category><category><![CDATA[.NET]]></category><dc:creator><![CDATA[Dave K]]></dc:creator><pubDate>Tue, 01 Aug 2023 13:59:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/pakTZIspHO0/upload/694c08030cdc18ec6eece91177dd403c.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>For the fourth article in my <a target="_blank" href="https://davek.dev/series/pdf-splitter">PDF Splitter series</a>, we will start working with PDF files in .NET MAUI. Helpfully, MAUI contains a lot of useful PDF tools for reading PDF files out of the box, so we do not need to use any additional libraries for now.</p>
<p>By the end of this article we will be able to:</p>
<ul>
<li><p>Open a PDF file</p>
</li>
<li><p>Display a list of pages</p>
</li>
<li><p>Select and view an individual page</p>
</li>
</ul>
<h3 id="heading-handling-pages">Handling Pages</h3>
<p>Before we can think about opening a PDF file, the first thing we need to do is create somewhere to store information about each page within that file so we can track the status of each page.</p>
<p>To do this we create a new class to represent a page which I've added into my 'models' directory. This class will initially allow us to maintain some of the state of the page within our application, for example, if the page is selected and also return a 'name' we can bind to when displaying the page.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">PdfPageItem</span>
{
    <span class="hljs-keyword">public</span> PdfPage Page {<span class="hljs-keyword">get</span>;<span class="hljs-keyword">set</span>;}

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> PageNumber { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> PageName { <span class="hljs-keyword">get</span> { <span class="hljs-keyword">return</span> <span class="hljs-string">$"Page <span class="hljs-subst">{PageNumber}</span>"</span>; } }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> Selected { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }        
}
</code></pre>
<p>This class includes a PdfPage reference, which can be found in the <a target="_blank" href="http://Windows.Data">Windows.Data</a>.Pdf namespace.</p>
<h3 id="heading-working-with-randomaccessstreams">Working with RandomAccessStreams</h3>
<p>Now that we have a representation of our page, we want to be able to take this further and be able to display a small preview of our page and a bigger view of our page when we click on the preview.</p>
<p>To do this in MAUI we can render our PDF file 'on-demand' into an InMemoryRandomAccessStream and then set our ImageSource content to the stream, which is what's used by the UI to 'binds' to our image:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">PdfPageItem</span>
{
    <span class="hljs-comment">//.. Earlier items omitted for brevity</span>

    <span class="hljs-keyword">public</span> ImageSource Preview =&gt; ImageSource.FromStream(() =&gt; Task.Run(GeneratePreview).Result.AsStream());

    <span class="hljs-keyword">public</span> ImageSource PageView =&gt; ImageSource.FromStream(() =&gt; Task.Run(GenerateView).Result.AsStream());

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;InMemoryRandomAccessStream&gt; <span class="hljs-title">GeneratePreview</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">double</span> resizeFactor = Page.Size.Height / Page.Size.Width;
        <span class="hljs-keyword">double</span> destinationHeight = <span class="hljs-number">120</span>;
        <span class="hljs-keyword">double</span> destinationWidth = destinationHeight / resizeFactor;

        <span class="hljs-keyword">await</span> Page.PreparePageAsync();
        <span class="hljs-keyword">var</span> stream = <span class="hljs-keyword">new</span> InMemoryRandomAccessStream();
        PdfPageRenderOptions pdfPageRenderOptions = <span class="hljs-keyword">new</span> PdfPageRenderOptions();
        pdfPageRenderOptions.DestinationHeight = (<span class="hljs-keyword">uint</span>)destinationHeight;
        pdfPageRenderOptions.DestinationWidth= (<span class="hljs-keyword">uint</span>)destinationWidth;

        <span class="hljs-keyword">await</span> Page.RenderToStreamAsync(stream, pdfPageRenderOptions);
        stream.Seek(<span class="hljs-number">0</span>);

        <span class="hljs-keyword">return</span> stream;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;InMemoryRandomAccessStream&gt; <span class="hljs-title">GenerateView</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">await</span> Page.PreparePageAsync();
        <span class="hljs-keyword">var</span> stream = <span class="hljs-keyword">new</span> InMemoryRandomAccessStream();
        <span class="hljs-keyword">await</span> Page.RenderToStreamAsync(stream);
        stream.Seek(<span class="hljs-number">0</span>);

        <span class="hljs-keyword">return</span> stream;
    }
}
</code></pre>
<p>To generate the main view we render the page as it is, but to generate the preview, you can see we 'resize' the page during rendering. This resizes will both reduce the size and subsequently the quality of the rendered image, so you may want to play around with the destination height to adjust this. I have found 120 seems to provide a nice balance.</p>
<h3 id="heading-creating-the-pdf-service">Creating the PDF Service</h3>
<p>Now that we have something to break our PDF Item into, we need to create the service to load the file.</p>
<p>The below code is the start of our service and accepts a pdf file path as a string, loads and breaks down the pdf file into its pages as individual page items and then finally stores those pages in an ObservableCollection which our UI can bind to later.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">PdfService</span> : <span class="hljs-title">IPdfService</span>
{
    <span class="hljs-keyword">private</span> PdfDocument _document;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> _filePath;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">PdfService</span>(<span class="hljs-params"></span>)</span>
    {
        Items = <span class="hljs-keyword">new</span> ObservableCollection&lt;PdfPageItem&gt;();
    }   

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">LoadPdf</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> path</span>)</span>
    {
        Items.Clear();

        _filePath = path;

        <span class="hljs-keyword">var</span> file = <span class="hljs-keyword">await</span> StorageFile.GetFileFromPathAsync(path);
        _document = <span class="hljs-keyword">await</span> PdfDocument.LoadFromFileAsync(file);        

        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt;= _document.PageCount; i++)
        {
            Items.Add(<span class="hljs-keyword">new</span> PdfPageItem
            {
                Page = _document.GetPage((<span class="hljs-keyword">uint</span>)i<span class="hljs-number">-1</span>),
                PageNumber = i                

            }); ; 
        }
    }

    <span class="hljs-keyword">public</span> ObservableCollection&lt;PdfPageItem&gt; Items { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">private</span> <span class="hljs-keyword">set</span>; }
}
</code></pre>
<p>Because the purpose of this PdfSplitter application is to allow us to select and extract pages into a new PDF file, we can then expand on this service to create a second collection to track selected pages and enable us to move pages between the two:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">PdfService</span> : <span class="hljs-title">IPdfService</span>
{
    <span class="hljs-keyword">private</span> PdfDocument _document;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> _filePath;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">PdfService</span>(<span class="hljs-params"></span>)</span>
    {
        Items = <span class="hljs-keyword">new</span> ObservableCollection&lt;PdfPageItem&gt;();
        SelectedItems = <span class="hljs-keyword">new</span> ObservableCollection&lt;PdfPageItem&gt;(); 
    }   

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">LoadPdf</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> path</span>)</span>
    {
        SelectedItems.Clear();
        Items.Clear();

        _filePath = path;

        <span class="hljs-keyword">var</span> file = <span class="hljs-keyword">await</span> StorageFile.GetFileFromPathAsync(path);
        _document = <span class="hljs-keyword">await</span> PdfDocument.LoadFromFileAsync(file);        

        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt;= _document.PageCount; i++)
        {
            Items.Add(<span class="hljs-keyword">new</span> PdfPageItem
            {
                Page = _document.GetPage((<span class="hljs-keyword">uint</span>)i<span class="hljs-number">-1</span>),
                PageNumber = i                

            }); ; 
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">UnloadPdf</span>(<span class="hljs-params"></span>)</span>
    {
        Items.Clear();
        SelectedItems.Clear();
        _document = <span class="hljs-literal">null</span>;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">SelectItem</span>(<span class="hljs-params">PdfPageItem item</span>)</span>
    {
        SelectedItems.Add(item);
        Items.Remove(item);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">UnselectItem</span>(<span class="hljs-params">PdfPageItem item</span>)</span>
    {
        SelectedItems.Remove(item);
        Items.Add(item);
        Items = <span class="hljs-keyword">new</span> ObservableCollection&lt;PdfPageItem&gt;(Items.OrderBy(x =&gt; x.PageNumber));
    }

    <span class="hljs-keyword">public</span> ObservableCollection&lt;PdfPageItem&gt; SelectedItems { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">private</span> <span class="hljs-keyword">set</span>; }

    <span class="hljs-keyword">public</span> ObservableCollection&lt;PdfPageItem&gt; Items { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">private</span> <span class="hljs-keyword">set</span>; }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> PdfFilePath =&gt; _filePath;
}
</code></pre>
<p>I have also added the functionality 'unload' a PDF, should we wish to, along with creating an interface for our dependency injection container, in the MauiProgram.cs file:</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> MauiApp <span class="hljs-title">CreateMauiApp</span>(<span class="hljs-params"></span>)</span>
{
    <span class="hljs-keyword">var</span> builder = MauiApp.CreateBuilder();
    builder
        .UseMauiApp&lt;App&gt;()
        .RegisterAppServices()
        .RegisterViewModels()
        .RegisterViews()
        .ConfigureFonts(fonts =&gt;
        {
            fonts.AddFont(<span class="hljs-string">"OpenSans-Regular.ttf"</span>, <span class="hljs-string">"OpenSansRegular"</span>);
            fonts.AddFont(<span class="hljs-string">"OpenSans-Semibold.ttf"</span>, <span class="hljs-string">"OpenSansSemibold"</span>);
            fonts.AddFont(<span class="hljs-string">"MaterialIcons-Regular.ttf"</span>, <span class="hljs-keyword">alias</span>: <span class="hljs-string">"Icons"</span>);
        });

    <span class="hljs-keyword">return</span> builder.Build();
}

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> MauiAppBuilder <span class="hljs-title">RegisterViews</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> MauiAppBuilder builder</span>)</span> 
{
    <span class="hljs-comment">//..</span>
}

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> MauiAppBuilder <span class="hljs-title">RegisterViewModels</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> MauiAppBuilder builder</span>)</span>
{
    <span class="hljs-comment">//..</span>

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> MauiAppBuilder <span class="hljs-title">RegisterAppServices</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> MauiAppBuilder builder</span>)</span>
{
    builder.Services.AddSingleton&lt;IPdfService, PdfService&gt;();

    <span class="hljs-keyword">return</span> builder;
}
</code></pre>
<p>Now that we have the PDF service ready to be used, in <a target="_blank" href="https://davek.dev/net-maui-working-with-pdf-files-pt-2">part 2</a>, we update our UI to allow us to open, and work with a PDF file.</p>
]]></content:encoded></item><item><title><![CDATA[.NET MAUI - Basic Navigation]]></title><description><![CDATA[Basic Navigation in .NET MAUI]]></description><link>https://davek.dev/net-maui-basic-navigation</link><guid isPermaLink="true">https://davek.dev/net-maui-basic-navigation</guid><category><![CDATA[C#]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Developer]]></category><category><![CDATA[#dotnet-maui]]></category><category><![CDATA[.NET]]></category><dc:creator><![CDATA[Dave K]]></dc:creator><pubDate>Wed, 12 Apr 2023 16:09:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/_94HLr_QXo8/upload/86cd7b0f25ced2a07c8dc791e03d14cd.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>In this article, I'm going to introduce basic navigation into my .NET MAUI PDF Splitter application.</p>
<p>If you're following my <a target="_blank" href="https://davek.dev/series/pdf-splitter">PDF Splitter Application series</a>, you will have a simple application based on the out-the-box .NET template with a menu bar, which we will use to drive our navigation.</p>
<p>If not you can jump to the complete code for the series <a target="_blank" href="https://github.com/davek-dev/PdfSplitter/tree/main/PdfSplitter">here</a>.</p>
<h3 id="heading-the-pdf-view-page">The PDF View Page</h3>
<p>Before we can add navigation to our application, we first need to create a new page to navigate to. Go ahead and create a new PdfViewPage.xaml file in our Views directory, and a PdfViewPageViewModel.cs file in our ViewModels directory.</p>
<p>These will eventually display the components that form the UI of our application, but for now, we don't need to add anything to it.</p>
<h3 id="heading-registering-our-pages">Registering our Pages</h3>
<p>Let go and update our MauiProgram.cs to make sure our new view and view model are registered, so we're ready to use them. If you've not followed the series from the start, the full code for this page can be found <a target="_blank" href="https://github.com/davek-dev/PdfSplitter/blob/main/PdfSplitter/MauiProgram.cs">here</a>:</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> MauiAppBuilder <span class="hljs-title">RegisterViews</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> MauiAppBuilder builder</span>)</span> 
    {
        builder.Services.AddSingleton&lt;AppShell&gt;();
        builder.Services.AddSingleton&lt;MainPage&gt;();
        builder.Services.AddSingleton&lt;PdfViewPage&gt;();        

        <span class="hljs-keyword">return</span> builder;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> MauiAppBuilder <span class="hljs-title">RegisterViewModels</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> MauiAppBuilder builder</span>)</span>
    {
        builder.Services.AddSingleton&lt;AppShellViewModel&gt;();
        builder.Services.AddSingleton&lt;MainPageViewModel&gt;();
        builder.Services.AddSingleton&lt;PdfViewPageViewModel&gt;();

        <span class="hljs-keyword">return</span> builder;
    }
</code></pre>
<h3 id="heading-registering-routes">Registering Routes</h3>
<p>We now need to register a route with our AppShell view. To keep it simple we can define a name for our page in the XAML for the page, then use that name for routing.</p>
<p>Define a name in the PdfViewPage.xaml using the x:Name property.</p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;?xml version="1.0" encoding="utf-8" ?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">ContentPage</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://schemas.microsoft.com/dotnet/2021/maui"</span>
             <span class="hljs-attr">xmlns:x</span>=<span class="hljs-string">"http://schemas.microsoft.com/winfx/2009/xaml"</span>
             <span class="hljs-attr">xmlns:Controls</span>=<span class="hljs-string">"clr-namespace:PdfSplitter.Controls"</span>
             <span class="hljs-attr">x:Class</span>=<span class="hljs-string">"PdfSplitter.Views.PdfViewPage"</span>             
             <span class="hljs-attr">x:Name</span>=<span class="hljs-string">"pdfExtractorViewPage"</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">Grid</span> /&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">ContentPage</span>&gt;</span>
</code></pre>
<p>We can then register our route in the AppShell.xaml.cs file:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">partial</span> <span class="hljs-keyword">class</span> <span class="hljs-title">AppShell</span> : <span class="hljs-title">Shell</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">AppShell</span>(<span class="hljs-params">AppShellViewModel viewModel</span>)</span>
    {
        InitializeComponent();
        BindingContext = viewModel;

        <span class="hljs-comment">// Register routes</span>
        Routing.RegisterRoute(<span class="hljs-keyword">nameof</span>(PdfViewPage), <span class="hljs-keyword">typeof</span>(PdfViewPage));
    }   

}
</code></pre>
<p>Finally, to use our route, we will update the Open File command to navigate when selected. We will implement the file selection command later but for now, we can just add the routing to a new SelectFile function into our AppShellViewModel.cs file and extend our <a target="_blank" href="https://davek.dev/net-maui-creating-a-xaml-file-menu">menu item command functionality from our previous post</a> to call out to our new function:</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">OnMenuItemClicked</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> item</span>)</span>
    {
        <span class="hljs-keyword">switch</span> (item) {
            <span class="hljs-keyword">case</span> <span class="hljs-string">"Exit"</span>:
                Application.Current.Quit();
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">"Open"</span>:
                <span class="hljs-keyword">await</span> SelectFile();
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">"Close"</span>:        
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">default</span>:
                <span class="hljs-keyword">break</span>;
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">SelectFile</span>(<span class="hljs-params"></span>)</span>
    {      
         <span class="hljs-keyword">await</span> Shell.Current.GoToAsync(<span class="hljs-keyword">nameof</span>(PdfViewPage));        
    }
</code></pre>
<h3 id="heading-summary">Summary</h3>
<p>As you can see, adding basic navigation to an MAUI app is as simple as creating a page, giving it a name and registering it as a route. Next up for us is to start looking at how we can load and display a PDF file.</p>
]]></content:encoded></item><item><title><![CDATA[.NET MAUI - Creating a XAML File Menu]]></title><description><![CDATA[Creating a file menu in XAML with .NET MAUI]]></description><link>https://davek.dev/net-maui-creating-a-xaml-file-menu</link><guid isPermaLink="true">https://davek.dev/net-maui-creating-a-xaml-file-menu</guid><category><![CDATA[#dotnet-maui]]></category><category><![CDATA[C#]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[.NET]]></category><category><![CDATA[Developer]]></category><dc:creator><![CDATA[Dave K]]></dc:creator><pubDate>Wed, 12 Apr 2023 15:47:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/Gs-tdnDyYKE/upload/e49255c189bc2078f6a5661b376cb149.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>In this article, I'm going to add a file menu to my .NET MAUI PDF Splitter application.</p>
<p>If you're following my <a target="_blank" href="https://davek.dev/series/pdf-splitter">PDF Splitter Application series</a>, you will have a simple application based on the out-the-box .NET template which we will now start to build upon.</p>
<p>If not you can jump to the final code for the series <a target="_blank" href="https://github.com/davek-dev/PdfSplitter/tree/main/PdfSplitter">here</a>.</p>
<h3 id="heading-the-menu-bar">The Menu Bar</h3>
<p>We are going to add a simple menu bar to our application, which has two top-level items (File and About) and some sub-items as outlined below:</p>
<ul>
<li><p>File</p>
<ul>
<li><p>Open</p>
</li>
<li><p>Close</p>
</li>
<li><p>[Separator]</p>
</li>
<li><p>Exit</p>
</li>
</ul>
</li>
<li><p>About</p>
<ul>
<li>About</li>
</ul>
</li>
</ul>
<p>To add these to our UI we can simply update our AppShell.xaml as follows:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">Shell.MenuBarItems</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">MenuBarItem</span> <span class="hljs-attr">Text</span>=<span class="hljs-string">"File"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">MenuFlyoutItem</span> <span class="hljs-attr">Text</span>=<span class="hljs-string">"Open"</span> <span class="hljs-attr">Command</span>=<span class="hljs-string">"{Binding OnMenuItemClickedCommand}"</span> <span class="hljs-attr">CommandParameter</span>=<span class="hljs-string">"Open"</span> /&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">MenuFlyoutItem</span> <span class="hljs-attr">Text</span>=<span class="hljs-string">"Close"</span> <span class="hljs-attr">Command</span>=<span class="hljs-string">"{Binding OnMenuItemClosePdfClickedCommand}"</span> <span class="hljs-attr">CommandParameter</span>=<span class="hljs-string">"Close"</span> /&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">MenuFlyoutSeparator</span> /&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">MenuFlyoutItem</span> <span class="hljs-attr">Text</span>=<span class="hljs-string">"Exit"</span> <span class="hljs-attr">Command</span>=<span class="hljs-string">"{Binding OnMenuItemClickedCommand}"</span> <span class="hljs-attr">CommandParameter</span>=<span class="hljs-string">"Exit"</span> /&gt;</span>     
        <span class="hljs-tag">&lt;/<span class="hljs-name">MenuBarItem</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">MenuBarItem</span> <span class="hljs-attr">Text</span>=<span class="hljs-string">"About"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">MenuFlyoutItem</span> <span class="hljs-attr">Text</span>=<span class="hljs-string">"About"</span> <span class="hljs-attr">Command</span>=<span class="hljs-string">"{Binding OnMenuItemAboutClickedCommand}"</span> <span class="hljs-attr">CommandParameter</span>=<span class="hljs-string">"About"</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">MenuBarItem</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Shell.MenuBarItems</span>&gt;</span>
</code></pre>
<p>As you can see, each of the items in the file menu (except the separator) is bound to a command. Some are bound to the same command, in this instance both Exit and Open are bound to the OnMenuItemClickedCommand, whereas others are bound to individual commands. The reason for this is dependent on what needs to happen when the command is triggered.</p>
<h3 id="heading-maui-commands-and-the-icommand-interface">MAUI Commands and the ICommand Interface</h3>
<p>Handling simple events that occur in the UI on the back end of an MAUI application can be done through the use of commands.</p>
<p>The ICommand interface allows us to define commands and what happens when a command is triggered.</p>
<p>For a command implementation, we must provide an implementation of what happens when we trigger that command, in the form of an action parameter.</p>
<p>We can additionally provide a second function parameter, CommandCanExecute which returns whether the command can be triggered or not. This option is used when we want to enable or disable a control based on the current application state. If we omit it, it will always be true.</p>
<p>Finally, we are also able to define a command parameter, which we can pass from the UI into the command itself.</p>
<p>I will use all three options below to define our commands for this application.</p>
<p>As our AppShell.xaml is bound to our AppShellViewModel (see previous article for more details) we need to add our command implementation to our AppShellViewModel.cs file as below:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">AppShellViewModel</span>
{
    <span class="hljs-keyword">public</span> ICommand OnMenuItemClickedCommand { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">private</span> <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> ICommand OnMenuItemClosePdfClickedCommand { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">private</span> <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> ICommand OnMenuItemAboutClickedCommand { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">private</span> <span class="hljs-keyword">set</span>; }

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">bool</span> pdfOpen = <span class="hljs-literal">false</span>;    

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">AppShellViewModel</span>(<span class="hljs-params"></span>)</span>
    {        

        OnMenuItemClickedCommand = <span class="hljs-keyword">new</span> Command&lt;<span class="hljs-keyword">string</span>&gt;(<span class="hljs-keyword">async</span> (s) =&gt; <span class="hljs-keyword">await</span> OnMenuItemClicked(s));
        OnMenuItemClosePdfClickedCommand = <span class="hljs-keyword">new</span> Command&lt;<span class="hljs-keyword">string</span>&gt;(<span class="hljs-keyword">async</span> (s) =&gt; <span class="hljs-keyword">await</span> OnMenuItemClicked(s), (s) =&gt; PdfOpen);

        OnMenuItemAboutClickedCommand = <span class="hljs-keyword">new</span> Command(DisplayAbout);
    }     

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">OnMenuItemClicked</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> item</span>)</span>
    {
        <span class="hljs-keyword">switch</span> (item) {
            <span class="hljs-keyword">case</span> <span class="hljs-string">"Exit"</span>:
                Application.Current.Quit();
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">"Open"</span>:
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">"Close"</span>:
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">default</span>:
                <span class="hljs-keyword">break</span>;
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DisplayAbout</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-comment">// Omitted for brevity</span>
    }
}
</code></pre>
<p>Firstly we define three commands that will implement the ICommand interface.</p>
<p>The first 2 commands (OnMenuItemClickedCommand, OnMenuItemClosePdfClickedCommand), both receive a string command parameter and call the OnMenuItemClicked function, passing that parameter and following the path in the switch statement according to which CommandParameter value was passed in from the UI. For now these don't do anything but we will add more functionality in later stages.</p>
<p>The OnMenuItemClosePdfClickedCommand also provides a second function, which returns the value of the pdfOpen field. As this is initially false, this means that the 'Close' button on our file menu will be disabled when we initially launch our application. One thing to note, if we want to enable our command later, we have to set the pdfOpen field to 'true' but also tell our application to re-evaluate the status of the command by calling:</p>
<pre><code class="lang-csharp">(OnMenuItemClosePdfClickedCommand <span class="hljs-keyword">as</span> Command).ChangeCanExecute();
</code></pre>
<p>We will implement this later in the series when we start to look at opening files.</p>
<p>Finally, our last command OnMenuItemAboutClickedCommand simply calls the DisplayAbout function directly when triggered.</p>
<p>Now we should be able to launch our application and it should display a file menu. In the above code, you can see I have also implemented the 'Exit' code so selecting Exit should quit the application!</p>
<p>The next step is to implement some basic navigation!</p>
]]></content:encoded></item><item><title><![CDATA[.NET MAUI - Creating a New Project]]></title><description><![CDATA[Creating a new project in .NET MAUI]]></description><link>https://davek.dev/net-maui-creating-a-new-project</link><guid isPermaLink="true">https://davek.dev/net-maui-creating-a-new-project</guid><category><![CDATA[C#]]></category><category><![CDATA[#dotnet-maui]]></category><category><![CDATA[software development]]></category><category><![CDATA[Developer]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Dave K]]></dc:creator><pubDate>Wed, 12 Apr 2023 15:45:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/OXmym9cuaEY/upload/6d0b1f609649ea4d4bd974786ab72757.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>This article is the third article in my PDF Splitter series but the first one in which we start to drill down into <a target="_blank" href="https://github.com/davek-dev/PdfSplitter/tree/main/PdfSplitter">the code</a>.</p>
<h3 id="heading-creating-the-project">Creating the Project</h3>
<p>For this tutorial, I'm going to be using Visual Studio, in my case, I'm using Visual Studio Community, which is available to download for free from <a target="_blank" href="https://visualstudio.microsoft.com/vs/community/">here</a>.</p>
<p>Create a new .NET MAUI App from the start-up menu, by selecting the top option in the list as displayed below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681222442304/a772e958-406f-4dad-b465-6f2a46f4c2e4.png" alt class="image--center mx-auto" /></p>
<p>This out-the-box gives us a starting project to work with, that can be built and executed, so we already have our first .NET MAUI application up and running!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681222950811/56d5a0cc-dcc4-4e18-88c9-05e2f6f3d05a.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-the-default-files">The Default Files</h3>
<p>The default application is compiled from a handful of files provided in the default solution:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681223318003/3ae5db32-a9ed-44b2-a272-4fb3a6b7304a.png" alt /></p>
<ul>
<li><p>MauiProgram.cs - This is the entry point of our application. We can register all the required views, view models and services with our <a target="_blank" href="https://en.wikipedia.org/wiki/Dependency_injection">dependency injection</a> container here. We will cover the Model-View-ViewModel pattern later in this article.</p>
</li>
<li><p>App.xaml - The App.xaml file has a corresponding App.xaml.cs file. Between them, they describe the host window and code for the application. There is very little code in here, and we will make only minor modifications to this file for our application.</p>
</li>
<li><p>AppShell - The application shell (xaml and cs) files provide the main host of our application components. It is where we can code our static components such as menu bars and status bars and handle navigation.</p>
</li>
</ul>
<p>All xaml files for MAUI have a corresponding cs file. They are usually bundled together in the Visual Studio solution explorer and can be seen by expanding the xaml file displayed.</p>
<h3 id="heading-the-mvvm-design-pattern">The MVVM Design Pattern</h3>
<p>The Model-View-ViewModel (MVVM) design pattern was a new design pattern introduced when Microsoft first released Windows Presentation Foundation (WPF) as an alternative UI framework for .NET Windows applications to the traditional Winforms application.</p>
<p>It has been <a target="_blank" href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel">covered extensively over the years</a>, so I'm not going to go into too much detail here. The main driving force behind the MVVM was to allow the UI code and the business logic to be separated, in a similar vein to how MVC might work in a web application. There are, obviously, 3 main components to the design pattern:</p>
<ul>
<li><p>View - This is what the user see's, and is described by the Xaml files that we create. Whilst every Xaml file has a corresponding cs file, which could contain a lot of the 'code-behind' functionality, we should look to separate that functionality into a separate view model.</p>
</li>
<li><p>View Model - The view model contains all the commands and properties that we'd look to interact with from a UI component. We inject these view models into the 'code behind' cs file and bind our Views to them. As such the view will have a dependency on the view model, but the view model has no knowledge of the view. This makes our code more 'loosely coupled'.</p>
</li>
<li><p>Model - The term model in this instance can refer to the business logic driving the application itself. The view models will trigger state changes in the business logic and the view will react to those via changes in properties on the view models.</p>
</li>
</ul>
<p>This separation of concerns design pattern allows specialist UI/UX designers to focus on only that aspect of an application, and c# developers to focus on the business logic. Additionally, because there are no dependencies directly to the views, it can make our applications much more testable as we can create unit tests to test the majority of the code without having to directly interact with the UI itself.</p>
<p>Now we've covered the default project structure and design patterns, let's write some code!</p>
<h3 id="heading-the-first-steps">The First Steps</h3>
<p>Before we do anything else, let's create some new directories for our application to help keep our code structures. To start with, I created 3 directories, 'Models', 'Views' and 'ViewModels'.</p>
<p>Then I will move the AppShell.xaml to the Views directory as this is the first view we will use.</p>
<p>To keep within our MVVM design, we then need to update our application to allow us to provide a view model for the AppShell.xaml view. However, as the AppShell does not get initialised by our dependency injection (DI) container, we cannot use the standard method of just registering the views and view models and letting DI handle the rest. We need to rather pass it through the App.cs to where the AppShell is instantiated.</p>
<p>Let's create an AppShellViewModel inside our ViewModels folder:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">AppShellViewModel</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">AppShellViewModel</span>(<span class="hljs-params"></span>)</span>
    {

    }    
}
</code></pre>
<p>For now, it's pretty simple, but we'll extend this shortly.</p>
<p>We then need to register our view model to allow it to work with dependency injection so we can pass it into our App.cs later.</p>
<p>Inside the MauiProgram.cs we can create new RegisterViews and RegisterViewModels functions and then register both our AppShell view and AppShellViewModel with our application builder through these functions:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">MauiProgram</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> MauiApp <span class="hljs-title">CreateMauiApp</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">var</span> builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp&lt;App&gt;()
            .RegisterViewModels()
            .RegisterViews()
            .ConfigureFonts(fonts =&gt;
            {
                fonts.AddFont(<span class="hljs-string">"OpenSans-Regular.ttf"</span>, <span class="hljs-string">"OpenSansRegular"</span>);
                fonts.AddFont(<span class="hljs-string">"OpenSans-Semibold.ttf"</span>, <span class="hljs-string">"OpenSansSemibold"</span>);       
            });
        <span class="hljs-keyword">return</span> builder.Build();
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> MauiAppBuilder <span class="hljs-title">RegisterViews</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> MauiAppBuilder builder</span>)</span> 
    {
        builder.Services.AddSingleton&lt;AppShell&gt;();
        <span class="hljs-keyword">return</span> builder;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> MauiAppBuilder <span class="hljs-title">RegisterViewModels</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> MauiAppBuilder builder</span>)</span>
    {
        builder.Services.AddSingleton&lt;AppShellViewModel&gt;();
        <span class="hljs-keyword">return</span> builder;
    }
}
</code></pre>
<p>We can then inject the view model into our AppShell.cs file and tell the application to use the view model as our binding context. This tells the AppShell view to use the view model as its source of data, commands and events rather than the default AppShell.cs file:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">partial</span> <span class="hljs-keyword">class</span> <span class="hljs-title">AppShell</span> : <span class="hljs-title">Shell</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">AppShell</span>(<span class="hljs-params">AppShellViewModel viewModel</span>)</span>
    {
        InitializeComponent();
        BindingContext = viewModel;
    }   
}
</code></pre>
<p>And because our AppShell is initialised inside the App.cs we have to use our DI to pass the view model to the App.cs first, and then pass that through to the AppShell:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">partial</span> <span class="hljs-keyword">class</span> <span class="hljs-title">App</span> : <span class="hljs-title">Application</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">App</span>(<span class="hljs-params">AppShellViewModel viewModel</span>)</span>
    {
        InitializeComponent();
        MainPage = <span class="hljs-keyword">new</span> AppShell(viewModel);
    }
}
</code></pre>
<h3 id="heading-model-binding-and-inotifypropertychanged">Model Binding and INotifyPropertyChanged</h3>
<p>One final item I like to include in my projects is a base class to handle property changes, which can then be inherited by and view model classes.</p>
<p>One of the key concepts of MAUI and using model binding is how we tell the view when something has changed and needs updating.</p>
<p>The way we do this is through the implementation of the INotifyPropertyChanged interface, whereby we trigger the OnPropertyChanged event which is then handled by the view through the binding.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> <span class="hljs-title">BindableModelBase</span> : <span class="hljs-title">BindableObject</span>, <span class="hljs-title">INotifyPropertyChanged</span>
{
    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">NotifyPropertyChanged</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params">Expression&lt;Func&lt;T&gt;&gt; property</span>)</span>
    {
        <span class="hljs-keyword">if</span>(<span class="hljs-keyword">this</span>.OnPropertyChanged!= <span class="hljs-literal">null</span>)
        {
            OnPropertyChanged(GetMemberInfo(property).Name);
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> MemberInfo <span class="hljs-title">GetMemberInfo</span>(<span class="hljs-params">LambdaExpression expression</span>)</span> 
    {
        <span class="hljs-keyword">var</span> e = expression.Body <span class="hljs-keyword">as</span> MemberExpression;
        <span class="hljs-keyword">return</span> e.Member;         
    }
}
</code></pre>
<p>By inheriting the above class in our view models, we can simply call:</p>
<pre><code class="lang-csharp">NotifyPropertyChanged(() =&gt; PropertyName);
</code></pre>
<p>Whenever we update a property value, this should trigger the view to refresh any values that are bound to that property.</p>
<p>Now that we have got a base structure in place, we're ready to start adding our <a target="_blank" href="https://davek.dev/net-maui-creating-a-xaml-file-menu">file menu</a>, a main home page and some routing.</p>
]]></content:encoded></item><item><title><![CDATA[Getting Started with .NET MAUI - A PDF Splitter]]></title><description><![CDATA[For this series, I will create a PDF Splitter application using .NET MAUI. This will be a Windows application which will enable me to split out pages from…]]></description><link>https://davek.dev/getting-started-with-net-maui-a-pdf-splitter</link><guid isPermaLink="true">https://davek.dev/getting-started-with-net-maui-a-pdf-splitter</guid><category><![CDATA[C#]]></category><category><![CDATA[#dotnet-maui]]></category><category><![CDATA[Blogging]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[.NET]]></category><dc:creator><![CDATA[Dave K]]></dc:creator><pubDate>Fri, 03 Mar 2023 13:58:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/CSWllKT9wPw/upload/deff55d69423d9c658e67d725fb7f6a2.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>For <a target="_blank" href="https://davek.dev/series/pdf-splitter">this series</a>, I will create a PDF Splitter application using <a target="_blank" href="https://dotnet.microsoft.com/en-us/apps/maui">.NET MAUI</a>. This will be a Windows application which will enable me to split out pages from a PDF file into multiple pdf files as required.</p>
<p>.NET Multi-platform App UI (MAUI) is a user interface framework that is designed to allow a developer to create applications that target one or multiple different platforms.</p>
<p>In my <a target="_blank" href="https://hashnode.com/post/cldyu3y5608dzpunve0xo7s8w">previous post about becoming a better developer</a>, I talk a bit about how this project came about, my background with WPF, a precursor to MAUI, and also how I believe personal projects can help us on our journey to become better developers.</p>
<h3 id="heading-the-plan">The Plan</h3>
<p>This series goes through the key steps I take as I create the PDF Splitter application.</p>
<p>The application will be designed to:</p>
<ul>
<li><p>Allow me to open a PDF and display the list of pages</p>
</li>
<li><p>Allow me to select a page and view the page's contents</p>
</li>
<li><p>Allow a page to be marked to be extracted into a new PDF</p>
</li>
<li><p>Allow me to save any pages marked for extraction into a new PDF file.</p>
</li>
</ul>
<h3 id="heading-the-design">The Design</h3>
<p>Although it will evolve as the project progresses, the design is a pretty simple component-based layout. There will be three main components to the design, that allow me to:</p>
<ul>
<li><p>Display the pages of the selected PDF</p>
</li>
<li><p>View a selected page</p>
</li>
<li><p>Display and save a list of pages selected for extraction</p>
</li>
</ul>
<h3 id="heading-summary">Summary</h3>
<p>Although this isn't going to be a step-by-step guide, I will cover some of the key topics as I go through the journey, including:</p>
<p>Components and Views</p>
<p>The Model - View - ViewModel (MVVM) approach</p>
<p>Adding controls and model binding</p>
<p>Working with random access memory streams to display images in C#</p>
<p>The full code is available <a target="_blank" href="https://github.com/davek-dev/PdfSplitter">here</a>, and the full series can be found <a target="_blank" href="https://davek.dev/series/pdf-splitter">here</a>.</p>
]]></content:encoded></item><item><title><![CDATA[How to Improve as a Software Developer]]></title><description><![CDATA[Having spent over 10 years as a software developer and having managed teams and mentored people from other areas of technology, it won't come as a surprise…]]></description><link>https://davek.dev/how-to-improve-as-a-software-developer</link><guid isPermaLink="true">https://davek.dev/how-to-improve-as-a-software-developer</guid><category><![CDATA[software development]]></category><category><![CDATA[learning]]></category><category><![CDATA[Developer]]></category><category><![CDATA[Blogging]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Dave K]]></dc:creator><pubDate>Fri, 10 Feb 2023 18:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/1K9T5YiZ2WU/upload/ebb356b6dce9c3fc04c3e7aad4cef85e.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-where-to-start">Where to Start</h3>
<p>Having spent over 10 years as a software developer and having managed teams and mentored people from other areas of technology, it won't come as a surprise that this question has been asked of me on more than one occasion. I've read or heard this question asked many times over the years, and most commonly, the answer given is always: <strong>Just start writing code.</strong></p>
<p>The reality, though, is that that answer isn't entirely helpful, or complete. A lot of time it's not particularly helpful at all.</p>
<p>It's not easy to get started and just write code. Sure, you could write something to display 'Hello World!' to a console, in fact as a first step you probably should, but this isn't going to get you far.</p>
<p>The real answer should be: <strong>You need to write code, that solves a problem for you.</strong></p>
<p>It doesn't have to be good code, no one starts out writing good code. It doesn't need to look pretty, and you certainly don't need to compare yourself to every YouTuber that has created a video, after spending hours prepping and completing multiple takes.</p>
<p>The only thing that matters is that it solves a problem for you and that it works.</p>
<p>Why is this so important? <strong>The truth is all about motivation</strong>. In reality, it's difficult to come up with a real-world problem you need to solve, and the chances are, if you look online someone may already have solved that problem, but that's not the point. If you have a problem you would like to solve, and you have the desire to find a way to solve it yourself, then you will be motivated to stick to the problem and find a way to complete a solution.</p>
<p>I've never personally found it easy to write code for code's sake. If I'm not working on something for a reason, and by reason, it has to be more than that just because I want to write something, then I often find halfway through the project, that if get sidetracked, or lose interest, I'll never return to that code and it'll remain forever unfinished.</p>
<h3 id="heading-a-bit-of-background">A Bit of Background</h3>
<p>Before I became a software engineer, I worked in other areas of IT, working in support, or as a network engineer. I'd completed a computer science degree prior but never really made the most of it at the time. Throughout, my time in these jobs, whilst I enjoyed them, my passion was always in coding.</p>
<p>As such, I always found myself coding in my spare time, finding projects that solved a problem for me. My first few 'personal projects' were actually:</p>
<ul>
<li><p>An application to manage and tag my MP3 collection.</p>
</li>
<li><p>An application for my family to manage their digitised film collection, that is additionally connected to IMDB to display the synopsis and rating of each film in the collection to make it easier to decide what to watch.</p>
</li>
<li><p>An application from when I worked in IT Support for a college, which allowed us to do mass imports of student accounts into Active Directory, allowing the year's intake to be created in minutes rather than the days it took previously to manually input the accounts.</p>
</li>
</ul>
<p>None of these applications would be looked upon as being well-engineered or good examples of coding, but because they solved real problems, I had the motivation to see them through to completion.</p>
<h3 id="heading-so-why-am-i-talking-about-this-now">So Why am I Talking About This Now?</h3>
<p>Well, in truth learning never really ends. For most of my recent career, my focus has been on engineering web-based and back-end platforms. However, when I started, a lot of my focus was on desktop applications and I did a lot of work with <a target="_blank" href="https://learn.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-wpf?view=vs-2022">Windows Presentation Foundation (WPF)</a> applications.</p>
<p>Recently, I have been thinking about a day-to-day issue with document management in my own home, I have huge amounts of physical documents I could do with digitising and destroying, after all, who works from paper these days?</p>
<p>I could scan these documents into one single PDF file and then split them into individual documents later. This is far more efficient than splitting them up, scanning each document and then manually renaming them individually. I'm sure there will be plenty of tools to do this already but to me, this is an opportunity to revisit those days of desktop application development.</p>
<p>I came up with a plan:</p>
<ul>
<li><p>Create a PDF Splitting application using <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/maui/what-is-maui?view=net-maui-7.0">.NET Multi-Platform App UI (.NET MAUI)</a> a more modern implementation loosely based on WPF.</p>
</li>
<li><p>Write about my findings as I go, as a <a target="_blank" href="https://davek.dev/series/pdf-splitter">series</a> on <a target="_blank" href="https://davek.dev">my blog</a>.</p>
</li>
</ul>
<p>Having a plan to solve a real world problem has got me excited about writing code for a personal project again, and writing about it also makes me think a bit more about what I'm doing as I go. To me, even though I've been writing software for over 15 years in various capacities, this is still going to be an opportunity to learn.</p>
]]></content:encoded></item><item><title><![CDATA[2022 In Review -A Developer Retrospective]]></title><description><![CDATA[2022 In Review - A Developer Retrospective]]></description><link>https://davek.dev/2022-in-review-a-developer-retrospective</link><guid isPermaLink="true">https://davek.dev/2022-in-review-a-developer-retrospective</guid><category><![CDATA[#DevRetro2022]]></category><category><![CDATA[Blogging]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[iwritecode]]></category><category><![CDATA[Developer]]></category><dc:creator><![CDATA[Dave K]]></dc:creator><pubDate>Wed, 21 Dec 2022 10:14:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1671615592690/abpUoL4Fy.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As a developer, I am very familiar with the idea of a 'retro'. Retros are an important step in the agile methodology, allowing a team to look back over a sprint, a project or some other unit of work to determine what this did well, what could be done better, and any lessons learned to take forwards.</p>
<p>However, we often don't take time to look back at our own individual journeys and reflect on our personal achievements. As developers, we're often great at concerning ourselves with those things we are still yet to understand, but not so good at giving ourselves credit for what we do.</p>
<p>So each year I like to look back and reflect on three things I have learned in the past 12 months.</p>
<p>This is the first time I've ever composed a more conversational blog post, so this is another achievement in itself, but if I'd had authored a similar post at the end of 2021 I'd have listed Kubernetes, Blazor and NoSQL databases as my three key learnings.</p>
<p>As primarily a .Net C# software engineer, many people presume that day-to-day life is all about writing code, as indeed I did when I started my first software engineer role 15 years ago, but as I progress along my career path, I'm finding less and less of the day job is coding, and more of my time is spent in application design and architecture.</p>
<p>This is why I love my career, no 2 days are the same, every day has new challenges to overcome, new skills to learn and new ideas to swap with my colleagues.</p>
<h2 id="heading-my-2022-retro">My 2022 Retro</h2>
<p>So as I look back at 2022, what are three key new areas that I have been working in that I have put into practice?</p>
<h3 id="heading-authenticationauthorisation">Authentication/Authorisation</h3>
<p>You may think this is something you hit quite early on in the career path of a developer, and you'd be correct! But this year I've been digging deeper into configuration, JWT, cookies and even re-writing some core OIDC code to suit specific use cases where the out-of-the-box .NET Core OIDC libraries didn't provide the flexibility required to do what was required. Walking through other users' code and re-writing parts to suit your use cases is a great way to broaden your knowledge and understanding of how things are designed to work.</p>
<h3 id="heading-etl-event-streaming">ETL Event Streaming</h3>
<p>Extract, transform and load. Three words seem to have taken over my life towards the middle of 2022. How to get data from one or more back-end systems to a front-end system in a way that can be delivered to an end user quickly and is structured to suit the use cases. It's a pretty simple pattern really, and somewhat follows a similar design as the <a target="_blank" href="https://learn.microsoft.com/en-us/azure/architecture/patterns/cqrs">CQRS architectural design</a>, but on an architectural rather than application level.</p>
<p>The basic premise is that you can 'stream' data from back-end data sources, often SQL but this could be any data source, and then filter and transform the elements of the data that are required into a more usable structure into, most commonly a NoSQL database such as <a target="_blank" href="https://www.mongodb.com">MongoDB</a>, that can then be delivered to front end systems in a faster, more structured format than getting the data directly from source may provide. Updates are then passed back to the source data stores and transformed and streamed back through to the front-end data sources, and the cycle continues.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671615358411/PITf99tHN.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-api-gateways-ocelot">API Gateways (Ocelot)</h3>
<p>Towards the end of 2022, my focus shifted towards <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/architecture/microservices/multi-container-microservice-net-applications/implement-api-gateways-with-ocelot">API Gateways using Ocelot</a>. API gateways are not new. Most cloud developers will be using some form of API gateway, they are standard tools in <a target="_blank" href="https://aws.amazon.com/api-gateway/">AWS for example</a>. However, for none cloud-based systems they are a tool that is often overlooked but can allow a development team to provide a much greater degree of security, flexibility and visibility of requests and data moving into and out of the platform.</p>
<h2 id="heading-whats-in-store-for-2023">What's in store for 2023?</h2>
<p>As I look ahead to 2023, I figured I'd make a note of what 3 areas I believe will form a key part of my journey ahead. Indeed, it'll be interesting to see how much of this comes to fruition, and what changes, as, as any software engineer knows, priorities and focus can shift almost overnight from one project or process to another.</p>
<p>As of now, the three areas I am anticipating I will be focussing on are:</p>
<ul>
<li><p>Application security - Focusing more on API security rather than front-end security as in 2022.</p>
</li>
<li><p>More cloud (CDK, AWS Lambda/Azure Functions)</p>
</li>
<li><p>Observability - Distributed tracing and open telemetry.</p>
</li>
</ul>
<p>I would also like to complete my <a target="_blank" href="https://davek.dev/series/to-do-application">to-do series</a> and spend more time working with IoT.</p>
]]></content:encoded></item><item><title><![CDATA[Mutation Testing with Stryker .Net]]></title><description><![CDATA[Mutation testing with Stryker.Net]]></description><link>https://davek.dev/mutation-testing-with-stryker-net</link><guid isPermaLink="true">https://davek.dev/mutation-testing-with-stryker-net</guid><category><![CDATA[C#]]></category><category><![CDATA[.NET]]></category><category><![CDATA[Testing]]></category><category><![CDATA[unit testing]]></category><category><![CDATA[stryker]]></category><dc:creator><![CDATA[Dave K]]></dc:creator><pubDate>Mon, 24 Oct 2022 07:00:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/SxVuXIRG8J4/upload/v1666365691406/cwomIsnyV2.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-what-is-mutation-testing">What is Mutation Testing</h3>
<p>Every developer writes unit tests, and much of the reporting on unit testing is around code coverage, with tools such as <a target="_blank" href="https://www.sonarqube.org/">SonarQube</a> incorporated in build pipelines to enforce a targeted percentage of lines of codes covered by tests.  We write numerous tests, cover countless lines of code to get through this gate, but how do we really know how good these tests are, or if we're really testing anything at all?  </p>
<p>How do we 'test the tests'?</p>
<p>This is where mutation testing comes in.  Mutation testing, in its simplest form, is taking a test, manipulating the code being tested and then executing the test to see if it still passes.  If the test fails, the mutant is said to have been killed, and if the test passes, the mutant deemed to have survived.  </p>
<p>The great thing about mutation tests, is that because they work directly on our unit tests, we do not need to write any additional code, so there's not really an excude not to at least explore mutation testing.  For test written in C# and .Net, we can use <a target="_blank" href="https://stryker-mutator.io/docs/stryker-net/getting-started/">Stryker.NET</a> to execute mutation tests, but versions of Stryker are available for JavaScript and Scala also.</p>
<h3 id="heading-a-quick-example">A Quick Example</h3>
<h4 id="heading-a-simple-test">A Simple Test</h4>
<p>Let's take the following piece of code and associated test:</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">VehicleCheck</span>
</span>{
    public bool IsMotorbike(bool hasEngine, int numberOfWheels)
    {
        <span class="hljs-keyword">if</span> (hasEngine &amp;&amp; numberOfWheels == <span class="hljs-number">2</span>)
            <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }
}


public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">VehicleCheckTest</span>
</span>{
    [Fact]
    public <span class="hljs-keyword">void</span> HasTwoWheelsAndEngine_IsMotorbike_Succeed()
    {
        <span class="hljs-keyword">var</span> checker = <span class="hljs-keyword">new</span> VehicleCheck();

        <span class="hljs-keyword">var</span> isMotorbike = checker.IsMotorbike(<span class="hljs-literal">true</span>, <span class="hljs-number">2</span>);

        Assert.True(isMotorbike);
    }
}
</code></pre><p>If we run this test, it will pass.  </p>
<h4 id="heading-what-does-stryker-do">What Does Stryker Do?</h4>
<p>Stryker will go through the being tested and start to make changes based on a simple set of 'mutations' as outlined <a target="_blank" href="https://stryker-mutator.io/docs/stryker-net/mutations/">here</a>.</p>
<p>For our test, Stryker will make a number of mutations to the code as follows :</p>
<ul>
<li>The &amp;&amp; becomes ||</li>
<li>The true becomes false</li>
<li>The false becomes true</li>
<li>the (hasEngine &amp;&amp; numberOfWheels == 2) becomes !(hasEngine &amp;&amp; numberOfWheels == 2)</li>
<li>Delete the entire contents of the code block</li>
</ul>
<p>For our example, we will only consider the first one:</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">VehicleCheck</span>
</span>{
    public bool IsMotorbike(bool hasEngine, int numberOfWheels)
    {
        <span class="hljs-keyword">if</span> (hasEngine || numberOfWheels == <span class="hljs-number">2</span>)
            <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }
}
</code></pre><p>For each mutation, Stryker will then run the unit tests again, and for the example above the test will still pass.</p>
<h4 id="heading-so-whats-the-problem">So, What's the Problem?</h4>
<p>The main purpose of unit tests is to highlight if someone makes a breaking change to our code.  Stryker has made a significant change in the logic of the application, and yet all the tests still pass.  This is the opposite of what our test suite should be designed to do.  </p>
<p>Stryker will report this back as a survived mutant and therefore a failed mutation test. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1666365422233/0FM87Pwaf.JPG" alt="Survived.JPG" /></p>
<p>Code coverage metrics will still report a high degree of coverage which is great, but Stryker is suggesting to us that the quality of our test scenarios could be improved, as we can currently make changes to the code logic, and they will still pass.</p>
<p>Here it's pretty clear now that if I ran the test against the mutated code claiming to have no engine and 2 wheels, or an engine and 4 wheels, I'd still pass the check for a motorbike, which is clearly incorrect.</p>
<h4 id="heading-lets-kill-the-mutant">Lets Kill the Mutant</h4>
<p>Because Stryker requires that all unit tests will pass before running mutation tests, when Stryker makes a change and re-runs the related tests, only one test has to fail for the mutant to be deemed killed.  For the above example, we could simply add a couple of additional tests to cover those aforementioned scenarios.</p>
<p>Let's add those tests:</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">VehicleCheckTest</span>
</span>{
    [Fact]
    public <span class="hljs-keyword">void</span> HasTwoWheelsAndEngine_IsMotorbike_Succeed()
    {
        <span class="hljs-keyword">var</span> checker = <span class="hljs-keyword">new</span> VehicleCheck();

        <span class="hljs-keyword">var</span> isMotorbike = checker.IsMotorbike(<span class="hljs-literal">true</span>, <span class="hljs-number">2</span>);

        Assert.True(isMotorbike);
    }


    [Fact]
    public <span class="hljs-keyword">void</span> HasFourWheelsAndEngine_IsMotorbike_Fails()
    {
        <span class="hljs-keyword">var</span> checker = <span class="hljs-keyword">new</span> VehicleCheck();

        <span class="hljs-keyword">var</span> isMotorbike = checker.IsMotorbike(<span class="hljs-literal">true</span>, <span class="hljs-number">4</span>);

        Assert.False(isMotorbike);
    }

    [Fact]
    public <span class="hljs-keyword">void</span> HasTwoWheelsAndNoEngine_IsMotorbike_Fails()
    {
        <span class="hljs-keyword">var</span> checker = <span class="hljs-keyword">new</span> VehicleCheck();

        <span class="hljs-keyword">var</span> isMotorbike = checker.IsMotorbike(<span class="hljs-literal">false</span>, <span class="hljs-number">2</span>);

        Assert.False(isMotorbike);
    }
}
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1666365381776/y4cqUBK83.JPG" alt="Killed.JPG" /></p>
<p>You will actually notice that in the first run 5 mutants were counted and in the second 6 mutants were counted.  In both instances, Stryker actually found 8 possible mutations, but there was no test coverage for all of them.  This is something that could also be considered when reviewing the quality of the tests that have been created.</p>
<h3 id="heading-how-do-i-run-these-tests">How Do I Run These Tests?</h3>
<p>The simplest way to run tests with Stryker is to install Stryker globally</p>
<pre><code>dotnet tool install -g dotnet-stryker
</code></pre><p>And then navigate to the directory where your unit test project is and run</p>
<pre><code>dotnet stryker
</code></pre><h3 id="heading-html-reports">HTML Reports</h3>
<p>By default, Stryker also creates a nice HTML report output that allows you to view the output scores and review what was changed for each test, the below example being from the first test showing the survived mutation:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1666365365723/thbIzeHO8.JPG" alt="report.JPG" /></p>
]]></content:encoded></item><item><title><![CDATA[Hosting and Deploying from your own Docker Registry]]></title><description><![CDATA[For anyone who's been following my to-do series, then this article builds upon this post where I discuss setting up a free virtual machine on Oracle Cloud…]]></description><link>https://davek.dev/hosting-and-deploying-from-your-own-docker-registry</link><guid isPermaLink="true">https://davek.dev/hosting-and-deploying-from-your-own-docker-registry</guid><category><![CDATA[C#]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Docker]]></category><category><![CDATA[.NET]]></category><category><![CDATA[Cloud]]></category><dc:creator><![CDATA[Dave K]]></dc:creator><pubDate>Wed, 10 Aug 2022 16:16:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/Tk0B3Dfkf_4/upload/v1660145962710/DvhkxRxjq.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<h4 id="heading-setting-up">Setting Up</h4>
<p>For anyone who's been following my <a target="_blank" href="https://davek.dev/series/to-do-application">to-do series</a>, then this article builds upon this <a target="_blank" href="https://davek.dev/installing-docker-and-portainer-on-a-free-oracle-vm">post</a> where I discuss setting up a free virtual machine on Oracle Cloud, and from there setting up Docker with an application called Portainer, to help manage containers running on that virtual machine instance.  Even if you haven't been following the series then feel free to head there if you would like to get set up with a free Oracle Cloud VM or do not currently have a docker host set up.  Either way, it's by no means essential for following the rest of this article.</p>
<h4 id="heading-what-is-a-container-registry">What is a Container Registry</h4>
<p>Put simply, when we want to use Docker to deploy applications we build container images. We can use pre-built container images, or create our own.  Most often we will do a combination of the two, as containers are basically prebuilt images layered upon existing images and repackaged.  Once we have a final image, we then need somewhere to store it to deploy it.  Thats where a container registry comes in.  The most popular and well known of these is the default Docker container registry <a target="_blank" href="https://hub.docker.com/">Docker Hub</a>.</p>
<h4 id="heading-source-code">Source Code</h4>
<p>Source code for our To-Do application at the end of this step can be found <a target="_blank" href="https://github.com/davek-dev/to-do/tree/main/4.%20Adding%20Docker%20Support/src/davek.dev.todo">here</a>.</p>
<h3 id="heading-installing-our-registry">Installing our Registry</h3>
<p>There are a number of options for container registries our there, some of the most popular include <a target="_blank" href="https://github.com/docker/distribution-library-image">Registry</a> from Docker themselves, and <a target="_blank" href="https://goharbor.io/">VMWare Harbor</a>.  For this walkthrough we will use Registry as it is a simple implementaation which provides us with all the functionality we need for this <a target="_blank" href="https://davek.dev/series/to-do-application">to-do series</a> of articles.</p>
<p>As Registry is in itself deployed as a container, and we already have Docker set up on our existing virtual machine, all we need to do is log into our virtual machine instance and deploy the Registry container.  </p>
<pre><code>docker run <span class="hljs-operator">-</span>d <span class="hljs-operator">-</span>p <span class="hljs-number">9444</span>:<span class="hljs-number">5000</span> <span class="hljs-operator">-</span><span class="hljs-operator">-</span>restart<span class="hljs-operator">-</span>always <span class="hljs-operator">-</span><span class="hljs-operator">-</span>name container<span class="hljs-operator">-</span>registry registry:latest
</code></pre><p>With above command, we launch the container in 'detached' mode (-d), specifying that we want to use port 9444 of our local machine to access the container via it's internally exposed port 5000 (-p).  We also provide the restart policy, name the container, in our instance to container-registry and tell Docker to use the latest version of the Registry image.</p>
<p>Once deployed, if you have previously installed Portainer you should see it in the list of running containers:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660142903094/7pTt372Hl.jpg" alt="Screenshot_20220810-154648_Chrome.jpg" /></p>
<p>But you could just as easilly check the status by entering the following Docker command:</p>
<pre><code><span class="hljs-attribute">docker</span> ps
</code></pre><h3 id="heading-adding-docker-support-to-our-to-do-application">Adding Docker Support to Our To-Do Application</h3>
<p> To add docker support we firstly need to create a dockerfile for our application.  </p>
<p>Add the following to the folder containing the csproj file of your application.  You will most likely need to change the paths and project name to match the structure of your application:</p>
<pre><code>FROM mcr.microsoft.com/dotnet<span class="hljs-operator">/</span>aspnet:<span class="hljs-number">6.0</span> AS base
WORKDIR <span class="hljs-operator">/</span>app
EXPOSE <span class="hljs-number">80</span>
EXPOSE <span class="hljs-number">443</span>

FROM mcr.microsoft.com/dotnet<span class="hljs-operator">/</span>sdk:<span class="hljs-number">6.0</span> AS build
WORKDIR <span class="hljs-operator">/</span>src
COPY [<span class="hljs-string">"davek.dev.todo/davek.dev.todo.csproj"</span>, <span class="hljs-string">"davek.dev.todo/"</span>]
RUN dotnet restore <span class="hljs-string">"davek.dev.todo/davek.dev.todo.csproj"</span>
COPY . .
WORKDIR <span class="hljs-string">"/src/"</span>
RUN dotnet build <span class="hljs-string">"davek.dev.todo/davek.dev.todo.csproj"</span> <span class="hljs-operator">-</span>c Release <span class="hljs-operator">-</span>o <span class="hljs-operator">/</span>app<span class="hljs-operator">/</span>build

FROM build AS publish
RUN dotnet publish <span class="hljs-string">"davek.dev.todo/davek.dev.todo.csproj"</span> <span class="hljs-operator">-</span>c Release <span class="hljs-operator">-</span>o <span class="hljs-operator">/</span>app<span class="hljs-operator">/</span>publish

FROM base AS final
WORKDIR <span class="hljs-operator">/</span>app
COPY <span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-keyword">from</span><span class="hljs-operator">=</span>publish <span class="hljs-operator">/</span>app<span class="hljs-operator">/</span>publish .
ENTRYPOINT [<span class="hljs-string">"dotnet"</span>, <span class="hljs-string">"davek.dev.todo.dll"</span>]
</code></pre><p>This dockerfile explains the steps we go through to build our application container as follows:</p>
<ol>
<li><p>We first specify our base image.  This is the image that contains the required runtime libraries so run our application.  In this instance we are deploying to and ASP.NET image running on .Net 6.</p>
</li>
<li><p>We then specify a build image.  This image contains all the required SDK libraries to build our image.  We are actually going to be building our image in one container and then deploy or publish it to another. </p>
</li>
<li><p>We then copy our csproj file and run a dotnet restore against it, to pull in any additional libraries we may require.  </p>
</li>
<li><p>We copy the remaining files from our project into the container, and build our application.</p>
</li>
<li><p>We publish our application to a 'Release' directory.</p>
</li>
<li><p>We copy our published files into our 'final' container and tell the container that when started, to launch our application through the entrypoint directive.</p>
</li>
</ol>
<p>We can now tell docker to use the above file to build our image.  If you have docker already installed on your development machine then we can run a docker build as below.  If you don't have docker installed, Docker Desktop can be downloaded <a target="_blank" href="https://www.docker.com/products/docker-desktop/">here</a>. </p>
<pre><code>docker build <span class="hljs-operator">-</span>f .\davek.dev.todo\Dockerfile <span class="hljs-operator">-</span>t to<span class="hljs-operator">-</span>do:<span class="hljs-number">1.0</span> .
</code></pre><p>Note:  I am running this from a command prompt in my src directory.  You may need to alter file paths to suit your existing application structure.</p>
<p>Using the -t command I also set an image name and version at the time I build the container image.</p>
<h3 id="heading-uploading-our-image-to-our-registry">Uploading our Image to our Registry</h3>
<p>Once we have an image we need to tag it with our registry details.  We can do that simply by re-tagging the container we just built as follows:</p>
<pre><code><span class="hljs-selector-tag">docker</span> <span class="hljs-selector-tag">tag</span> <span class="hljs-selector-tag">to-do</span><span class="hljs-selector-pseudo">:1.0</span> <span class="hljs-selector-attr">[IP address of vm]</span>:<span class="hljs-selector-attr">[port of registry]</span>/<span class="hljs-selector-tag">to-do</span><span class="hljs-selector-pseudo">:1.0</span>
</code></pre><p>If you access your docker host using a domain name you can use that instead if the IP address.</p>
<p>You can then push the container to your repository using the tag specified in the previous command:</p>
<pre><code><span class="hljs-selector-tag">docker</span> <span class="hljs-selector-tag">push</span>  <span class="hljs-selector-attr">[IP address of vm]</span>:<span class="hljs-selector-attr">[port of registry]</span>/<span class="hljs-selector-tag">to-do</span><span class="hljs-selector-pseudo">:1.0</span>
</code></pre><p>Note: If you get an error of 'http: server gave HTTP response to HTTPS client' you may need to add the registry to the insecure-registries config in the Docker Desktop &gt; Docker Engine json config and apply/restart.</p>
<p>This should start uploading the image to your own registry.  </p>
<h3 id="heading-deploying-from-our-registry">Deploying from our Registry</h3>
<h4 id="heading-pulling-the-image">Pulling the Image</h4>
<p>Now we have uploaded our image to our repostory, we can pull our image with</p>
<pre><code><span class="hljs-selector-tag">docker</span> <span class="hljs-selector-tag">pull</span> <span class="hljs-selector-tag">localhost</span>:<span class="hljs-selector-attr">[port of registry]</span>/<span class="hljs-selector-tag">to-do</span><span class="hljs-selector-pseudo">:1.0</span>
</code></pre><p>and then when we run our docker image command our new image should appear in the list.</p>
<p>####</p>
<p>We can then launch our container with:</p>
<pre><code>docker run <span class="hljs-operator">-</span>d <span class="hljs-operator">-</span>p <span class="hljs-number">8080</span>:<span class="hljs-number">80</span> <span class="hljs-operator">-</span><span class="hljs-operator">-</span>restart<span class="hljs-operator">-</span>always <span class="hljs-operator">-</span><span class="hljs-operator">-</span>name to<span class="hljs-operator">-</span>do localhost:[port of registry]<span class="hljs-operator">/</span>to<span class="hljs-operator">-</span>do:<span class="hljs-number">1.0</span>
</code></pre><p>The application should then be available at http://localhost:8080 although, if using the current example application then we will not currently have any accessible endpoints to view.  However we can see it in our portainer instance or our docker ps output.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660148124739/2vwiRrAsL.jpg" alt="Screenshot_20220810-171443_Chrome.jpg" /></p>
]]></content:encoded></item><item><title><![CDATA[Installing Docker and Portainer on a Free Oracle VM]]></title><description><![CDATA[Getting started with Docker and Portainer on Oracle Cloud free tier.]]></description><link>https://davek.dev/installing-docker-and-portainer-on-a-free-oracle-vm</link><guid isPermaLink="true">https://davek.dev/installing-docker-and-portainer-on-a-free-oracle-vm</guid><category><![CDATA[Docker]]></category><category><![CDATA[Cloud]]></category><category><![CDATA[Oracle Cloud]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Portainer]]></category><dc:creator><![CDATA[Dave K]]></dc:creator><pubDate>Tue, 12 Jul 2022 09:26:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/tjX_sniNzgQ/upload/v1657617847885/L1Th84n9E.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>Containers are a popular way to package and deploy applications in modern day software development practices.  For this article, I will discuss setting up a new environment that we can use to host containers using Docker and use an application called Portainer to provide a nice way to manager them without having to do so through the Docker command line.  This is a great way for beginners to familiarise themselves with the Docker platform.</p>
<h3 id="heading-what-is-docker">What is Docker?</h3>
<p>Docker is a platform to help develop, build and run applications quickly, in a self-contained way that allows us to decouple our applications from the underlying infrastructure.  Applications run in 'containers' that are designed to be lightweight, and contain all the required dependencies to allow the application to run.</p>
<p>A more in depth introduction to Docker can be found on the Docker website <a target="_blank" href="https://www.docker.com/resources/what-container/">here</a></p>
<h3 id="heading-what-is-portainer">What is Portainer?</h3>
<p>Portainer is a container management tool that itself runs inside a container within docker.  It provides a simple user interface (UI) that allows us to manage and monitor all aspects of our docker deployment.  It comes as both a free community edition and more featured business edition options.  </p>
<p>More information can be found <a target="_blank" href="https://www.portainer.io/">here</a></p>
<h3 id="heading-oracle-free-tier">Oracle Free Tier</h3>
<p>Oracle Cloud offers one of the more generous set of always free services, including low powered virtual machines that are ideal for small containerised workloads.  You can see a full list of their always free services <a target="_blank" href="https://www.oracle.com/uk/cloud/free/#always-free">here</a> and register for a new account <a target="_blank" href="https://www.oracle.com/uk/cloud/free/">here</a> if you wish to use an Oracle Cloud VM to follow this guide.</p>
<h3 id="heading-setting-up-the-virtual-machine">Setting up the Virtual Machine</h3>
<p>Once you have created an account in Oracle Cloud, the first thing to do is set up a 'compartment' for our virtual machine and related services to run in.  Compartments allow us to segregate different services into related groups.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1657615060944/Emnjwt5re.JPG" alt="1.JPG" /></p>
<p>Once the compartment is created, we can select 'Compute' and 'Create a new compute instance'.  Provide  a name for our virtual machine and select the compartment we have just created.  I also prefer to change the image from the default Oracle Linux to Ubuntu as a personal preference, and for this guide I will be using the Ubuntu image.  You can leave the shape to the default value, it should be labelled as 'Always Free'.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1657615208822/cdbv_8FNF.JPG" alt="2.JPG" /></p>
<p>In the networking section, select 'Create new virtual cloud network' and assign the subnet a memorable name.  You should also ensure 'Assign a public IP address' is selected.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1657615344349/s1dPcgmER.JPG" alt="3.JPG" /></p>
<p>In the 'Add SSH keys' section, where it gives you the option to download the keys, ensure you download the private key as we will need this to access the virtual machine later.</p>
<p>Click 'Create' and the instance will be provisioned. </p>
<h3 id="heading-connecting-to-the-virtual-machine">Connecting to the Virtual Machine</h3>
<h4 id="heading-configuring-the-vm-firewall">Configuring the VM Firewall</h4>
<p>Once provisioned you should see the subnet name on the right-hand side under the 'Primary VNIC' heading, click on it.</p>
<p>Here you can edit the default security list, so if you have a static IP you may want to restrict port 22 to just your Own IP address. As you need a CIDR not just the IP, if you're adding a single IP you can just add /32 to the end of your local IP address.</p>
<p>You should also allow access to port 9443 as we will use this later.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1657615605265/7Wcg7qrkv.JPG" alt="4.JPG" /></p>
<h4 id="heading-using-puttygen-to-convert-the-ssh-key">Using Puttygen to Convert the SSH Key</h4>
<p>In this guide, we will be using Putty to connect to our virtual machine.  To do this, we firstly need to convert our SSH key to the correct type for Putty to use. </p>
<p>If you don't already have Putty installed, you can download it <a target="_blank" href="https://www.putty.org/">here</a>.</p>
<p>Once installed, launch Puttygen, which comes bundled with Putty.</p>
<p>Click 'Load' then select the private key downloaded from Oracle Cloud earlier.  You will then be prompted that you should save the key in Putty's own format.  Click 'OK' and then 'Save private key' to save the key in the required format.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1657615921705/KrYRFMjUy.JPG" alt="5.JPG" /></p>
<h4 id="heading-connecting-via-ssh-with-putty">Connecting via SSH with Putty</h4>
<p>Open 'Putty' then scroll down on the left menu to the Connection =&gt; SSH =&gt; Auth section.</p>
<p>In the 'Private key for authentication' box, click 'Browse' and select the ppk file created by Puttygen.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1657616073947/-DFt2knpD.JPG" alt="6.JPG" /></p>
<p>Click back to the 'Session' option and enter the public IP address of the VM instance created earlier.  You can also give this profile a name and click 'Save' to allow you to easily re-connect later.</p>
<p>Once done, click 'Open' and you should see a connection being made to your virtual machine.  If you used the Ubuntu image, your username will be 'ubuntu'.  If you used a different image, then the username should be displayed on your virtual machine details screen in Oracle Cloud.  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1657616261589/VnNtpN6lz.JPG" alt="7.JPG" /></p>
<h3 id="heading-installing-docker">Installing Docker</h3>
<h4 id="heading-setting-up-the-repository">Setting up the Repository</h4>
<p>Firstly, we need to ensure our system is up-to-date and then install the Docker repository to allow us to download and install the Docker application.</p>
<pre><code>sudo apt-<span class="hljs-keyword">get</span> <span class="hljs-keyword">update</span>
</code></pre><pre><code>sudo apt<span class="hljs-operator">-</span>get install \
    ca<span class="hljs-operator">-</span>certificates \
    curl \
    gnupg \
    lsb<span class="hljs-operator">-</span>release
</code></pre><pre><code> sudo mkdir <span class="hljs-operator">-</span>p <span class="hljs-operator">/</span>etc<span class="hljs-operator">/</span>apt<span class="hljs-operator">/</span>keyrings
</code></pre><pre><code> curl -fsSL <span class="hljs-symbol">https:</span>/<span class="hljs-regexp">/download.docker.com/linux</span><span class="hljs-regexp">/ubuntu/gpg</span> <span class="hljs-params">| sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg</span>
</code></pre><pre><code> echo \
  <span class="hljs-string">"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
  $(lsb_release -cs) stable"</span> <span class="hljs-operator">|</span> sudo tee <span class="hljs-operator">/</span>etc<span class="hljs-operator">/</span>apt<span class="hljs-operator">/</span>sources.list.d/docker.list <span class="hljs-operator">&gt;</span> <span class="hljs-operator">/</span>dev<span class="hljs-operator">/</span>null
</code></pre><h4 id="heading-install-docker-ce">Install Docker CE</h4>
<p>Then we can go ahead and install the Docker application</p>
<pre><code>sudo apt<span class="hljs-operator">-</span>get update
sudo apt<span class="hljs-operator">-</span>get install docker<span class="hljs-operator">-</span>ce docker<span class="hljs-operator">-</span>ce<span class="hljs-operator">-</span>cli containerd.io docker<span class="hljs-operator">-</span>compose<span class="hljs-operator">-</span>plugin
</code></pre><p>And we can add our current user to the docker group to save us needing to run as sudo each time we want to run a Docker command.</p>
<pre><code><span class="hljs-attribute">sudo</span> usermod -aG docker <span class="hljs-variable">$USER</span>
</code></pre><p>We should now close our session and log back in to allow the changes to take effect.</p>
<h3 id="heading-portainer">Portainer</h3>
<h4 id="heading-installing-portainer">Installing Portainer</h4>
<p>Firstly, we need to install a volume for our Portainer data.  Because Docker containers are self-contained, when we tear down our container, we also lose any data stored within the container.  To prevent data loss, we use Docker to create volumes, which are basically storage areas on the host machine that are mapped into a container, so that when the container is destroyed, the volume and data stored within it are retained.  This is useful for when we're upgrading or redeploying containers, and can re-map the volume to the new container without data loss.</p>
<pre><code>docker volume <span class="hljs-keyword">create</span> portainer_data
</code></pre><p>We can then tell Docker to run the Portainer container.  In the command below, we provide port mappings which tell Docker to expose port 8000 from within the container to port 9443 on the host machine.  Remember, we allowed access to 9443 when we configured the virtual machine firewall earlier. </p>
<p>We also give the container a name, a restart policy and link 2 volumes.  The one we just created above, and the docker socket.  This allows Portainer to execute Docker commands to allow it to manage Docker for us.</p>
<p>The final line is the image name and tag.  At the time of writing 2.9.3 was the latest version of Portainer container.  If this image doesn't already exist on the local machine, Docker will go ahead and download it for you.</p>
<pre><code>docker run <span class="hljs-operator">-</span>d <span class="hljs-operator">-</span>p <span class="hljs-number">8000</span>:<span class="hljs-number">8000</span> <span class="hljs-operator">-</span>p <span class="hljs-number">9443</span>:<span class="hljs-number">9443</span> <span class="hljs-operator">-</span><span class="hljs-operator">-</span>name portainer \
    <span class="hljs-operator">-</span><span class="hljs-operator">-</span>restart<span class="hljs-operator">=</span>always \
    <span class="hljs-operator">-</span>v <span class="hljs-operator">/</span><span class="hljs-keyword">var</span><span class="hljs-operator">/</span>run<span class="hljs-operator">/</span>docker.sock:<span class="hljs-operator">/</span><span class="hljs-keyword">var</span><span class="hljs-operator">/</span>run<span class="hljs-operator">/</span>docker.sock \
    <span class="hljs-operator">-</span>v portainer_data:<span class="hljs-operator">/</span>data \
    portainer<span class="hljs-operator">/</span>portainer<span class="hljs-operator">-</span>ce:<span class="hljs-number">2.9</span><span class="hljs-number">.3</span>
</code></pre><p>When this has completed the installation, we should be able to list the containers in our Docker instance and see our Portainer container running:</p>
<pre><code><span class="hljs-attribute">docker</span> ps
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1657617322652/ScE5bVdXs.JPG" alt="10.JPG" /></p>
<h4 id="heading-accessing-portainer">Accessing Portainer</h4>
<p>We should now be able to access our Portainer instance at :9443</p>
<p>You may be presented with a certificate error as Portainer uses a self-signed certificate.  You can safely ignore this. </p>
<p>The first time you load the Portainer interface you will be asked to create a user account.  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1657617424261/-cTGqYSym.JPG" alt="11.JPG" /></p>
<p>Create an account and then when presented with the environment wizard, select 'Proceed with the current environment'.</p>
<p>You should then be presented with the local environment, which should have a single container (our Portainer container) up and running:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1657617507287/B8bKN9whG.JPG" alt="12.JPG" /></p>
<h3 id="heading-summary">Summary</h3>
<p>We now have a Virtual Machine up and running complete with Docker and Portainer to allow us to manage our Docker containers and images.  Go ahead and explore the user interface and you should see the Portainer image in the images section, our volume in the volume section.  If you go into the container itself you should be able to see how the port mappings and volumnes are confgured, along with a number of other options you can configure on a container when required.</p>
]]></content:encoded></item><item><title><![CDATA[Using AWS SQS Queues in C# and .Net 6]]></title><description><![CDATA[This is the third article in the 'To-Do List' series. You do not need to follow the series to follow this tutorial, but you may find that some parts of the…]]></description><link>https://davek.dev/using-aws-sqs-queues-in-c-and-net-6</link><guid isPermaLink="true">https://davek.dev/using-aws-sqs-queues-in-c-and-net-6</guid><category><![CDATA[C#]]></category><category><![CDATA[AWS]]></category><category><![CDATA[.NET]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[SQS]]></category><dc:creator><![CDATA[Dave K]]></dc:creator><pubDate>Fri, 17 Jun 2022 16:20:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/pT4gB7T6tog/upload/v1655482775651/CkArPWlHc.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>This is the third article in the <a target="_blank" href="https://davek.dev/series/to-do-application">'To-Do List' series</a>.  You do not need to follow the series to follow this tutorial, but you may find that some parts of the tutorial refer to previous articles.</p>
<p>Here, I am going to extend my application to include an SQS queue we can use to add new items to our lists.  This gives us an option to add items to our list from anywhere without having to expose our API to the public.</p>
<p>The architecture at the completion of this article will look like the below:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1655479664175/gwVEbLad7.png" alt="image.png" /></p>
<p>All code for relating to this tutorial can be found on GitHub <a target="_blank" href="https://github.com/davek-dev/to-do/tree/main/3.%20SQS%20in%20.Net%206/src/davek.dev.todo">here</a>.</p>
<h3 id="heading-setting-up-the-sqs-queue">Setting up the SQS Queue</h3>
<h4 id="heading-create-a-user-account">Create a User Account</h4>
<p>If you have not already set up an AWS account, you can register for one <a target="_blank" href="https://aws.amazon.com/">here</a>.  At the time of writing, all the tools we're using in this article fall within the Free Tier, so there should be no costs associated, but you should confirm this.</p>
<p>Once you have an AWS account, the first thing to do is set up a new IAM account that our API will use to read/write to the queue.</p>
<p>Go into the IAM service and select 'Add User'.  Provide a username and ensure the 'Access key...' option is selected:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1655480070826/f7mv-8O6a.png" alt="image.png" /></p>
<p>Click through to the final page, and make a note of the access key and the secret key, as we will need these later.  Click 'Close'.  Then, you should be able to go back into the 'Users' screen and select the user we have just created.  Make a note of the ARN value for our user.</p>
<h4 id="heading-create-the-sqs-queue">Create the SQS Queue</h4>
<p>Now we have a user, we can go into the SQS service and select 'Create Queue'.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1655480262375/vfZB4ctRf.png" alt="image.png" /></p>
<p>Give the queue a name, and then scroll down to the 'Access policy' section.  We can leave the method as 'Basic', and then when we want to define who can send and who can receive to the queue, select 'Only the specified AWS accounts, IAM users and roles' and enter the ARN value for the user we created (above).  Make sure this is done for both send and receive.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1655480367740/Vlm1_QnZx.png" alt="image.png" /></p>
<p>Once the queue is created, make a note of the name, ID and region the queue exists in. We will need these to configure our API.</p>
<h3 id="heading-adding-the-sqs-code-to-our-api">Adding the SQS Code to our API</h3>
<h4 id="heading-creating-the-options">Creating the Options</h4>
<p>We will use the Options pattern to import our queue configuration into our API. We can add the following into our appsettings.json, filling in the values we have previously obtained:</p>
<pre><code><span class="hljs-string">"SqsOptions"</span> : {
    <span class="hljs-string">"SqsRegion"</span> : <span class="hljs-string">""</span>,
    <span class="hljs-string">"SqsQueueId"</span> : <span class="hljs-string">""</span>,
    <span class="hljs-string">"SqsQueueName"</span> : <span class="hljs-string">""</span>,
    <span class="hljs-string">"IamAccessKey"</span> : <span class="hljs-string">""</span>,
    <span class="hljs-string">"IamSecretKey"</span> : <span class="hljs-string">""</span>
  }
</code></pre><p>And create a new 'SqsOptions' class to match:</p>
<pre><code><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">SqsOptions</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> SqsRegion { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> SqsQueueId { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> SqsQueueName { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> IamAccessKey { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> IamSecretKey { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>;}
}
</code></pre><p>We can then simply add the below line to our Program.cs to import the options into our API dependency injection container:</p>
<pre><code>builder.Services.Configure&lt;SqsOptions<span class="hljs-operator">&gt;</span>(builder.Configuration.GetSection(<span class="hljs-string">"SqsOptions"</span>));
</code></pre><h4 id="heading-creating-an-sqs-client-factory">Creating an SQS Client Factory</h4>
<p>I will use the <a target="_blank" href="https://en.wikipedia.org/wiki/Factory_method_pattern">factory pattern</a> here, in the same way as I did previously for the data access connection in my <a target="_blank" href="https://davek.dev/crud-with-mongodb-in-c-and-net-6#heading-mongodb-factory">previous post</a>.  This allows us to separate out the code that depends on the external AWS library to a minimal class, and makes the main SQS service more testable.</p>
<p>The factory is responsible for taking the SQS Options and configuring the client for connecting to the queue.  I have also extracted an interface for this, code of which can be found in the GitHub repository.</p>
<pre><code><span class="hljs-keyword">public</span> class SqsClientFactory : ISqsClientFactory
{
    <span class="hljs-keyword">private</span> readonly IOptions<span class="hljs-operator">&lt;</span>SqsOptions<span class="hljs-operator">&gt;</span> _options;

    <span class="hljs-keyword">public</span> SqsClientFactory(IOptions<span class="hljs-operator">&lt;</span>SqsOptions<span class="hljs-operator">&gt;</span> options)
    {
        _options <span class="hljs-operator">=</span> options;
    }

    <span class="hljs-keyword">public</span> IAmazonSQS GetSqsClient()
    {
        <span class="hljs-keyword">var</span> config <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> AmazonSQSConfig
        {
            RegionEndpoint <span class="hljs-operator">=</span> RegionEndpoint.GetBySystemName(_options.Value.SqsRegion),
            ServiceURL <span class="hljs-operator">=</span> $<span class="hljs-string">"https://sqs.{_options.Value.SqsRegion}.amazonaws.com"</span>
        };

       <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> AmazonSQSClient(_options.Value.IamAccessKey, _options.Value.IamSecretKey, config);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> GetSqsQueue() <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span>
        $<span class="hljs-string">"https://sqs.{_options.Value.SqsRegion}.amazonaws.com/{_options.Value.SqsQueueId}/{_options.Value.SqsQueueName}"</span>;
}
</code></pre><p>The factory is then added to the Program.cs as follows:</p>
<pre><code>builder.Services.AddSingleton&lt;ISqsClientFactory, SqsClientFactory<span class="hljs-operator">&gt;</span>();
</code></pre><h4 id="heading-the-sqs-service">The SQS Service</h4>
<p>The SQS Service is primarily designed to take messages off the SQS Queue, deserialise them back into a list of To-Do Items and return them to the calling service.  For our service, we have also included the functionality to drop messages onto the queue, which should allow us to test the end-to-end process.</p>
<p>The SQS Service calls the SQS Factory to obtain a client and then uses that client to add and retrieve messages. Again an interface has been added but excluded from here for brevity.</p>
<pre><code><span class="hljs-keyword">public</span> class SqsService : ISqsService
{
    <span class="hljs-keyword">private</span> readonly ISqsClientFactory _sqsClientFactory;

    <span class="hljs-keyword">public</span> SqsService(ISqsClientFactory sqsClientFactory)
    {
        _sqsClientFactory <span class="hljs-operator">=</span> sqsClientFactory;
    }

    <span class="hljs-keyword">public</span> async Task<span class="hljs-operator">&lt;</span>IEnumerable<span class="hljs-operator">&lt;</span>ToDoItemModel<span class="hljs-operator">&gt;</span><span class="hljs-operator">&gt;</span> GetToDoItemsAsync()
    {
        <span class="hljs-keyword">var</span> messages <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> List<span class="hljs-operator">&lt;</span>ToDoItemModel<span class="hljs-operator">&gt;</span>();

        <span class="hljs-keyword">var</span> request <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> ReceiveMessageRequest
        {
            QueueUrl <span class="hljs-operator">=</span> _sqsClientFactory.GetSqsQueue(),
            MaxNumberOfMessages <span class="hljs-operator">=</span> <span class="hljs-number">10</span>,
            VisibilityTimeout <span class="hljs-operator">=</span> <span class="hljs-number">10</span>,
            WaitTimeSeconds <span class="hljs-operator">=</span> <span class="hljs-number">10</span>,
        };

        <span class="hljs-keyword">var</span> response <span class="hljs-operator">=</span> await _sqsClientFactory.GetSqsClient().ReceiveMessageAsync(request);

        foreach (<span class="hljs-keyword">var</span> message in response.Messages)
        {
            <span class="hljs-keyword">try</span>
            {
                <span class="hljs-keyword">var</span> m <span class="hljs-operator">=</span> JsonSerializer.Deserialize&lt;ToDoItemModel<span class="hljs-operator">&gt;</span>(message.Body);
                <span class="hljs-keyword">if</span>(m <span class="hljs-operator">!</span><span class="hljs-operator">=</span> null)
                    messages.Add(m);
            }
            <span class="hljs-keyword">catch</span>
            {
                <span class="hljs-comment">// Invalid message, ignore</span>
            }
        }

        <span class="hljs-keyword">return</span> messages;
    }

    <span class="hljs-keyword">public</span> async Task PublishToDoItemAsync(ToDoItemModel item)
    {
        <span class="hljs-keyword">var</span> request <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> SendMessageRequest
        {
            MessageBody <span class="hljs-operator">=</span> JsonSerializer.Serialize(item),
            QueueUrl <span class="hljs-operator">=</span> _sqsClientFactory.GetSqsQueue(),
        };

         <span class="hljs-keyword">var</span> client <span class="hljs-operator">=</span>  _sqsClientFactory.GetSqsClient();
         await client.SendMessageAsync(request);
    }
}
</code></pre><p>We can then drop this into our Program.cs:</p>
<pre><code>builder.Services.AddTransient&lt;ISqsService, SqsService<span class="hljs-operator">&gt;</span>();
</code></pre><h4 id="heading-putting-it-all-together">Putting it all Together</h4>
<p>For this demonstration, I am just going to create a simple controller that allows us to push a message onto the queue, and then check the queue for messages and for any it finds, write them into our database.  I will also return the number of messages found so we can see something has happened:</p>
<pre><code>[Route(<span class="hljs-string">"[controller]"</span>)]
<span class="hljs-keyword">public</span> class SqsController : ControllerBase
{
    <span class="hljs-keyword">private</span> readonly ISqsService _sqsService;
    <span class="hljs-keyword">private</span> readonly IToDoItemService _toDoItemService;

    <span class="hljs-keyword">public</span> SqsController(ISqsService sqsService, IToDoItemService toDoItemService)
    {
        _sqsService <span class="hljs-operator">=</span> sqsService;
        _toDoItemService <span class="hljs-operator">=</span> toDoItemService;
    }

    [HttpPost(<span class="hljs-string">"Create"</span>)]
    <span class="hljs-keyword">public</span> async Task<span class="hljs-operator">&lt;</span>IActionResult<span class="hljs-operator">&gt;</span> PublishToDoItem([FromBody] ToDoItemModel model)
    {
        <span class="hljs-keyword">try</span>
        {
            await _sqsService.PublishToDoItemAsync(model);
            <span class="hljs-keyword">return</span> Ok();
        }
        <span class="hljs-keyword">catch</span> (Exception ex)
        {
            <span class="hljs-keyword">return</span> BadRequest(ex.Message);
        }
    }

    [HttpGet(<span class="hljs-string">"Retrieve"</span>)]
    <span class="hljs-keyword">public</span> async Task<span class="hljs-operator">&lt;</span>IActionResult<span class="hljs-operator">&gt;</span> RetrieveToDoItems()
    {
        <span class="hljs-keyword">try</span>
        {
            <span class="hljs-keyword">var</span> items <span class="hljs-operator">=</span> await _sqsService.GetToDoItemsAsync();

            foreach (<span class="hljs-keyword">var</span> item in items)
            {
                await _toDoItemService.CreateItemAsync(item);
            }

            <span class="hljs-keyword">return</span> Ok(items.Count());
        }
        <span class="hljs-keyword">catch</span> (Exception ex)
        {
            <span class="hljs-keyword">return</span> BadRequest(ex.Message);
        }
    }
}
</code></pre><p> When we launch our application, we can navigate to the swagger page and send a new request to the 'Create' endpoint on our SQS controller:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1655481505727/BsOJSXSU1.png" alt="image.png" /></p>
<p>This should publish our To-Do item onto our queue.  All being well, we should get a 200 OK response.</p>
<p>We can then make a call to our 'Retrieve' endpoint.  This should pull any messages down from the queue and push them into our database.  Note: Depending on the set-up, you can specify the maximum number of messages to retrieve in a single request. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1655481682168/C5neoY_X_.png" alt="image.png" /></p>
<p>Here we can see we have pulled down the single item we have added to our queue, and a 1 is displayed as the response.</p>
<p>To verify we have then added this to our database, we can call the 'GetOpenItems' endpoint on our 'ToDoItem' controller and we should see our new item along with any previous items we have created appear in our list:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1655481731984/tebFICfvl.png" alt="image.png" /></p>
<h3 id="heading-summary">Summary</h3>
<p>This covers the basic steps to reading and writing from an SQS Queue.  We currently haven't implemented a way to continuously poll for our new items.  This will be covered in a separate article, where we can add a recurring job to Hangfire, that we <a target="_blank" href="https://davek.dev/using-hangfire-and-mongodb-for-scheduling-in-net-6">previously configured</a> to allow us to monitor our queue.</p>
]]></content:encoded></item><item><title><![CDATA[CRUD with MongoDB in C# and .Net 6]]></title><description><![CDATA[Using MongoDB with asp.net core in c#]]></description><link>https://davek.dev/crud-with-mongodb-in-c-and-net-6</link><guid isPermaLink="true">https://davek.dev/crud-with-mongodb-in-c-and-net-6</guid><category><![CDATA[MongoDB]]></category><category><![CDATA[C#]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[.NET]]></category><category><![CDATA[asp.net core]]></category><dc:creator><![CDATA[Dave K]]></dc:creator><pubDate>Wed, 15 Jun 2022 13:19:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/lRoX0shwjUQ/upload/v1655299077438/woe7ct9x3.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>In the second part of the 'To-Do List' series, I'm going to introduce the basic functionality to read and write to MongoDB from C# in .Net 6.  This will build upon the code from my <a target="_blank" href="https://davek.dev/using-hangfire-and-mongodb-for-scheduling-in-net-6">previous article</a>, which also explains how to get a free Atlas MongoDB set-up to host your database if you do not currently have a database set up.</p>
<h3 id="heading-architecture">Architecture</h3>
<p>We're going to use a pretty standard layered pattern here, separating our code into three layers:</p>
<ul>
<li>Presentation layer (This is where our controllers will go)</li>
<li>Application layer  (Our business logic lives here)</li>
<li>Data access layer (Interaction with MongoDB)</li>
</ul>
<p>One of my favourite articles around the layered approach is <a target="_blank" href="https://jeffreypalermo.com/2008/07/the-onion-architecture-part-1/">this one</a> by Jeffrey Palermo on 'Onion Architecture'.</p>
<p>This may seem a bit overkill for now, but this project will grow, and we should always try to implement good practices from the start.</p>
<p>All source for this is available on GitHub <a target="_blank" href="https://github.com/davek-dev/to-do/tree/main/2.%20MongoDB%20in%20C%23%20and%20.Net%206/src/davek.dev.todo">here</a>.</p>
<h3 id="heading-data-access-layer">Data Access Layer</h3>
<h4 id="heading-data-model">Data Model</h4>
<p>To store data in MongoDB, we need a data model.  For this example, I have created  a simple ToDoListItemModel.cs class that defines the basic element we will store in our database.  I have also created a second ToDoItemNoteModel class that will allow me to add notes to the item at a later date.  The notes will be stored in an array on the to-do list item.  As MongoDB is not a relational database, we will store notes as an array on the parent to-do list item model.</p>
<pre><code><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ToDoItemModel</span>
{    
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-keyword">public</span> DateTime DateCreated { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-keyword">public</span> DateTime? DateCompleted { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Title { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Description { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-keyword">public</span> ToDoItemNoteModel[] Notes { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> Complete { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}
</code></pre><pre><code><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ToDoItemNoteModel</span>
{
    <span class="hljs-keyword">public</span> DateTime DateCreated { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Note { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}
</code></pre><h4 id="heading-mongodb-factory">MongoDB Factory</h4>
<p>To interact with the database, I have decided to use the <a target="_blank" href="https://en.wikipedia.org/wiki/Factory_method_pattern">factory pattern</a>, which allows me to abstract away some configuration from the data access services.  This will make unit testing of our services much more straightforward. Unit testing will be covered in a later article.</p>
<p>This factory can be injected into all of our data access services (we currently only have one) and be called upon to create a new connection to a database collection.  </p>
<p>Note:  I have also created interfaces for these services which will be used to add the services to the dependency injection container.  For the interface code, you can refer to the <a target="_blank" href="https://github.com/davek-dev/to-do/tree/main/2.%20MongoDB%20in%20C%23%20and%20.Net%206/src/davek.dev.todo">GitHub repository</a> if required.</p>
<pre><code><span class="hljs-keyword">public</span> class MongoDbFactory : IMongoDbFactory
{
    <span class="hljs-keyword">private</span> readonly IMongoClient _client;

    <span class="hljs-keyword">public</span> MongoDbFactory(<span class="hljs-keyword">string</span> connectionString)
    {
        <span class="hljs-keyword">var</span> settings <span class="hljs-operator">=</span> MongoClientSettings.FromConnectionString(connectionString);
        settings.ServerApi <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> ServerApi(ServerApiVersion.V1);

        _client <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> MongoClient(settings);
    }

    <span class="hljs-keyword">public</span> IMongoCollection<span class="hljs-operator">&lt;</span>T<span class="hljs-operator">&gt;</span> GetCollection<span class="hljs-operator">&lt;</span>T<span class="hljs-operator">&gt;</span>(<span class="hljs-keyword">string</span> databaseName, <span class="hljs-keyword">string</span> collectionNme)
    {
        <span class="hljs-keyword">return</span> _client.GetDatabase(databaseName).GetCollection&lt;T<span class="hljs-operator">&gt;</span>(collectionNme);
    }
}
</code></pre><h4 id="heading-data-access-service">Data Access Service</h4>
<p>Reading and writing operations for our collection are added to a data access service.  There should be no business logic in here, as that will be added to our service layer.  The sole responsibility of data access service is the basic database operations.  For now, I have included some basic create, read, update and delete (CRUD) operations that we will need to get stared with our application.</p>
<p>I have left the name of our database and collection hard coded for now, but this could be moved to config if required.  You will see how the factory is injected in the constructor and then called upon to create a new connection to our specific collection using generics, which I will cover in a later article.</p>
<pre><code><span class="hljs-keyword">public</span> class ToDoItemDataAccessService : IToDoItemDataAccessService
{
    <span class="hljs-keyword">private</span> readonly IMongoCollection<span class="hljs-operator">&lt;</span>ToDoItemModel<span class="hljs-operator">&gt;</span> _toDoItems;

    <span class="hljs-keyword">public</span> ToDoItemDataAccessService(IMongoDbFactory mongoDbFactory)
    {
        _toDoItems <span class="hljs-operator">=</span> mongoDbFactory.GetCollection&lt;ToDoItemModel<span class="hljs-operator">&gt;</span>(<span class="hljs-string">"ToDo"</span>, <span class="hljs-string">"ToDoItems"</span>);
    }

    <span class="hljs-keyword">public</span> async Task CreateItemAsync(ToDoItemModel model)
    {
        await _toDoItems.InsertOneAsync(model);
    }

    <span class="hljs-keyword">public</span> async Task<span class="hljs-operator">&lt;</span>ToDoItemModel<span class="hljs-operator">&gt;</span> GetToDoItemAsync(<span class="hljs-keyword">string</span> id)
    {
        <span class="hljs-keyword">var</span> results <span class="hljs-operator">=</span> await _toDoItems.FindAsync(x <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> x.Id <span class="hljs-operator">=</span><span class="hljs-operator">=</span> id);
        <span class="hljs-keyword">return</span> await results.SingleAsync();
    }

    <span class="hljs-keyword">public</span> async Task<span class="hljs-operator">&lt;</span>IEnumerable<span class="hljs-operator">&lt;</span>ToDoItemModel<span class="hljs-operator">&gt;</span><span class="hljs-operator">&gt;</span> GetOpenToDoItemsAsync()
    {
        <span class="hljs-keyword">var</span> results <span class="hljs-operator">=</span> await _toDoItems.FindAsync(x <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> <span class="hljs-operator">!</span>x.Complete);
        <span class="hljs-keyword">return</span> await results.ToListAsync();
    }

    <span class="hljs-keyword">public</span> async Task UpdateToDoItemAsync(ToDoItemModel model)
    {
        await _toDoItems.FindOneAndReplaceAsync(x <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> x.Id <span class="hljs-operator">=</span><span class="hljs-operator">=</span> model.Id, model);
    }

    <span class="hljs-keyword">public</span> async Task DeleteToDoItemAsync(<span class="hljs-keyword">string</span> id)
    {
        await _toDoItems.DeleteOneAsync(x <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> x.Id <span class="hljs-operator">=</span><span class="hljs-operator">=</span> id);
    }
}
</code></pre><h3 id="heading-service-layer">Service Layer</h3>
<p>The service layer for this application should contain all our business logic.  In this example, we don't yet have much business logic, so for now on the creation function we use it to set the ID and the creation date and make sure any other values are reset, and for the remaining functions it will act as a simple pass through.  I have created the ID as a GUID and converted to a string, rather than using the out the box BSON ID functionality as this makes it easier for us to search against later.  Notice the data access layer service is injected into the service layer service again through the constructor.</p>
<pre><code><span class="hljs-keyword">public</span> class ToDoItemService : IToDoItemService
{
    <span class="hljs-keyword">private</span> readonly IToDoItemDataAccessService _toDoItemDataAccessService;

    <span class="hljs-keyword">public</span> ToDoItemService(IToDoItemDataAccessService toDoItemDataAccessService)
    {
        _toDoItemDataAccessService <span class="hljs-operator">=</span> toDoItemDataAccessService;
    }

    <span class="hljs-keyword">public</span> async Task CreateItemAsync(ToDoItemModel model)
    {
        model.Id <span class="hljs-operator">=</span> Guid.NewGuid().ToString();
        model.DateCreated <span class="hljs-operator">=</span> DateTime.Now;
        model.DateCompleted <span class="hljs-operator">=</span> null;
        await _toDoItemDataAccessService.CreateItemAsync(model);
    }

    <span class="hljs-keyword">public</span> async Task<span class="hljs-operator">&lt;</span>ToDoItemModel<span class="hljs-operator">&gt;</span> GetToDoItemAsync(<span class="hljs-keyword">string</span> id)
    {
        <span class="hljs-keyword">return</span> await _toDoItemDataAccessService.GetToDoItemAsync(id);
    }

    <span class="hljs-keyword">public</span> async Task<span class="hljs-operator">&lt;</span>IEnumerable<span class="hljs-operator">&lt;</span>ToDoItemModel<span class="hljs-operator">&gt;</span><span class="hljs-operator">&gt;</span> GetOpenToDoItemsAsync()
    {
        <span class="hljs-keyword">return</span> await _toDoItemDataAccessService.GetOpenToDoItemsAsync();
    }

    <span class="hljs-keyword">public</span> async Task UpdateToDoItemAsync(ToDoItemModel model)
    {
        await _toDoItemDataAccessService.UpdateToDoItemAsync(model);
    }

    <span class="hljs-keyword">public</span> async Task DeleteToDoItemAsync(<span class="hljs-keyword">string</span> id)
    {
        await _toDoItemDataAccessService.DeleteToDoItemAsync(id);
    }
}
</code></pre><h3 id="heading-presentation-layer">Presentation Layer</h3>
<p>For the top level, we have a simple controller that utilises the service layer services, so allow us to receive REST requests and respond accordingly.  I have only included create and get for now, but this could easily be extended to hook up the remaining actions.</p>
<pre><code>[Route(<span class="hljs-string">"[controller]"</span>)]
<span class="hljs-keyword">public</span> class ToDoItemController : ControllerBase
{
    <span class="hljs-keyword">private</span> readonly IToDoItemService _toDoItemService;

    <span class="hljs-keyword">public</span> ToDoItemController(IToDoItemService toDoItemService)
    {
        _toDoItemService <span class="hljs-operator">=</span> toDoItemService;
    }

    [HttpPost(<span class="hljs-string">"Create"</span>)]
    <span class="hljs-keyword">public</span> async Task<span class="hljs-operator">&lt;</span>IActionResult<span class="hljs-operator">&gt;</span> CreateToDoItem([FromBody] ToDoItemModel model)
    {
        <span class="hljs-keyword">try</span>
        {
            await _toDoItemService.CreateItemAsync(model);
            <span class="hljs-keyword">return</span> Ok();
        }
        <span class="hljs-keyword">catch</span> (Exception ex)
        {
            <span class="hljs-keyword">return</span> BadRequest(ex.Message);
        }
    }

    [HttpGet(<span class="hljs-string">"Get"</span>)]
    <span class="hljs-keyword">public</span> async Task<span class="hljs-operator">&lt;</span>IActionResult<span class="hljs-operator">&gt;</span> GetToDoItem([FromQuery]<span class="hljs-keyword">string</span> id)
    {
        <span class="hljs-keyword">try</span>
        {
            <span class="hljs-keyword">var</span> item <span class="hljs-operator">=</span> await _toDoItemService.GetToDoItemAsync(id);
            <span class="hljs-keyword">return</span> Ok(item);
        }
        <span class="hljs-keyword">catch</span> (Exception ex)
        {
            <span class="hljs-keyword">return</span> BadRequest(ex.Message);
        }
    }

    [HttpGet(<span class="hljs-string">"GetOpenItems"</span>)]
    <span class="hljs-keyword">public</span> async Task<span class="hljs-operator">&lt;</span>IActionResult<span class="hljs-operator">&gt;</span> GetOpenItems()
    {
        <span class="hljs-keyword">try</span>
        {
            <span class="hljs-keyword">var</span> items <span class="hljs-operator">=</span> await _toDoItemService.GetOpenToDoItemsAsync();
            <span class="hljs-keyword">return</span> Ok(items);
        }
        <span class="hljs-keyword">catch</span> (Exception ex)
        {
            <span class="hljs-keyword">return</span> BadRequest(ex.Message);
        }
    }
}
</code></pre><h3 id="heading-putting-it-all-together">Putting it all Together</h3>
<p>The only task remaining is to add the above services into the dependency injection container.  We do this in the Program.cs.</p>
<pre><code>builder.Services.AddTransient&lt;IToDoItemDataAccessService, ToDoItemDataAccessService<span class="hljs-operator">&gt;</span>();
builder.Services.AddTransient&lt;IToDoItemService, ToDoItemService<span class="hljs-operator">&gt;</span>();

builder.Services.AddSingleton&lt;IMongoDbFactory<span class="hljs-operator">&gt;</span>(<span class="hljs-keyword">new</span> MongoDbFactory(builder.Configuration.GetValue&lt;<span class="hljs-keyword">string</span><span class="hljs-operator">&gt;</span>(<span class="hljs-string">"ConnectionStrings:MongoDb"</span>)));
</code></pre><p>As you can see, we add the services as transient, which means they will be re-created for each request.  However, as the factory is used to handle connectivity to the database, to ensure consistency, we add this as a singleton.  </p>
<h3 id="heading-running-the-application">Running the Application</h3>
<p>We're now ready to run the application and add and retrieve data.  We can do this through the swagger page that's built into the default .Net 6 Web API templates.</p>
<p>We should be able to send a simple request with just the following fields, the rest have been removed.  As we progress with this project we will create specific models to create, update etc. but for now we've reused the same one to keep it simple.  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1655297090509/iXFFArdwh.png" alt="image.png" /></p>
<p>After executing the query, we should be able to see the entry in our MongoDB collection:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1655298329727/xpilalLjVJ.png" alt="image.png" /></p>
<p>Note:  If the collection didn't previously exist MongoDB will create it for you.</p>
<p>Calling the 'Get Open Items' endpoint should also return our single to-do item:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1655298488970/3eQfQdDJf.png" alt="image.png" /></p>
<p>And if we take the GUID out of there and apply it to our 'Get' function we should also be able to find our single result:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1655298543505/4o8Q5yfHx.png" alt="image.png" /></p>
<h3 id="heading-summary">Summary</h3>
<p>In this tutorial we have now successfully been able to connect to our MongoDB instance, add records to a collection and retrieve those records from the collection.  In further articles we will also start to add to and update the data in these records as we start to improve our application.</p>
]]></content:encoded></item><item><title><![CDATA[Using Hangfire and MongoDB for Scheduling in .Net 6]]></title><description><![CDATA[Using Hangfire and MongoDB for Scheduling in .Net 6]]></description><link>https://davek.dev/using-hangfire-and-mongodb-for-scheduling-in-net-6</link><guid isPermaLink="true">https://davek.dev/using-hangfire-and-mongodb-for-scheduling-in-net-6</guid><category><![CDATA[MongoDB]]></category><category><![CDATA[.NET]]></category><category><![CDATA[C#]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[hangfire]]></category><dc:creator><![CDATA[Dave K]]></dc:creator><pubDate>Fri, 10 Jun 2022 17:29:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/rBPOfVqROzY/upload/v1654874749021/2MCVNF19s.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>This is the first in my series of articles, which aims to build a working ‘To-Do’ list application whilst exploring a whole range of different technologies and frameworks.  </p>
<p>A bit more background is given in my <a target="_blank" href="https://davek.dev/hello-world">introduction page</a>. </p>
<p>To start with, I am going to create the initial building blocks for our application, which in this case consists of a .Net 6 Web API, and MongoDB back end to store our to-do items, and I’m also going to include a Hangfire job scheduler which will be used in later articles as we look to expand the architecture.</p>
<p>I will also include some <a target="_blank" href="https://c4model.com/">C4 modelling</a> as we expand the architecture to show where we are in the process of building this application. The initial model will simply look like:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654874619001/y1vHNgaXi.png" alt="image.png" /></p>
<p>All source for this is available on GitHub <a target="_blank" href="https://github.com/davek-dev/to-do/tree/main/1.%20Hangfire%20and%20Mongo%20DB">here</a>.</p>
<h3 id="heading-what-is-hangfire">What is Hangfire?</h3>
<p><a target="_blank" href="https://www.hangfire.io/">Hangfire</a> is an open-source background processing and scheduling library for .Net applications.  It is a great tool for running regular or long-running jobs in the background, and can even be used in asp.net web applications.  It can support multiple instances of an API, so workloads can be scaled up or down, and multiple queues of differing priorities used if required.</p>
<p>Furthermore, it is also quite extensible, there are many additional libraries which can be used with Hangfire, and you are always free to write your own.  In this tutorial, we will use Mongo DB as the persistent storage medium for Hangfire instead of the default SQL Server implementation.  </p>
<p>We will also use the Hangfire Dashboard which provides a decent user interface for observing Hangfire jobs, and the Hangfire Console, as this is a great extension for allowing us to output more information to the UI when a job is running.</p>
<h3 id="heading-what-is-mongodb">What is MongoDB?</h3>
<p><a target="_blank" href="https://www.mongodb.com">Mongo DB</a> is an open-source NoSQL database.  NoSQL databases support storing data in ‘documents’, in Mongo DB’s case these documents are stored as JSON objects. </p>
<p>NoSQL databases are by their nature very fast and scalable, and good for storing unstructured data.  They offer an alternative to traditional SQL databases, which have a more rigid structure.  Whilst NoSQL databases are quick, because they are unstructured in nature, they do not have the same concept of relationships like JOIN's and so are not suitable for more relational data.</p>
<h3 id="heading-getting-started-with-mongo-db">Getting started with Mongo DB</h3>
<p>To get started with Mongo DB you can create a free Mongo Atlas Database in the cloud at <a target="_blank" href="https://www.mongodb.com/atlas/database">https://www.mongodb.com/atlas/database</a>.  From there you can use the quick start tool to create a shared cluster, select a host and region and some credentials, as well as restrict access to certain IP addresses if you wish.</p>
<p>Once you have created your account and first database, you should see your deployments as below:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654870660166/RKB_Ye4de.png" alt="image.png" /></p>
<p>You can then select 'Browse Collections' and it will ask you to create your first database and collection.  In this example, I have created a database and collection, both called 'ToDo'.</p>
<p>Once we have a database, we can then select the 'Connect' button, change the Driver to C# and select the latest version (2.13 at the time of writing).  This will generate our connection string for us:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654870858614/89SaF4s1R.png" alt="image.png" /></p>
<p>Save this for later use.  The connection string will also be missing the database name, so when we come to use it later, we must remember to include this between the '/' and the '?' towards the end of the connection string.</p>
<h3 id="heading-building-the-net-6-api">Building the .Net 6 API</h3>
<p>If you haven’t the latest .net SDK installed, this can be downloaded from 
<a target="_blank" href="https://dotnet.microsoft.com/en-us/download">https://dotnet.microsoft.com/en-us/download</a>. </p>
<p>Create a folder for the new project and then create a new C# web API project with the command:</p>
<p><code>dotnet new webapi -n [project name]</code> </p>
<p>Open the '.csproj' with your IDE of choice.  I prefer Rider from JetBrains, but Visual Studio Community or any other compatible IDE would be fine.</p>
<h4 id="heading-install-libraries">Install Libraries</h4>
<p>We’re going to need to install a few packages from <a target="_blank" href="https://www.nuget.org/packages">Nuget</a> to get started with MongoDB and Hangfire:</p>
<ul>
<li>MongoDB.Driver</li>
<li>Hangfire</li>
<li>Hangfire.Console</li>
<li>Hangfire.Mongo</li>
</ul>
<p>These should be enough to get us started, and they will automatically pull in any additional package dependencies they require.</p>
<h4 id="heading-set-up-hangfire">Set up Hangfire</h4>
<p>To add Hangfire, we can create a new static ‘HangfireService’ with the following 'ConfigureHangfireService' extension method.  I've added this to a 'StartUp' directory within the project, but you can structure the project however you feel works for you. Make sure to include the ‘UseConsole()’ call to activate the Hangfire Console we will use later:</p>
<pre><code><span class="hljs-keyword">public</span> static class HangfireService
{
    <span class="hljs-keyword">public</span> static void ConfigureHangfireService(<span class="hljs-built_in">this</span> WebApplicationBuilder builder)
    {
        <span class="hljs-keyword">var</span> mongoUrlBuilder <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> MongoUrlBuilder(builder.Configuration.GetValue&lt;<span class="hljs-keyword">string</span><span class="hljs-operator">&gt;</span>(<span class="hljs-string">"ConnectionStrings:MongoDb"</span>));
        <span class="hljs-keyword">var</span> mongoClient <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> MongoClient(mongoUrlBuilder.ToMongoUrl());

        builder.Services.AddHangfire(configuration <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> configuration
            .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
            .UseSimpleAssemblyNameTypeSerializer()
            .UseRecommendedSerializerSettings()
            .UseConsole()
            .UseMongoStorage(mongoClient, mongoUrlBuilder.DatabaseName, <span class="hljs-keyword">new</span> MongoStorageOptions
            {
                MigrationOptions <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> MongoMigrationOptions
                {
                    MigrationStrategy <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> MigrateMongoMigrationStrategy(),
                    BackupStrategy <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> CollectionMongoBackupStrategy()
                },
                Prefix <span class="hljs-operator">=</span> <span class="hljs-string">"todo.hangfire"</span>,
                CheckConnection <span class="hljs-operator">=</span> <span class="hljs-literal">false</span>
            })
        );

        builder.Services.AddHangfireServer(serverOptions <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span>
        {
            serverOptions.ServerName <span class="hljs-operator">=</span> <span class="hljs-string">"ToDo.Hangfire"</span>;
        });
    }
}
</code></pre><p>If you are using Atlas, you may need to ensure the 'CheckConnection' value is set to false as above, or Hangfire may time out before it completes the initial connection.</p>
<p>Note:  If you are using a non-clustered Mongo DB collection, you may need to set the queue job strategy as follows in the above config:</p>
<pre><code><span class="hljs-attr">CheckQueuedJobsStrategy</span> = CheckQueuedJobsStrategy.TailNotificationsCollection
</code></pre><p>We then need to add a new connection string to our appSettings.json file, be sure to include the collection name you created earlier between the / and the ?:</p>
<pre><code><span class="hljs-string">"ConnectionStrings"</span>: {
    <span class="hljs-string">"MongoDb"</span> : <span class="hljs-string">"&lt;Your connection string here&gt;"</span>
  }
</code></pre><p>And then we can update our Program.cs file as follows to add the Hangfire service and dashboard with the following lines:</p>
<pre><code>builder.ConfigureHangfireService();
</code></pre><pre><code>app.UseHangfireDashboard();
</code></pre><p>If we now launch our application, we should see the Hangfire collections added to the database we have previously created in Mongo DB:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654871422339/d1ssTv7sY.png" alt="image.png" /></p>
<p>And be able to visit the Hangfire dashboard running on <a target="_blank" href="https://localhost:&lt;port&gt;/hangfire">https://localhost:/hangfire</a> </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654871455782/z25uFfARq.png" alt="image.png" /></p>
<p>Note: In the footer of the dashboard, you should also be able to see the sanitised connection string, so you know it’s connecting to the correct database.  </p>
<h4 id="heading-creating-a-hangfire-job-and-viewing-output-on-the-console">Creating a Hangfire job and viewing output on the console</h4>
<p>To demonstrate how we can schedule a job and output some information to the Hangfire console, for now I’m just going to create a simple job that executes on a Cron schedule that outputs the current date and time and the current UTC date and time.</p>
<p>Firstly, we can create a simple jobs class as below, and to use the console we pass in a ‘PerformContext’ parameter.  This will be injected by Hangfire, so we don’t need to pass anything other than null.  </p>
<pre><code><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Jobs</span> : <span class="hljs-title">IJobs</span>
{
    [<span class="hljs-meta">Queue(<span class="hljs-meta-string">"default"</span>)</span>]
    [<span class="hljs-meta">JobDisplayName(<span class="hljs-meta-string">"Display current date and time"</span>)</span>]
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DisplayCurrentDateTime</span>(<span class="hljs-params">PerformContext context</span>)</span>
    {
        context.WriteLine(<span class="hljs-string">$"The current date and time is: <span class="hljs-subst">{DateTime.Now.ToString(CultureInfo.CurrentCulture)}</span>"</span>);
        context.WriteLine(<span class="hljs-string">$"The current UTC date and time is: <span class="hljs-subst">{DateTime.UtcNow.ToString(CultureInfo.CurrentCulture)}</span>"</span>);
    }
}
</code></pre><p>We then need to create an interface for the Jobs class, so we can add to our dependency injection container.  </p>
<pre><code><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IJobs</span>
{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">DisplayCurrentDateTime</span>(<span class="hljs-params">PerformContext context</span>)</span>;
}
</code></pre><pre><code>builder.Services.AddTransient&lt;IJobs, Jobs<span class="hljs-operator">&gt;</span>();
</code></pre><p>And finally, create a configuration class where we can configure the job to get added to the scheduler along with the schedule, in this case a Cron schedule to run every 5 minutes:</p>
<pre><code><span class="hljs-keyword">public</span> static class HangfireJobConfiguration
{
    <span class="hljs-keyword">public</span> static void ConfigureJobs(<span class="hljs-built_in">this</span> WebApplication app)
    {
        app.Services.CreateScope();

        RecurringJob.AddOrUpdate(() <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> app.Services.GetService&lt;IJobs<span class="hljs-operator">&gt;</span>().DisplayCurrentDateTime(null),
            <span class="hljs-string">"*/5 * * * *"</span>);
    }
}
</code></pre><p>which can be hooked up to our 'PRogram.cs' by calling</p>
<p><code>builder.ConfigureHangfireService();</code> </p>
<p>By launching our application, and going to the Hangfire Dashboard, we should see our job appear on the 'Recurring Jobs' tab, in this case to execute every 5 minutes:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654871817165/MYD9fMExi.png" alt="image.png" /></p>
<p>And if we view the job details after it has successfully completed, we should see the expected output on the Hangfire console:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654872062450/PTClssI_P.png" alt="image.png" /></p>
<h3 id="heading-summary">Summary</h3>
<p>We have now configured our API to connect to Mongo DB and included the Hangfire scheduler with the Hangfire Dashboard and Hangfire Console.  We can create jobs and add them to our API to execute on a schedule. </p>
<p>Whilst the current job is not of much use in a real world scenario, we will revisit this later where we will use the scheduler for a number of different tasks.</p>
]]></content:encoded></item><item><title><![CDATA[Where to start, and what am I doing here?]]></title><description><![CDATA[Many years ago, when I just started out as a junior software developer, I started a blog as a way to document my learnings and hopefully benefit others…]]></description><link>https://davek.dev/hello-world</link><guid isPermaLink="true">https://davek.dev/hello-world</guid><category><![CDATA[Hello World]]></category><category><![CDATA[Developer]]></category><category><![CDATA[DevLife]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Dave K]]></dc:creator><pubDate>Wed, 08 Jun 2022 15:56:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/67L18R4tW_w/upload/v1654703717311/u52rXf338.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Many years ago, when I just started out as a junior software developer, I started a blog as a way to document my learnings and hopefully benefit others.  </p>
<p>Whilst that is technically still live, I never really maintained it, and it has laid dormant for years, other than me periodically moving it from host to host. Many of the posts are now out of date. Surprisingly, a few on the subject of WPF are still getting regular visits.  [Update: I have now migrated those old pages to <a target="_blank" href="https://davek.dev/series/talking-it-through">here</a>].</p>
<p>At some point, I always wanted to get back to it, and now feels like the right time. I have spent 15 years designing, developing and releasing software, and am still always learning something new, finding new tips and tricks and improving on my knowledge.  Now, maybe it's time to document and share those things I have learned on my journey, just in case someone else may find it useful.  </p>
<p>In software development, there is often no single correct way to do things, and differing ideas and styles can sometimes lead to quite heated debates about what is and isn't 
good practice, and as in life, we often have choices to make based on the circumstances we find ourselves in.  We will always make mistakes, and if there's ever a developer that looks back on something they have done previously and doesn't find anything they could have improved, I'd happily show you a liar.  There is always scope to learn, scope to grow, and scope to explore new concepts.</p>
<p>The first thing I plan to do is create a series of technical walkthroughs with the ultimate aim of making a 'to-do list' application.</p>
<p>Yes, this has been done multiple times before, and no, I don't plan on doing it the 'correct' way.  Instead, I aim to throw in a wide range of different tools, technologies, and concepts showing differing ideas and different approaches to the problem.  I will also aim to discuss benefits and drawbacks of the approaches I am taking. Finally, the aim is to use some technologies I am comfortable with (it will start as a C#/Net6 API) and also some I have not used much or at all before, so I'll be learning as I go.  </p>
<p>Hopefully, at the end of it, I'll have something I'm proud of.  No, not the application, there will almost certainly be better options out there for that, but the journey and the knowledge that I have gained and shared.  I'll also no doubt add other either related, or unrelated articles and posts as I go.</p>
<p>Thanks for reading, and I look forward to sharing this adventure with you all.</p>
]]></content:encoded></item><item><title><![CDATA[Using Swagger to Document DotNet Core APIs]]></title><description><![CDATA[Swagger is a specification of rules/notation used to define how an API should be documented. As of Swagger version 2.0, it is now been renamed to the…]]></description><link>https://davek.dev/using-swagger-to-document-dotnet-core-apis</link><guid isPermaLink="true">https://davek.dev/using-swagger-to-document-dotnet-core-apis</guid><category><![CDATA[ASP]]></category><category><![CDATA[api]]></category><category><![CDATA[software development]]></category><category><![CDATA[dotnet]]></category><category><![CDATA[.NET Core]]></category><category><![CDATA[dotnetcore]]></category><category><![CDATA[.NET]]></category><category><![CDATA[swagger]]></category><dc:creator><![CDATA[Dave K]]></dc:creator><pubDate>Sat, 27 Jun 2020 17:26:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1655387238968/eco2e8FoU.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-what-is-swagger-and-why-should-i-use-it">What is swagger and why should I use it?</h3>
<p>Swagger is a specification of rules/notation used to define how an API should be documented. As of Swagger version 2.0, it is now been renamed to the <a target="_blank" href="https://github.com/OAI/OpenAPI-Specification">OpenApi</a> specification. This reflects that the specification is now widely adopted in the software development world.<br />Swagger itself comprises of a <a target="_blank" href="https://github.com/swagger-api">number of tools</a> developed by <a target="_blank" href="https://swagger.io/">SmartBear</a>. These tools can be combined to produce smart and standardised API documentation.<br />When adding Swagger documentation to ASP.net core API’s, Swashbuckle is the most commonly used tool.  </p>
<h3 id="heading-what-is-swashbuckle">What is Swashbuckle?</h3>
<p>Swashbuckle is a a library that combines a number of Swagger libraries into one useful tool used to create documentation for ASP.net Core applications. This enables us to add Swagger documentation quickly and with minimal code. It is another <a target="_blank" href="https://github.com/domaindrivendev/Swashbuckle.AspNetCore">open-source</a> library and so can and is used in projects of all sizes.  </p>
<h3 id="heading-adding-swashbuckle-to-my-dotnet-core-api">Adding Swashbuckle to my DotNet Core API</h3>
<p>To demonstrate the use of Swashbuckle and Swagger and how easy it can be used to document an API, I have created a quick step-by-step guide.  </p>
<p>To start with, create an new ASP.net core Web API project in Visual Studio. You can remove everything from the ‘Controllers’ folder and create a new controller called ‘GreetingController’.  </p>
<p>Add the following code to the controller:</p>
<pre><code>\[Produces(<span class="hljs-string">"application/json"</span>)\]
\[Route(<span class="hljs-string">"api/Greeting"</span>)\]
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">GreetingController</span> : <span class="hljs-title">Controller</span>
{
  HttpGet(<span class="hljs-string">"SayHello"</span>)\]
  <span class="hljs-function"><span class="hljs-keyword">public</span> IActionResult <span class="hljs-title">SayHello</span>(<span class="hljs-params">\[FromQuery\] <span class="hljs-keyword">string</span> name</span>)</span>
  {
    <span class="hljs-keyword">return</span> Ok(<span class="hljs-string">$"Hello <span class="hljs-subst">{name}</span>"</span>);
  }
}
</code></pre><p>You can then add the Swashbuckle and Swagger libraries by adding the Swashbuckle package via Nuget. Use the following command in the Package Manager Console to install the latest version.</p>
<pre><code><span class="hljs-keyword">Install</span>-<span class="hljs-keyword">Package</span> Swashbuckle.AspNetCore
</code></pre><p>To the startup.cs file add the following code to the ConfigureServices method, below the services.AddMvc(); line. You may need to add a reference to the Microsoft.OpenApi.Models by adding ‘using Microsoft.OpenApi.Models;’ at the top of the startup.cs file.</p>
<pre><code>services.AddSwaggerGen(c <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span>
{
c.SwaggerDoc(<span class="hljs-string">"v1"</span>, <span class="hljs-keyword">new</span> OpenApiInfo { Title <span class="hljs-operator">=</span> <span class="hljs-string">"Talking I.T. Through Swagger Demo API"</span>, Version <span class="hljs-operator">=</span> <span class="hljs-string">"v1"</span> });
});
</code></pre><p>and the following to the Configuration method under app.UseMvc();</p>
<pre><code>app.UseSwagger();
</code></pre><p>The above should be enough to generate the API documentation for our API in Json format. To view the API documentation you can launch the application and navigate to http://localhost:[port]/swagger/v1/swagger.json and you should see something similar to the following:  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1655387464131/4ZWcc0k9Y.jpg" alt="swaggerjson.jpg" /></p>
<p>This in itself can be useful for sharing the the API definition with other code generation and testing tools, but where Swashbuckle really excels is that it can also build a nice user interface using Swagger UI that can be used to directly document and test the API functions through your web browser.<br />To do this, add the following code to our Configure method in the StartUp.cs file:</p>
<pre><code>app.UseSwaggerUI(c <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span>
{
c.SwaggerEndpoint(<span class="hljs-string">"/swagger/v1/swagger.json"</span>, <span class="hljs-string">"Talking I.T. Through API V1"</span>);
});
</code></pre><p>Launch the application and navigate to http://localhost:[port]/swagger/index.html and you should see the single SayHello get API endpoint we created earlier.  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1655387394733/9_OuY9ydb.jpg" alt="SwaggerGet.jpg" /></p>
<p>You can select the endpoint, click ‘Try It Out’ and send requests to test the API is responding as expected.  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1655387499831/YCML81RxE.jpg" alt="SwaggerGetResponse.jpg" /></p>
<p>Note: It is recommended to put the app.UseSwaggerUI set-up code inside the env.IsDevelopment if statement wrapper, to prevent this being exposed in production environments. For development purposes you could also update the development profile in the launchSettings.json file to point directly at the Swagger UI to load the UI automatically when launching the API from Visual Studio.  </p>
<p>Now add a second post endpoint to out Greetings controller as follows:</p>
<pre><code>\[HttpPost(<span class="hljs-string">"SayHelloByPost"</span>)\]
<span class="hljs-function"><span class="hljs-keyword">public</span> IActionResult <span class="hljs-title">SayHelloByPost</span>(<span class="hljs-params">\[FromBody\] <span class="hljs-keyword">string</span> name</span>)</span>
{
<span class="hljs-keyword">return</span> Ok(<span class="hljs-string">$"Hello <span class="hljs-subst">{name}</span>"</span>);
}
</code></pre><p>And then re-launch the application and you should see the new endpoint is automatically picked up and added to the Swagger UI page.  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1655387526273/JVW5GVSTB.jpg" alt="SwaggerWithPost.jpg" /></p>
<h3 id="heading-common-errors">Common Errors</h3>
<p>If you get an error ‘Failed to load API definition’ or you are missing some of the expected endpoints from Swagger UI, make sure that you have specified HTTP decorators such as [HttpGet] or [HttpPost] on your API endpoint definitions inside you controllers or Swagger will not be able to document the endpoints.  </p>
<h3 id="heading-why-this-article-now">Why This Article Now?</h3>
<p>Two reasons. Whilst many people already know and use Swagger, many may not and if I can help just one person then I will be happy.  </p>
<p>Secondly, many of my future posts around Asp.net Core development will focus on API development. Because of this, many of my demo’s may use Swagger UI as to show the API applications in action, so this post will always be here to refer people back to.  </p>
<p>Hope it helps!  </p>
<p>The complete code for this article is available <a target="_blank" href="https://github.com/Talking-I-T-Through/swagger_demo">here</a>.</p>
<p>The post <a target="_blank" href="https://davek.dev/using-swagger-to-document-dotnet-core-apis">Using Swagger to Document DotNet Core APIs</a> appeared first on <a target="_blank" href="https://talkingitthrough.co.uk">Talking I.T. Through</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Advanced 7 Segment Display Driver with a 4511 IC and Raspberry Pi]]></title><description><![CDATA[In my first post of this series I discussed a very simple way of driving a 7 segment display directly through the Raspberry Pi 2. Whilst this does word, in…]]></description><link>https://davek.dev/advanced-7-segment-display-driver-with-a-4511-ic-and-raspberry-pi</link><guid isPermaLink="true">https://davek.dev/advanced-7-segment-display-driver-with-a-4511-ic-and-raspberry-pi</guid><category><![CDATA[software]]></category><category><![CDATA[software development]]></category><category><![CDATA[Raspberry Pi]]></category><category><![CDATA[.NET]]></category><category><![CDATA[cmos]]></category><dc:creator><![CDATA[Dave K]]></dc:creator><pubDate>Wed, 27 Apr 2016 18:42:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1655388383547/pln-JxLnU.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-background">Background</h3>
<p>In my <a target="_blank" href="https://davek.dev/creating-a-seven-segment-display-driver-with-raspberry-pi">first post of this series</a> I discussed a very simple way of driving a 7 segment display directly through the Raspberry Pi 2.  Whilst this does word, in practice it has a number of caveats and limitations.  Firstly the current through each LED is limited to what can be provided by each GPIO pin on the Raspberry Pi.  Secondly, if all segments are lit, then the cumulative current going into a GPIO input pin exceeds the recommended input current.  Whilst I have no doubt the Raspberry Pi can handle it, I would not recommend it for long term usage.  </p>
<p>Source code available on <a target="_blank" href="https://github.com/davek17/PiSSD.Net">Github</a>  </p>
<h3 id="heading-introduction">Introduction</h3>
<p>To improve on the previous post and drive a seven segment display in a more effective way, I will make two significant changes.  Firstly I will use a CMOS4511 integrated circuit chip to drive the 7 segment display from a binary input.  Secondly, to protect the GPIO input transistors will be used to switch the displays on and off and the circuit will sink to ground rather than the GPIO pins.  </p>
<h3 id="heading-pre-requisites">Pre-Requisites</h3>
<p>1 x Raspberry Pi 2<br />1 x Cmos 4511 IC<br />4 x NPN Transistors (more or less depending on number of digits on display)<br />1 x 5641AS 7 segment display (Or similar 7 segment display)<br />7 x 220 Ohm Resistor<br />4 x 1 kOhm Resistor (Same number as transistors)  </p>
<h3 id="heading-fritzing">Fritzing</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1655388458070/SukQ3_F9_.jpg" alt="ssd4511.jpg" /></p>
<h3 id="heading-circuit">Circuit</h3>
<p>The above fritzing diagram displays the complete circuit used in the demonstration.  Different GPIO pins can be used if desirable for output to both the 4511 and the GPIO.  </p>
<p>The CMOS4511 IC is used to convert a binary input to a 7 segment display output. The pin-out for the 4511 can be found  on the <a target="_blank" href="https://www.sparkfun.com/datasheets/IC/74HC4511.pdf">datasheet</a>.  The 4 inputs D0 – D3 are connected to the Raspberry Pi, and the 7 outputs a to g are connected to the corresponding segments on the display via 220 Ohm resistors.Vcc, BL and LT should all be connected to the power source [recommended 3.3v] and ground should be connected to ground.  LE can be left unconnected.  </p>
<p>From the display, each digit display pin should be connected to the collector of an NPN transistor, and each transistor emitter can be connected to ground.  Each transistor base can be connected to a GPIO pin via a 1 kOhm resistor.</p>
<h3 id="heading-code">Code</h3>
<p>As the core code will be identical to the <a target="_blank" href="https://davek.dev/creating-a-seven-segment-display-driver-with-raspberry-pi">previous driver</a> then it makes sense to abstract our new driver from the previous code.  To do this we need to make a few small changes.  </p>
<p>Firstly as we’re going to use 4 pins rather than 7 to drive our display, we need to override the SetDisplay method in our existing class, so this should now be set to virtual to allow us to do this.We will also need to override the ClearDisplay() method so this is also set as virtual.  </p>
<p>On top of this, as we’re using a different set of GPIO pins, we need to be able to provide a different constructor, but as we don’t want to use the original base constructor, we must provide another, in this case parameter-less constructor.  As we only want derived classes to be able to use this, we can set the constructor as protected.  We can also take advantage of this constructor to set up the cancellation tokens that were previously set in the main constructor, preventing the need to provide protected accessors to these fields.</p>
<pre><code>protected Display()
{
  <span class="hljs-built_in">this</span>.cts <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> CancellationTokenSource();
  <span class="hljs-built_in">this</span>.token <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> CancellationToken();
}
</code></pre><p>The final thing we need to do to our original class is to make the displays array accessible to derived classes</p>
<pre><code><span class="hljs-keyword">protected</span> GpioPin\[\] Displays
        {
            <span class="hljs-keyword">get</span>
            {
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.displays;
            }
            <span class="hljs-keyword">set</span>
            {
                <span class="hljs-keyword">this</span>.displays = value;
            }
        }
</code></pre><p>Now we’re ready to create our new derived class.  A new constructor similar to our original base class should be created but we only need to provide 4 output pins [for the 4511 D0-D3] and then our display pins.  The initialisation of the pins is then carried out as per the base class.<br />Next we can provide the overridden SetDisplay method.  Instead of converting the supplied int to it’s 7 segment representation, this version converts the supplied in to it’s binary representation.</p>
<pre><code>protected <span class="hljs-keyword">override</span> void SetDisplay(GpioPin displayPin, <span class="hljs-keyword">int</span> value)
        {
            <span class="hljs-built_in">this</span>.ClearDisplay();
            switch (value)
            {
                case <span class="hljs-number">0</span>:
                    <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.pinBcd0, <span class="hljs-built_in">this</span>.pinBcd1, <span class="hljs-built_in">this</span>.pinBcd2, <span class="hljs-built_in">this</span>.pinBcd3 });
                    <span class="hljs-keyword">break</span>;
                case <span class="hljs-number">1</span>:
                    <span class="hljs-built_in">this</span>.SetHigh(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.pinBcd0 });
                    <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.pinBcd1, <span class="hljs-built_in">this</span>.pinBcd2, <span class="hljs-built_in">this</span>.pinBcd3 });
                    <span class="hljs-keyword">break</span>;
                case <span class="hljs-number">2</span>:
                    <span class="hljs-built_in">this</span>.SetHigh(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.pinBcd1 });
                    <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.pinBcd0, <span class="hljs-built_in">this</span>.pinBcd2, <span class="hljs-built_in">this</span>.pinBcd3 });
                    <span class="hljs-keyword">break</span>;
                case <span class="hljs-number">3</span>:
                    <span class="hljs-built_in">this</span>.SetHigh(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.pinBcd0, <span class="hljs-built_in">this</span>.pinBcd1 });
                    <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.pinBcd2, <span class="hljs-built_in">this</span>.pinBcd3 });
                    <span class="hljs-keyword">break</span>;
                case <span class="hljs-number">4</span>:
                    <span class="hljs-built_in">this</span>.SetHigh(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.pinBcd2 });
                    <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.pinBcd0, <span class="hljs-built_in">this</span>.pinBcd1, <span class="hljs-built_in">this</span>.pinBcd3 });
                    <span class="hljs-keyword">break</span>;
                case <span class="hljs-number">5</span>:
                    <span class="hljs-built_in">this</span>.SetHigh(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.pinBcd0, <span class="hljs-built_in">this</span>.pinBcd2 });
                    <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.pinBcd1,<span class="hljs-built_in">this</span>.pinBcd3 });
                    <span class="hljs-keyword">break</span>;
                case <span class="hljs-number">6</span>:
                    <span class="hljs-built_in">this</span>.SetHigh(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.pinBcd1, <span class="hljs-built_in">this</span>.pinBcd2});
                    <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.pinBcd0, <span class="hljs-built_in">this</span>.pinBcd3 });
                    <span class="hljs-keyword">break</span>;
                case <span class="hljs-number">7</span>:
                    <span class="hljs-built_in">this</span>.SetHigh(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.pinBcd0, <span class="hljs-built_in">this</span>.pinBcd1, <span class="hljs-built_in">this</span>.pinBcd2 });
                    <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.pinBcd3 });
                    <span class="hljs-keyword">break</span>;
                case <span class="hljs-number">8</span>:
                    <span class="hljs-built_in">this</span>.SetHigh(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.pinBcd3 });
                    <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.pinBcd0, <span class="hljs-built_in">this</span>.pinBcd1, <span class="hljs-built_in">this</span>.pinBcd2 });
                    <span class="hljs-keyword">break</span>;
                case <span class="hljs-number">9</span>:
                    <span class="hljs-built_in">this</span>.SetHigh(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.pinBcd0, <span class="hljs-built_in">this</span>.pinBcd3 });
                    <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.pinBcd1, <span class="hljs-built_in">this</span>.pinBcd2 });
                    <span class="hljs-keyword">break</span>;
                case <span class="hljs-number">10</span>:  <span class="hljs-comment">// Clear Display</span>
                    <span class="hljs-built_in">this</span>.SetHigh(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.pinBcd0, <span class="hljs-built_in">this</span>.pinBcd1, <span class="hljs-built_in">this</span>.pinBcd2, <span class="hljs-built_in">this</span>.pinBcd3 });
                    <span class="hljs-keyword">break</span>;
                default:
                    <span class="hljs-built_in">this</span>.SetHigh(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.pinBcd0, <span class="hljs-built_in">this</span>.pinBcd1, <span class="hljs-built_in">this</span>.pinBcd2, <span class="hljs-built_in">this</span>.pinBcd3 });
                    <span class="hljs-keyword">break</span>;
            }
            <span class="hljs-built_in">this</span>.SetHigh(<span class="hljs-keyword">new</span> GpioPin\[\] { displayPin });
        }
</code></pre><p>There is one other change in this method.  That is that instead of setting the GPIO pin low to turn the display digit on, this time we set the GPIO high.  This is because instead of turning the pin low to allow current to sink into the GPIO pin, we now turn set the pin high which then ‘switches’ the transistor which allows current to flow and sink to the ground rail.  It is for this reason we also override the ClearDisplays method to set all GPIO pins low [instead of high].</p>
<pre><code>protected <span class="hljs-keyword">override</span> void ClearDisplay()
{
  <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-built_in">this</span>.Displays);
}
</code></pre><h3 id="heading-video">Video</h3>
<p>The below video shows the project in action</p>
<iframe width="640" height="360" src="https://www.youtube.com/embed/ozGGiTvvSHw?feature=oembed"></iframe>

<p>The post <a target="_blank" href="https://davek.dev/advanced-7-segment-display-driver-with-a-4511-ic-and-raspberry-pi">[RPi Series] Advanced 7 Segment Display Driver with a 4511 IC</a> appeared first on <a target="_blank" href="https://talkingitthrough.co.uk">Talking I.T. Through</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Creating a Seven Segment Display Driver with Raspberry Pi]]></title><description><![CDATA[This post is intended to be the first in a series of posts as I delve into the world of software and hardware development using Windows IoT on the…]]></description><link>https://davek.dev/creating-a-seven-segment-display-driver-with-raspberry-pi</link><guid isPermaLink="true">https://davek.dev/creating-a-seven-segment-display-driver-with-raspberry-pi</guid><category><![CDATA[software]]></category><category><![CDATA[software development]]></category><category><![CDATA[Raspberry Pi]]></category><category><![CDATA[iot]]></category><category><![CDATA[display]]></category><dc:creator><![CDATA[Dave K]]></dc:creator><pubDate>Wed, 30 Mar 2016 18:31:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1655388336133/Ou2Q9mIzC.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-background">Background</h3>
<p>This post is intended to be the first in a series of posts as I delve into the world of software and hardware development using Windows IoT on the Raspberry Pi.  </p>
<p><a target="_blank" href="https://github.com/davek17/PiSSD.Net">Download Source Code</a>  </p>
<p>Introduction</p>
<p>Before doing anything else on the Raspberry Pi, the first task I decided to embark on is displaying output so that I could see the result of any processing being done by my applications.  A seven segment display is a simple way of displaying basic numeric output, whether it be temperature, humidity or just a timer.  </p>
<p>Seven segment displays can have one or more digits, and come with either common anode or common cathode circuitry.  Common anode displays have a shared input for each segment, and each segment has it’s own output, and common cathode have a separate input for each segment of a display and a common output.<br />Displays that have more than one digit, will have either one anode or one cathode for each digit, but the segment inputs/output are shared.  As only one digit can be displayed at any one time, to display numbers across multiple digits, each digit and it’s segments must be switched on and off very quickly giving the impression to the human eye that all required digits are displayed continuously.  </p>
<p>The below solution was written using a 4 digit 7 segment common cathode display, but the library is intentionally written to allow for it to be used on a 7 segment common cathode display of any number of digits through the GPIO output.  </p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<ul>
<li>Raspberry Pi running Windows IoT.</li>
<li>8 x 220 ohm resistors.</li>
<li>7 segment common cathode display. I used a 5641AS in this demo but any will work, just change the pins accordingly.</li>
<li>Breadboard.</li>
<li>Connector wires.</li>
</ul>
<h3 id="heading-fritzing-diagram">Fritzing Diagram</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1655388078671/FFuBo2Vce.jpg" alt="ssdfritz.jpg" /></p>
<h3 id="heading-seven-segment-display-diagram">Seven Segment Display Diagram</h3>
<p>The display used when composing this code was a 5641AS which has 12 pins running anti-clockwise from the bottom left.  The data sheets can be found on Google but the pin layout is as follows:</p>
<ol>
<li>E</li>
<li>D</li>
<li>Decimal Point</li>
<li>C</li>
<li>G</li>
<li>Digit 4</li>
<li>B</li>
<li>Digit 3</li>
<li>Digit 2</li>
<li>F</li>
<li>A</li>
<li>Digit 1</li>
</ol>
<h3 id="heading-the-code">The Code</h3>
<p>The full solution so available on GitHub [link above] but can be split into 3 main sections, initialization, building the output and displaying the output.  </p>
<p>####Initialization  </p>
<p>To set-up the displays, we need to know which output pins are going to drive the segments and which will drive the displays.  Whilst the number of segments is fixed (7, or 8 including the decimal point), the number of digits available on the display may vary depending on the display used.  In this example we have 4 digits so we need to provide 4 additional pin numbers and initialize them.  </p>
<p>The segments are passed explicitly, and any remaining pins are assumed to be one for each display, passed through the params parameter. Each display linked output pin and segment output is set to high, meaning there is no voltage differential and no current will flow. Consequently, all displays will be off.</p>
<pre><code><span class="hljs-keyword">public</span> Display(<span class="hljs-keyword">int</span> segA, <span class="hljs-keyword">int</span> segB, <span class="hljs-keyword">int</span> segC, <span class="hljs-keyword">int</span> segD, <span class="hljs-keyword">int</span> segE, <span class="hljs-keyword">int</span> segF, <span class="hljs-keyword">int</span> segG, params <span class="hljs-keyword">int</span>\[\] displayPins)
        {
            <span class="hljs-built_in">this</span>.Displays <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> GpioPin\[displayPins.Length\];
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i <span class="hljs-operator">&lt;</span> displayPins.Length; i<span class="hljs-operator">+</span><span class="hljs-operator">+</span>)
            {
                GpioPin pin <span class="hljs-operator">=</span> GpioController.GetDefault().OpenPin(displayPins\[i\]);
                pin.Write(GpioPinValue.High);
                pin.SetDriveMode(GpioPinDriveMode.Output);
                <span class="hljs-built_in">this</span>.Displays\[i\] <span class="hljs-operator">=</span> pin;
            }
            <span class="hljs-built_in">this</span>.SetupOutputPin(ref <span class="hljs-built_in">this</span>.PinSegA, segA);
            <span class="hljs-built_in">this</span>.SetupOutputPin(ref <span class="hljs-built_in">this</span>.PinSegB, segB);
            <span class="hljs-built_in">this</span>.SetupOutputPin(ref <span class="hljs-built_in">this</span>.PinSegC, segC);
            <span class="hljs-built_in">this</span>.SetupOutputPin(ref <span class="hljs-built_in">this</span>.PinSegD, segD);
            <span class="hljs-built_in">this</span>.SetupOutputPin(ref <span class="hljs-built_in">this</span>.PinSegE, segE);
            <span class="hljs-built_in">this</span>.SetupOutputPin(ref <span class="hljs-built_in">this</span>.PinSegF, segF);
            <span class="hljs-built_in">this</span>.SetupOutputPin(ref <span class="hljs-built_in">this</span>.PinSegG, segG);
            <span class="hljs-built_in">this</span>.cts <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> CancellationTokenSource();
            <span class="hljs-built_in">this</span>.token <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> CancellationToken();
        }
        <span class="hljs-keyword">private</span> void SetupOutputPin(ref GpioPin pin, <span class="hljs-keyword">int</span> pinNo)
        {
            pin <span class="hljs-operator">=</span> GpioController.GetDefault().OpenPin(pinNo);
            pin.Write(GpioPinValue.High);
            pin.SetDriveMode(GpioPinDriveMode.Output);
        }
</code></pre><h4 id="heading-building-the-output">Building the Output</h4>
<p>To provide an easy way for the consumer to set the value to display, we will do the work within the library.  Lets say we want to display the int 1234, then we need to split the individual numbers into an array of individual digits, with the length of the array being the less than or the same as the number of digits we can display, depending if we’re to display leading zeros.  </p>
<p>In the code below, we firstly run some checks to ensure we have a valid number to display, and enough digits to display it. We then go and break it up into its individual digits through the %10 [modulus] calculation.</p>
<pre><code><span class="hljs-keyword">public</span> void DisplayNumber(<span class="hljs-keyword">int</span> number, <span class="hljs-keyword">bool</span> displayLeadingZero <span class="hljs-operator">=</span> <span class="hljs-literal">true</span>)
        {
            <span class="hljs-built_in">this</span>.displayNo <span class="hljs-operator">=</span> number;
            <span class="hljs-built_in">this</span>.displayLeadingZero <span class="hljs-operator">=</span> displayLeadingZero;
            <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.displayNo <span class="hljs-operator">&lt;</span> <span class="hljs-number">0</span>)
            {
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ArgumentOutOfRangeException(<span class="hljs-string">"Number cannot be negative"</span>);
            }
            <span class="hljs-keyword">int</span> checkMax <span class="hljs-operator">=</span> <span class="hljs-number">1</span>;
            <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i <span class="hljs-operator">&lt;</span> <span class="hljs-built_in">this</span>.DisplayDigits.Length; i<span class="hljs-operator">+</span><span class="hljs-operator">+</span>)
            {
                checkMax <span class="hljs-operator">=</span> checkMax \<span class="hljs-operator">*</span> <span class="hljs-number">10</span>;
            }
            <span class="hljs-keyword">if</span>(number <span class="hljs-operator">&gt;</span><span class="hljs-operator">=</span> checkMax)
            {
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ArgumentException(<span class="hljs-string">"Cannot display numbers greater than "</span> <span class="hljs-operator">+</span> (checkMax <span class="hljs-operator">-</span> <span class="hljs-number">1</span>).ToString());
            }
            <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.displayNo <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">0</span>)
            {
                <span class="hljs-built_in">this</span>.Blank();
                <span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>.DisplayDigits.Length <span class="hljs-operator">&gt;</span> <span class="hljs-number">0</span>)
                {
                    <span class="hljs-built_in">this</span>.DisplayDigits\[<span class="hljs-number">0</span>\] <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;
                }
            }
            <span class="hljs-keyword">else</span>
            {
                List listOfInts <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> List();
                <span class="hljs-keyword">while</span> (<span class="hljs-built_in">this</span>.displayNo <span class="hljs-operator">&gt;</span> <span class="hljs-number">0</span>)
                {
                    listOfInts.Add(<span class="hljs-built_in">this</span>.displayNo <span class="hljs-operator">%</span> <span class="hljs-number">10</span>);
                    <span class="hljs-built_in">this</span>.displayNo <span class="hljs-operator">=</span> <span class="hljs-built_in">this</span>.displayNo <span class="hljs-operator">/</span> <span class="hljs-number">10</span>;
                }
                <span class="hljs-keyword">if</span> (displayLeadingZero)
                {
                    <span class="hljs-keyword">while</span> (listOfInts.Count <span class="hljs-operator">&lt;</span> <span class="hljs-built_in">this</span>.Displays.Length)
                    {
                        listOfInts.Add(<span class="hljs-number">0</span>);
                    }
                }
                <span class="hljs-keyword">else</span>
                {
                    <span class="hljs-keyword">while</span> (listOfInts.Count <span class="hljs-operator">&lt;</span> <span class="hljs-built_in">this</span>.Displays.Length)
                    {
                        listOfInts.Add(<span class="hljs-number">10</span>);
                    }
                }
                <span class="hljs-built_in">this</span>.DisplayDigits <span class="hljs-operator">=</span> listOfInts.ToArray();
            }
</code></pre><h4 id="heading-displaying-the-output">Displaying the Output</h4>
<p>To display the digits on the output display quickly enough to deceive the eye into thinking all displays are on simultaneously, we have to create a permanent loop that’s sole job is to switch each display on and off in turn. This is done through the ‘Start’ method, which simply starts a loop, and displays the digits in the previously calculated array. If the array is updated, the display automatically updates.</p>
<pre><code><span class="hljs-keyword">private</span> void Start()
        {
            <span class="hljs-keyword">if</span> (running)
            {
                <span class="hljs-keyword">return</span>;
            }
            running <span class="hljs-operator">=</span> <span class="hljs-literal">true</span>;
            Task.Factory.StartNew(() <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span>
            {
                <span class="hljs-keyword">while</span> (<span class="hljs-operator">!</span><span class="hljs-built_in">this</span>.cts.IsCancellationRequested)
                {
                    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.DisplayDigits <span class="hljs-operator">=</span><span class="hljs-operator">=</span> null)
                    {
                        <span class="hljs-built_in">this</span>.Blank();
                    }
                    <span class="hljs-keyword">int</span>\[\] arrDigs <span class="hljs-operator">=</span> <span class="hljs-built_in">this</span>.DisplayDigits;
                    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i <span class="hljs-operator">&lt;</span> arrDigs.Length; i<span class="hljs-operator">+</span><span class="hljs-operator">+</span>)
                    {
                        <span class="hljs-built_in">this</span>.SetDisplay(<span class="hljs-built_in">this</span>.Displays\[i\], arrDigs\[i\]);
                    }
                }
            }, token);
        }
</code></pre><p>The set display function turns all the displays off [set to high], then sets the segments required to display a specific digit to high/low depending on the digit and then sets the display pin to low, allowing the current to flow for just that single digit. This rotates through each digit in turn turning each one on and off. This happens faster than the eye can detect, giving the impression all digits are on simultaneously.</p>
<pre><code><span class="hljs-keyword">private</span> void SetDisplay(GpioPin displayPin, <span class="hljs-keyword">int</span> value)
        {
            <span class="hljs-built_in">this</span>.ClearDisplay();
            switch (value)
            {
                case <span class="hljs-number">0</span>:
                    <span class="hljs-built_in">this</span>.SetHigh(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.PinSegA, <span class="hljs-built_in">this</span>.PinSegB, <span class="hljs-built_in">this</span>.PinSegC, <span class="hljs-built_in">this</span>.PinSegD, <span class="hljs-built_in">this</span>.PinSegE, <span class="hljs-built_in">this</span>.PinSegF });
                    <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.PinSegG });
                    <span class="hljs-keyword">break</span>;
                case <span class="hljs-number">1</span>:
                    <span class="hljs-built_in">this</span>.SetHigh(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.PinSegB, <span class="hljs-built_in">this</span>.PinSegC });
                    <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.PinSegA, <span class="hljs-built_in">this</span>.PinSegD, <span class="hljs-built_in">this</span>.PinSegE, <span class="hljs-built_in">this</span>.PinSegF, <span class="hljs-built_in">this</span>.PinSegG });
                    <span class="hljs-keyword">break</span>;
                case <span class="hljs-number">2</span>:
                    <span class="hljs-built_in">this</span>.SetHigh(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.PinSegA, <span class="hljs-built_in">this</span>.PinSegB, <span class="hljs-built_in">this</span>.PinSegD, <span class="hljs-built_in">this</span>.PinSegE, <span class="hljs-built_in">this</span>.PinSegG });
                    <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.PinSegC, <span class="hljs-built_in">this</span>.PinSegF });
                    <span class="hljs-keyword">break</span>;
                case <span class="hljs-number">3</span>:
                    <span class="hljs-built_in">this</span>.SetHigh(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.PinSegA, <span class="hljs-built_in">this</span>.PinSegB, <span class="hljs-built_in">this</span>.PinSegC, <span class="hljs-built_in">this</span>.PinSegD, <span class="hljs-built_in">this</span>.PinSegG });
                    <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.PinSegE, <span class="hljs-built_in">this</span>.PinSegF });
                    <span class="hljs-keyword">break</span>;
                case <span class="hljs-number">4</span>:
                    <span class="hljs-built_in">this</span>.SetHigh(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.PinSegB, <span class="hljs-built_in">this</span>.PinSegC, <span class="hljs-built_in">this</span>.PinSegF, <span class="hljs-built_in">this</span>.PinSegG });
                    <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.PinSegA, <span class="hljs-built_in">this</span>.PinSegD, <span class="hljs-built_in">this</span>.PinSegE });
                    <span class="hljs-keyword">break</span>;
                case <span class="hljs-number">5</span>:
                    <span class="hljs-built_in">this</span>.SetHigh(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.PinSegA, <span class="hljs-built_in">this</span>.PinSegC, <span class="hljs-built_in">this</span>.PinSegD, <span class="hljs-built_in">this</span>.PinSegF, <span class="hljs-built_in">this</span>.PinSegG });
                    <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.PinSegB, <span class="hljs-built_in">this</span>.PinSegE });
                    <span class="hljs-keyword">break</span>;
                case <span class="hljs-number">6</span>:
                    <span class="hljs-built_in">this</span>.SetHigh(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.PinSegA, <span class="hljs-built_in">this</span>.PinSegC, <span class="hljs-built_in">this</span>.PinSegD, <span class="hljs-built_in">this</span>.PinSegE, <span class="hljs-built_in">this</span>.PinSegF, <span class="hljs-built_in">this</span>.PinSegG });
                    <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.PinSegB });
                    <span class="hljs-keyword">break</span>;
                case <span class="hljs-number">7</span>:
                    <span class="hljs-built_in">this</span>.SetHigh(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.PinSegA, <span class="hljs-built_in">this</span>.PinSegB, <span class="hljs-built_in">this</span>.PinSegC });
                    <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.PinSegD, <span class="hljs-built_in">this</span>.PinSegE, <span class="hljs-built_in">this</span>.PinSegF, <span class="hljs-built_in">this</span>.PinSegG });
                    <span class="hljs-keyword">break</span>;
                case <span class="hljs-number">8</span>:
                    <span class="hljs-built_in">this</span>.SetHigh(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.PinSegA, <span class="hljs-built_in">this</span>.PinSegB, <span class="hljs-built_in">this</span>.PinSegC, <span class="hljs-built_in">this</span>.PinSegD, <span class="hljs-built_in">this</span>.PinSegE, <span class="hljs-built_in">this</span>.PinSegF, <span class="hljs-built_in">this</span>.PinSegG });
                    <span class="hljs-keyword">break</span>;
                case <span class="hljs-number">9</span>:
                    <span class="hljs-built_in">this</span>.SetHigh(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.PinSegA, <span class="hljs-built_in">this</span>.PinSegB, <span class="hljs-built_in">this</span>.PinSegC, <span class="hljs-built_in">this</span>.PinSegD, <span class="hljs-built_in">this</span>.PinSegF, <span class="hljs-built_in">this</span>.PinSegG });
                    <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.PinSegE });
                    <span class="hljs-keyword">break</span>;
                case <span class="hljs-number">10</span>:  <span class="hljs-comment">// Clear Display</span>
                    <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.PinSegA, <span class="hljs-built_in">this</span>.PinSegB, <span class="hljs-built_in">this</span>.PinSegC, <span class="hljs-built_in">this</span>.PinSegD, <span class="hljs-built_in">this</span>.PinSegE, <span class="hljs-built_in">this</span>.PinSegF, <span class="hljs-built_in">this</span>.PinSegG });
                    <span class="hljs-keyword">break</span>;
                default:
                    <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-keyword">new</span> GpioPin\[\] { <span class="hljs-built_in">this</span>.PinSegA, <span class="hljs-built_in">this</span>.PinSegB, <span class="hljs-built_in">this</span>.PinSegC, <span class="hljs-built_in">this</span>.PinSegD, <span class="hljs-built_in">this</span>.PinSegE, <span class="hljs-built_in">this</span>.PinSegF, <span class="hljs-built_in">this</span>.PinSegG });
                    <span class="hljs-keyword">break</span>;
            }
            <span class="hljs-built_in">this</span>.SetLow(<span class="hljs-keyword">new</span> GpioPin\[\] { displayPin });
        }
</code></pre><p>The full code listing including a demo application are available via the link at the top of the page.  </p>
<h3 id="heading-video">Video</h3>
<p>The below is a short video of output generated by using this library.</p>
<iframe width="640" height="360" src="https://www.youtube.com/embed/uFJewEzlvv0?feature=oembed"></iframe>

<p>Future Development</p>
<p>Currently the output is limited to whole, positive integers.  Future improvements could include display of decimal or negative numbers, or some alphanumeric characters (e.g. C or F for temperature displays).  </p>
<p>The post <a target="_blank" href="https://davek.dev/creating-a-seven-segment-display-driver-with-raspberry-pi">[RPi Series] Creating a Seven Segment Display Driver</a> appeared first on <a target="_blank" href="https://talkingitthrough.co.uk">Talking I.T. Through</a>.</p>
]]></content:encoded></item></channel></rss>