<?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[Blog | Goldy Mariz Lunesa]]></title><description><![CDATA[A collection of my digitized thoughts and musings, now accessible over the cyber web space.

.NET ⭒ React ⭒ Node.js ⭒ Python ⭒ Azure]]></description><link>https://blog.gmlunesa.com</link><generator>RSS for Node</generator><lastBuildDate>Thu, 19 Nov 2026 06:33:34 GMT</lastBuildDate><atom:link href="https://blog.gmlunesa.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Dependency Injection: AddSingleton, AddScoped, AddTransient Differences]]></title><description><![CDATA[Dependency Injection is a design pattern used to achieve loose coupling and to increase the maintainability in our code. Using dependency injection in C#…]]></description><link>https://blog.gmlunesa.com/dependency-injection-addsingleton-addscoped-addtransient-differences</link><guid isPermaLink="true">https://blog.gmlunesa.com/dependency-injection-addsingleton-addscoped-addtransient-differences</guid><category><![CDATA[C#]]></category><category><![CDATA[dotnet]]></category><category><![CDATA[design patterns]]></category><dc:creator><![CDATA[Goldy Mariz Lunesa 🇵🇭]]></dc:creator><pubDate>Fri, 01 Mar 2024 14:27:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1709303109170/4cefc11b-d937-40c8-b4e2-6aa420978c46.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Dependency Injection is a design pattern used to achieve loose coupling and to increase the maintainability in our code. Using dependency injection in C# and .NET is pretty easy. We are provided with the following methods to register our services: <code>AddSingleton</code>, <code>AddScoped</code>, <code>AddTransient</code>. However, it is important to know the differences between these three methods to be able to manage and configure the lifetimes of the services within our applications.</p>
<h2 id="heading-brief-rundown">Brief Rundown</h2>
<ul>
<li><p><strong>AddSingleton</strong>: A single instance of a service will be created and reused for every request, throughout the application's lifetime.</p>
<ul>
<li><div data-node-type="callout">
  <div data-node-type="callout-emoji">💡</div>
  <div data-node-type="callout-text">Best used for services that require to maintain a shared state throughout the entire application.</div>
  </div>
</li>
<li><div data-node-type="callout">
  <div data-node-type="callout-emoji">❗</div>
  <div data-node-type="callout-text">Need to ensure mutability of the shared state. Need to also be careful with thread safety of the services.</div>
  </div>
</li>
</ul>
</li>
<li><p><strong>AddScoped</strong>: A new instance of the service will be created once per request within the scope or context. In the case of ASP.NET, a new instance would be created per each HTTP request (the scope)</p>
<ul>
<li><div data-node-type="callout">
  <div data-node-type="callout-emoji">💡</div>
  <div data-node-type="callout-text">Best used for services that require to maintain state throughout a request (e.g. user information)</div>
  </div>
</li>
</ul>
</li>
<li><p><strong>AddTransient</strong>: A new instance of the service will be created for each request. Each time a service is resolved, a new instance will be provided.</p>
<ul>
<li><div data-node-type="callout">
  <div data-node-type="callout-emoji">💡</div>
  <div data-node-type="callout-text">Best used for stateless services where a new instance is required for each request.</div>
  </div>
</li>
<li><div data-node-type="callout">
  <div data-node-type="callout-emoji">❗</div>
  <div data-node-type="callout-text">Entails heavy initialization, and might cause unnecessary overhead.</div>
  </div>


</li>
</ul>
</li>
</ul>
<h2 id="heading-usage">Usage</h2>
<p>We will dive deeper on the life cycles of the dependency injections. In this article, we will:</p>
<ul>
<li><p>Create an ASP.NET Core Web API app that uses dependency injection</p>
</li>
<li><p>Write several interfaces and corresponding implementations</p>
</li>
<li><p>Use service lifetime and scoping for DI</p>
</li>
</ul>
<p>We are going to create an ASP.NET Core Web API minimal app to better illustrate the differences between the lifetime and scope of the DI methods. This is loosely based on the <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-usage">Microsoft docs</a>.</p>
<h3 id="heading-code">Code</h3>
<p>To start, let's create and define our interfaces.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IExampleService</span>
{
    Guid Value { <span class="hljs-keyword">get</span>; }
}
</code></pre>
<p>The <code>IExampleService</code> interface contains:</p>
<ul>
<li>A <code>Guid Id</code> property that represents a unique identifier of the service.</li>
</ul>
<p>Next, create the subinterfaces for <code>IExampleService</code> that will represent the different lifetimes, and will be invoked by their corresponding methods. Create a class <code>ExampleService</code> that implement the subinterfaces, and will provide a unique GUID.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">ISingletonExampleService</span> : <span class="hljs-title">IExampleService</span> { }
<span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IScopedExampleService</span> : <span class="hljs-title">IExampleService</span> { }
<span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">ITransientExampleService</span> : <span class="hljs-title">IExampleService</span> { }

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ExampleService</span> : <span class="hljs-title">ISingletonExampleService</span>, <span class="hljs-title">IScopedExampleService</span>, <span class="hljs-title">ITransientExampleService</span>
{
    <span class="hljs-keyword">public</span> Guid Id { <span class="hljs-keyword">get</span>; } = Guid.NewGuid();
}
</code></pre>
<p>In an ASP.NET Core minimal API, add each type to the container according to its named lifetime.</p>
<p>In our <code>/example</code> endpoint, define the dependencies to inject. To better understand the differences, we inject two instances of each service. Create a log to show the ID of the services.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">This is for example purposes only. In reality, requests like these are done in different parts of the codebase.</div>
</div>

<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton&lt;ISingletonExampleService&gt;(<span class="hljs-keyword">new</span> ExampleService());
builder.Services.AddScoped&lt;IScopedExampleService, ExampleService&gt;();
builder.Services.AddTransient&lt;ITransientExampleService, ExampleService&gt;();

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

app.MapGet(<span class="hljs-string">"/example"</span>, (ISingletonExampleService exampleSingle1, ISingletonExampleService exampleSingle2,
                        IScopedExampleService exampleScoped1, IScopedExampleService exampleScoped2,
                        ITransientExampleService exampleTransient1, ITransientExampleService exampleTransient2) =&gt;
{
    <span class="hljs-keyword">return</span> <span class="hljs-string">$"Singleton instance: <span class="hljs-subst">{exampleSingle1.Id}</span>\n"</span> +
            <span class="hljs-string">$"Singleton instance: <span class="hljs-subst">{exampleSingle2.Id}</span>\n\n"</span> +
            <span class="hljs-string">$"Scoped instance 1: <span class="hljs-subst">{exampleScoped1.Id}</span>\n"</span> +
            <span class="hljs-string">$"Scoped instance 2: <span class="hljs-subst">{exampleScoped2.Id}</span>\n\n"</span> +
            <span class="hljs-string">$"Transient instance 1: <span class="hljs-subst">{exampleTransient1.Id}</span>\n"</span> +
            <span class="hljs-string">$"Transient instance 2: <span class="hljs-subst">{exampleTransient2.Id}</span>"</span>;
});

app.Run();
</code></pre>
<h3 id="heading-result">Result</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1709301682662/1ffea00f-3016-4677-a962-64611aba06a3.gif" alt="Singleton never changes, scoped changes changes only after a new scope (HTTP request), transient always changes" class="image--center mx-auto" /></p>
<p>What we can observe whenever we create a new HTTP request (by pressing the Refresh button):</p>
<ul>
<li><p>Singleton: Never changes</p>
</li>
<li><p>Scoped: Changes only after a new HTTP request (new scope)</p>
</li>
<li><p>Transient: Always changes</p>
</li>
</ul>
<p>The code is available on <a target="_blank" href="https://github.com/gmlunesa/DependencyInjectionExample">Github</a>.</p>
<h2 id="heading-remarks">Remarks</h2>
<p>Understanding the different types of service lifetimes is important to successfully manage the dependencies and ensure correct behavior within our C# applications. We must always consider the requirements of the project and the attributes of the services in order to choose the proper service lifetime for each registration.</p>
]]></content:encoded></item><item><title><![CDATA[Is it worth learning C# in 2024?]]></title><description><![CDATA[In this article by Goldy Mariz Lunesa @gmlunesa, we will discuss if C# is worth learning in 2024.]]></description><link>https://blog.gmlunesa.com/is-it-worth-learning-c-in-2024</link><guid isPermaLink="true">https://blog.gmlunesa.com/is-it-worth-learning-c-in-2024</guid><category><![CDATA[.NET]]></category><category><![CDATA[C#]]></category><dc:creator><![CDATA[Goldy Mariz Lunesa 🇵🇭]]></dc:creator><pubDate>Wed, 24 Jan 2024 13:46:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706103720170/375135c0-81cd-4019-9adb-4a27c6290e02.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I often see this question pop out in online communities— from developers still starting out, to experienced ones who would like to explore the .NET ecosystem. In today's blog, I will be giving some insights and hopefully help you find an answer.</p>
<h2 id="heading-a-brief-refresher">A brief refresher</h2>
<p>Taking it right from the <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/">Microsoft docs</a>,</p>
<blockquote>
<p>C# is a modern, object-oriented, and type-safe programming language. C# programs run on .NET, a virtual execution system called the common language runtime (CLR) and a set of class libraries.</p>
</blockquote>
<p>To put it simply, C# is the programming language, while .NET is the runtime which executes your code.</p>
<h2 id="heading-things-to-consider">Things to consider</h2>
<h3 id="heading-longevity">Longevity</h3>
<p>C# is backed by Microsoft, a billion-dollar company. C# and .NET is constantly worked on and improved by the best developers and architects. You can check out their activities at <a target="_blank" href="https://github.com/dotnet/">Github</a> or view their community standups at <a target="_blank" href="https://www.youtube.com/@dotnet">Youtube</a>.</p>
<h3 id="heading-developer-experience">Developer Experience</h3>
<p>You can easily start coding in C# and build .NET applications with Visual Studio and/or Visual Studio Code. Both of these have excellent C# support that make life easier for us devs. They are also actively maintained with frequent releases. Deploying your C# applications to the cloud is also breeze with Azure, which is also another product of Microsoft.</p>
<h3 id="heading-what-you-can-build">What you can build</h3>
<p>C# can be used to develop multiple types of applications. In combination of the .NET Core cross-platform support and frameworks like ASP.NET, Blazor, MAUI, WinUI, Unity and many more, you can do these things with C#:</p>
<ul>
<li><p>Web development</p>
</li>
<li><p>Game development</p>
</li>
<li><p>Desktop app development</p>
</li>
<li><p>Internet of Things (IoT) development</p>
</li>
<li><p>Single codebase for native mobile apps (e.g. iOS, Android)</p>
</li>
</ul>
<h3 id="heading-proximity">Proximity</h3>
<p>Another thing to consider is the job market around your area. Do research in job boards in your city and observe the demand. Some regions are hiring C#/.NET developers more than others.</p>
<p>My personal observation is that C# is not exactly trendy or considered as cool unlike the more popular languages used by startups. It gives priority to stability and long term sustainability over development speed. So a lot of times, I have observed that most companies who favor C# or hire C# developers are usually enterprise level. I think this is also factor to consider when choosing your career trajectory— what types of applications you want to be doing, or what type of environment you want to be working in.</p>
<p>There's even an interesting Reddit thread related to this topic: <a target="_blank" href="https://www.reddit.com/r/csharp/comments/193gznd/net_developers_are_we_doomed_to_boring_enterprise/">.NET developers, are we doomed to boring enterprise software forever?</a></p>
<h2 id="heading-so-what-now">So what now?</h2>
<p>I have been a full-time developer for almost 6 years now, and I've worked with C#, Javascript (NodeJS and React) and Python; C# is my favorite. Functional, versatile and fast!</p>
<p>If you are interested in getting started with C#, the <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/csharp/">Microsoft docs</a> and the <a target="_blank" href="https://www.youtube.com/@dotnet">DotNet Youtube</a> channel are great places to start!</p>
]]></content:encoded></item><item><title><![CDATA[Deploy serverless Node.js Functions to Azure Functions]]></title><description><![CDATA[Previously, deploying an application involved tasks such as setting up a virtual machine, implementing security measures, and installing the necessary…]]></description><link>https://blog.gmlunesa.com/deploy-serverless-nodejs-functions-azure</link><guid isPermaLink="true">https://blog.gmlunesa.com/deploy-serverless-nodejs-functions-azure</guid><dc:creator><![CDATA[Goldy Mariz Lunesa 🇵🇭]]></dc:creator><pubDate>Mon, 29 May 2023 09:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1685460262435/2ae9a0bf-3064-424c-82b4-9bbb7eb59de5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Previously, deploying an application involved tasks such as setting up a virtual machine, implementing security measures, and installing the necessary frameworks. This complex process often resulted in unnecessary costs when the applications were not in use.</p>
<p>However, with the advancement of cloud computing, it is now possible to leverage <strong>serverless computing</strong> for your platform and deployment infrastructure, allowing you to focus solely on coding.</p>
<p>I had a small task that I wanted to do for my website's <a target="_blank" href="https://gmlunesa.com/goals">Goals</a> page— I needed to access <a target="_blank" href="https://github.com/makenotion/notion-sdk-js">Notion SDK for Javascript</a>, retrieve and format the data for my Gatsby frontend to use. However, it was such a small task that I felt that it did not warrant the hassle to build a whole application to do so, hence, I thought it was a great use case for Azure Functions. In this article, I will share how I used Azure Functions to deploy a serverless Node.js function, from the comfort of my VSCode IDE.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>I had the following installed:</p>
<ul>
<li>An <a target="_blank" href="https://azure.microsoft.com/en-us/">Azure</a> account with an active subscription.</li>
<li>Node.js 16.x or above.</li>
<li><a target="_blank" href="https://learn.microsoft.com/en-us/cli/azure/install-azure-cli">Azure CLI</a></li>
<li>Visual Studio Code</li>
<li><a target="_blank" href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=v4%2Cwindows%2Ccsharp%2Cportal%2Cbash#v2">Azure Functions Core Tools</a></li>
<li>Azure Functions extension (optional if using terminal)</li>
</ul>
<h2 id="heading-creating-our-azure-function-project">Creating our Azure Function project</h2>
<p>On Visual Studio Code, I did the following steps:</p>
<ul>
<li>Access the Azure extension on the Activity Bar.</li>
<li>On <strong>Workspace</strong> Local, click the + button.</li>
<li>Choose <code>Create Function</code>.</li>
<li>Enter the details on the succeeding prompts.</li>
</ul>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Prompt</td><td>Selection</td></tr>
</thead>
<tbody>
<tr>
<td>Language</td><td><code>Javascript</code></td></tr>
<tr>
<td>JS Programming Model</td><td><code>Model V4 (Preview)</code></td></tr>
<tr>
<td>Template</td><td><code>HTTP Trigger</code></td></tr>
</tbody>
</table>
</div><p>If using the Azure CLI, simply type in the following command:</p>
<pre><code class="lang-sh">func new
</code></pre>
<h2 id="heading-run-locally">Run locally</h2>
<p>To run the function locally on VS Code:</p>
<ul>
<li>Press <code>F5</code>.</li>
<li>Access the Azure extension on the Activity Bar.</li>
<li>Expand <strong>Workspace</strong> &gt; <strong>Local</strong> &gt; <strong>Functions</strong>.</li>
<li>Right click and choose <code>Execute Function Now</code>.</li>
</ul>
<p>To run the function locally using the Azure CLI:</p>
<pre><code class="lang-sh">func start
</code></pre>
<h2 id="heading-deploy-to-azure">Deploy to Azure</h2>
<p>Prior to deploying your function code to Azure, these essential resources must be established:</p>
<ul>
<li><a target="_blank" href="https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/manage-resource-groups-portal">Resource Group</a>: Serves as a logical container for interconnected resources.</li>
<li><a target="_blank" href="https://learn.microsoft.com/en-us/azure/storage/common/storage-account-overview">Storage account</a>: Stores and Manages state and other pertinent data related to your functions.</li>
<li><a target="_blank" href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-overview?pivots=programming-language-javascript">Function App</a>: Provides the execution environment for your function code; Corresponds to the local function project.</li>
</ul>
<p>To create these resources, use the following commands using Azure CLI.</p>
<ul>
<li>Login to Azure<ul>
<li><pre><code class="lang-sh">az login
</code></pre>
</li>
</ul>
</li>
<li>Create resource group on the desired region.<ul>
<li><pre><code class="lang-sh">az group create --name &lt;RESOURCE_GROUP_NAME&gt; --location &lt;REGION&gt;
</code></pre>
</li>
</ul>
</li>
<li>Create a general-purpose storage account in the newly created resource group and desired region.<ul>
<li><pre><code class="lang-sh">az storage account create --name &lt;STORAGE_NAME&gt; --location &lt;REGION&gt; --resource-group &lt;RESOURCE_GROUP_NAME&gt; --sku Standard_LRS --allow-blob-public-access <span class="hljs-literal">false</span>
</code></pre>
</li>
</ul>
</li>
<li>Create a function app in Azure.<ul>
<li><pre><code class="lang-sh">az functionapp create --resource-group &lt;RESOURCE_GROUP_NAME&gt; --consumption-plan-location &lt;REGION&gt; --runtime node --runtime-version &lt;NODE_VERSION&gt; --functions-version 4 --name &lt;FUNCTION_APP_NAME&gt; --storage-account &lt;STORAGE_NAME&gt;
</code></pre>
</li>
</ul>
</li>
<li>Enable the V4 programming model app to run in Azure.<ul>
<li><pre><code class="lang-sh">az functionapp config appsettings <span class="hljs-built_in">set</span> --name &lt;FUNCTION_APP_NAME&gt; --resource-group &lt;RESOURCE_GROUP_NAME&gt; --settings AzureWebJobsFeatureFlags=EnableWorkerIndexing
</code></pre>
</li>
</ul>
</li>
</ul>
<p>We can now deploy the function app to Azure!</p>
<pre><code class="lang-sh">func azure functionapp publish &lt;FUNCTION_APP_NAME&gt;
</code></pre>
<h3 id="heading-environment-variables">Environment Variables</h3>
<p>To configure environment variables for local environment:</p>
<ul>
<li>Go to <code>local.settings.json</code> and add environment variables under <strong>Values</strong>.</li>
</ul>
<p>To configure environment variables for deployed app:</p>
<p>If using Azure Portal:</p>
<ul>
<li>Navigate to your function app.</li>
<li>Go to <strong>Settings</strong> &gt; <strong>Configuration</strong> &gt; <strong>Application Settings</strong> and add desired environment variables.<p>
<img src="https://raw.githubusercontent.com/gmlunesa/gmlunesa.github.io/development/src/blog/deploy-serverless-nodejs-functions-azure/images/AzureFuncConfig.png" alt="Azure Function Configuration Settings" class="small-img" />
</p>

</li>
</ul>
<p>If using Azure CLI:</p>
<ul>
<li><p>Run the following command:</p>
<ul>
<li><pre><code class="lang-sh">az functionapp config appsettings <span class="hljs-built_in">set</span> --name &lt;FUNCTION_APP_NAME&gt; \
--resource-group &lt;RESOURCE_GROUP_NAME&gt; \
--settings &lt;CUSTOM_KEY&gt;=&lt;VALUE&gt;
</code></pre>
</li>
</ul>
</li>
</ul>
<h3 id="heading-continuous-deployment">Continuous Deployment</h3>
<p>By leveraging source control integration, Azure Functions lets you to achieve continuous deployment of your code. This integration facilitates a seamless workflow where any updates made to the code automatically trigger the deployment process to Azure.</p>
<p>On the Azure portal:</p>
<ul>
<li>Navigate to your function app.</li>
<li>Go to <strong>Settings</strong> &gt; <strong>Deployment Center</strong> &gt; <strong>Application Settings</strong> and choose the desired <code>Source</code>.</li>
<li>Authorize accordingly.</li>
<li>Choose the Organization, Repository and Branch where you want your function to be deployed from.</li>
<li>Review all details and press the <code>Finish</code> button.</li>
</ul>
<p>This is how my settings for my project looks like:</p>
<p>
  <img src="https://raw.githubusercontent.com/gmlunesa/gmlunesa.github.io/development/src/blog/deploy-serverless-nodejs-functions-azure/images/AzureSetupCD.png" alt="Azure Function Configuration Settings" class="small-img" />
</p>

<p>When successfully configured, the code from the specified repository will be deployed to the function app. Any modifications or commits in the deployment source will initiate a deployment process, ensuring that those changes are promptly applied to the function app.</p>
<h2 id="heading-remarks">Remarks</h2>
<p>That is it! The whole process of deploying a serverless function is an easy one, especially with the help of relevant Azure extensions on VS Code. I also don't have to worry about racking up server costs.</p>
]]></content:encoded></item><item><title><![CDATA[Using Options pattern on ASP.NET]]></title><description><![CDATA[In practically every project or application, there is a requirement to configure and modify various settings based on the environment being operated on. A…]]></description><link>https://blog.gmlunesa.com/using-options-pattern-on-aspnet</link><guid isPermaLink="true">https://blog.gmlunesa.com/using-options-pattern-on-aspnet</guid><dc:creator><![CDATA[Goldy Mariz Lunesa 🇵🇭]]></dc:creator><pubDate>Sat, 15 Apr 2023 09:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1685596175504/b52afd35-56a9-43c5-a5f9-bae7ef62b171.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In practically every project or application, there is a requirement to configure and modify various settings based on the environment being operated on. A prime example of this is handling connection strings for databases, which should ideally remain confidential and not be exposed. Other types of configurations could be paths, default values, user secrets, et cetera. For .NET and ASP.NET, these settings could be stored in environmental variables, <code>appsettings.json</code>, user secrets, a key vault (like Azure Key Vault), databases, or other custom settings files.</p>
<p>.NET provides the <code>IOptions</code> interface to be able to use strongly typed configuration values from the aforementioned files above. This way, we can also observe the <strong>Options pattern</strong>.</p>
<h2 id="heading-options-pattern">Options Pattern</h2>
<p>According to Microsoft, the options pattern utilizes classes to provide strongly-typed access to groups of related configuration values. When these values are isolated by scenario into separate classes, the application would adhere to two important software engineering principles:</p>
<ul>
<li><p>Interface Segregation Principle (ISP): Classes that depend on configuration settings depend only on configuration settings that they use.</p>
</li>
<li><p>Separation of Concerns: Settings for different parts of the application are not dependent or tightly coupled with each other.</p>
</li>
</ul>
<h2 id="heading-configuration-binding">Configuration Binding</h2>
<p>Let's say we would like to access the configuration values under <code>LongPollingOptions</code> from an <code>appsettings.json</code>.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"LongPollingOptions"</span>: {
    <span class="hljs-attr">"AutoRetry"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"IntervalSeconds"</span>: <span class="hljs-number">3000</span>
  },
  <span class="hljs-attr">"DatabaseLogLevel"</span>: <span class="hljs-string">"Warning"</span>
}
</code></pre>
<p>We should create a strongly typed options class that matches the section of the configuration file.</p>
<pre><code class="lang-cs"><span class="hljs-keyword">public</span> <span class="hljs-keyword">sealed</span> <span class="hljs-keyword">class</span> <span class="hljs-title">LongPollingOptions</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> AutoRetry { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> IntervalSeconds { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}
</code></pre>
<p>To follow the options pattern, the options class must:</p>
<ul>
<li>Built as non-abstract with a public constructor with no parameters</li>
<li>Contain public read-write properties to bind (fields are <strong><em>not</em></strong> bound)</li>
</ul>
<p>We can now bind the configuration values to the options class. In <code>Program.cs</code>, insert the following code after declaring and initializing the WebApplication builder.</p>
<pre><code class="lang-cs"><span class="hljs-comment">// Program.cs</span>
<span class="hljs-comment">// Declare and initialize WebApplication builder</span>
<span class="hljs-keyword">var</span> builder = WebApplication.CreateBuilder(args);

<span class="hljs-comment">// Insert following code to bind configuration data</span>
builder.Services.Configure&lt;LongPollingOptions&gt;(builder.Configuration.GetSection(<span class="hljs-string">"LongPollingOptions"</span>));
</code></pre>
<p>Let's discuss the code that was inserted bit by bit.</p>
<pre><code class="lang-cs">builder.Configuration.GetSection(<span class="hljs-string">"LongPollingOptions"</span>)
</code></pre>
<p>The preceding code retrieves a configuration section by its name, <code>LongPollingOptions</code> as specified here.</p>
<pre><code class="lang-cs">builder.Services.Configure&lt;LongPollingOptions&gt;(builder.Configuration.GetSection(<span class="hljs-string">"LongPollingOptions"</span>));
</code></pre>
<p>In the preceding code, the <code>LongPollingOptions</code> configuration section that was retrieved is bound to the <code>LongPollingOptions</code> instance. This hydrates the C# <code>LongPollingOptions</code> object properties with corresponding values from the configuration. It is then added to the dependency injection service container.</p>
<p>That's it! The newly created strongly typed <code>LongPollingOptions</code> options could now be accessed anywhere in the application that need to call it.</p>
<h2 id="heading-access-the-options">Access the options</h2>
<p>The following code demonstrates how we can access the options in our classes.</p>
<pre><code class="lang-cs"><span class="hljs-keyword">public</span> <span class="hljs-keyword">sealed</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ExampleService</span>
{
  <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> LongPollingOptions _options;

  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ExampleService</span>(<span class="hljs-params">IOptions&lt;LongPollingOptions&gt; options</span>)</span> =&gt;
      _options = options.Value;

  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DisplayValues</span>(<span class="hljs-params"></span>)</span>
  {
      Console.WriteLine(<span class="hljs-string">$"LongPollingOptions.AutoRetry=<span class="hljs-subst">{_options.AutoRetry}</span>"</span>);
      Console.WriteLine(<span class="hljs-string">$"LongPollingOptions.IntervalSeconds=<span class="hljs-subst">{_options.IntervalSeconds}</span>"</span>);
  }
}
</code></pre>
]]></content:encoded></item><item><title><![CDATA[C#: Int.Parse versus Convert.ToInt32]]></title><description><![CDATA[What is the difference between the Int.Parse and Convert.ToInt32 methods? This question recently popped up in my head and prompted me to conduct more…]]></description><link>https://blog.gmlunesa.com/c-intparse-versus-converttoint32</link><guid isPermaLink="true">https://blog.gmlunesa.com/c-intparse-versus-converttoint32</guid><dc:creator><![CDATA[Goldy Mariz Lunesa 🇵🇭]]></dc:creator><pubDate>Thu, 05 Jan 2023 09:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1685027163443/6e580850-dcdc-4415-9141-8ee947adade2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>What is the difference between the Int.Parse and Convert.ToInt32 methods?</p>
</blockquote>
<p>This question recently popped up in my head and prompted me to conduct more research, which is now laid out in this article.</p>
<h2 id="heading-key-notes">Key Notes</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td></td><td>Int.Parse</td><td>Convert.ToInt32</td></tr>
</thead>
<tbody>
<tr>
<td>Objective</td><td>Converts the string representation of a number to its 32-bit signed integer equivalent.</td><td>Converts a specified value to a 32-bit signed integer.</td></tr>
<tr>
<td>Syntax</td><td><code>Int32.Parse(String);</code></td><td><code>Convert.ToInt32(String)</code></td></tr>
<tr>
<td>Null Parameters</td><td>Returns <code>ArgumentNullException</code>.</td><td>Returns <code>0</code>.</td></tr>
</tbody>
</table>
</div><h2 id="heading-intparse">Int.Parse</h2>
<p><code>Int.Parse</code> is a method that converts the string representation of a number to its 32-bit signed integer equivalent.</p>
<h3 id="heading-syntax">Syntax</h3>
<pre><code class="lang-cs"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">Parse</span> (<span class="hljs-params"><span class="hljs-keyword">string</span> s</span>)</span>;
</code></pre>
<p>Let's demonstrate this method in the following example:</p>
<pre><code class="lang-cs"><span class="hljs-keyword">string</span>[] values = { <span class="hljs-string">"+500"</span>, <span class="hljs-string">"-0"</span>, <span class="hljs-string">"1,300,423"</span>, <span class="hljs-string">"$230,873,083"</span>,
                                <span class="hljs-string">"0xFA1C"</span>, <span class="hljs-string">"-10"</span>, <span class="hljs-string">"007"</span>, <span class="hljs-string">"2147483647"</span>,
                                <span class="hljs-string">"2147483648"</span>, <span class="hljs-string">"16e05"</span>, <span class="hljs-string">"134985.0"</span>, <span class="hljs-string">"-12039"</span>,
                                <span class="hljs-string">"-2147483648"</span>, <span class="hljs-string">"-2147483649"</span> };
<span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">string</span> <span class="hljs-keyword">value</span> <span class="hljs-keyword">in</span> values)
{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">int</span> number = Int32.Parse(<span class="hljs-keyword">value</span>);
        Console.WriteLine(<span class="hljs-string">"{0} --&gt; {1}"</span>, <span class="hljs-keyword">value</span>, number);
    }
    <span class="hljs-keyword">catch</span> (FormatException) {
        Console.WriteLine(<span class="hljs-string">"{0}: Bad Format"</span>, <span class="hljs-keyword">value</span>);
    }
    <span class="hljs-keyword">catch</span> (OverflowException) {
        Console.WriteLine(<span class="hljs-string">"{0}: Overflow"</span>, <span class="hljs-keyword">value</span>);
    }
}

<span class="hljs-comment">/**
Outputs the following:
+500 --&gt; 500
-0 --&gt; 0
1,300,423: Bad Format
$230,873,083: Bad Format
0xFA1C: Bad Format
-10 --&gt; -10
007 --&gt; 7
2147483647 --&gt; 2147483647
2147483648: Overflow
16e05: Bad Format
134985.0: Bad Format
-12039 --&gt; -12039
-2147483648 --&gt; -2147483648
-2147483649: Overflow
**/</span>
</code></pre>
<h2 id="heading-converttoint32">Convert.ToInt32</h2>
<p><code>Convert.ToInt32</code> is a method that converts the specified string representation of a number to an equivalent 32-bit signed integer.</p>
<h3 id="heading-syntax-1">Syntax</h3>
<pre><code class="lang-cs"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">ToInt32</span> (<span class="hljs-params"><span class="hljs-keyword">string</span>? <span class="hljs-keyword">value</span></span>)</span>;
</code></pre>
<p>Let's demonstrate this method in the following example:</p>
<pre><code class="lang-cs"><span class="hljs-keyword">string</span>[] values = { <span class="hljs-string">"One"</span>, <span class="hljs-string">"1.34e28"</span>, <span class="hljs-string">"-26.87"</span>, <span class="hljs-string">"-18"</span>, <span class="hljs-string">"-6.00"</span>,
                                <span class="hljs-string">" 0"</span>, <span class="hljs-string">"137"</span>, <span class="hljs-string">"1601.9"</span>, Int32.MaxValue.ToString() };
<span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">string</span> <span class="hljs-keyword">value</span> <span class="hljs-keyword">in</span> values)
{
    <span class="hljs-keyword">try</span>
    {
        <span class="hljs-keyword">int</span> number = Int32.Parse(<span class="hljs-keyword">value</span>);
        Console.WriteLine(<span class="hljs-string">"{0} --&gt; {1}"</span>, <span class="hljs-keyword">value</span>, number);
    }
    <span class="hljs-keyword">catch</span> (FormatException)
    {
        Console.WriteLine(<span class="hljs-string">"{0}: Bad Format"</span>, <span class="hljs-keyword">value</span>);
    }
    <span class="hljs-keyword">catch</span> (OverflowException)
    {
        Console.WriteLine(<span class="hljs-string">"{0}: Overflow"</span>, <span class="hljs-keyword">value</span>);
    }
}
<span class="hljs-comment">/**
Outputs the following:
One: Bad Format
1.34e28: Bad Format
-26.87: Bad Format
-18 --&gt; -18
-6.00: Bad Format
 0 --&gt; 0
137 --&gt; 137
1601.9: Bad Format
2147483647 --&gt; 2147483647
**/</span>
</code></pre>
<h2 id="heading-looking-closer">Looking Closer</h2>
<h3 id="heading-similarities">Similarities</h3>
<p>These are the similar behaviors between <code>Int.Parse</code> and <code>Convert.ToInt32</code>:</p>
<ul>
<li>Convert a string to an integer.</li>
<li>Raise Format exception when parameter is a datatype other than an integer.</li>
<li>Raise Overflow exception when parameter is a large value.</li>
</ul>
<h3 id="heading-differences">Differences</h3>
<p>Although they operate similarly, these behaviors are where <code>Int.Parse</code> and <code>Convert.ToInt32</code> differ:</p>
<ul>
<li><code>Int.Parse</code> works on a <code>string</code> exclusively, while<code>Convert.ToInt32</code> accepts any <code>object</code> (unless if the <code>object</code> does not implement <code>IConvertible</code>.</li>
<li><code>Convert.Int32</code> accepts null parameter and simply returns <code>0</code>, while <code>Int.Parse</code> raises an exception.</li>
</ul>
<p>Interestingly enough, I looked over the <a target="_blank" href="https://source.dot.net/#System.Private.CoreLib/src/libraries/System.Private.CoreLib/src/System/Convert.cs,069d595792a157df">source code</a> of <code>Convert.ToInt32</code> and it simply calls <code>Int.Parse</code>.</p>
<h3 id="heading-inttryparse">Int.TryParse</h3>
<p>Another similar method to <code>Int.Parse</code> is <code>Int.TryParse</code>. It converts the string representation of a number to its 32-bit signed integer equivalent. However, the return value indicates whether the conversion succeeded.</p>
<h2 id="heading-remarks">Remarks</h2>
<p>Personally, I gravitate towards using <code>Int.TryParse</code>, since it makes the application more robust and enables me to prevent unhandled exceptions.</p>
<p>A preferable use case for <code>Convert.ToInt32</code> is when the type of <code>object</code> is unknown. Based on the source code, if the unknown <code>object</code> parameter is your type is already an <code>int</code>, <code>short</code> or <code>byte</code>, it will directly return it, no parsing needed. If the unknown <code>object</code> parameter is a <code>double</code>, it will round it and return it, no parsing needed. If it's a string, it will simply call <code>Int.Parse</code>.</p>
<p>To read more about this topic, please check out my sources:</p>
<ul>
<li><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/system.int32.parse?view=net-6.0">Int32.Parse Method</a></li>
<li><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-6.0">Int32.TryParse Method</a></li>
<li><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/system.convert.toint32?view=net-6.0">Convert.ToInt32 Method</a></li>
<li><a target="_blank" href="https://source.dot.net/#System.Private.CoreLib/src/libraries/System.Private.CoreLib/src/System/Convert.cs,069d595792a157df">.NET Source Browser</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Creating a wholesome chat space with Tensorflow]]></title><description><![CDATA[Along with the growing accessibility of the internet across the world, offensive actions across the virtual space have also become increasingly prevalent…]]></description><link>https://blog.gmlunesa.com/creating-a-wholesome-chat-space-with-tensorflow</link><guid isPermaLink="true">https://blog.gmlunesa.com/creating-a-wholesome-chat-space-with-tensorflow</guid><category><![CDATA[Machine Learning]]></category><category><![CDATA[React]]></category><dc:creator><![CDATA[Goldy Mariz Lunesa 🇵🇭]]></dc:creator><pubDate>Thu, 15 Dec 2022 09:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1673322112915/yBR6FS4PF.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Along with the growing accessibility of the internet across the world, offensive actions across the virtual space have also become increasingly prevalent. According to <a target="_blank" href="https://www.pewresearch.org/internet/2021/01/13/the-state-of-online-harassment/">Pew Research</a>, roughly 4 in 10 Americans have experienced online harrassment. Through machine learning, we can help to improve user experience to avoid negative interactions.</p>
<p>
  <img src="https://raw.githubusercontent.com/gmlunesa/gmlunesa.github.io/development/src/blog/creating-a-wholesome-chat-space-with-tensorflow/images/NotoxShowcase.png" alt=".NET MAUI app mockup" class="small-img" />
</p>

<h2 id="heading-using-machine-learning-models">Using machine learning models</h2>
<p>In this blog post, I will provide a walkthrough on how to integrate and use a machine learning model in a chat application to prevent rude messages from being sent. Of course, there is a simple option to identify toxic messages by checking if the message contains a word that is deemed inappropriate. However, this approach may overlook semantic context and may misclassify the message. Take these two sentences for example:</p>
<ul>
<li>The weather is <strong><mark>horrible</mark></strong>.</li>
<li>You are <strong><mark>horrible</mark></strong>.</li>
</ul>
<p>If the word horrible was in the list of inappropriate words, the first sentence will be misclassified as toxic. Context <em>matters</em>, hence we will harness the power of machine learning to take this a step further.</p>
<p>This project will be using a pre-trained TensorFlow model from <a target="_blank" href="https://www.tensorflow.org/js">Tensorflow.js</a>. The model detects whether the text contains toxic content such as threatening language, insults, obscenities, identity-based hate, or explicit language. It is built on top of the Universal Sentence Encoder (<a target="_blank" href="https://arxiv.org/pdf/1803.11175.pdf">Cer et al., 2018</a>), a model that encodes text into 512-dimensional embedding and uses the Transformer (<a target="_blank" href="https://arxiv.org/pdf/1706.03762.pdf">Vaswani et al, 2017</a>) architecture, which is a state-of-the-art method for modelling language.</p>
<p>The model will then be integrated to a React chat application that is bootstrapped with <a target="_blank" href="https://github.com/gmlunesa/techst/">Techst</a>, a plug and play chat platform template.</p>
<h2 id="heading-chat-platform-setup">Chat platform setup</h2>
<ul>
<li><p>Clone the Techst repository (alternative: <a target="_blank" href="https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-repository-from-a-template">Create a repository from a template - GitHub Docs</a>)</p>
<pre><code class="lang-bash">git <span class="hljs-built_in">clone</span> https://github.com/gmlunesa/techst.git
</code></pre>
</li>
<li><p>Install Node modules</p>
<pre><code class="lang-bash">npm install
</code></pre>
</li>
<li><p>Go to the <a target="_blank" href="https://console.firebase.google.com">Firebase Console</a>.</p>
<ul>
<li>Add a project.</li>
<li>Add <code>Authentication</code> with <code>Email/Password</code> as the <code>Sign-in method</code>.</li>
<li>Add a <code>Firestore Database</code>.</li>
<li><p>Add a <code>Storage</code>.</p>
</li>
<li><p>Add a <code>Web</code> application.</p>
</li>
<li><p>Copy the Firebase configuration that has been generated.</p>
</li>
</ul>
</li>
<li><p>Open the <code>firebase.sample.js</code> file, paste and replace the Firebase configuration under the <code>// TODO: Replace</code> comment.</p>
<pre><code class="lang-js"> <span class="hljs-comment">// <span class="hljs-doctag">TODO:</span> Replace</span>
 <span class="hljs-attr">apiKey</span>: <span class="hljs-string">'YOUR_API_KEY'</span>,
 <span class="hljs-attr">authDomain</span>: <span class="hljs-string">'YOUR_AUTH_DOMAIN'</span>,
 <span class="hljs-attr">projectId</span>: <span class="hljs-string">'YOUR_PROJECT_ID'</span>,
 <span class="hljs-attr">storageBucket</span>: <span class="hljs-string">'YOUR_STORAGE_BUCKET'</span>,
 <span class="hljs-attr">messagingSenderId</span>: <span class="hljs-string">'YOUR_MESSAGING_SENDER_ID'</span>,
 <span class="hljs-attr">appId</span>: <span class="hljs-string">'YOUR_APP_ID'</span>,
</code></pre>
</li>
<li><p>Rename the <code>firebase.sample.js</code> file to <code>firebase.js</code>.</p>
</li>
</ul>
<h2 id="heading-tensorflow-integration">Tensorflow Integration</h2>
<p>Now that the chat application is up and running, we can now incorporate Tensorflow in our app.</p>
<ul>
<li><p>Install relevant Tensorflow packages</p>
<pre><code class="lang-bash">npm install @tensorflow/tfjs @tensorflow-models/toxicity
</code></pre>
</li>
<li><p>Open <code>src/components/Input.js</code></p>
</li>
<li><p>Import the load method from the Toxicity model.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Input.js</span>
<span class="hljs-keyword">import</span> { load } <span class="hljs-keyword">from</span> <span class="hljs-string">"@tensorflow-models/toxicity"</span>;
</code></pre>
</li>
<li><p>Inside the functional component, add the following states.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Input.js</span>
<span class="hljs-keyword">const</span> [isToxic, setIsToxic] = useState(<span class="hljs-literal">false</span>);
<span class="hljs-keyword">const</span> [isClassifying, setIsClassifying] = useState(<span class="hljs-literal">false</span>);
<span class="hljs-keyword">const</span> [hasLoaded, setHasLoaded] = useState(<span class="hljs-literal">false</span>);
</code></pre>
<ul>
<li><p><code>isToxic</code>: variable to contain the toxicity assessment from model</p>
</li>
<li><p><code>isClassifying</code>: variable to keep track of the classification process</p>
</li>
<li><p><code>hasLoaded</code>: variable to keep track whether the model has loaded</p>
</li>
</ul>
</li>
<li><p>Inside the functional component, insert the useRef hook.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Input.js</span>
<span class="hljs-keyword">const</span> model = useRef(<span class="hljs-literal">null</span>);
</code></pre>
<ul>
<li><code>model</code>: retain the Tensorflow model that will persist for the full lifetime of the Input component</li>
</ul>
</li>
<li><p>Inside the functional component, insert the useEffect hook.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Input.js</span>
useEffect(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loadModel</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> threshold = <span class="hljs-number">0.9</span>;
    model.current = <span class="hljs-keyword">await</span> load(threshold);
    setHasLoaded(<span class="hljs-literal">true</span>);
  }
  loadModel();
}, []);
</code></pre>
<ul>
<li><p>Inside the useEffect hook, we load the model through the <code>load</code> method from Tensorflow, which accepts an optional parameter <code>threshold</code>. Its default value is <code>0.85</code>, but we will tweak it to <code>0.9</code>.</p>
</li>
<li><p>The <code>load</code> method also loads the topology and weights, and returns a Promise which is resolved with the model.</p>
<blockquote>
<p><strong>Topology</strong>: a file describing the architecture of a model (what operations it uses) and containing references to the model's weights which are stored externally.</p>
<p><strong>Weights</strong>: binary files containing the model's weights, usually stored in the same directory as topology.</p>
<p>Source: <a target="_blank" href="https://www.tensorflow.org/js/guide/save_load">Tensorflow</a></p>
</blockquote>
</li>
</ul>
</li>
<li><p>Inside the functional component, add the following code at the top of the <code>handleSend</code> method.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Input.js</span>

<span class="hljs-comment">// Set state variables</span>
setIsSending(<span class="hljs-literal">true</span>);
setIsClassifying(<span class="hljs-literal">true</span>);

<span class="hljs-keyword">const</span> predictions = <span class="hljs-keyword">await</span> model.current.classify([text]);
setIsClassifying(<span class="hljs-literal">false</span>);

<span class="hljs-keyword">const</span> toxicityResult = predictions[<span class="hljs-number">6</span>].results[<span class="hljs-number">0</span>].match;

<span class="hljs-comment">// Set the state variable with the final prediction result</span>
setIsToxic(toxicityResult);

<span class="hljs-keyword">if</span> (!toxicityResult) {
  <span class="hljs-comment">// Move the message sending code here</span>
}
</code></pre>
<ul>
<li><p>The <code>classify</code> method takes a parameter of a string array to be evaluated to predict the toxicity. It returns a Promise that is resolved with a <code>predictions</code> array.</p>
</li>
<li><p>The <code>predictions</code> array is an array of objects containing the probabilities for each label. A label is what the TensorFlow model can provide predictions for: <code>identity_attack</code>, <code>insult</code>, <code>obscene</code>, <code>severe_toxicity</code>, <code>sexual_explicit</code>, <code>threat</code>, and <code>toxicity</code>. For each toxicity label, there is an array of raw probabilities for each input sentence along with the final prediction. The final prediction can be any of the following:</p>
<ul>
<li><code>true</code> if the probability of a match exceeds the confidence threshold,</li>
<li><code>false</code> if the probability of <em>not</em> a match exceeds the confidence threshold, and</li>
<li><code>null</code> if neither probability exceeds the threshold.</li>
</ul>
</li>
<li><p>We will be getting the final prediction value from the <code>toxicity</code> label, which is the seventh item in the array, hence <code>predictions[6].results[0].match</code>.</p>
</li>
</ul>
</li>
<li><p>We are done with incorporating the TensorFlow model in our code! The next step would be to use the prediction result to show a reminder or not.</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// Input.js</span>

{
  isToxic &amp;&amp; <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ChatReminder</span>&gt;</span>Pls be kind.<span class="hljs-tag">&lt;/<span class="hljs-name">ChatReminder</span>&gt;</span></span>;
}
</code></pre>
</li>
</ul>
<p>That is it! If a user attempts to send a toxic message, it will filtered out by the machine learning model and will not be sent. A more positive space has now been created 🌱.</p>
<h2 id="heading-next-steps">Next steps</h2>
<p>While this is an exciting project, running the model and its classification process in the browser's main thread might pose some blockages in the application. I will be looking into the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">Web Workers API - Web APIs | MDN</a> to separate the model's processing logic.</p>
<p>Here are some useful links that you may want to check out:</p>
<ul>
<li><a target="_blank" href="https://github.com/gmlunesa/notox">Notox Source Code</a></li>
<li><a target="_blank" href="https://github.com/gmlunesa/techst/">Techst</a></li>
<li><a target="_blank" href="https://www.tensorflow.org/js">TensorFlowJS</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[One Year of .NET 6: My Top Favorite Features]]></title><description><![CDATA[As we approach the first anniversary of the .NET 6 general launch (originally released last November 8, 2021), I thought I would share my favorite…]]></description><link>https://blog.gmlunesa.com/one-year-net-6-my-top-favorite</link><guid isPermaLink="true">https://blog.gmlunesa.com/one-year-net-6-my-top-favorite</guid><category><![CDATA[.NET]]></category><category><![CDATA[dotnet]]></category><dc:creator><![CDATA[Goldy Mariz Lunesa 🇵🇭]]></dc:creator><pubDate>Fri, 04 Nov 2022 09:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1673322143490/YRDnXxykw.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As we approach the first anniversary of the .NET 6 general launch (originally released last November 8, 2021), I thought I would share my favorite additions to the latest and greatest ;) version of .NET 6. Let's review the goals of .NET 6. If we take a look at Microsoft's initiatives available in this <a target="_blank" href="https://themesof.net/query?q=group%3Atheme%20is%3Aopen%20-is%3Atask%20-is%3Abottomup%20%28no%3Amilestone%20or%20milestone%3A%3E%3D6.0%20milestone%3A%3C7.0%29">site</a>, the .NET 6 release aimed to accomplish the following:</p>
<ul>
<li>Appeal to net-new developers, students and new technologists</li>
<li>Provide a great client app development experience</li>
<li>Get recognized as compelling framework for building cloud native apps</li>
<li>Improve startup and throughput using runtime execution information</li>
<li>Grow the .NET ecosystem through increased Quality, Confidence and Support</li>
<li>Meet Developer Expectations</li>
</ul>
<h2 id="heading-c-10">C# 10</h2>
<p>Alongside .NET 6, Microsoft also launched the newest version of C#, which is C# 10. It introduces new language features, such as global usings (which I wrote about <a target="_blank" href="https://gmlunesa.com/blog/net-6-global-using-directives">here</a>), file-scoped namespaces, extended property patterns, null argument checks, lambda improvements to name a few. The <a target="_blank" href="https://devblogs.microsoft.com/dotnet/welcome-to-csharp-10/">Microsoft blog</a> goes in much more detail about the brand new additions.</p>
<h2 id="heading-minimal-apis">Minimal APIs</h2>
<p>The ASP.NET team rolled out the Minimal APIs, which are a straightforward way to create HTTP APIs with minimal dependencies. Minimal APIs hook into ASP.NET Core’s hosting and routing capabilities and allow developers to create fully functioning APIs with just a few lines of code. Hence, they are recommended for everyone who wants to build microservices and apps but only want to include a minimum number of files and dependencies in ASP.NET Core.</p>
<p>With Minimal APIs, we can build an API with just <strong>3 lines of code</strong>.</p>
<pre><code class="lang-cs"><span class="hljs-keyword">var</span> app = WebApplication.Create(args);

app.MapGet(<span class="hljs-string">"/"</span>, () =&gt; <span class="hljs-string">"Hello World!"</span>);

app.Run();
</code></pre>
<p>This structure is very reminiscent of the <a target="_blank" href="https://expressjs.com/en/starter/hello-world.html">Express app model</a>. This is also a great way for newbies or devs from JS background to get into .NET in general.</p>
<h2 id="heading-hot-reload">Hot Reload</h2>
<p>Developers from other spaces, particularly in the front-end ecosystem, are already familiar with the concept of Hot Reload— save a file and see the changes almost instantaneously. Admittedly, establishing hot reload with a statically typed language is exponentially more complex compared to a traditionally interpreted language like JavaScript, so this feature had a long time coming along.</p>
<p>Finally, with .NET 6, developers can modify the apps managed source code while the application is running, eliminating the need to manually pause, hit a breakpoint or restart as a whole. Personally it still has some bugs here and there but overall it has improved my productivity when developing .NET apps or in other terms, my developer inner-loop performance!</p>
<h2 id="heading-simplified-http-logging">Simplified HTTP logging</h2>
<p>.NET 6 introduced the HTTP Logging middleware for ASP.NET Core applications that logs information about incoming HTTP requests and HTTP responses, like:</p>
<ul>
<li>HTTP request information</li>
<li>Common properties</li>
<li>Headers</li>
<li>Body</li>
<li>HTTP response information</li>
</ul>
<p>To enabled the said middleware, just add the following code:</p>
<pre><code class="lang-cs"><span class="hljs-keyword">var</span> builder = WebApplication.CreateBuilder(args);

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

<span class="hljs-comment">// Add this code</span>
app.UseHttpLogging();
</code></pre>
<p>This feature is really useful and replaces the custom middleware, libraries, or solutions we had to use to log simple HTTP requests before. However, HTTP Logging <em><strong>can reduce the performance of an app</strong></em>. The following needs to be considered to factor in performance impact:</p>
<ul>
<li>Filter which parts of the request and/or response to log.</li>
<li>Filter which headers to log.</li>
<li>Filter which information about incoming requests and/or responses to log.</li>
<li>Avoid logging sensitive data such as personally identifiable information (PII).</li>
<li>Test the performance impact of selected logging properties.</li>
</ul>
<h2 id="heading-remarks">Remarks</h2>
<p>The new LTS version of .NET looks promising, both in the newly introduced features and benchmarks. I've had a great experience with it so far, I haven't encountered any major bug or issue. The Microsoft documentation is also very reliable which makes things definitely easier.</p>
<p>Microsoft is rolling out a new .NET version, .NET 7 (STS) on the 8th of November 2022! Details are available at <a target="_blank" href="https://www.dotnetconf.net/">.NET Conf website</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Building a cross platform application with .NET MAUI]]></title><description><![CDATA[In today's blog, we will be creating a simple cross-platform application with .NET MAUI. I'll be providing a general walk-through and useful resources so…]]></description><link>https://blog.gmlunesa.com/building-a-cross-platform-application</link><guid isPermaLink="true">https://blog.gmlunesa.com/building-a-cross-platform-application</guid><category><![CDATA[.NET]]></category><category><![CDATA[dotnet]]></category><category><![CDATA[#dotnet-maui]]></category><category><![CDATA[Android]]></category><dc:creator><![CDATA[Goldy Mariz Lunesa 🇵🇭]]></dc:creator><pubDate>Wed, 19 Oct 2022 09:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1673322152243/_jI9FMPOm.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In today's blog, we will be creating a simple cross-platform application with .NET MAUI. I'll be providing a general walk-through and useful resources so you can build your own app as well!</p>
<p>
  <img src="https://raw.githubusercontent.com/gmlunesa/gmlunesa.github.io/development/src/blog/building-a-cross-platform-application/images/mockup.png" alt=".NET MAUI app mockup" class="small-img" />
</p>


<p>The app, which I called ChooseDay, shows different types of recommended themed days. It retrieves data from a server and displays them accordingly. With .NET MAUI, this runs on Android, Windows, iOS and Mac (although I haven't personally tested with the last two since I don't have an Apple device).</p>
<h2 id="heading-introduction">Introduction</h2>
<p>I heard some buzz about .NET MAUI a couple of months ago during the .NET Conf: Focus on MAUI last August. However, I haven't really taken a closer look about it until coming across <a target="_blank" href="https://www.youtube.com/c/JamesMontemagno">James Montemagno</a>'s Youtube channel. I downloaded the .NET Multi-platform App UI development workload in my VS2022, started coding and got honestly impressed with how easy and seamless it was to set up an app that could run across multiple platforms!</p>
<h3 id="heading-about-net-maui">About .NET MAUI</h3>
<p>.NET Multi-platform App UI, or .NET MAUI in short, is cross-platform framework from Microsoft for creating native mobile and desktop apps with C# and XAML. Through .NET MAUI, we can write and develop apps that can run on Android, iOS, macOS, and Windows all from a single shared code-base. Through this, elements like UI layout and design, tests and business logic for different platforms that you or your organization supports are unified and consolidated. <em>Write once, run anywhere</em>. How powerful is that?</p>
<h3 id="heading-supported-platforms">Supported platforms</h3>
<ul>
<li>Android 5.0 (API 21) or higher</li>
<li>iOS 10 or higher</li>
<li>macOS 10.13 or higher (using Mac Catalyst)</li>
<li>Windows desktop and UWP, using WinUI 3</li>
<li>Tizen, supported by Samsung</li>
<li>Linux, supported by the community</li>
</ul>
<h3 id="heading-native-performance">Native performance</h3>
<ul>
<li>.NET MAUI for Android performs just-in-time (JIT) compilation to a native assembly.</li>
<li>.NET MAUI for iOS does full ahead-of-time (AOT) compilation to produce a native ARM assembly code.</li>
<li>.NET MAUI for macOS apps utilizes Mac Catalyst and supplements with additional AppKit and platform APIs.</li>
<li>.NET MAUI for Windows uses the Windows UI 3 (WinUI 3) library.</li>
</ul>
<h2 id="heading-setup">Setup</h2>
<p>Let's go through the setup and installation part. Please take note that I am using my Windows machine for this blog's tutorial.</p>
<h3 id="heading-creating-our-project">Creating our project</h3>
<p>To start developing, we would need to have <a target="_blank" href="https://visualstudio.microsoft.com/vs/">Visual Studio 2022</a>. Using the Visual Studio Installer, please select the <strong>.NET Multi-platform App UI development</strong> workload and install accordingly.</p>
<p>
  <img src="https://raw.githubusercontent.com/gmlunesa/gmlunesa.github.io/development/src/blog/building-a-cross-platform-application/images/setup.png" alt="VS2022 MAUI workload setup" class="small-img" />
</p>

<p>Let's now create a new project to get everything ready.</p>
<ul>
<li>Open <strong>Visual Studio 2022</strong>.</li>
<li>Click the <strong>Create a new project</strong> button.</li>
<li>In the <strong>All project types</strong> drop-down, select <strong>MAUI</strong>.</li>
<li>Click the <strong>.NET MAUI App</strong> template and press <strong>Next</strong>.</li>
</ul>
<p>
  <img src="https://raw.githubusercontent.com/gmlunesa/gmlunesa.github.io/development/src/blog/building-a-cross-platform-application/images/newproject.png" alt="Create a new project." class="small-img" />
</p>

<ul>
<li>Please configure your project accordingly (Project name, location and solution name).</li>
<li>Please choose at least <strong>.NET 6.0</strong> as the framework.</li>
</ul>
<p>⚠️ Upon creating a project, you may encounter a Windows Security Alert that contains a warning regarding the firewall blocking some features. Please select <strong>Allow access</strong>.</p>
<h3 id="heading-first-test-run">First test run</h3>
<p>Let's do a test run on our first ever MAUI app. In the Visual Studio toolbar, please press the <strong>Windows Machine</strong> button to build and run the app. It is set as the default debug target.</p>
<p>
  <img src="https://raw.githubusercontent.com/gmlunesa/gmlunesa.github.io/development/src/blog/building-a-cross-platform-application/images/windows_machine.png" alt="Windows Machine debug." class="small-img" />
</p>

<p>Ta-da! Our first cross-platform app using .NET MAUI is up and running. I am using Windows dark theme hence the color.</p>
<p>
  <img src="https://raw.githubusercontent.com/gmlunesa/gmlunesa.github.io/development/src/blog/building-a-cross-platform-application/images/running_firsttime.png" alt="First test run on Windows." class="small-img" />
</p>

<p>⚠️ If Developer Mode is not yet enabled on your machine, you may encounter an <strong>Enable Developer Mode for Windows</strong> dialog. Please follow the instructions accordingly.</p>
<p>We can also run this using an Android emulator. To do so, please click the debug target drop-down menu, and select <strong>net6.0-android</strong> under <strong>Framework</strong>.</p>
<p>
  <img src="https://raw.githubusercontent.com/gmlunesa/gmlunesa.github.io/development/src/blog/building-a-cross-platform-application/images/android_framework.png" alt="Choosing Android framework." class="small-img" />
</p>

<p>⚠️ If you haven't accepted the Android SDK license yet, please check the <strong>Error List</strong> window. You may see an error detailing that the Android Sdk licenses must be accepted. Please accept accordingly.</p>
<p>You'll see the Android Emulator selected in the debug target drop-down menu if this is your first time building a .NET MAUI app. Please click the button. A <strong>New Device</strong> window will open and will guide you through the download and setup of an emulator image.</p>
<p>
  <img src="https://raw.githubusercontent.com/gmlunesa/gmlunesa.github.io/development/src/blog/building-a-cross-platform-application/images/adm.png" alt="Android Device Manager" class="small-img" />
</p>

<p>After successfully downloading and setting up an emulator image, you may now select it as the debug target.</p>
<p>
  <img src="https://raw.githubusercontent.com/gmlunesa/gmlunesa.github.io/development/src/blog/building-a-cross-platform-application/images/pixel_machine.png" alt="Android debug target." class="small-img" />
</p>

<p>Our app will now run in the Android emulator! Please take note that it may take a while during the first time.</p>
<p>
  <img src="https://raw.githubusercontent.com/gmlunesa/gmlunesa.github.io/development/src/blog/building-a-cross-platform-application/images/running_firsttime_android.png" alt="First test run on Android." class="small-img" />
</p>

<p>If you have any questions in the installation and setup, please check this <a target="_blank" href="https://dotnet.microsoft.com/en-us/learn/maui/first-app-tutorial/intro">Microsoft tutorial</a>.</p>
<h3 id="heading-project-structure">Project structure</h3>
<p>Let's briefly cover the default files in our starter project.</p>
<p>📄 <strong>App.xaml</strong>: Contains the application resources that the app will use in the XAML layout.</p>
<p>📄 <strong>App.xaml.cs</strong> - Defines the App class which represents the application at runtime.</p>
<p>📄 <strong>AppShell.xaml</strong> - Contains the main structure of a .NET MAUI application.<strong>MainPage.xaml</strong> - Contains the user interface definition.</p>
<p>📄 <strong>MainPage.xaml.cs</strong> - Defines the logic for event handlers and actions triggered by the controls on the related page.</p>
<p>📄 <strong>MauiProgram.cs</strong> - Enables the app to be initialized in a single entry position.</p>
<p>📁 <strong>/Platforms</strong> - Contains initialization code files and resources for different supported platforms.</p>
<p>📁 <strong>/Resources</strong> - Contains application resources that define default styles and colors for each built-in control of .NET MAUI.</p>
<p>You may also refer to the official <a target="_blank" href="https://learn.microsoft.com/en-us/training/modules/build-mobile-and-desktop-apps/3-create-a-maui-project-visual-studio#net-maui-project-structure-and-application-startup">Microsoft training documentation</a> for more information.</p>
<h2 id="heading-coding">Coding</h2>
<p>Now that we have covered the basics, it is now time to code!</p>
<h3 id="heading-dependencies">Dependencies</h3>
<p>In this project, we will be using the Model-View-ViewModel (MVVM) design pattern. Please install <strong>CommunityToolkit.Mvvm</strong> via Nuget.</p>
<p>
  <img src="https://raw.githubusercontent.com/gmlunesa/gmlunesa.github.io/development/src/blog/building-a-cross-platform-application/images/nuget_mvvm.png" alt="First test run on Android." class="small-img" />
</p>

<h3 id="heading-model">Model</h3>
<p>Let's make a class to represent the Day object, which will contain the details of each of the themed days.</p>
<ul>
<li>Create folder called <code>Models</code>.</li>
<li>Create a file called <code>Day.cs</code> inside the newly created <code>Models</code> folder.</li>
<li>Copy and paste the following.</li>
</ul>
<pre><code class="lang-cs"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Day</span>
{
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Name { <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> List&lt;<span class="hljs-keyword">string</span>&gt; Activities { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
  <span class="hljs-keyword">public</span> Uri Image { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}
</code></pre>
<h3 id="heading-services">Services</h3>
<p>Let's create a service that will contain our retrieval of data from the server.</p>
<ul>
<li>Create folder called <code>Services</code>.</li>
<li>Create a file called <code>MyDayService.cs</code> inside the newly created <code>Services</code> folder.</li>
<li>Copy and paste the following.</li>
</ul>
<pre><code class="lang-cs"><span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;summary&gt;</span></span>
<span class="hljs-comment"><span class="hljs-doctag">///</span> This service will handle HTTP requests to retrieve data from the cloud</span>
<span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;/summary&gt;</span></span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">MyDayService</span>
{
  HttpClient httpClient;
  List&lt;Day&gt; days = <span class="hljs-keyword">new</span>();

  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">MyDayService</span>(<span class="hljs-params"></span>)</span>
  {
    httpClient = <span class="hljs-keyword">new</span> HttpClient();
  }

  <span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;List&lt;Day&gt;&gt; GetDays()
  {
    <span class="hljs-keyword">if</span> (days?.Count &gt; <span class="hljs-number">0</span>)
      <span class="hljs-keyword">return</span> days;

    <span class="hljs-keyword">var</span> url = <span class="hljs-string">"https://gist.githubusercontent.com/gmlunesa/e90fe9869419f02952352b764bde54da/raw/721d211fc6d91c1bbb3f67baec8de87088ab3222/chooseday.json"</span>;

    <span class="hljs-keyword">var</span> response = <span class="hljs-keyword">await</span> httpClient.GetAsync(url);

    <span class="hljs-keyword">if</span> (response.IsSuccessStatusCode)
    {
      days = <span class="hljs-keyword">await</span> response.Content.ReadFromJsonAsync&lt;List&lt;Day&gt;&gt;();
    }

    <span class="hljs-keyword">return</span> days;
  }
}
</code></pre>
<p><strong>🔎 Code Notes</strong></p>
<ul>
<li>Inside of our newly created <code>MyDayService</code>, we created an <code>HttpClient</code> that does an API call to our data source.</li>
<li>We then deserialize the data into a list of <code>Day</code> objects in the <code>GetDays</code> method.</li>
</ul>
<h3 id="heading-viewmodels">ViewModels</h3>
<p>Let's create our <em>Viewmodels</em>, which will act as the intermediary between the views and the model. We will be implementing the MVVM pattern to perform data binding from properties between visual objects in the views and the underlying data. You may refer to the <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/maui/xaml/fundamentals/mvvm">official Microsoft documentation</a> for more information about the topic.</p>
<p>The .NET Community Toolkit offers the <code>CommunityToolkit.Mvvm</code> library (currently v8.0.0 as of time of writing) with source generators that automatically produces code that used to be manually written. This greatly simplifies our implementation of the MVVM pattern in our project. Since we already installed it in the previous steps, we can now use it in our code.</p>
<ul>
<li>Create folder called <code>ViewModels</code>.</li>
<li>Create a file called <code>BaseViewModel.cs</code> inside the newly created <code>ViewModels</code> folder. This will be our common view model for the app pages.</li>
<li>Copy and paste the following.</li>
</ul>
<pre><code class="lang-cs"><span class="hljs-keyword">public</span> <span class="hljs-keyword">partial</span> <span class="hljs-keyword">class</span> <span class="hljs-title">BaseViewModel</span> : <span class="hljs-title">ObservableObject</span>
{
  <span class="hljs-comment">// Using the ObservableObject available from the CommunityToolkit.Mvvm,</span>
  <span class="hljs-comment">// INotifyPropertyChanged implementation is already automatically generated.</span>
  [<span class="hljs-meta">ObservableProperty</span>]
  [<span class="hljs-meta">NotifyPropertyChangedFor(nameof(IsNotBusy))</span>]
  <span class="hljs-keyword">bool</span> isBusy;

  [<span class="hljs-meta">ObservableProperty</span>]
  <span class="hljs-keyword">string</span> title;

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

  }

  <span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> IsNotBusy =&gt; !IsBusy;

}
</code></pre>
<p><strong>🔎 Code Notes</strong></p>
<ul>
<li>Our <code>BaseViewModel</code> implements the <code>ObservableObject</code> base class available from the <code>CommunityToolkit.Mvvm</code>, which automatically generates the <code>INotifyPropertyChanged</code> implementation.</li>
<li>We have also added the <code>ObservableProperty</code> attribute to our two fields, <code>isBusy</code> and <code>title</code>, to expose them.</li>
<li>The <code>NotifyPropertyChangedFor</code> attribute will notify the field <code>IsNotBusy</code> when the value of <code>isBusy</code> changes.</li>
</ul>
<p>Let us now create our main viewmodel, which inherits the <code>BaseViewModel</code>.</p>
<ul>
<li>Create a file called <code>MyDaysViewModel.cs</code> inside the newly <code>ViewModels</code> folder.</li>
<li>Copy and paste the following.</li>
</ul>
<pre><code class="lang-cs"><span class="hljs-keyword">public</span> <span class="hljs-keyword">partial</span> <span class="hljs-keyword">class</span> <span class="hljs-title">MyDaysViewModel</span> : <span class="hljs-title">BaseViewModel</span>
{
  MyDayService myDayService;

  <span class="hljs-comment">// ObservableCollection is used since it has built-in support to raise CollectionChanged</span>
  <span class="hljs-comment">// OnPropertyChanged does not need to be called</span>
  <span class="hljs-keyword">public</span> ObservableCollection&lt;Day&gt; MyDays { <span class="hljs-keyword">get</span>; } = <span class="hljs-keyword">new</span>();

  <span class="hljs-comment">// Inject MyDayService through the constructor</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">MyDaysViewModel</span>(<span class="hljs-params">MyDayService myDayService</span>)</span>
  {
    Title = <span class="hljs-string">"ChooseDay by gmlunesa"</span>;
    <span class="hljs-keyword">this</span>.myDayService = myDayService;
  }

  <span class="hljs-comment">// RelayCommand enables us to bind the command and data between the viewmodel and view</span>
  <span class="hljs-comment">// Generates GetMyDaysCommand automatically</span>
  [<span class="hljs-meta">RelayCommand</span>]
  <span class="hljs-function"><span class="hljs-keyword">async</span> Task <span class="hljs-title">GetMyDaysAsync</span>(<span class="hljs-params"></span>)</span>
  {
    <span class="hljs-keyword">if</span> (IsBusy)
      <span class="hljs-keyword">return</span>;

    <span class="hljs-comment">// Toggle IsBusy to true when making calls to the server</span>
    <span class="hljs-comment">// False when finished with the call to the server</span>
    <span class="hljs-keyword">try</span>
    {
      IsBusy = <span class="hljs-literal">true</span>;

      <span class="hljs-comment">// Retrieve data from the server through the MyDayService</span>
      <span class="hljs-keyword">var</span> days = <span class="hljs-keyword">await</span> myDayService.GetDays();

      <span class="hljs-keyword">if</span>(MyDays.Count != <span class="hljs-number">0</span>)
        MyDays.Clear();

      <span class="hljs-keyword">foreach</span>(<span class="hljs-keyword">var</span> day <span class="hljs-keyword">in</span> days)
        MyDays.Add(day);
    }
    <span class="hljs-keyword">catch</span> (Exception ex)
    {
      Debug.WriteLine(ex);
      <span class="hljs-keyword">await</span> Shell.Current.DisplayAlert(<span class="hljs-string">"Error!"</span>, <span class="hljs-string">"Unable to get days."</span>, <span class="hljs-string">"OK"</span>);
    }
    <span class="hljs-keyword">finally</span>
    {
      IsBusy = <span class="hljs-literal">false</span>;
    }
  }
}
</code></pre>
<p><strong>🔎 Code Notes</strong></p>
<ul>
<li>We created an <code>ObservableCollection</code> of <code>Day</code> objects. We specifically use <code>ObservableCollection</code> since it has built-in support to raise <code>CollectionChanged</code>, so <code>OnPropertyChanged</code> does not need to be called.</li>
<li>We also inject the <code>MyDayService</code> we created earlier through the constructor.</li>
<li>In the method <code>GetMyDaysAsync</code>, we use the <code>MyDayService</code> to get the data and save it in the <code>ObservableCollection</code>.</li>
<li>We also set the <code>IsBusy</code> field to true when making the server call, then to false afterwards.</li>
<li>The <code>RelayCommand</code> attribute from <code>CommunityToolkit.Mvvm</code> is added to the <code>GetMyDaysAsync</code> method. This generates <code>GetMyDaysCommand</code> automatically and enables us to bind the <code>GetMyDaysCommand</code> and data between the viewmodel and view.</li>
</ul>
<h3 id="heading-register-dependencies">Register Dependencies</h3>
<p>We need to register our newly created service and viewmodel as dependencies.</p>
<ul>
<li>Open the <code>MauiProgram.cs</code> file.</li>
<li>Copy and paste the following code before the builder calls the <code>Build()</code> method.</li>
</ul>
<pre><code class="lang-cs">builder.Services.AddSingleton&lt;MyDayService&gt;();
builder.Services.AddSingleton&lt;MyDaysViewModel&gt;();
builder.Services.AddSingleton&lt;MainPage&gt;();
</code></pre>
<ul>
<li>Your <code>MauiProgram</code> class should look like this.</li>
</ul>
<pre><code class="lang-cs"><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;()
      .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>);
      });

    builder.Services.AddSingleton&lt;MyDayService&gt;();
    builder.Services.AddSingleton&lt;MyDaysViewModel&gt;();
    builder.Services.AddSingleton&lt;MainPage&gt;();

    <span class="hljs-keyword">return</span> builder.Build();
  }
}
</code></pre>
<p><strong>🔎 Code Notes</strong></p>
<ul>
<li>We registered <code>MyDayService</code>, <code>MyDaysViewModel</code>, <code>MainPage</code> as <em>Singletons</em>, which means that they will only be instantiated once throughout the app lifecycle.</li>
</ul>
<p>Next, we need to inject the <code>MyDaysViewModel</code> into the <code>MainPage</code>.</p>
<ul>
<li>Open the <code>MainPage.xaml.cs</code> file.</li>
<li>Insert the following code to the constructor.</li>
</ul>
<pre><code class="lang-cs"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">MainPage</span>(<span class="hljs-params">MyDaysViewModel viewModel</span>)</span>
{
  InitializeComponent();

  <span class="hljs-comment">// Inject view model to the main page</span>
  BindingContext = viewModel;

}
</code></pre>
<h3 id="heading-ui">UI</h3>
<p>Most of the backend part has already been configured! Let's now work on the user interface.</p>
<p>I first added some additional fonts to our project to add some dimension. Please download the font files from these locations:</p>
<ul>
<li><a target="_blank" href="https://github.com/gmlunesa/ChooseDay/raw/master/ChooseDay/Resources/Fonts/OpenSans-Bold.ttf">OpenSans-Bold</a></li>
<li><a target="_blank" href="https://github.com/gmlunesa/ChooseDay/raw/master/ChooseDay/Resources/Fonts/OpenSans-LightItalic.ttf">OpenSans-LightItalic.ttf</a></li>
</ul>
<p>After downloading, place these files in <code>/Resources/Fonts</code>.</p>
<p>We can now focus on the XAML files.</p>
<p>First, let's define custom styles for our application. Please note that you can also edit <code>/Resources/Styles/Styles.xaml</code> directly. I'm just doing these extra steps so I'll have some experience.</p>
<ul>
<li>Create a new file <code>CustomStyles.xaml</code> inside the <code>/Resources/Styles</code> folder.</li>
<li>Copy and paste the following.</li>
</ul>
<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">?xaml-comp</span> <span class="hljs-attr">compile</span>=<span class="hljs-string">"true"</span> ?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">ResourceDictionary</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>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">Color</span> <span class="hljs-attr">x:Key</span>=<span class="hljs-string">"Primary"</span>&gt;</span>#BE123C<span class="hljs-tag">&lt;/<span class="hljs-name">Color</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Color</span> <span class="hljs-attr">x:Key</span>=<span class="hljs-string">"Rose300Accent"</span>&gt;</span>#FDA4AF<span class="hljs-tag">&lt;/<span class="hljs-name">Color</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">Color</span> <span class="hljs-attr">x:Key</span>=<span class="hljs-string">"LightBackground"</span>&gt;</span>#F3F6F4<span class="hljs-tag">&lt;/<span class="hljs-name">Color</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Color</span> <span class="hljs-attr">x:Key</span>=<span class="hljs-string">"DarkBackground"</span>&gt;</span>#212121<span class="hljs-tag">&lt;/<span class="hljs-name">Color</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">Style</span> <span class="hljs-attr">TargetType</span>=<span class="hljs-string">"Shell"</span> <span class="hljs-attr">ApplyToDerivedTypes</span>=<span class="hljs-string">"True"</span>&gt;</span><span class="xml">
        <span class="hljs-tag">&lt;<span class="hljs-name">Setter</span> <span class="hljs-attr">Property</span>=<span class="hljs-string">"Shell.BackgroundColor"</span> <span class="hljs-attr">Value</span>=<span class="hljs-string">"{AppThemeBinding Light={StaticResource Primary}, Dark={StaticResource Gray950}}"</span> /&gt;</span>
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">Style</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">Style</span> <span class="hljs-attr">TargetType</span>=<span class="hljs-string">"Page"</span> <span class="hljs-attr">ApplyToDerivedTypes</span>=<span class="hljs-string">"True"</span>&gt;</span><span class="xml">
        <span class="hljs-tag">&lt;<span class="hljs-name">Setter</span> <span class="hljs-attr">Property</span>=<span class="hljs-string">"BackgroundColor"</span>
                <span class="hljs-attr">Value</span>=<span class="hljs-string">"{AppThemeBinding Light={StaticResource LightBackground}, Dark={StaticResource DarkBackground}}"</span> /&gt;</span>
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">Style</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">Style</span> <span class="hljs-attr">ApplyToDerivedTypes</span>=<span class="hljs-string">"True"</span> <span class="hljs-attr">TargetType</span>=<span class="hljs-string">"NavigationPage"</span>&gt;</span><span class="xml">
        <span class="hljs-tag">&lt;<span class="hljs-name">Setter</span> <span class="hljs-attr">Property</span>=<span class="hljs-string">"BackgroundColor"</span> <span class="hljs-attr">Value</span>=<span class="hljs-string">"{AppThemeBinding Light={StaticResource LightBackground}, Dark={StaticResource DarkBackground}}"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Setter</span> <span class="hljs-attr">Property</span>=<span class="hljs-string">"BarBackgroundColor"</span> <span class="hljs-attr">Value</span>=<span class="hljs-string">"{StaticResource Primary}"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Setter</span> <span class="hljs-attr">Property</span>=<span class="hljs-string">"BarTextColor"</span> <span class="hljs-attr">Value</span>=<span class="hljs-string">"White"</span> /&gt;</span>
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">Style</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">Style</span> <span class="hljs-attr">x:Key</span>=<span class="hljs-string">"ButtonOutline"</span> <span class="hljs-attr">TargetType</span>=<span class="hljs-string">"Button"</span>&gt;</span><span class="xml">
        <span class="hljs-tag">&lt;<span class="hljs-name">Setter</span> <span class="hljs-attr">Property</span>=<span class="hljs-string">"FontFamily"</span> <span class="hljs-attr">Value</span>=<span class="hljs-string">"OpenSansSemibold"</span>/&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Setter</span> <span class="hljs-attr">Property</span>=<span class="hljs-string">"Background"</span> <span class="hljs-attr">Value</span>=<span class="hljs-string">"{AppThemeBinding Light={StaticResource LightBackground}, Dark={StaticResource DarkBackground}}"</span>/&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Setter</span> <span class="hljs-attr">Property</span>=<span class="hljs-string">"TextColor"</span> <span class="hljs-attr">Value</span>=<span class="hljs-string">"{AppThemeBinding Light={StaticResource Black}, Dark={StaticResource White}}"</span>/&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Setter</span> <span class="hljs-attr">Property</span>=<span class="hljs-string">"BorderColor"</span> <span class="hljs-attr">Value</span>=<span class="hljs-string">"{StaticResource Primary}"</span>/&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Setter</span> <span class="hljs-attr">Property</span>=<span class="hljs-string">"BorderWidth"</span> <span class="hljs-attr">Value</span>=<span class="hljs-string">"2"</span>/&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Setter</span> <span class="hljs-attr">Property</span>=<span class="hljs-string">"CornerRadius"</span> <span class="hljs-attr">Value</span>=<span class="hljs-string">"10"</span>/&gt;</span>
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">Style</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">Style</span> <span class="hljs-attr">x:Key</span>=<span class="hljs-string">"CardView"</span> <span class="hljs-attr">TargetType</span>=<span class="hljs-string">"Frame"</span>&gt;</span><span class="xml">
        <span class="hljs-tag">&lt;<span class="hljs-name">Setter</span> <span class="hljs-attr">Property</span>=<span class="hljs-string">"BorderColor"</span> <span class="hljs-attr">Value</span>=<span class="hljs-string">"Transparent"</span>/&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Setter</span> <span class="hljs-attr">Property</span>=<span class="hljs-string">"HasShadow"</span> <span class="hljs-attr">Value</span>=<span class="hljs-string">"True"</span>/&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Setter</span> <span class="hljs-attr">Property</span>=<span class="hljs-string">"Shadow"</span> <span class="hljs-attr">Value</span>=<span class="hljs-string">"2"</span>/&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Setter</span> <span class="hljs-attr">Property</span>=<span class="hljs-string">"Background"</span> <span class="hljs-attr">Value</span>=<span class="hljs-string">"{AppThemeBinding Light={StaticResource White}, Dark={StaticResource Black}}"</span>/&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Setter</span> <span class="hljs-attr">Property</span>=<span class="hljs-string">"CornerRadius"</span> <span class="hljs-attr">Value</span>=<span class="hljs-string">"3"</span>/&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Setter</span> <span class="hljs-attr">Property</span>=<span class="hljs-string">"IsClippedToBounds"</span> <span class="hljs-attr">Value</span>=<span class="hljs-string">"True"</span>/&gt;</span>
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">Style</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">ResourceDictionary</span>&gt;</span>
</code></pre>
<ul>
<li>Add a reference to the <code>CustomStyles.xaml</code> in the <code>App.xaml</code>.</li>
</ul>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">ResourceDictionary</span> <span class="hljs-attr">Source</span>=<span class="hljs-string">"Resources/Styles/CustomStyles.xaml"</span> /&gt;</span>
</code></pre>
<p>Let us now work on our <code>MainPage.xaml</code> file and see our backend in action.</p>
<p>ℹ️ To make our job easier, let us first delete all the code inside the <code>ContentPage</code> tag.</p>
<ul>
<li>Add <code>xmlns:viewmodels="clr-namespace:&lt;namespace&gt;.ViewModels"</code>, <code>xmlns:models="clr-namespace:&lt;namespace&gt;.Models"</code>, <code>x:DataType="viewmodels:MyDaysViewModel"</code> to the <code>ContentPage</code> tag. Through this compiled binding, we are specifying that this page will bind to the <code>MyDaysViewModel</code> directly. This will also enable Intellisense to assist us better and offers error checking and performance enhancements.</li>
</ul>
<pre><code class="lang-xml"><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:viewmodels</span>=<span class="hljs-string">"clr-namespace:ChooseDay.ViewModels"</span>
            <span class="hljs-attr">xmlns:models</span>=<span class="hljs-string">"clr-namespace:ChooseDay.Models"</span>
            <span class="hljs-attr">x:DataType</span>=<span class="hljs-string">"viewmodels:MyDaysViewModel"</span>
            <span class="hljs-attr">x:Class</span>=<span class="hljs-string">"ChooseDay.MainPage"</span>&gt;</span>
</code></pre>
<ul>
<li>Let's add the first data binding, specifically the <code>Title</code> property defined in our viewmodel.</li>
</ul>
<pre><code class="lang-xml"><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:viewmodels</span>=<span class="hljs-string">"clr-namespace:ChooseDay.ViewModels"</span>
            <span class="hljs-attr">xmlns:models</span>=<span class="hljs-string">"clr-namespace:ChooseDay.Models"</span>
            <span class="hljs-attr">x:DataType</span>=<span class="hljs-string">"viewmodels:MyDaysViewModel"</span>
            <span class="hljs-attr">x:Class</span>=<span class="hljs-string">"ChooseDay.MainPage"</span>
            <span class="hljs-attr">Title</span>=<span class="hljs-string">"{Binding Title}"</span>&gt;</span>
</code></pre>
<p>ℹ️ The next code modifications will be inside the <code>ContentPage</code> tag.</p>
<ul>
<li>Add a <code>Grid</code> inside the <code>ContentPage</code>. The grid will have 4 rows: for the title, for the subtitle, for the content, and then for the button area.</li>
</ul>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">Grid</span> <span class="hljs-attr">Padding</span>=<span class="hljs-string">"12"</span>
      <span class="hljs-attr">RowDefinitions</span>=<span class="hljs-string">"AUTO,AUTO,*,AUTO"</span>&gt;</span>
</code></pre>
<ul>
<li>Add the first two rows containing the content for our title and subtitle.</li>
</ul>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">HorizontalStackLayout</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">Label</span> <span class="hljs-attr">FontFamily</span>=<span class="hljs-string">"OpenSans-Bold"</span> <span class="hljs-attr">FontSize</span>=<span class="hljs-string">"24"</span> <span class="hljs-attr">Text</span>=<span class="hljs-string">"Your Days"</span> /&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">HorizontalStackLayout</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">Label</span> <span class="hljs-attr">FontFamily</span>=<span class="hljs-string">"OpenSans-LightItalic"</span>
        <span class="hljs-attr">FontSize</span>=<span class="hljs-string">"16"</span>
        <span class="hljs-attr">Text</span>=<span class="hljs-string">"Choose a theme day for yourself."</span>
        <span class="hljs-attr">TextColor</span>=<span class="hljs-string">"{AppThemeBinding Light={StaticResource Gray600}, Dark={StaticResource Gray100}}"</span>
        <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"1"</span> /&gt;</span>
</code></pre>
<ul>
<li>Let's add a <code>CollectionView</code> and set the <code>ItemsSource</code> to bind to our <code>ObservableCollection</code> of <code>Day</code> objects.</li>
</ul>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">CollectionView</span> <span class="hljs-attr">ItemsSource</span>=<span class="hljs-string">"{Binding MyDays}"</span>
                <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"2"</span>
                <span class="hljs-attr">Margin</span>=<span class="hljs-string">"0,14"</span>&gt;</span>


<span class="hljs-tag">&lt;/<span class="hljs-name">CollectionView</span>&gt;</span>
</code></pre>
<ul>
<li>Define the <code>ItemsLayout</code> inside the <code>CollectionView</code>.</li>
</ul>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">CollectionView</span> <span class="hljs-attr">ItemsSource</span>=<span class="hljs-string">"{Binding MyDays}"</span>
                <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"2"</span>
                <span class="hljs-attr">Margin</span>=<span class="hljs-string">"0,14"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">CollectionView.ItemsLayout</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">LinearItemsLayout</span> <span class="hljs-attr">Orientation</span>=<span class="hljs-string">"Vertical"</span>
                        <span class="hljs-attr">ItemSpacing</span>=<span class="hljs-string">"16"</span>/&gt;</span>

  <span class="hljs-tag">&lt;/<span class="hljs-name">CollectionView.ItemsLayout</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">CollectionView</span>&gt;</span>
</code></pre>
<ul>
<li>Add an <code>ItemTemplate</code> inside the <code>CollectionView</code>. This will be the design of each item in the list.</li>
</ul>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">CollectionView</span> <span class="hljs-attr">ItemsSource</span>=<span class="hljs-string">"{Binding MyDays}"</span>
                <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"2"</span>
                <span class="hljs-attr">Margin</span>=<span class="hljs-string">"0,14"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">CollectionView.ItemsLayout</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">LinearItemsLayout</span> <span class="hljs-attr">Orientation</span>=<span class="hljs-string">"Vertical"</span>
                          <span class="hljs-attr">ItemSpacing</span>=<span class="hljs-string">"16"</span>/&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">CollectionView.ItemsLayout</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">CollectionView.ItemTemplate</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">DataTemplate</span> <span class="hljs-attr">x:DataType</span>=<span class="hljs-string">"models:Day"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Frame</span> <span class="hljs-attr">HeightRequest</span>=<span class="hljs-string">"275"</span>
                  <span class="hljs-attr">Padding</span>=<span class="hljs-string">"0"</span>
                  <span class="hljs-attr">Style</span>=<span class="hljs-string">"{StaticResource CardView}"</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.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">ColumnDefinition</span> <span class="hljs-attr">Width</span>=<span class="hljs-string">"2*"</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">Source</span>=<span class="hljs-string">"{Binding Image}"</span>
                          <span class="hljs-attr">Aspect</span>=<span class="hljs-string">"AspectFill"</span> /&gt;</span>

                  <span class="hljs-tag">&lt;<span class="hljs-name">Grid</span> <span class="hljs-attr">Grid.Column</span>=<span class="hljs-string">"1"</span>
                        <span class="hljs-attr">Padding</span>=<span class="hljs-string">"16"</span>
                        <span class="hljs-attr">RowDefinitions</span>=<span class="hljs-string">"AUTO,AUTO,*"</span>&gt;</span>

                      <span class="hljs-tag">&lt;<span class="hljs-name">Label</span> <span class="hljs-attr">Text</span>=<span class="hljs-string">"{Binding Name}"</span>
                          <span class="hljs-attr">FontSize</span>=<span class="hljs-string">"20"</span>
                          <span class="hljs-attr">FontFamily</span>=<span class="hljs-string">"OpenSans-SemiBold"</span>/&gt;</span>


                      <span class="hljs-tag">&lt;<span class="hljs-name">FlexLayout</span> <span class="hljs-attr">BindableLayout.ItemsSource</span>=<span class="hljs-string">"{Binding Activities}"</span>
                              <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"1"</span>
                              <span class="hljs-attr">Wrap</span>=<span class="hljs-string">"Wrap"</span>
                              <span class="hljs-attr">AlignItems</span>=<span class="hljs-string">"Start"</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">Frame</span> <span class="hljs-attr">Padding</span>=<span class="hljs-string">"8"</span>
                                      <span class="hljs-attr">Margin</span>=<span class="hljs-string">"1"</span>
                                      <span class="hljs-attr">BorderColor</span>=<span class="hljs-string">"Transparent"</span>
                                      <span class="hljs-attr">BackgroundColor</span>=<span class="hljs-string">"{StaticResource Rose300Accent}"</span>&gt;</span>
                                      <span class="hljs-tag">&lt;<span class="hljs-name">Label</span> <span class="hljs-attr">Text</span>=<span class="hljs-string">"{Binding .}"</span>
                                              <span class="hljs-attr">TextColor</span>=<span class="hljs-string">"{StaticResource Gray900}"</span> /&gt;</span>
                                  <span class="hljs-tag">&lt;/<span class="hljs-name">Frame</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">FlexLayout</span>&gt;</span>

                      <span class="hljs-tag">&lt;<span class="hljs-name">Label</span> <span class="hljs-attr">Text</span>=<span class="hljs-string">"{Binding Description}"</span>
                          <span class="hljs-attr">TextColor</span>=<span class="hljs-string">"{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource Gray100}}"</span>
                          <span class="hljs-attr">Padding</span>=<span class="hljs-string">"0,20,0,0"</span>
                          <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"2"</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</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">Frame</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">CollectionView.ItemTemplate</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">CollectionView</span>&gt;</span>
</code></pre>
<ul>
<li>Add a <code>Button</code> inside our <code>Grid</code>. This will be the last row in the grid. Note that we are using the <code>GetMyDaysCommand</code> and <code>IsNotBusy</code> generated from the <code>MyDaysViewModel</code>.</li>
</ul>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">Button</span> <span class="hljs-attr">Text</span>=<span class="hljs-string">"Get Recommendations"</span>
        <span class="hljs-attr">Command</span>=<span class="hljs-string">"{Binding GetMyDaysCommand}"</span>
        <span class="hljs-attr">IsEnabled</span>=<span class="hljs-string">"{Binding IsNotBusy}"</span>
        <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"3"</span>
        <span class="hljs-attr">Style</span>=<span class="hljs-string">"{StaticResource ButtonOutline}"</span>/&gt;</span>
</code></pre>
<ul>
<li>Lastly, let's add an <code>ActivityIndicator</code>. Note that we are using the <code>IsNotBusy</code> generated from the <code>MyDaysViewModel</code>.</li>
</ul>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">ActivityIndicator</span> <span class="hljs-attr">IsVisible</span>=<span class="hljs-string">"{Binding IsBusy}"</span>
                    <span class="hljs-attr">IsRunning</span>=<span class="hljs-string">"{Binding IsBusy}"</span>
                    <span class="hljs-attr">HorizontalOptions</span>=<span class="hljs-string">"FillAndExpand"</span>
                    <span class="hljs-attr">VerticalOptions</span>=<span class="hljs-string">"CenterAndExpand"</span>
                    <span class="hljs-attr">Grid.RowSpan</span>=<span class="hljs-string">"2"</span>
                    <span class="hljs-attr">Grid.ColumnSpan</span>=<span class="hljs-string">"2"</span>/&gt;</span>
</code></pre>
<ul>
<li>Review your <code>App.xaml</code>. It should look like the following.</li>
</ul>
<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:viewmodels</span>=<span class="hljs-string">"clr-namespace:ChooseDay.ViewModels"</span>
            <span class="hljs-attr">xmlns:models</span>=<span class="hljs-string">"clr-namespace:ChooseDay.Models"</span>
            <span class="hljs-attr">x:DataType</span>=<span class="hljs-string">"viewmodels:MyDaysViewModel"</span>
            <span class="hljs-attr">x:Class</span>=<span class="hljs-string">"ChooseDay.MainPage"</span>
            <span class="hljs-attr">Title</span>=<span class="hljs-string">"{Binding Title}"</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">Grid</span> <span class="hljs-attr">Padding</span>=<span class="hljs-string">"12"</span>
          <span class="hljs-attr">RowDefinitions</span>=<span class="hljs-string">"AUTO,AUTO,*,AUTO"</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">HorizontalStackLayout</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Label</span> <span class="hljs-attr">FontFamily</span>=<span class="hljs-string">"OpenSans-Bold"</span> <span class="hljs-attr">FontSize</span>=<span class="hljs-string">"24"</span> <span class="hljs-attr">Text</span>=<span class="hljs-string">"Your Days"</span> /&gt;</span>

        <span class="hljs-tag">&lt;/<span class="hljs-name">HorizontalStackLayout</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">Label</span> <span class="hljs-attr">FontFamily</span>=<span class="hljs-string">"OpenSans-LightItalic"</span>
              <span class="hljs-attr">FontSize</span>=<span class="hljs-string">"16"</span>
              <span class="hljs-attr">Text</span>=<span class="hljs-string">"Choose a theme day for yourself."</span>
              <span class="hljs-attr">TextColor</span>=<span class="hljs-string">"{AppThemeBinding Light={StaticResource Gray600}, Dark={StaticResource Gray100}}"</span>
              <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"1"</span> /&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">CollectionView</span> <span class="hljs-attr">ItemsSource</span>=<span class="hljs-string">"{Binding MyDays}"</span>
                            <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"2"</span>
                            <span class="hljs-attr">Margin</span>=<span class="hljs-string">"0,14"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">CollectionView.ItemsLayout</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">LinearItemsLayout</span> <span class="hljs-attr">Orientation</span>=<span class="hljs-string">"Vertical"</span>
                                  <span class="hljs-attr">ItemSpacing</span>=<span class="hljs-string">"16"</span>/&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">CollectionView.ItemsLayout</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">CollectionView.ItemTemplate</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">DataTemplate</span> <span class="hljs-attr">x:DataType</span>=<span class="hljs-string">"models:Day"</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">Frame</span> <span class="hljs-attr">HeightRequest</span>=<span class="hljs-string">"275"</span>
                          <span class="hljs-attr">Padding</span>=<span class="hljs-string">"0"</span>
                          <span class="hljs-attr">Style</span>=<span class="hljs-string">"{StaticResource CardView}"</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.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">ColumnDefinition</span> <span class="hljs-attr">Width</span>=<span class="hljs-string">"2*"</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">Source</span>=<span class="hljs-string">"{Binding Image}"</span>
                                  <span class="hljs-attr">Aspect</span>=<span class="hljs-string">"AspectFill"</span> /&gt;</span>

                            <span class="hljs-tag">&lt;<span class="hljs-name">Grid</span> <span class="hljs-attr">Grid.Column</span>=<span class="hljs-string">"1"</span>
                                  <span class="hljs-attr">Padding</span>=<span class="hljs-string">"16"</span>
                                  <span class="hljs-attr">RowDefinitions</span>=<span class="hljs-string">"AUTO,AUTO,*"</span>&gt;</span>

                                <span class="hljs-tag">&lt;<span class="hljs-name">Label</span> <span class="hljs-attr">Text</span>=<span class="hljs-string">"{Binding Name}"</span>
                                  <span class="hljs-attr">FontSize</span>=<span class="hljs-string">"20"</span>
                                  <span class="hljs-attr">FontFamily</span>=<span class="hljs-string">"OpenSans-SemiBold"</span>/&gt;</span>


                                <span class="hljs-tag">&lt;<span class="hljs-name">FlexLayout</span> <span class="hljs-attr">BindableLayout.ItemsSource</span>=<span class="hljs-string">"{Binding Activities}"</span>
                                        <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"1"</span>
                                        <span class="hljs-attr">Wrap</span>=<span class="hljs-string">"Wrap"</span>
                                        <span class="hljs-attr">AlignItems</span>=<span class="hljs-string">"Start"</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">Frame</span> <span class="hljs-attr">Padding</span>=<span class="hljs-string">"8"</span>
                                              <span class="hljs-attr">Margin</span>=<span class="hljs-string">"1"</span>
                                              <span class="hljs-attr">BorderColor</span>=<span class="hljs-string">"Transparent"</span>
                                              <span class="hljs-attr">BackgroundColor</span>=<span class="hljs-string">"{StaticResource Rose300Accent}"</span>&gt;</span>
                                                <span class="hljs-tag">&lt;<span class="hljs-name">Label</span> <span class="hljs-attr">Text</span>=<span class="hljs-string">"{Binding .}"</span>
                                                      <span class="hljs-attr">TextColor</span>=<span class="hljs-string">"{StaticResource Gray900}"</span> /&gt;</span>
                                            <span class="hljs-tag">&lt;/<span class="hljs-name">Frame</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">FlexLayout</span>&gt;</span>

                                <span class="hljs-tag">&lt;<span class="hljs-name">Label</span> <span class="hljs-attr">Text</span>=<span class="hljs-string">"{Binding Description}"</span>
                                        <span class="hljs-attr">TextColor</span>=<span class="hljs-string">"{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource Gray100}}"</span>
                                        <span class="hljs-attr">Padding</span>=<span class="hljs-string">"0,20,0,0"</span>
                                        <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"2"</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</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">Frame</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">CollectionView.ItemTemplate</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">CollectionView</span>&gt;</span>


        <span class="hljs-tag">&lt;<span class="hljs-name">Button</span> <span class="hljs-attr">Text</span>=<span class="hljs-string">"Get Recommendations"</span>
                <span class="hljs-attr">Command</span>=<span class="hljs-string">"{Binding GetMyDaysCommand}"</span>
                <span class="hljs-attr">IsEnabled</span>=<span class="hljs-string">"{Binding IsNotBusy}"</span>
                <span class="hljs-attr">Grid.Row</span>=<span class="hljs-string">"3"</span>
                <span class="hljs-attr">Style</span>=<span class="hljs-string">"{StaticResource ButtonOutline}"</span>/&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">ActivityIndicator</span> <span class="hljs-attr">IsVisible</span>=<span class="hljs-string">"{Binding IsBusy}"</span>
                          <span class="hljs-attr">IsRunning</span>=<span class="hljs-string">"{Binding IsBusy}"</span>
                          <span class="hljs-attr">HorizontalOptions</span>=<span class="hljs-string">"FillAndExpand"</span>
                          <span class="hljs-attr">VerticalOptions</span>=<span class="hljs-string">"CenterAndExpand"</span>
                          <span class="hljs-attr">Grid.RowSpan</span>=<span class="hljs-string">"2"</span>
                          <span class="hljs-attr">Grid.ColumnSpan</span>=<span class="hljs-string">"2"</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>That is it! You can now run and test the application, through the emulators or an actual device! I was able to do this within a few hours. (Most of my time was spent on downloading updates and emulators)</p>
<h2 id="heading-remarks">Remarks</h2>
<p>I thoroughly enjoyed this first coding experience with .NET MAUI! I am really glad that Microsoft offers this framework wherein we could deploy applications across multiple types of devices, using only one codebase. Personally here are the list of things that I would like to explore:</p>
<ul>
<li>Learn more about XAML (I have limited experience with this).</li>
<li>Build a .NET MAUI Blazor app.</li>
<li>Integrate CRUD in a .NET MAUI app.</li>
<li>Consume REST API calls in a .NET MAUI app.</li>
<li>Use device integrations with a .NET MAUI app.</li>
</ul>
<h3 id="heading-resources">Resources</h3>
<p>Here are the following links that you can visit in order to learn more about .NET MAUI.</p>
<ul>
<li><a target="_blank" href="https://github.com/gmlunesa/ChooseDay/tree/tutorial">Source Code</a></li>
<li><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/maui/">Microsoft Documentation</a></li>
<li><a target="_blank" href="https://dotnet.microsoft.com/en-us/learn/maui">Microsoft Learn</a></li>
<li><a target="_blank" href="https://learn.microsoft.com/en-us/training/paths/build-apps-with-dotnet-maui/">Microsoft Training- Build mobile and desktop apps with .NET MAUI</a></li>
<li><a target="_blank" href="https://www.youtube.com/c/JamesMontemagno">James Montemagno YouTube</a></li>
<li><a target="_blank" href="https://www.youtube.com/c/GeraldVersluis">Gerald Versluis YouTube</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[.NET 6: Global Using Directives]]></title><description><![CDATA[A long and extensive list of using directives at the top of a .cs or .razor file is a familiar sight as a C# developer. The more dependencies you have, the…]]></description><link>https://blog.gmlunesa.com/net-6-global-using-directives</link><guid isPermaLink="true">https://blog.gmlunesa.com/net-6-global-using-directives</guid><category><![CDATA[.NET]]></category><category><![CDATA[dotnet]]></category><category><![CDATA[C#]]></category><dc:creator><![CDATA[Goldy Mariz Lunesa 🇵🇭]]></dc:creator><pubDate>Sat, 11 Dec 2021 09:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1673322134458/HKZQgxV_k.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A long and extensive list of <code>using</code> directives at the top of a <code>.cs</code> or <code>.razor</code> file is a familiar sight as a C# developer. The more dependencies you have, the longer this list goes. Some apply the <code>#region</code> directive on this part of the code, while others utilize tinker with their IDE setting— just to be able to collapse this area.</p>
<p>This convention has been around since .NET Framework 1.0 was launched in the year 2002. Although there is nothing technically wrong with this, it clutters the top space of the files. Additionally, many common libraries are duplicated across multiple files even under same namespaces.</p>
<p>As of <a target="_blank" href="https://devblogs.microsoft.com/dotnet/welcome-to-csharp-10/">November 2021</a>, developers now have an option to address this issue through C# 10's <strong>global <code>using</code> directive</strong>.</p>
<h2 id="heading-global-using-directive">Global Using Directive</h2>
<p>With this new feature, a developer may add the <code>global</code> modifier to a <code>using</code> directive, to signify that the qualified namespace is applied to all files during compilation.</p>
<h3 id="heading-syntax">Syntax</h3>
<pre><code class="lang-cs"><span class="hljs-keyword">global</span> <span class="hljs-keyword">using</span> &lt;<span class="hljs-keyword">namespace</span>&gt;;
</code></pre>
<p>The global modifier may also be combined with the <code>static</code> modifier or applied to a <code>using alias</code> directive.</p>
<pre><code class="lang-cs"><span class="hljs-keyword">global</span> <span class="hljs-keyword">using</span> <span class="hljs-keyword">static</span> System.Math;
</code></pre>
<p>Some rules to keep track of:</p>
<ul>
<li><code>global using</code> directives must appear before all <code>using</code> directives without the global modifier</li>
<li><code>global using</code> directives must appear before all namespace and type declarations in the file</li>
</ul>
<p>Moreover, the order of <code>global using</code> directives does not matter, either in a single file, or between multiple files. The <code>global using</code> directives may be placed in any source file, but personally, I like to keep them all in one file since it's more organized in that manner.</p>
<h2 id="heading-implicit-global-using-directives">Implicit Global Using Directives</h2>
<p>.NET 6 also offers a set of <strong>implicit</strong> global using directives for projects for the most common libraries. This means that the compiler will automatically add a bunch of namespaces based on the project type, which will then be available out of the box.</p>
<p>As an example, the following libraries are implicitly added in a console application, which we do not have to specify them.</p>
<pre><code class="lang-cs"><span class="hljs-keyword">using</span> System;
<span class="hljs-keyword">using</span> System.IO;
<span class="hljs-keyword">using</span> System.Collections.Generic;
<span class="hljs-keyword">using</span> System.Linq;
<span class="hljs-keyword">using</span> System.Net.Http;
<span class="hljs-keyword">using</span> System.Threading;
<span class="hljs-keyword">using</span> System.Threading.Tasks;
</code></pre>
<p>You may deactivate the implicit global using directives by adding this code to the <code>.csproj</code> file.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">ImplicitUsings</span>&gt;</span>disable<span class="hljs-tag">&lt;/<span class="hljs-name">ImplicitUsings</span>&gt;</span>
</code></pre>
<h2 id="heading-requirements">Requirements</h2>
<p>To be able to use the <code>global using</code> directives, you must have the following:</p>
<ul>
<li><a target="_blank" href="https://dotnet.microsoft.com/en-us/download/dotnet/6.0">.NET 6 SDK</a></li>
</ul>
<h2 id="heading-reflection">Reflection</h2>
<p>This newly added feature is helpful in maintaining the cleanliness of our source files. However, before we use the <code>global using</code> directives in different libraries, we must first consider and assess the situation.</p>
<ul>
<li>Will it introduce any naming conflicts in the project? If so, will aliasing the namespace be an option?</li>
<li>Will the directive be used in one file? If so, there is no need to add it in the global scope.</li>
</ul>
<p>If you would like to learn more about .NET 6 and C# 10, please check the following references.</p>
<ul>
<li><a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-10#global-using-directives">What's new in C# 10</a></li>
<li><a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-6">What's new in .NET 6</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Develop and deploy an optimized site in a day]]></title><description><![CDATA[Days ago, I decided that my personal website needed updating, as some things weren't working anymore. The old version was written in plain HTML and CSS (as…]]></description><link>https://blog.gmlunesa.com/develop-and-deploy-an-optimized-site-in-a-day</link><guid isPermaLink="true">https://blog.gmlunesa.com/develop-and-deploy-an-optimized-site-in-a-day</guid><category><![CDATA[Gatsby]]></category><category><![CDATA[React]]></category><dc:creator><![CDATA[Goldy Mariz Lunesa 🇵🇭]]></dc:creator><pubDate>Fri, 30 Oct 2020 09:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1673322125801/0Jw8MzdsU.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Days ago, I decided that my <a href="https://gmlunesa.com" target="_blank">personal website</a> needed updating, as some things weren't working anymore. The <a href="https://gmlunesa.com/archive-gmlunesa-website" target="_blank">old version</a> was written in plain HTML and CSS (as I am a front-end newbie), and I wanted to try out the popular Javascript libraries everyone seems to be talking about— React and Vue. As I did my research, I discovered more frameworks built on top of those, as well as a <code>technology</code> called static site generators. If you want to build a website fast without compromising speed and quality, then this article might be for you.</p>
<h2 id="heading-exploring-our-options">Exploring our options</h2>
<p>Perhaps, the easiest way to publish your website is to download free HTML templates, edit them with your information and upload them to Github pages or your own server. However, this method leaves out important aspects such as SEO and performance optimization.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1673322122062/k4hpLzzlB.png" alt="Options" /></p>
<p>There are also multiple website builders available in the market. Most of them offer free tiers, but in my experience and observation, websites built through free tiers load slower and do not offer many customization options.</p>
<h2 id="heading-static-site-generators-and-gatsby">Static Site Generators and Gatsby</h2>
<p>This is where static site generators come in. A static site generator (SSG) is a tool that takes your source files and content, apply it to your template, then generate a structure of static HTML pages that are ready to be viewed by the users.</p>
<p>Let's compare this to a dynamic content management system (like Wordpress), which manage and store content in a database. When a user requests for a particular page</p>
<ul>
<li>📊 data has to be retrieved from the database</li>
<li>📁 integrate it to the template files</li>
<li>🌐 generate an HTML page and serve it to the user.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1673322124126/g5guIEF-I.png" alt="Comparison" /></p>
<p>Sounds like a longer process for each page view, right? With static site generators, when a user requests for a particular page, the server just serves the generated static HTML pages, thus, removing the latency of database processes.</p>
<p>There are already multiple static site generators available. After reading comparisons, I chose to go with <a href="https://www.gatsbyjs.com/features/jamstack/" target="_blank">Gatsby</a>
due to the optimization options it offers as well as the rich ecosystem of tools
and plugins.</p>
<p>There are also so many <a href="https://www.gatsbyjs.com/starters/" class="text-rose-500" target="_blank">Gatsby starters</a> available, which work similar to HTML templates— you download a Gatsby template, customize it with your information and upload your website to the web! These are the added benefits to your site:</p>
<ul>
<li>💨 <strong>Fast</strong> - no need to wait for the server runtime to generate your pages, since the pages are already generated during build time</li>
<li>🔒 <strong>Secure</strong> - no database queries that might compromise your security</li>
<li>💸 <strong>Inexpensive</strong> - companies like Netlify, Vercel and even Github offer free hosting for your Gatsby or SSG-powered sites</li>
<li>🔎 <strong>Better SEO</strong> - due to site speed, search engines can give your site a better rating</li>
</ul>
<p>
  <img src="https://dev-to-uploads.s3.amazonaws.com/i/j9y9fiq5jd8p1v0v4y61.png" alt="My site's Lighthouse scores" class="small-img" />
</p>

<p>It can be the same effort as coding a standard HTML site, but with 1000x power! Important things like site optimization and speed already gets taken care of, so you can focus more on customizing the visual components and writing the content for your site.</p>
<h2 id="heading-moving-forward">Moving forward</h2>
<p>So that's how you can utilize static site generators to help you develop and deploy a fast and optimized site in just a day! Web development technologies have come so far, you better not miss out.</p>
<p>If you are looking for a minimalist personal website, you can check out the <a href="https://github.com/gmlunesa/gatsby-starter-personal-portfolio" class="text-rose-500" target="_blank">starter</a> that I made. ✨ <a href="https://gatsby-starter-personal-portfolio.vercel.app" class="text-rose-500" target="_blank">Demo link here!</a>
It has dark mode, super fast speed, high Google Lighthouse rating, and beginner-friendly code!</p>
<p>With that being said, it will take more than a day to achieve a fully featured website and master web development skills. Gatsby and static site generators offer a good starting point in deploying your own website, for personal or prototype purposes.</p>
]]></content:encoded></item></channel></rss>