<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Piero De Tomi on Medium]]></title>
        <description><![CDATA[Stories by Piero De Tomi on Medium]]></description>
        <link>https://medium.com/@pierodetomi?source=rss-dfbb5dbfc15------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9CUf4QsybOnhlzBI36JGQw.jpeg</url>
            <title>Stories by Piero De Tomi on Medium</title>
            <link>https://medium.com/@pierodetomi?source=rss-dfbb5dbfc15------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:07:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pierodetomi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[OAuth Authentication With Individual User Accounts in ASP.NET Core 6]]></title>
            <link>https://pierodetomi.medium.com/oauth-authentication-with-individual-user-accounts-in-asp-net-core-6-3a50ce35d430?source=rss-dfbb5dbfc15------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a50ce35d430</guid>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Piero De Tomi]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 13:04:03 GMT</pubDate>
            <atom:updated>2023-01-04T13:04:03.080Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BztJg7y-uHUU_69yxDwvPw.jpeg" /></figure><p>Some time ago I wrote an article about <a href="https://medium.com/@pierodetomi/oauth-authentication-with-individual-user-accounts-on-asp-net-core-2-2-31a884c3dbfb">OAuth authentication in ASP.NET Core 2.2</a>, using the third party library <a href="https://github.com/openiddict/openiddict-core">OpenIddict</a> to implement the authentication middleware.</p><p>Since then new versions of .NET has come and current version is <strong>.NET 6</strong>.</p><p>For this reason I decided to rework the “old” solution and create a new version of it, using the latest ASP.NET version available.</p><p>I’ve prepared a <a href="https://github.com/pierodetomi/net6-oauth-app-boilerplate">Github repository</a> with a .NET 6 project with all necessary configurations already in place.<br>You can clone this project and use it as a starting point for any application with an API that needs OAuth authentication.</p><p>Once you have downloaded and compiled the code, you can start the application and call the /api/account/register endpoint to register an account and the /auth/token endpoint to exchange your credentials with an <strong>access token</strong> to use for authorized access to secure API endpoints.</p><h3>The Database Provider</h3><p>I used <a href="https://docs.microsoft.com/en-us/ef/core/providers/sqlite/?tabs=vs">EntityFramework Core SQLite</a> provider for this project, since it’s lighweight and portable, but you can easily switch to SQL Server if you need, the code would be almost identical.</p><p>To switch to SQL Server you only need to:</p><ul><li>Change the connection string in appsettings.json file</li><li>Install the <a href="https://docs.microsoft.com/en-us/ef/core/providers/sql-server/?tabs=vs">Entityframework Core SQL Server</a> NuGet package (and uninstall the SQLite version)</li><li>Change all places in code where there are explicit references to SQLite provider’s methods, in order to use the same methods from the SQL Server package</li></ul><h3>Usage Example</h3><h3>Create a Secure Controller</h3><p>You can create a controller with a secure endpoint with a code like this:</p><pre>[Route(&quot;api/[controller]&quot;)]<br>[ApiController]<br>public class ItemsController : AuthControllerBase<br>{<br>    private readonly IItemRepository _itemRepo;<br><br>    public ItemsController(<br>        UserManager&lt;AppUser&gt; userManager,<br>        IItemRepository itemRepo<br>    ) : base(userManager)<br>    {<br>        _itemRepo = itemRepo;<br>    }<br><br>    [HttpGet]<br>    [AllowAnonymous]<br>    public List&lt;Item&gt; Get() =&gt; Try(() =&gt;<br>    {<br>        return _itemRepo.GetAll().ToList();<br>    });<br><br>    [HttpPost]<br>    public Item Add([FromBody] Item item) =&gt; Try(() =&gt;<br>    {<br>        _itemRepo.Add(item);<br>        _itemRepo.Commit();<br><br>        return item;<br>    /});<br><br>    [HttpDelete(&quot;{id}&quot;)]<br>    public IActionResult Delete(Guid id) =&gt; Try(() =&gt;<br>    {<br>        _itemRepo.Delete(_ =&gt; _.Id == id);<br>        return Ok();<br>    });<br>}</pre><p>The above example makes use of a sample database repository IItemRepository, but you can replace it with whatever you want.</p><h3>Register an Account</h3><p>You need to call the /api/account/register endpoint to register a new user account:</p><pre>curl --location --request POST &#39;/api/account/register&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--data-raw &#39;{<br>    &quot;email&quot;: &quot;user@domain.com&quot;,<br>    &quot;password&quot;: &quot;ThisIsMyPassword&quot;<br>}&#39;</pre><h3>Get an Access Token</h3><p>Once you created an account, you can call the /auth/token endpoint to obtain an access token using your credentials:</p><pre>curl --location --request POST &#39;/auth/token&#39; \<br>--header &#39;Content-Type: application/x-www-form-urlencoded&#39; \<br>--data-urlencode &#39;username=user@domain.com&#39; \<br>--data-urlencode &#39;password=ThisIsMyPassword&#39; \<br>--data-urlencode &#39;grant_type=password&#39;</pre><h3>Call a Secure Endpoint</h3><p>With a valid access token in your hands you can call a secure API endpoint putting the token in the Authorization request header, as per OAuth standard:</p><pre>curl --location --request POST &#39;/api/items&#39; \<br>--header &#39;Authorization: Bearer &lt;your_token&gt;&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--data-raw &#39;{<br>    &quot;name&quot;: &quot;Test Item&quot;<br>}&#39;</pre><h3>Conclusion</h3><p>From here it’s all in your hands. You can now develop your next amazing API!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a50ce35d430" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Append Dynamic HTML With Scripts to the DOM]]></title>
            <link>https://pierodetomi.medium.com/how-to-append-dynamic-html-with-scripts-to-the-dom-14509c1ca784?source=rss-dfbb5dbfc15------2</link>
            <guid isPermaLink="false">https://medium.com/p/14509c1ca784</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Piero De Tomi]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 12:16:38 GMT</pubDate>
            <atom:updated>2023-01-04T12:16:38.105Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pxm9TU1YtVgceS2MWcbSVQ.jpeg" /></figure><h3>A Typical Use Case</h3><p>Let’s make an example: our frontend code makes a GET request to the server to read a dynamic piece of HTML that have to be included in our page.</p><p>At this point we would usually append that piece of HTML with some code like:</p><pre>// ... somewhere in our code we get the reference to the container element...<br>const containerElement = document.getElementById(&#39;container&#39;);<br><br>const html = &#39;&lt;div&gt;Hello from server&lt;/div&gt;&#39;;<br><br>// Append the content of &quot;html&quot; variable to the container element<br>containerElement.appendChild(containerElement);</pre><p>Or also:</p><pre>// ... somewhere in our code we get the reference to the container element...<br>const containerElement = document.getElementById(&#39;container&#39;);<br><br>const html = &#39;&lt;div&gt;Hello from server&lt;/div&gt;&#39;;<br><br>// Make the content of &quot;html&quot; variable the content of the container element<br>containerElement.innerHTML = html;</pre><h3>Special Use Case</h3><p>The above one was a simple example. But what if the response from the server was something like the following?</p><pre>&lt;div&gt;<br>  &lt;button onclick=&quot;showAlert()&quot;&gt;CLICK ME&lt;/button&gt;<br>&lt;/div&gt;<br><br>&lt;script type=&quot;text/javascript&quot;&gt;<br>  function showAlert() {<br>    alert(&#39;Hello there!&#39;);<br>  }<br>&lt;/script&gt;</pre><p>You’re starting to get where I’m heading, right?</p><p>That &lt;script&gt; tag will actually be included in the DOM, but its code <em>won’t be executed</em>.</p><p>That’s because we’re appending the HTML we receive from the server in a way that it’s not attached to the active context of the page.</p><p>Fortunately there’s a way to append HTML allowing the execution of scripts inside of it.</p><h3>The Solution: The Range.createContextualFragment() Method</h3><p>The solution I’m going to show you involves the use of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Range/createContextualFragment?retiredLocale=it"><strong>Range.createContextualFragment()</strong></a> method and it’s simple as the following few lines of code:</p><pre>// ... somewhere in our code we get the reference to the container element...<br>const containerElement = document.getElementById(&#39;container&#39;);<br><br>const range = document.createRange();<br>const contextualFragment = range.createContextualFragment(containerElement);<br><br>containerElement.appendChild(contextualFragment);</pre><p>With this code, any scripts included in the HTML contained in the html variable will be executed once appended to the DOM.</p><h3>Beware of Security Risks</h3><p>The above solution can be useful in some (usually rare) cases, but be aware that this approach comes with its risks: <strong><em>you should use it only when you totally trust the source of the HTML that you receive</em></strong> and if you’re 100% sure that this will not contain something that could represent a security breach or some unwanted content or behavior in your page.</p><h3>A Real World Example</h3><p>The technique that I’ve just described is the one that I’m actually using in the <a href="https://github.com/pierodetomi/ngwp-theme-kit/blob/master/angular/library/projects/ngwp-theme-kit/src/lib/directives/widget-area.directive.ts">WidgetAreaDirective</a> directive inside the <a href="https://github.com/pierodetomi/ngwp-theme-kit">NgWP Theme Kit</a> library.</p><p>The directive calls a custom API endpoint (located in the theme’s files in WordPress) and retrieves the HTML of the specified widget area ID.</p><p>When the server answers back with the HTML content of the widget area, we append it to the DOM using the same technique described in this article:</p><pre>private _updateWidgetHtml(html: string) {<br>  const container = this._elementRef.nativeElement as HTMLElement;<br><br>  /**<br>     * Creating a &quot;contextual fragment&quot; will allow the execution<br>     * of any scripts included in the received HTML.<br>     */<br>  const range = document.createRange();<br>  const fragment = range.createContextualFragment(html);<br>  container.appendChild(fragment);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14509c1ca784" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hosting an Angular App Inside a WordPress Site]]></title>
            <link>https://pierodetomi.medium.com/hosting-an-angular-app-inside-a-wordpress-site-69865ae339b3?source=rss-dfbb5dbfc15------2</link>
            <guid isPermaLink="false">https://medium.com/p/69865ae339b3</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[web-app-development]]></category>
            <dc:creator><![CDATA[Piero De Tomi]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 12:16:38 GMT</pubDate>
            <atom:updated>2023-01-04T12:16:38.085Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*Xgy8TJV03ng3BF4adFpR2g.jpeg" /></figure><h3>Sometimes You Want to Have Something More Dynamic</h3><p>Let’s suppose you have a self-hosted website developed with WordPress. It may be a blog, portfolio, company landing page or whatever.</p><p>We all know you can easily add static pages in a WordPress website, but that’s all they are: static pages.</p><p>What if you wanted to have something more dynamic and/or interactive?</p><p>Your answer at this point may be: “well, you can develop a WordPress plugin for that!”.</p><p><strong><em>That’s actually true</em></strong>, but…</p><h3>Not All of Us Are WordPress Experts</h3><p>Truth is that <strong>not all of us are WordPress experts</strong>. And some of us don’t even want to be! (spoiler: I’m inside that category)</p><p>I didn’t ever work professionally with PHP.<br>The only PHP projects I’ve worked on were all on my spare time and they were quite simple. I’m not really interested in learning WordPress deeply on the technical side, but I do have a blog running on WordPress self-hosted.<br>In my case it would take me 1/3 of the time to develop an Angular app rather than developing a WordPress plugin, so… why would I have to waste my time?</p><p>So what if I told you that you can develop an Angular app and host it inside a static page inside your WordPress website?</p><p>And before you panic: <strong><em>I’m not talking about iframes</em></strong>. Using the technique I’ll show you here you’ll achieve a “clean” integration of your app.</p><h3>The Technique Step by Step</h3><p>Ok, let’s proceed step by step and see how it’s done.</p><h3>1. Creating the Static Page in WordPress</h3><p>The first think we need to make is creating the page that will actually host our app.</p><p>I’m not going to cover this step here since it’s so easy and (just in case you really need it) there are already a lot of tutorials online about this — “Google is your friend” they say :)</p><p>Please take note of the <strong>slug</strong> of the page you’re going to create, since we’ll need it in the next steps.</p><h3>2. Creating the Angular App</h3><p>The first step clearly is to create an Angular app. We can do this with the cli command:</p><pre>ng new ng-app --routing</pre><h3>3. Setting the APP_BASE_HREF Token Value</h3><p>Normally this isn’t required for “standard” Angular scenarios. And even when you do need to change the base href of an app, you usually do so by changing the value of the href attribute of the &lt;base /&gt; tag inside the index.html file of your Angular app.</p><p>In our case we won’t use the index.html file (generated by the cli) inside WordPress, so we need another way to set the base href of the application.</p><p>We’ll do this by inserting the following line inside the providers property of the @NgModule declaration in the app.module.ts file.</p><pre>{ provide: APP_BASE_HREF, useValue: &#39;/ng&#39; },</pre><p>I’ve used /ng because that’s the slug of the static page that I’ve created in WordPress. Here you’ll need to set whatever you chose as the slug of the page.</p><p>We’re simply telling Angular that the base address of our app will be the one specified for the APP_BASE_HREF.</p><h3>4. Developing the Angular App</h3><p>At this point you can develop your app as you want.</p><p>There’s not so much to say, only you know what you need… go and implement it!</p><h3>5. Creating the Custom Page Template in WordPress</h3><p>Locate the page.php file of your theme.<br>You can find this file at the root of your WordPress theme, so the path will be:</p><pre>wp-content/themes/&lt;theme-name&gt;/page.php</pre><p>Duplicate this file and rename it using the following structure:</p><pre>page-&lt;slug&gt;.php</pre><p>You have to replace &lt;slug&gt; with the actual slug of the static page you created at <strong>step 1</strong> of this tutorial.</p><p>For example, my slug was ng so I had to name the page page-ng.php.</p><p>Doing so will ensure that WordPress loads your custom page template (and not the default one) when you request to load your new static page in the browser.</p><h3>6. Making Changes to the Custom Page Template</h3><p>This is the last one. I promise.</p><p>Now you’ll need to understand how your theme’s page is structured (in terms of DOM structure) and decide where you want to host your app inside the page: this is up to you and specific to everyone’s needs, so you’ll have to figure it out on your own.</p><p>Once you know where you want your app to appear inside the page, place the following code in the specific point:</p><pre>&lt;app-root&gt;&lt;/app-root&gt;</pre><p>This will load the root component of your Angular app inside the page, at the specific location that you chose.</p><p>Now build the app with ng build or ng build --prod (in case you want a production build).</p><p>Navigate to the dist folder of your app, open the index.html file and copy all the &lt;script&gt; tags you find before the closing &lt;/body&gt; tag of the page, as you can see in the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*MvdzydivL7ZE1bcp.png" /></figure><p>Paste the code you just copied inside the custom page template (in my case page-ng.php) somewhere suitable near the end of the file, and update the src attributes of these tags in order to <strong>point to the correct location of these files</strong>.</p><p><em>Please note that this last operation is crucial, so make sure you’re using the right paths, otherwise the integration won’t work at all. Just think what the paths should be in order for the browser to be able to load them properly.</em></p><p>DONE.</p><h3>Enjoy Your App Inside WordPress</h3><p>If you did everything correctly you’ll be able to see your app loading the static page you created in WordPress (in my case /ng).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*-E8KaUCUxHEh-jTC.png" /></figure><h3>Conclusion</h3><p>I know it’s been lengthy to follow along, but I assure you this is actually shorter to do rather than to read. Just try and you’ll see.</p><p>I hope this will be useful for you. I think you can do great things on your WordPress site with this technique, make good use of it! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69865ae339b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OAuth authentication with individual user accounts on ASP.NET Core 2.2]]></title>
            <link>https://pierodetomi.medium.com/oauth-authentication-with-individual-user-accounts-on-asp-net-core-2-2-31a884c3dbfb?source=rss-dfbb5dbfc15------2</link>
            <guid isPermaLink="false">https://medium.com/p/31a884c3dbfb</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[identity]]></category>
            <category><![CDATA[oauth]]></category>
            <dc:creator><![CDATA[Piero De Tomi]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 12:16:37 GMT</pubDate>
            <atom:updated>2023-01-04T12:16:37.482Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4D19RALBmVyK7us_7IqpNg.jpeg" /></figure><p>In this article I’ll walk you through the configuration of an ASP.NET Core 2.2 application that supports OAuth authentication with individual user accounts on SQL Server (through EntityFramework Core).</p><h3>If you’re in a hurry…</h3><p>… you can go directly to the <a href="https://github.com/pierodetomi/aspnetcore-openiddict-sample">GitHub repository</a> containing the final project, ready to use.</p><h3>What you’ll need</h3><p>Here’s a short list of what you’ll need to follow through this article:</p><ul><li><strong>Visual Studio:</strong> I’m currently using the 2017 Community version, but also Visual Studio 2019 should be fine</li><li><strong>SQL Server:</strong> the Express edition will be fine</li><li><a href="https://www.getpostman.com/"><strong>Postman</strong></a><strong>:</strong> we’ll use this tool to test our final configuration. You can use any other tool that allows you to make HTTP requests</li></ul><h3>Project creation</h3><p>Create a new ASP.NET Core 2.2 Web Application with the “Individual User Accounts” option selected in the “Change Authentication” menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*vnMZ3SJtUyK0CUBK.png" /></figure><p>Also choose to “Store user accounts in-app”: we’ll switch to SQL Server in a while.</p><h3>Switch from “in-app” database to SQL Server</h3><p>Look at your project structure, locate and open the <em>appsettings.json</em> configuration file and change the connection string named <em>DefaultConnection</em> in order to point to an existing (empty) SQL Server database.</p><p>Now you need to apply the schema to your empty database, in order to have the tables required for the authentication to work.</p><p>Open the Package Manager Console and execute the <em>Update-Database</em> command: your database should now have the following tables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/0*taZaE0lI47U-K8NL.png" /></figure><p>Before moving to the next part, let’s create a demo user account and test the authentication.</p><p>Launch the application, navigate to the <em>/Identity/Account/Register</em> page and register a new user account: I used <strong>demo@domain.com</strong> as username and <strong>Password_123</strong> as password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Sw4R81C6Uyv9NgZQ.png" /></figure><h3>OpenIddict installation</h3><p>To configure OAuth we’ll use the <a href="https://github.com/openiddict/openiddict-core">OpenIddict</a> library.<br>Open the NuGet Package Manager and install the following packages:</p><ul><li><strong>OpenIddict </strong>— version 2.0.0</li><li><strong>OpenIddict.EntityFrameworkCore </strong>— version 2.0.0</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*C4zsA-oYhv-f-7-R.png" /></figure><p>Now we’ll add a simple API controller that you’ll use later to test the authentication.</p><h3>Sample API Controller</h3><p>Create a new folder called <em>Controllers</em> and add a new file <em>SampleController.cs</em> to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/0*OzhDeSj52CzWxdW6.png" /></figure><p>The controller will have the following code:</p><pre>using Microsoft.AspNetCore.Authorization;<br>using Microsoft.AspNetCore.Mvc;<br>using OpenIddict.Validation;<br>using System.Collections.Generic;<br><br>namespace OAuthWebApp.Controllers<br>{<br>    [Authorize(AuthenticationSchemes = OpenIddictValidationDefaults.AuthenticationScheme)]<br>    [ApiController]<br>    [Route(&quot;api/[controller]&quot;)]<br>    public class SampleController : ControllerBase<br>    {<br>        [HttpGet]<br>        public List&lt;string&gt; Get()<br>        {<br>            return new List&lt;string&gt;<br>            {<br>                &quot;This&quot;,<br>                &quot;is&quot;,<br>                &quot;a&quot;,<br>                &quot;test&quot;<br>            };<br>        }<br>    }<br>}</pre><h3>Startup configuration</h3><p>Following the instructions provided in the <a href="https://github.com/openiddict/openiddict-core">official repository</a> of OpenIddict, change the content of the <em>Startup.cs</em> file as follows:</p><pre>using AspNet.Security.OpenIdConnect.Primitives;<br>using Microsoft.AspNetCore.Builder;<br>using Microsoft.AspNetCore.Hosting;<br>using Microsoft.AspNetCore.Identity;<br>using Microsoft.AspNetCore.Mvc;<br>using Microsoft.EntityFrameworkCore;<br>using Microsoft.Extensions.Configuration;<br>using Microsoft.Extensions.DependencyInjection;<br>using OAuthWebApp.Data;<br><br>namespace OAuthWebApp<br>{<br>    public class Startup<br>    {<br>        public Startup(IConfiguration configuration)<br>        {<br>            Configuration = configuration;<br>        }<br><br>        public IConfiguration Configuration { get; }<br><br>        // This method gets called by the runtime. Use this method to add services to the container.<br>        public void ConfigureServices(IServiceCollection services)<br>        {<br>            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);<br><br>            services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;<br>            {<br>                options.UseSqlServer(<br>                    Configuration.GetConnectionString(&quot;DefaultConnection&quot;));<br><br>                options.UseOpenIddict();<br>            });<br>            services.AddIdentity&lt;IdentityUser, IdentityRole&gt;()<br>                .AddEntityFrameworkStores&lt;ApplicationDbContext&gt;()<br>                .AddDefaultTokenProviders();<br><br>            // Configure Identity to use the same JWT claims as OpenIddict instead<br>            // of the legacy WS-Federation claims it uses by default (ClaimTypes),<br>            // which saves you from doing the mapping in your authorization controller.<br>            services.Configure&lt;IdentityOptions&gt;(options =&gt;<br>            {<br>                options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;<br>                options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;<br>                options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;<br>            });<br><br>            services.AddOpenIddict()<br>                .AddCore(options =&gt;<br>                {<br>                    // Configure OpenIddict to use the default entities<br>                    options.UseEntityFrameworkCore()<br>                           .UseDbContext&lt;ApplicationDbContext&gt;();<br>                })<br>                .AddServer(options =&gt;<br>                {<br>                    // Register the ASP.NET Core MVC binder used by OpenIddict.<br>                    // Note: if you don&#39;t call this method, you won&#39;t be able to<br>                    // bind OpenIdConnectRequest or OpenIdConnectResponse parameters.<br>                    options.UseMvc();<br><br>                    // Enable the token endpoint (required to use the password flow).<br>                    options.EnableTokenEndpoint(&quot;/auth/token&quot;);<br><br>                    // Allow client applications to use the grant_type=password flow.<br>                    options.AllowPasswordFlow();<br><br>                    // Accept token requests that don&#39;t specify a client_id.<br>                    options.AcceptAnonymousClients();<br>                })<br>                .AddValidation();<br>        }<br><br>        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.<br>        public void Configure(IApplicationBuilder app, IHostingEnvironment env)<br>        {<br>            if (env.IsDevelopment())<br>            {<br>                app.UseDeveloperExceptionPage();<br>                app.UseDatabaseErrorPage();<br>            }<br>            else<br>            {<br>                app.UseExceptionHandler(&quot;/Error&quot;);<br>                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.<br>                app.UseHsts();<br>            }<br><br>            app.UseAuthentication();<br>            app.UseMvcWithDefaultRoute();<br>            app.UseWelcomePage();<br>        }<br>    }<br>}</pre><h3>Token Endpoint implementation</h3><p>In our configuration we specified the <em>/auth/token</em> path as our token endpoint, but the application doesn’t have this endpoint yet.</p><p>Inside the <em>Controllers</em> folder add a new file called <em>AuthController.cs</em>, with the following content:</p><pre>using AspNet.Security.OpenIdConnect.Extensions;<br>using AspNet.Security.OpenIdConnect.Primitives;<br>using AspNet.Security.OpenIdConnect.Server;<br>using Microsoft.AspNetCore.Authentication;<br>using Microsoft.AspNetCore.Identity;<br>using Microsoft.AspNetCore.Mvc;<br>using OpenIddict.Abstractions;<br>using OpenIddict.Core;<br>using OpenIddict.EntityFrameworkCore.Models;<br>using System.Linq;<br>using System.Threading.Tasks;<br><br>namespace OAuthWebApp.Controllers<br>{<br>    [Route(&quot;[controller]&quot;)]<br>    public class AuthController : ControllerBase<br>    {<br>        private readonly OpenIddictApplicationManager&lt;OpenIddictApplication&gt; applicationManager;<br>        private readonly SignInManager&lt;IdentityUser&gt; signInManager;<br>        private readonly UserManager&lt;IdentityUser&gt; userManager;<br><br>        public AuthController(<br>            OpenIddictApplicationManager&lt;OpenIddictApplication&gt; applicationManager,<br>            SignInManager&lt;IdentityUser&gt; signInManager,<br>            UserManager&lt;IdentityUser&gt; userManager)<br>        {<br>            this.applicationManager = applicationManager;<br>            this.signInManager = signInManager;<br>            this.userManager = userManager;<br>        }<br><br>        [HttpPost]<br>        [Route(&quot;token&quot;)]<br>        public async Task&lt;IActionResult&gt; Token(OpenIdConnectRequest requestModel)<br>        {<br>            if (!requestModel.IsPasswordGrantType())<br>            {<br>                // Return bad request if the request is not for password grant type<br>                return BadRequest(new OpenIdConnectResponse<br>                {<br>                    Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,<br>                    ErrorDescription = &quot;The specified grant type is not supported.&quot;<br>                });<br>            }<br><br>            var user = await userManager.FindByNameAsync(requestModel.Username);<br>            if (user == null)<br>            {<br>                // Return bad request if the user doesn&#39;t exist<br>                return BadRequest(new OpenIdConnectResponse<br>                {<br>                    Error = OpenIdConnectConstants.Errors.InvalidGrant,<br>                    ErrorDescription = &quot;Invalid username or password&quot;<br>                });<br>            }<br><br>            // Check that the user can sign in and is not locked out.<br>            // If two-factor authentication is supported, it would also be appropriate to check that 2FA is enabled for the user<br>            if (!await signInManager.CanSignInAsync(user) || (userManager.SupportsUserLockout &amp;&amp; await userManager.IsLockedOutAsync(user)))<br>            {<br>                // Return bad request is the user can&#39;t sign in<br>                return BadRequest(new OpenIdConnectResponse<br>                {<br>                    Error = OpenIdConnectConstants.Errors.InvalidGrant,<br>                    ErrorDescription = &quot;The specified user cannot sign in.&quot;<br>                });<br>            }<br><br>            if (!await userManager.CheckPasswordAsync(user, requestModel.Password))<br>            {<br>                // Return bad request if the password is invalid<br>                return BadRequest(new OpenIdConnectResponse<br>                {<br>                    Error = OpenIdConnectConstants.Errors.InvalidGrant,<br>                    ErrorDescription = &quot;Invalid username or password&quot;<br>                });<br>            }<br><br>            // The user is now validated, so reset lockout counts, if necessary<br>            if (userManager.SupportsUserLockout)<br>            {<br>                await userManager.ResetAccessFailedCountAsync(user);<br>            }<br><br>            // Create the principal<br>            var principal = await signInManager.CreateUserPrincipalAsync(user);<br><br>            // Claims will not be associated with specific destinations by default, so we must indicate whether they should<br>            // be included or not in access and identity tokens.<br>            foreach (var claim in principal.Claims)<br>            {<br>                // For this sample, just include all claims in all token types.<br>                // In reality, claims&#39; destinations would probably differ by token type and depending on the scopes requested.<br>                claim.SetDestinations(OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken);<br>            }<br><br>            // Create a new authentication ticket for the user&#39;s principal<br>            var ticket = new AuthenticationTicket(<br>                principal,<br>                new AuthenticationProperties(),<br>                OpenIdConnectServerDefaults.AuthenticationScheme);<br><br>            // Include resources and scopes, as appropriate<br>            var scope = new[]<br>            {<br>                OpenIdConnectConstants.Scopes.OpenId,<br>                OpenIdConnectConstants.Scopes.Email,<br>                OpenIdConnectConstants.Scopes.Profile,<br>                OpenIdConnectConstants.Scopes.OfflineAccess,<br>                OpenIddictConstants.Scopes.Roles<br>            }.Intersect(requestModel.GetScopes());<br><br>            ticket.SetScopes(scope);<br><br>            // Sign in the user<br>            return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);<br>        }<br>    }<br>}</pre><h3>Final test</h3><p>Open Postman and create a new request with the following configuration:</p><ul><li><strong>Method:</strong> POST</li><li><strong>URL:</strong> <a href="https://localhost:44388/auth/token">https://localhost:{PORT}/auth/token</a> — replace {PORT} with your local port</li><li><strong>Content-Type:</strong> application/x-www-form-urlencoded</li></ul><p>The request body should be configured as follows (using <strong>your</strong> <em>username</em> and <em>password</em> values):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*ktURXmUPfNY70ae4.png" /></figure><p>Execute the request and obtain the <strong>access_token</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*yH-aQF1MZEmv2fve.png" /></figure><p>At this point you can use the access token to setup a request to your /api/sample protected endpoint, specifying the access token as <em>Bearer Token:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*cW_dz316CcgmkyB3.png" /></figure><p>If you did everything correctly, you’ll receive the following response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*sZSRTkiA8W-3eShY.png" /></figure><h3>Conclusion</h3><p>I created a <a href="https://github.com/pierodetomi/aspnetcore-openiddict-sample">GitHub repository</a> with the project used in this article, feel free to download the code and use it as a starting point for your application (just remember to have SSL enabled on your project settings, otherwise the code won’t work properly).</p><p>I hope this article will help you to get up and running quickly — that’s the goal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31a884c3dbfb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Develop an Entire WordPress Theme in Angular]]></title>
            <link>https://pierodetomi.medium.com/how-to-develop-an-entire-wordpress-theme-in-angular-77419c660d58?source=rss-dfbb5dbfc15------2</link>
            <guid isPermaLink="false">https://medium.com/p/77419c660d58</guid>
            <category><![CDATA[wordpress-themes]]></category>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Piero De Tomi]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 12:16:37 GMT</pubDate>
            <atom:updated>2023-01-04T12:16:37.472Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P6sDv8Z-umcCrxrG_uamXw.jpeg" /></figure><p>If you’re like me you probably love Angular.</p><p>You use it every day in your professional activity and you think it’s (one of) the best frontend application frameworks out there right now.</p><p>If this is true, read on as I have something interesting to tell you today.</p><h3>WordPress: The Good Things and the Bad Things</h3><p>I love the <em>backend</em> of WordPress and the power of the <a href="https://wordpress.org/gutenberg/">Gutenberg</a> editor and its blocks.</p><p>On the other side I don’t love PHP as mush as I do for other server-side programming languages (e.g. C#). I’m not so experienced in PHP but I’ve always thought that the WordPress theme structure is a little nightmare to understand and to master.<br>I really think that the way WordPress wants you to structure a theme is over-complicated and can very easily bring you to bad design practices.</p><h3>NgWP Theme Kit: The Birth of a New Angular Library</h3><p>Wouldn’t it be great if we could implement a WordPress theme just by developing an Angular application?</p><p>Maybe we could use a library/tool/whatever that when we build the application applies the required transformations and produces an output package that satisfies the WordPress theme structure, but at the same time uses your Angular application as the theme frontend?</p><p>Following these thoughts I decided to develop my own solution to satisfy this requirement. And this is the story behind the birth of the <strong>NgWP Theme Kit</strong> Angular library that I’ve developed and is currently available as <a href="https://github.com/pierodetomi/ngwp-theme-kit">GitHub repository</a> (if you want to view the code) and as <a href="https://www.npmjs.com/package/ngwp-theme-kit">NPM package</a> (if you want to use it).</p><p>Before we continue, I’d like to throw a big disclaimer on the table: be warned that <strong><em>this library is just born and is still under development. It’s not 100% documented, it’s not 100% robust and probably won’t satisfy every use case. Please think carefully before using it for production scenarios — generally I’d advise not to do it.</em></strong></p><h3>Using the Library</h3><h3>Installation &amp; Module Import</h3><p>The first thing you need to do is to install the library in your Angular application:</p><pre>npm i ngwp-theme-kit</pre><p>Now you must import the <strong>NgwpThemeKitModule</strong> in your main module (usually app.module.ts):</p><pre>...<br><br>import { NgwpThemeKitModule } from &#39;ngwp-theme-kit&#39;;<br><br>...<br><br>@NgModule({<br>  ...<br>  imports: [<br>    ...<br><br>    NgwpThemeKitModule<br><br>    ...<br>  ],<br>  ...<br>})</pre><h3>Adding a themeconfig.json Configuration File</h3><p>This is the configuration file that the custom build tool will use to generate the WordPress theme.</p><p>Here you specify some key information about your theme (such as its <em>name</em>, <em>author</em> and a <em>description</em>) along with <strong><em>supported theme features</em></strong> (e.g. menus) and the <strong><em>customizer options</em></strong>.</p><p>For example, here is the content of the <a href="https://github.com/pierodetomi/ngwp-theme-kit/blob/master/angular/demo-theme/themeconfig.json">themeconfig.json</a> of the sample application that you can find in the GitHub repository of the library (called <strong>Demo Theme</strong>).</p><pre>{<br>  &quot;name&quot;: &quot;Demo Theme&quot;,<br>  &quot;description&quot;: &quot;A WordPress template developed with Angular frontend&quot;,<br>  &quot;author&quot;: &quot;Piero De Tomi&quot;,<br>  &quot;themeFeatures&quot;: [<br>    &quot;menus&quot;<br>  ],<br>  &quot;menus&quot;: [{<br>    &quot;location&quot;: &quot;header-menu&quot;,<br>    &quot;description&quot;: &quot;Header&quot;,<br>    &quot;initialName&quot;: &quot;Header Menu&quot;,<br>    &quot;initialEntries&quot;: [ &quot;Home&quot;, &quot;Blog&quot;, &quot;About Us&quot;, &quot;Privacy&quot; ],<br>    &quot;onlyRegisterLocation&quot;: false<br>  },{<br>    &quot;location&quot;: &quot;footer-menu&quot;,<br>    &quot;description&quot;: &quot;Footer&quot;,<br>    &quot;initialName&quot;: &quot;Footer Menu&quot;,<br>    &quot;initialEntries&quot;: [ &quot;Footer Item 1&quot;, &quot;Footer Item 2&quot;, &quot;Footer Item 3&quot;, &quot;Footer Item 4&quot; ],<br>    &quot;onlyRegisterLocation&quot;: false<br>  },{<br>    &quot;location&quot;: &quot;sidebar-menu&quot;,<br>    &quot;description&quot;: &quot;Sidebar Menu&quot;,<br>    &quot;onlyRegisterLocation&quot;: true<br>  }],<br>  &quot;sections&quot;: [{<br>    &quot;id&quot;: &quot;main&quot;,<br>    &quot;name&quot;: &quot;Main Config&quot;,<br>    &quot;description&quot;: &quot;Main configuration parameters&quot;,<br>    &quot;settings&quot;: [{<br>      &quot;id&quot;: &quot;title&quot;,<br>      &quot;label&quot;: &quot;Title&quot;,<br>      &quot;description&quot;: &quot;The title of this blog&quot;,<br>      &quot;defaultValue&quot;: null,<br>      &quot;controlType&quot;: &quot;text&quot;<br>    },{<br>      &quot;id&quot;: &quot;author&quot;,<br>      &quot;label&quot;: &quot;Author&quot;,<br>      &quot;description&quot;: &quot;The author of this blog&quot;,<br>      &quot;defaultValue&quot;: null,<br>      &quot;controlType&quot;: &quot;text&quot;<br>    },{<br>      &quot;id&quot;: &quot;logo&quot;,<br>      &quot;label&quot;: &quot;Logo&quot;,<br>      &quot;description&quot;: &quot;The website logo&quot;,<br>      &quot;defaultValue&quot;: null,<br>      &quot;controlType&quot;: &quot;image&quot;<br>    }]<br>  }]<br>}</pre><h3>Updating the build Script in package.json</h3><p>In order to “make the magic happen”, you need to modify the build script in your package.json file:</p><pre>{<br>  ...<br><br>  &quot;scripts&quot;: {<br>    ...<br><br>    &quot;build&quot;: &quot;ng build &amp;&amp; \&quot;./node_modules/ngwp-theme-kit/bin/NgWP.ThemeBuilder.exe\&quot; {{dist-path}} {{path-to-themeconfig.json}}&quot;,<br>    <br>    ...<br>  }<br><br>  ...<br>}</pre><p>In the above script you’ll have to replace:</p><ul><li>The {{dist-path}} token with your actual application’s dist path (usually dist/&lt;application name&gt;)</li><li>The {{path-to-themeconfig.json}} token with the actual file path of your themeconfig.json configuration file</li></ul><p>This script will build the application and run the <em>custom tool</em> (a .NET console application) that will transform the source files and will package the WordPress theme ready to be installed into your WordPress site.</p><h3>Sample Usage #1: Getting the Last 10 Blog Posts</h3><p>The <strong>NgWP Theme Kit</strong> library exports a series of services that allow you to access the CMS information, such as blog posts, categories, media and so on.</p><p>One of these services is the <strong>PostService</strong> service class: using this service you’ll be able to read blog posts.</p><p>For example, to read the last 10 blog posts you can write the following code:</p><pre>export class SampleComponent implements OnInit {<br>  public posts: IPost[] = [];<br><br>  constructor(private _postService: PostService) { }<br><br>  ngOnInit(): void {<br>    this._postService<br>      .get(1, 10)<br>      .subscribe((posts) =&gt; {<br>        this.posts = posts;<br>      });<br>  }<br>}</pre><p>Easy, right? Let’s see one more use case.</p><h3>Sample Usage #2: Reading a Custom Theme Setting</h3><p>Remember that in the themeconfig.json file you can specify custom theme sections and settings?</p><p>This will actually show the specified sections inside the WordPress Theme Customizer and you’ll be able to edit these values there.</p><p>You’ll also be able to <strong><em>read these values</em></strong> using the <strong>ThemeSettingsService</strong> service class, with a code like this:</p><pre>...<br>constructor(private _themeSettingsService: ThemeSettingsService) { }<br>...<br>this._themeSettingsService<br>   .get&lt;string&gt;(&#39;title&#39;)<br>   .subscribe((title) =&gt; {<br>      this.title = title;<br>   });<br>this._themeSettingsService<br>   .getImage(&#39;logo&#39;)<br>   .subscribe((logo) =&gt; {<br>      this.logo = logo;<br>   });</pre><h3>Other Code Samples</h3><p>You can find some more example usages on the <a href="https://github.com/pierodetomi/ngwp-theme-kit/tree/master/angular/demo-theme">Demo Theme</a> application inside the GitHub repository of the library.</p><h3>Building &amp; Packaging Your Theme</h3><p>To build and package your theme, simply execute the modified build script that you previously added to the package.json file:</p><pre>npm run build</pre><p>At the end of the script execution, you’ll find your theme files under the <em>dist</em> path of your application (depends on your configuration, but usually it’s dist/&lt;application-name&gt;).</p><p>Copy the folder you find inside the <em>dist</em> path into your WordPress theme’s folder, go to the “Theme” section in the admin panel of your WordPress website, activate your theme and you’re ready to go.</p><h3>BONUS: Changing the Theme’s Thumbnail</h3><p>The package you’ll build will ship with a default <strong>theme thumbnail</strong> (the screenshot.png file).</p><p>If you want to change the thumbnail of your theme, you’ll have to replace this image with your own.</p><h3>Conclusion</h3><p>That’s it for today’s article. I hope you find this library interesting and I’m sure we’ll do great things with it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77419c660d58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing a Messaging Service in Plain JavaScript]]></title>
            <link>https://pierodetomi.medium.com/implementing-a-messaging-service-in-plain-javascript-5516f6be8845?source=rss-dfbb5dbfc15------2</link>
            <guid isPermaLink="false">https://medium.com/p/5516f6be8845</guid>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Piero De Tomi]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 12:11:41 GMT</pubDate>
            <atom:updated>2023-01-04T12:11:41.853Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*PTMQMVQagscz67Xf0toZ0Q.jpeg" /></figure><h3>Introduction</h3><p>In 2020 talking about “plain JavaScript” may sound weird. We have TypeScript and we have a lot of libraries and excellent frameworks such as Angular, React and so on.</p><p>But truth is that from time to time, as a professional software engineer, you’ll find yourself working on a legacy web application that doesn’t use any framework on the frontend side. The only friendly-looking thing you’ll find (sometimes) will be jQuery. That’s it.</p><p>However you’ll still have to implement a good solution, hopefully structuring frontend in components, decoupling frontend from backend, writing JS modules to function as sort of view-models for your UI components. And while doing this you’ll need to use some sort of “communication protocol” to make these components work together well and talk each other.</p><p>I’ve recently been in this situation and one of the first things I did was implementing a <strong>Messaging Service</strong> JavaScript module to handle communication between components implementing the <a href="https://en.wikipedia.org/wiki/Messaging_pattern">Messaging Pattern</a>, more specifically the <a href="https://it.wikipedia.org/wiki/Publish/subscribe"><strong>publish/subscribe</strong></a> messaging pattern.</p><p>In this article I’ll show you the (very simple) code and I’ll explain how it works and the choices I made.</p><h3>GitHub Repository</h3><p>If you need the ready-made solution and you prefer to inspect the code by yourself, here’s the <a href="https://github.com/pierodetomi/js-messaging-service">GitHub repository</a> with the code: feel free to use it as you like.</p><p>You’ll find the module’s source code in the <strong>./services/messaging-service.js</strong> file.</p><h3>The Messaging Service Module</h3><p>To build a basic messaging service we need at least three main functions:</p><ul><li><strong>Subscribe</strong></li><li><strong>Publish</strong></li><li><strong><em>[Optional]</em> Unsubscribe</strong></li></ul><h3>The Subscribe Function</h3><p>This is the function that components will call to register themselves to be notified whenever a specific <em>topic</em> will be published.<br>In order to register, components need to provide information on:</p><ul><li>Who they are</li><li>The <em>topic</em> they’re interested in</li><li>What they’re going to do when something will be <em>published</em> about the topic</li></ul><p>The <strong>Subscribe </strong>function could look something like this:</p><pre>var subscriptions = [];<br><br>function subscribe (target, topic, callback) {<br>    if (hasSubscription(target))<br>        return;<br><br>    subscriptions.push({<br>        target,<br>        topic,<br>        callback<br>    });<br>}<br><br>function hasSubscription (target) {<br>    var found = false;<br><br>    for (var i = 0; i &lt; subscriptions.length; i++) {<br>        var subscription = subscriptions[i];<br><br>        if (subscription.target === target &amp;&amp; subscription.topic === topic) {<br>            found = true;<br>            break;<br>        }<br>    }<br><br>    return found;<br>}</pre><p>When this function is called we create an object (we’ll call it <strong>subscription object</strong>) and store it inside the <strong>subscriptions</strong> array variable for later use (line 7).</p><p>The purpose of the <strong>target</strong> parameter is to identify <em>who</em> is subscribing to the topic.<br>The <strong>topic</strong> parameter is the topic we’re subscribing to.<br>The <strong>callback</strong> parameter should be a delegate function that will be called when something will be published about that topic.</p><p>Finally, before creating the subscription object we check and make sure that we don’t already have a subscription for the same <strong><em>target/topic</em></strong> couple (line 4).<br>This check will avoid ending with duplicate subscriptions at runtime (and hence duplicate callback calls), although this should be ensured by writing the application code correctly (so you might want to disable this check if you WANT your application to behave badly in case of programming errors on this aspect).</p><h3>The Publish Function</h3><p>This is the function that components will call to publish something about a specific <em>topic</em>.<br>In order to use this function, components need to provide information on:</p><ul><li>The <em>topic</em> about which they’re publishing</li><li><em>What</em> they’re actually publishing (usually information/data)</li></ul><p>The <strong>Publish </strong>function could look something like this:</p><pre>function publish (topic, payload) {<br>    if (!payload)<br>        payload = null;<br><br>    for (var i = 0; i &lt; subscriptions.length; i++) {<br>        var subscription = subscriptions[i];<br><br>        if (subscription.topic === topic)<br>            subscription.callback(payload);<br>    }<br>}</pre><p>What is happening here is quite simple: when the publish function is called, the messaging service checks internally for any subscriptions (line 5) on the requested topic (line 8), and for each subscription that’s matching it calls the related callback, passing as parameter whatever is contained in the <strong>payload</strong> input parameter.</p><p>This way, every component subscribed to that topic will be passively notified and will do something (= whatever is inside the callback function), without even knowing <em>who</em> published the update on the topic: in fact they don’t care and <em>they don’t need to know who published the update </em>(= decoupling).</p><h3>The Unsubscribe Function</h3><p>This maybe considered as a bonus function. Its purpose, as you may think, is to allow a component to unsubscribe from a topic, in order to stop receiving topic updates.</p><p>The code is symmetrical to the <strong>subscribe</strong> function and looks like this:</p><pre>function unsubscribe (target, topic) {<br>    for (var i = subscriptions.length - 1; i &gt;= 0; i--) {<br>        var subscription = subscriptions[i];<br><br>        if (subscription.target === target &amp;&amp; subscription.topic === topic)<br>            subscriptions.splice(i, 1);<br>    }<br>}</pre><p>Here we’re simply removing any subscription object matching the provided target and topic parameters.</p><h3>Sample Code</h3><p>I prepared a <a href="https://github.com/pierodetomi/js-messaging-service">GitHub repository</a> with the messaging service code along with some sample code that demonstrates a possible use-case.</p><p>You can find the module’s source code in the ./services/messaging-service.js file.</p><p>Using npm (after executing npm install in the root project directory), you can run the sample code executing the following command:</p><pre>http-server -p [PORT]</pre><p>PORT should be whatever port you would like to start the local http server on.</p><p>Then loading the page <strong>http://localhost:[PORT]/index.html</strong> you’ll see the sample page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/0*Kj8DzVlHTV9o4E6x.png" /></figure><p>Now, as the quick tip suggests, if you click the “Change Name” button the name <strong>Jack Jones</strong> will change (I’ll leave the surprise of the result to you).</p><p>I know, it’s a super simple example, but it’s purpose is just to demonstrate how to practically use the messaging service: it’s up to you to leverage its full potential in a real web application.</p><h3>Conclusion</h3><p>Messaging is a simple but effective way to allow inter-component communication, maintaining separation/decoupling and allowing for cleaner code.</p><p>If you need to use the full code, don’t forget to head to the <a href="https://github.com/pierodetomi/js-messaging-service"><strong>GitHub repository</strong></a>, where you can find the complete source file.</p><p>I hope this can be helpful for you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5516f6be8845" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing a Synchronous HTTP Client in C#.NET]]></title>
            <link>https://pierodetomi.medium.com/implementing-a-synchronous-http-client-in-c-net-e1a72c06a600?source=rss-dfbb5dbfc15------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1a72c06a600</guid>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Piero De Tomi]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 12:11:41 GMT</pubDate>
            <atom:updated>2023-01-04T12:11:41.844Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*fwpuIKwehcTOW9QSGjlESw.jpeg" /></figure><p>You may be thinking that in 2019 this title is <em>non-sense</em>, and I’d be tempted to agree with you.</p><p>Not even I thought that in 2019 I would have found myself needing a synchronous http client implementation.</p><p><em>We have the </em><a href="https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.8">HttpClient</a><em>, right?</em></p><p>Unfortunately, not exactly.</p><p>What if you are in a context where you <strong><em>cannot</em></strong> use the asynchronous HttpClient?</p><h3>Intro — A Unity 3D Story</h3><p>Quick example: a few days ago I (re)started to use Unity 3D, because I had a nice idea for a simple 3D game and I wanted to implement it.</p><p>The architecture of the game is made of two parts:</p><ul><li>The server-side application, developed in ASP.NET Core 2.2, that exposes APIs used by the game</li><li>The client application, that’s the Unity game</li></ul><p>Once implemented the server-side APIs, I needed to call them from Unity scripts and I started writing asynchronous code as I do every time I use the HttpClient (GetAsync(), PostAsync(), etc.).</p><p>And while Visual Studio let me write async/await functions inside my code, Unity itself wasn’t working at all — the fun part is that Unity wasn’t even showing any error… it just didn’t do anything when I executed my scripts.</p><p>This made me discover that Unity does not support async/await: I also tried using the <a href="https://assetstore.unity.com/packages/tools/integration/async-await-support-101056">Async Await Support</a> package from the Unity Asset Store, but it didn’t work properly and I eventually decided to give up on the async aspect in Unity.</p><h3>My Decision — The SyncHttpClient</h3><p>Once I knew that async/await isn’t supported by Unity, the only thing left to do was writing synchronous HTTP requests the <em>old way</em>.</p><p>How?</p><p>Simple. Using the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.net.httpwebrequest?view=netframework-4.8">HttpWebRequest</a> class.</p><p>For those of you who don’t know this class, well… it’s been around for a lot of years in .NET, already before the advent of the HttpClient.<br>This class let’s you create synchronous HTTP requests, that’s all I needed in this case.</p><p>The only downside is that you need to write more code to achieve what you need and the code you end up with is more cumbersome than the code you’d write using the HttpClient.</p><p>Oh well… patience.</p><h3>Repository &amp; NuGet Package</h3><p>If you just want the code you can head directly to the <a href="https://github.com/pierodetomi/dotnet-webutils">GitHub repository</a> where I published the library or you can even download and use the <a href="https://www.nuget.org/packages/PieroDeTomi.DotNet.WebUtils/">NuGet Package</a> I published.</p><p>Either ways you’re covered — your choice.</p><h3>Some explanations</h3><p>The idea behind the <strong>HttpWebRequest</strong> is that you actually <em>create</em> the request object and then execute it.</p><p>This is how you create an HTTP request object:</p><pre>var url = &quot;https://yourdomain.com/api/sample&quot;;<br>var request = WebRequest.CreateHttp(url);<br>request.Method = &quot;GET&quot;; // or &quot;POST&quot;, &quot;PUT&quot;, &quot;PATCH&quot;, &quot;DELETE&quot;, etc.</pre><p>Let’s assume we’re creating a GET request to a resource.<br>Once created the request, we have to execute it, in order to obtain the <em>response</em>:</p><pre>using (var response = (HttpWebResponse)request.GetResponse())<br>{<br>    // Do something with the response<br>}</pre><p>Note that since the <strong>HttpWebResponse</strong> is <strong>IDisposable</strong> we wrap its usage in a using block.</p><p>Now we have the response, but we need to actually <em>read</em> it to get its content:</p><pre>// Get the stream associated with the response<br>using (var responseStream = response.GetResponseStream())<br>{<br>    // Get a reader capable of reading the response stream<br>    using (var myStreamReader = new StreamReader(responseStream, Encoding.UTF8))<br>    {<br>        // Read stream content as string<br>        var responseJSON = myStreamReader.ReadToEnd();<br>        <br>        // Assuming the response is in JSON format, deserialize it<br>        // creating an instance of TData type (generic type declared before).<br>        data = JsonConvert.DeserializeObject&lt;TData&gt;(responseJSON);<br>    }<br>}</pre><p>I placed a comment on every line in the code above, it should be easy to understand.</p><p>The thing I’d like to underline is that I used the <a href="https://www.nuget.org/packages/Newtonsoft.Json/">Newtonsoft.Json NuGet Package</a> to easily hande JSON serialization/deserialization.</p><h3>Wrap up</h3><p>The above code is only a sample usage of the HttpWebRequest class: you can find the complete <strong>SyncHttpClient</strong> implementation at my <a href="https://github.com/pierodetomi/dotnet-webutils">GitHub repository</a> — the class exposes <em>generic</em> methods and hides the usage of the HttpWebRequest class internally, making it very easy to send HTTP requests like we usually do with the HttpClient class.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1a72c06a600" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrate an Angular Application in Your ASP.NET Core Web Application]]></title>
            <link>https://pierodetomi.medium.com/integrate-an-angular-application-in-your-asp-net-core-web-application-545756060d1b?source=rss-dfbb5dbfc15------2</link>
            <guid isPermaLink="false">https://medium.com/p/545756060d1b</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Piero De Tomi]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 12:11:41 GMT</pubDate>
            <atom:updated>2023-01-04T12:11:41.830Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*zALr2EQwvZtqGEgNr5_KIg.png" /></figure><p>When you develop an Angular application that connects to a backend, there are cases in which you may want to serve the frontend files directly as part of the backend application, instead of serving them as an independent application.</p><p>An example? To simplify the authentication and authorization process.</p><p>In this scenario, you could delegate to the ASP.NET code the management of the authentication session (cookies, etc.) avoiding the need to manage auth tokens — with the consequent expiration/renewal problems.</p><p>In this article, I’ll guide you through the simple process of creating an Angular application and serve it directly as part of your ASP.NET Core web application.</p><h3>Angular App Creation</h3><p>The way we create the Angular application doesn’t change, we use the Angular CLI as usual:</p><pre>ng new demo-app</pre><p>Launching the application now with ng serve we’ll see the classic output of the <em>starter </em>template:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*6vRdZDb6upZLJJnm.png" /></figure><p>Not so interesting, but it’s fine for demonstration purposes.</p><p>At this point, we’ll <em>build</em> the application, in order to have the <em>dist</em> output.</p><pre>ng build --prod</pre><p>Ok, for now, it’s enough on the Angular side. Let’s switch to Visual Studio.</p><h3>ASP.NET Core Application Creation</h3><p>Open Visual Studio and create a new Web Application going into <em>File &gt; New Project &gt; ASP.NET Core Web Application</em>, give it a name and choose the <em>Web Application</em> template:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*9eWwHDZyO50SLjz3.png" /></figure><p>If we launch the application with <em>F5</em> (or <em>CTRL + F5</em>) we’ll see that Visual Studio has created the starting page for us, as usual:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*_GYPLUElMRTRCYP9.png" /></figure><p>We want to replace this content with our actual Angular application, so let’s start by importing the Angular project into our ASP.NET Core project directory.</p><h3>Move the Angular Project Under the ASP.NET Core Project Directory</h3><p>As the title says, we have to take the folder containing the Angular project and move that inside the folder created for the Visual Studio project.</p><p>I named my Angular project demo-app and my ASP.NET Core project DemoAngularIntegration, so the resulting file system hierarchy will be the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/0*KNRs-dIP4NObbGLh.png" /></figure><p>Now that we have the Angular files in place we need to tweak a couple of things in our ASP.NET application.</p><h3>Change the _Layout.cshtml markup</h3><p>If we want to have our ASP.NET Core application loading the Angular code, we actually need to <em>reference</em> those files and bring the Angular code into our application.</p><p>The first step is to change the main _Layout.cshtml markup in order to be the same as the index.html file of our Angular application inside the <em>dist</em> output folder.</p><p>Open the ~/Pages/Shared/_Layout.cshtml file, delete its content and copy/paste the markup from ~/[your_ng_app_name]/dist/[your_ng_app_name]/index.html.</p><p>The result should resemble something like this:</p><pre>&lt;!-- _Layout.cshtml --&gt;<br><br>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;title&gt;DemoApp&lt;/title&gt;<br>    &lt;base href=&quot;/&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br>    &lt;link rel=&quot;icon&quot; type=&quot;image/x-icon&quot; href=&quot;favicon.ico&quot;&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;styles......css&quot;&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;app-root&gt;&lt;/app-root&gt;<br>    <br>    &lt;script type=&quot;text/javascript&quot; src=&quot;runtime......js&quot;&gt;&lt;/script&gt;<br>    &lt;script type=&quot;text/javascript&quot; src=&quot;es2015-polyfills......js&quot;&gt;&lt;/script&gt;<br>    &lt;script type=&quot;text/javascript&quot; src=&quot;polyfills......js&quot;&gt;&lt;/script&gt;<br>    &lt;script type=&quot;text/javascript&quot; src=&quot;main......js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><h3>Install the BuildBundlerMinifier NuGet Package</h3><p>Open the <em>Package Manager Console</em> and execute the following command, to install the required package:</p><pre>Install-Package BuildBundlerMinifier</pre><p>We’ll use this package to be sure that the bundles are updated every time we compile the project.</p><h3>Create the Angular JS and CSS bundles</h3><p>Let’s take advantage of the new bundleconfig mechanism of ASP.NET Core and configure the bundles that we’ll load in our _Layout page.</p><p>Create a file called bundleconfig.json at the root level of your application and insert the following <em>json</em> code:</p><pre>// bundleconfig.json<br><br>[<br>  {<br>    &quot;outputFileName&quot;: &quot;wwwroot/js/app.js&quot;,<br>    &quot;inputFiles&quot;: [<br>      &quot;demo-app/dist/demo-app/runtime......js&quot;,<br>      &quot;demo-app/dist/demo-app/es2015-polyfills......js&quot;,<br>      &quot;demo-app/dist/demo-app/polyfills......js&quot;,<br>      &quot;demo-app/dist/demo-app/main......js&quot;<br>    ],<br>    &quot;minify&quot;: {<br>      &quot;enabled&quot;: false,<br>      &quot;renameLocals&quot;: false<br>    },<br>    &quot;sourceMap&quot;: false<br>  },<br>  {<br>    &quot;outputFileName&quot;: &quot;wwwroot/js/app.css&quot;,<br>    &quot;inputFiles&quot;: [<br>      &quot;demo-app/dist/demo-app/*.css&quot;<br>    ],<br>    &quot;minify&quot;: {<br>      &quot;enabled&quot;: false,<br>      &quot;renameLocals&quot;: false<br>    }<br>  }<br>]</pre><p>Note that in place of demo-app you should write your actual Angular app name.</p><h3>Reference the Bundles from _Layout.cshtml</h3><p>Now we need to insert the bundle references inside the _Layout.cshtml page.</p><p>The final code should be as follows:</p><pre>&lt;!-- _Layout.cshtml --&gt;<br><br>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;title&gt;DemoApp&lt;/title&gt;<br>    &lt;base href=&quot;/&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br>    &lt;link rel=&quot;icon&quot; type=&quot;image/x-icon&quot; href=&quot;favicon.ico&quot;&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;~/css/app.css&quot;&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;app-root&gt;&lt;/app-root&gt;<br>    <br>    &lt;script type=&quot;text/javascript&quot; src=&quot;~/js/app.js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>If you launch the application now it won’t work, and that’s because we still miss the @RenderBody() method call in the _Layout markup.</p><h3>Restore the RenderBody() Method Call</h3><p>Just place the RenderBody() statement in place of the &lt;app-root&gt; component, moving it to the ~/Pages/Index.cshtml page.</p><p>At the end of this operation you should have this result:</p><pre>&lt;!-- Index.cshtml --&gt;<br><br>@page<br>@model IndexModel<br>@{<br> ViewData[&quot;Title&quot;] = &quot;Home Page&quot;;<br>}<br><br>&lt;app-root&gt;&lt;/app-root&gt;</pre><pre>&lt;!-- _Layout.cshtml --&gt;<br><br>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;title&gt;DemoApp&lt;/title&gt;<br>    &lt;base href=&quot;/&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br>    &lt;link rel=&quot;icon&quot; type=&quot;image/x-icon&quot; href=&quot;favicon.ico&quot;&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;~/css/app.css&quot;&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    @RenderBody()<br>    <br>    &lt;script type=&quot;text/javascript&quot; src=&quot;~/js/app.js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><h3>Launch the Application — Check</h3><p>We’re ready to launch the application and if we did everything correctly we should see the Angular app served from the ASP.NET Core application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*EaNO2n3bsMKUQLqp.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=545756060d1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Cosmos DB as Identity Provider in ASP.NET Core 5 with EntityFramework Core]]></title>
            <link>https://pierodetomi.medium.com/using-cosmos-db-as-identity-provider-in-asp-net-core-5-with-entityframework-core-23c77d326134?source=rss-dfbb5dbfc15------2</link>
            <guid isPermaLink="false">https://medium.com/p/23c77d326134</guid>
            <category><![CDATA[identity-provider]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Piero De Tomi]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 12:11:41 GMT</pubDate>
            <atom:updated>2023-01-04T12:11:41.580Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dpB-UaYp_fRT2rYAXBnkVA.jpeg" /></figure><h3>Background Story</h3><p>I had an ASP.NET Core 5.0 Web Application based on the Angular SPA template and I needed to use a Cosmos DB database in the backend, but at the same time I wanted to use the Identity and Identity Server feature provided by ASP.NET Core.</p><p>And since this is not supported natively on Cosmos DB I decided to implement my own storage provider using the official <a href="https://docs.microsoft.com/en-us/ef/core/providers/cosmos/?tabs=dotnet-core-cli">EF Core Azure Cosmos DB Provider</a>.</p><p>Fortunately the ASP.NET Core Identity ecosystem has a <a href="https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity-custom-storage-providers?view=aspnetcore-5.0#the-aspnet-core-identity-architecture">good architecture</a> design and allows for customization/extension quite easily.</p><h3>The NuGet Package</h3><p>This task has been challenging and fun at the same time and the result was quite satisfying.</p><p>At the same time, I found very frustrating that Microsoft doesn’t provide an official Cosmos DB integration for Identity… after all Cosmos DB is a product owned by Microsoft.</p><p>These considerations made me decide to move the implementation of the storage provider to a <a href="https://www.nuget.org/packages/PieroDeTomi.EntityFrameworkCore.Identity.Cosmos/"><strong>NuGet package</strong></a>, in order to make it freely available to anyone.</p><h3>GitHub Repository</h3><p>If you’re interested to know how the provider is implemented in detail, you can head to its <a href="https://github.com/pierodetomi/efcore-identity-cosmos"><strong>GitHub Repository</strong></a>.</p><p>It is <strong>MIT</strong> licenced, that means you can do whatever you want with the code: copy, edit, redistribute, whatever.</p><p><strong>BUT…</strong></p><p>If you’re really interested in making modifications to this library, I suggest you to think about <strong><em>contributing</em></strong> directly to the repository.</p><h3>Installation (NuGet)</h3><p>To install the required package you can use the Package Manager UI in Visual Studio or execute the following command directly in the Package Manager Console inside Visual Studio.</p><pre>PM&gt; Install-Package PieroDeTomi.EntityFrameworkCore.Identity.Cosmos</pre><p>Please note that, to date, this package references version 5.0.3 of the ASP.NET Core Identity ecosystem packages, so you’ll be able to use it only if your project is targeting .NET 5.0.</p><h3>Integration Steps</h3><h3>Project Requirements</h3><p>The following steps assume that you have an ASP.NET Core 5 Web Application project that uses Identity and/or IdentityServer features.</p><h3>Cosmos DB Requirements</h3><h4>➥ Database</h4><p>Just as with EF Core on SQL Server, you have to manually create a database in your Cosmos DB instance to be able to operate.</p><h4>➥ Containers</h4><p>Since <strong>migrations are NOT supported when using EF Core on Cosmos DB</strong>, you’ll have to manually create the following containers in your database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/0*KwD3H79O8AFX0Sho.png" /></figure><h3>DbContext</h3><p>You have to create a DbContext that implements the provided CosmosIdentityDbContext type.</p><p>To start off you can create just an empty DbContext class that satisfies the above requirement:</p><pre>public class MyDbContext : CosmosIdentityDbContext&lt;IdentityUser&gt;<br>{<br>  public MyDbContext(DbContextOptions dbContextOptions, IOptions&lt;OperationalStoreOptions&gt; options)<br>    : base(dbContextOptions, options) { }<br>}</pre><p>Later in your development you’ll likely add some entities to your application: you’ll update the DbContext class adding the DbSet&lt;T&gt; properties and overriding the OnModelCreating() method for entity mappings:</p><pre>public class MyDbContext : CosmosIdentityDbContext&lt;IdentityUser&gt;<br>{<br>  public DbSet&lt;SampleEntity&gt; SampleEntities { get; set; }<br>  <br>  public DbSet&lt;OtherSampleEntity&gt; OtherSampleEntities { get; set; }<br>  <br>  public MyDbContext(DbContextOptions dbContextOptions, IOptions&lt;OperationalStoreOptions&gt; options)<br>    : base(dbContextOptions, options) { }<br>  <br>  protected override void OnModelCreating(ModelBuilder builder)<br>  {<br>    // DO NOT REMOVE THIS LINE. If you do, your context won&#39;t work as expected.<br>    base.OnModelCreating(builder);<br>    <br>    // TODO: Add your own fluent mappings<br>  }<br>}</pre><p>As specified in the above code snippet, when overriding the OnModelCreating() method it is <strong>crucial</strong> to not remove the base.OnModelCreating(builder) call: if you do so, the identity configuration mappings won’t be applied and the application won’t work properly.</p><h3>Configurations in Startup.cs File</h3><h4>➥ Remove the Default Identity Provider</h4><p>Remove the line where the default/current identity provider is added/configured.</p><p>If you just created a new project, this line should be something like:</p><pre>services.AddDefaultIdentity&lt;IdentityUser&gt;(options =&gt; options.SignIn.RequireConfirmedAccount = true)<br>  .AddEntityFrameworkStores&lt;ApplicationDbContext&gt;();</pre><h4>➥ Remove Default DbContext Configuration</h4><p>Remove the line where the SqlServer DbContext is configured.<br>It should be something like:</p><pre>services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;<br>  options.UseSqlServer(Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));</pre><h4>➥ Add Cosmos DB Identity Provider</h4><p>Now add the Cosmos DB provider:</p><pre>services.AddCosmosIdentity&lt;MyDbContext, IdentityUser, IdentityRole&gt;(<br>  // Auth provider standard configuration (e.g.: account confirmation, password requirements, etc.)<br>  options =&gt; ...,<br>  <br>  // Cosmos DB configuration options<br>  options =&gt; options.UseCosmos(<br>      &quot;your_cosmos_db_URL&quot;,<br>      &quot;your_cosmos_db_key&quot;,<br>      databaseName: &quot;your_db&quot;<br>  ),<br>  <br>  // If true, AddDefaultTokenProviders() method will be called on the IdentityBuilder instance<br>  addDefaultTokenProviders: false   <br>);</pre><h4>➥ Update IdentityServer Configuration (If Applicable)</h4><p>If your project is using <strong>IdentityServer</strong>, update the related configuration in order to use your new DbContext implementation:</p><pre>// Note that we&#39;re using MyDbContext as the second type parameter here...<br>services.AddIdentityServer().AddApiAuthorization&lt;IdentityUser, MyDbContext&gt;();</pre><h3>This provider &amp; Identity UI</h3><p>This provider is also compatible with <strong>Identity UI</strong>.</p><p>You can either use the default Identity UI (e.g.: in Startup.cs there’s a call to AddDefaultUI() method) or use the <a href="https://docs.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-5.0&amp;tabs=visual-studio">scaffolded</a> version of Identity UI.<br>Both scenarios should work out of the box without having to do anything else.</p><p>Finally you can also use your own implementation of Identity UI, as long as you use the Identity services (e.g.: UserManager and SignInManager).</p><h3>Available Services</h3><p>This library registers a basic Cosmos DB EntityFramework repository implementation in the application service collection.</p><p>You can resolve an instance of this repository in your constructors requiring the IRepository interface.</p><p>An example:</p><pre>public class MyClass {<br>  private readonly IRepository _repo;<br>  <br>  public MyClass(IRepository repo) {<br>    _repo = repo;<br>  }<br>  <br>  // ... Use the _repo instance methods to query the database<br>}</pre><h3>IRepository methods</h3><p>Just for your information, here is a summary of the available methods in the IRepository interface:</p><ul><li>Table&lt;TEntity&gt;()</li><li>GetById&lt;TEntity&gt;(string id)</li><li>TryFindOne&lt;TEntity&gt;(Expression&lt;Func&lt;TEntity, bool&gt;&gt; predicate)</li><li>Find&lt;TEntity&gt;(Expression&lt;Func&lt;TEntity, bool&gt;&gt; predicate)</li><li>Add&lt;TEntity&gt;(TEntity entity)</li><li>Update&lt;TEntity&gt;(TEntity entity)</li><li>DeleteById&lt;TEntity&gt;(string id)</li><li>Delete&lt;TEntity&gt;(TEntity entity)</li><li>Delete&lt;TEntity&gt;(Expression&lt;Func&lt;TEntity, bool&gt;&gt; predicate)</li><li>SaveChangesAsync()</li></ul><h3>Conclusion</h3><p>We’ve seen how to install and configure the Cosmos DB provider. It’s a simple task, isn’t it?</p><p>I hope you’ll find it useful, I’m currently using it for my project!</p><p>See you on the next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23c77d326134" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to easily setup a good water shader in Blender]]></title>
            <link>https://pierodetomi.medium.com/how-to-easily-setup-a-good-water-shader-in-blender-ebac8a094e35?source=rss-dfbb5dbfc15------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebac8a094e35</guid>
            <category><![CDATA[art]]></category>
            <category><![CDATA[3d]]></category>
            <category><![CDATA[blender]]></category>
            <category><![CDATA[3d-modeling]]></category>
            <dc:creator><![CDATA[Piero De Tomi]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 12:11:41 GMT</pubDate>
            <atom:updated>2023-01-04T12:11:41.511Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*MoxhOkqvQ5Xbi4UZJp-Zkg.png" /></figure><p>Water is such a complex material, with specific features like reflection and refraction and building a water shader in 3d programs is not a trivial task.</p><p>Today I’ll show you a simple and quick — but still effective — water shader setup in <strong>Blender 2.80</strong>.</p><p>For the demonstration I’ve setup a very basic river bed made of pebbles, with some mud and grass on the sides. I used a fluid simulation to obtain a mesh that will represent our water just to have some movement on the surface, rather than just creating a flat plane that would look boring.<br>I’ve also setup an HDRI environment map that will give us nice reflections on our water.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*2k5ftWh1iwqCBeAc.png" /></figure><p>In a moment we will create a new material and build our shader to make this water look good and believable.</p><h3>What we COULD do</h3><p>Think about water in real life: its main physical features are that it’s transparent and it has a reflective surface at the same time: we could use a transparency node, mix it with a reflection node, add glossiness and other details to build a super-complex setup, but I want to suggest a simplest and quickest way to achieve a nice result that still looks good.</p><h3>The idea — what we WILL do</h3><p>Basically the idea is to:</p><ul><li>Create a <strong>Glass</strong> shader node</li><li>Mix the glass node with a <strong>Transparent</strong> shader node, setting the proper <strong>IoR</strong> (read: <em>Index of Refraction</em>) of water, which is generally 1.33</li><li>Tweak the mix factor of the Glass and Transparent nodes to get the right balance between reflectivity and transparency</li></ul><p>Let’s see this plan in action.</p><h3>Walkthrough</h3><p>Create a <strong>Glass BSDF</strong> node, change its IOR field to 1.33 and connect it to the <em>Surface</em> socket of the <strong>Material Output</strong> node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*LFbSHF_K7skhY8qB.png" /></figure><p>The result is starting to look nice, but if you look at the surface from the top you’ll notice that there isn’t any transparency on the surface.</p><p>So let’s bring the transparency in the game.</p><p>Create a new <strong>Transparent BSDF</strong> node in the graph. Since we have to mix it with the glass node previously added, let’s also create a <strong>Mix Shader</strong> node in the graph.</p><p>Now connect the glass and the transparent nodes to the input sockets of the mix node, and also connect the output socket of the mix node to the material output node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*3fcmhfRLPB5CBjOI.png" /></figure><p>To see any change in the scene we also have to go under the <em>Surface</em> section of the water material (inside the right panel in Blender) and change the <strong>Blend Mode</strong> to <em>Alpha Blend</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*LwRYVjHy_oQDecFF.png" /></figure><p>Now the water is transparent… but it’s TOO transparent, right?</p><p>Well, I found that a good mix factor (for me) between the glass and the transparent shader is approximately 0.3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*KWKVW_PkkWN1J__I.png" /></figure><p>I suggest you to play further with the mix factor value on the Mix Shader node, ultil you find the right value that completely satisfies your taste.</p><p>And that’s it… we have water! :)</p><h3>Conclusion</h3><p>I’m aware that this shader won’t suit every use case, but it can save you a lot of time if you just need to have a water material that looks good without spending hours to build a complex shader graph.</p><p>Hope you like it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebac8a094e35" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>