<?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 Stephen Robert James Adam on Medium]]></title>
        <description><![CDATA[Stories by Stephen Robert James Adam on Medium]]></description>
        <link>https://medium.com/@stephen-adam?source=rss-ae04f4d0e60------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*MLaW6OMaWQxb4Pf6.</url>
            <title>Stories by Stephen Robert James Adam on Medium</title>
            <link>https://medium.com/@stephen-adam?source=rss-ae04f4d0e60------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 09:00:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stephen-adam/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[Docker, .NET Core 5.0, Angular 11, Nginx and Postgres on the Google Cloud Platform — Pt 2]]></title>
            <link>https://medium.com/geekculture/docker-net-core-5-0-angular-11-nginx-and-postgres-on-the-google-cloud-platform-pt-2-a8b32167e183?source=rss-ae04f4d0e60------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8b32167e183</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Stephen Robert James Adam]]></dc:creator>
            <pubDate>Thu, 15 Apr 2021 21:49:18 GMT</pubDate>
            <atom:updated>2021-06-01T06:40:25.272Z</atom:updated>
            <content:encoded><![CDATA[<h3>Docker, .NET Core 5.0, Angular 11, Nginx and Postgres on the Google Cloud Platform — Pt 2</h3><p><a href="https://stephen-adam.medium.com/docker-net-core-5-0-angular-11-nginx-and-postgres-on-the-google-cloud-platform-pt-1-363160e34439">In part 1</a> we built and ran our images locally and covered the docker-compose file and the docker build files. Now its time to look at moving everything to the cloud and getting it running almost for free!</p><p><a href="https://github.com/Pastafarian/GcpBlog">The source code for the example can be found here.</a></p><h3>Pushing The Api Docker Image</h3><p>When we move to the cloud we’ll be relying on the docker compose instance on our VM to pull down the prebuilt Api image we created in the first step. In order make our image accessable we’ll be putting it up on Docker Hub, a docker image repository; other repositories are available such as <a href="https://azure.microsoft.com/en-gb/services/container-registry/">Azure Container Registry</a> and <a href="https://cloud.google.com/container-registry">Google’s Container Registry</a>.</p><p>First you’ll need to <a href="https://hub.docker.com/signup">sign up</a> and create a Docker Hub account and give yourself a Docker ID.</p><p>Once you’ve completed this step it’s time to push our container to the hub with the following commands.</p><p>Enter in your Docker ID as your user name and then enter your password.</p><pre>docker login</pre><p>Now open powershell in the root of our solution where the docker-compose.yml file lives.</p><p>This will create a fresh images for our applications including the Api.</p><p><em>Note, it’s faster just to go the the server directory and run a docker build in there, but I want to keep things as simple as possible with as few commands to explain</em>.</p><pre>docker-compose build</pre><p>Docker images will show us all the images on our system, including the Api image.</p><pre>docker images</pre><p>We should get an output that looks something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*lRZ799BQDp7VwJHySv_-cg.png" /></figure><p>In order to push the api image to Docker Hub we’ll need to give it a tag including the Docker ID you gave it earlier. In my case it’s my name ‘stephenadam’</p><pre>docker tag gcpblog_api stephenadam/gcpblog_api</pre><p>Now to push our image to Docker Hub.</p><pre>docker push stephenadam/gcpblog_api</pre><p>Note, by default this image will be public to the outside world. Docker Hub allow you to have one private image for free, when working with your own site go to the settings for the image on Docker Hub and set it to private.</p><h3>Setting Up the Cloud Environment</h3><p>For this step we’ll need a Google account to access to the Google Cloud Platform and access the 3 month / $300 trial they offer.</p><p>Once you have signed into Google create a free Google Cloud Platform Account by going to the following URL.</p><p><a href="https://cloud.google.com/free/">https://cloud.google.com/free/</a></p><p>Next let’s go the the Cloud Console and get to work!</p><p><a href="https://console.cloud.google.com/">https://console.cloud.google.com/</a></p><p>First we need to create a VM to run our site on. Find the ‘Compute Engine’ on the left hand menu and then go to VM instances. While there are other options for running our code, Compute Engines VMs are the cheapest option and let us configure our own environment.</p><p>Google offers a free VM option whichh we’ll be using here. We’ll need to provision an f1-micro instance in one of the following locations — us-west1, us-central1 or us-east1.</p><p>The only option we’ll need to pay for later is the fixed IP which comes out as $2.88 a month. Not bad for a site hosted in GCP!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*kPxDpj_X-sdhlSK1d9qOxg.png" /></figure><p>Create an instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JI4AuJ0vPFVZp3pnwCL_tg.png" /></figure><p>Now we need to configure our virtual machine. For this example we’ll be leaving everything in its default setting apart from the following options:</p><p><strong>Name:</strong> Pick something suitable. I’ve gone for gcp-blog.<br><strong>Machine type:</strong> e2-small. This is a low powered machine but it’s cheap and will happily work for our purposes. <br><strong>Firewall: </strong>Here ensure we allow both HTTP and HTTPS access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*zuFVZMiN_2yR6N_CbAv9Dg.png" /></figure><p>We have up to 30 gig of free storage so go to the boot disk section and click on ‘Change’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*sjz4nbM0iwU5eWrOA9TZhw.png" /></figure><p>Now up the disk space to 30gig.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*k9ugDwe-ugC8cI-pQ6uHRQ.png" /></figure><p>If you have setup the machine successfully you should see the following message in the top right had screen when setting up the VM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*wTAaEc7GwbxLBJgQelcyHw.png" /></figure><p>Now just click the ‘Create’ button to create your VM.</p><p><strong>Setting Up a Swap File</strong></p><p>The f1-micro we’re using only has 614 meg of RAM available. We might run into trouble with this little working memory so let’s get around this by setting up a swap file in case we run out.</p><pre>sudo fallocate -l 1G /swapfile<br>sudo chmod 600 /swapfile<br>sudo mkswap /swapfile<br>sudo swapon /swapfile<br>echo &#39;/swapfile none swap sw 0 0&#39; | sudo tee -a /etc/fstab</pre><p><strong>Installing Docker on the VM</strong></p><p>Now we have our shiny new VM created we’re going to need to install docker and docker-compose on it in order to run our application. In the VM instrances section of the Compute Engine click on the SSH option to open up a command prompt on the machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E3zTKgs_8LP1o95_w6zqNw.png" /></figure><p>Run the following commands.</p><pre>sudo apt-get update</pre><pre>sudo apt-get install apt-transport-https ca-certificates curl gnupg-agent software-properties-common</pre><pre>sudo add-apt-repository “deb [arch=amd64] <a href="https://download.docker.com/linux/debian">https://download.docker.com/linux/debian</a> $(lsb_release -cs) stable”</pre><pre>sudo apt-get update</pre><pre>sudo apt-get install docker-ce docker-ce-cli containerd.io</pre><p>You may get the following error when running sudo ‘apt-get update’.</p><pre><a href="https://download.docker.com/linux/debian">https://download.docker.com/linux/debian</a> buster InRelease<br> The following signatures couldn’t be verified because the public key is not available: NO_PUBKEY 7EA0A9C3F273FCD8</pre><blockquote>The apt packaging system has a set of trusted keys that determine whether a package can be authenticated and therefore trusted to be installed on the system. Sometimes the system does not have all the keys it needs and runs into this issue. Fortunately, there is a quick fix. Each key that is listed as missing needs to be added to the apt key manager so that it can authenticate the packages.</blockquote><p><a href="https://chrisjean.com/fix-apt-get-update-the-following-signatures-couldnt-be-verified-because-the-public-key-is-not-available/">https://chrisjean.com/fix-apt-get-update-the-following-signatures-couldnt-be-verified-because-the-public-key-is-not-available/</a></p><p>In order to fix this we just need to run the following command with the missing key it’s complaining about.</p><pre>apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 7EA0A9C3F273FCD8</pre><p><strong>Installing Docker Compose on the VM</strong></p><pre>sudo curl -L “https://github.com/docker/compose/releases/download/1.28.6/docker-compose-$(uname -s)-$(uname -m)” -o /usr/local/bin/docker-compose</pre><pre>sudo chmod +x /usr/local/bin/docker-compose</pre><h3>Uploading the Site to Google’s CDN</h3><p>Now we’ve setup our shiny new VM it’s time to move our site to a bucket on Google’s CDN. It’s far cheaper to store and access our data from the CDN.</p><p>To keep things as simple as possible we’ll be serving our CDN files from the NGINX server on our VM via it’s reverse proxy feature.</p><p><em>Note, this is far from ideal in a production setup as we will be making two hops and losing much of the benifit of a CDN such as lowering the server load and geo location of the content.</em></p><p>First let’s build the site in production mode. We’ll need to update the ‘GcpBlog\client\src\environmentsenvironment.prod.ts’ to point to the correct domain. Here I’ve set it to gcpblog.dev.</p><pre>export const environment = {<br> production: true,<br> baseUrl: ‘<a href="https://gcpblog.dev/api/&#39;">https://gcpblog.dev/api/&#39;</a><br>};</pre><p>Now open the client directory in powershell and build the site in production mode.</p><pre>ng build --prod</pre><p>We now have our production ready files in the following folder.</p><pre>‘GcpBlog\client\dist\client’</pre><p>Now go the the Google Cloud Platform and go to ‘Cloud Storage’ in the left hand menu.</p><p>Click ‘Create Bucket’ and enter a name for our new storage bucket. You’ll need to use this later to configure our NGINX server.</p><p>Select your region setting and then select ‘standard’ for the storage class. Access control should be set to uniform and advanced settings should be left in their default state.</p><p>When presented with the new bucket, click upload files, select all the the files in the ‘GcpBlog\client\dist\client’ directory and upload them to our new bucket!</p><h4>Setting public permissions on the files</h4><p>By default the files will be private. The final step will be making them viewable to the outside world. To do this carry out the following steps.</p><p>Select the Permissions tab near the top of the page.</p><ul><li>Click the Add members button.</li><li>The Add members dialog box appears.</li><li>In the New members field, enter allUsers.</li><li>In the Select a role drop down, select the Cloud Storage sub-menu, and click the Storage Object Viewer option.</li><li>Click Save.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zde2xxILieZme-ayQBk6eg.png" /></figure><h3>Reserving a Static IP Address</h3><p>By default the IP address assigned to our VM is ephemeral, that is, it can change at any time. When we later come to point our domain A record at the VM we’ll want an IP address which won’t change.</p><p>To get our fixed IP address go to the left hand menu and select VPC Network from the Networking section. We should see the current external port of our VM along with a ‘Type’ drop down menu. Click on that and select ‘Static’ and give the IP address a name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*308JIxhzEd38s0D9CpPOfA.png" /></figure><p>We should now see the same IP address come up as static on the listing page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y-Q2LN5p7XZ-2T3FRmU05A.png" /></figure><h3>The Production Docker Compose</h3><p>The production dock-compose file is very similar to the compose file we used to run the application up locally in part 1. This along with other files which will live on the server can be found in the ‘vm-files’ folder in our solution.</p><p>Here I’ll cover off the differences before moving our application to the virtual machine.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa50830fa4d6ca457931b790db649528/href">https://medium.com/media/fa50830fa4d6ca457931b790db649528/href</a></iframe><p><strong>Postgres Database</strong></p><p>The Postgres database running on the database service is identical other than the volumes statement. When running our example locally we weren’t peristing our data — once the container was taken down, any changes to the database were lost.</p><p>Volumes option allow us to create a link between the container and the file system of the machine we are running on and to persist the data. Here we create a link between the ‘database-data’ volume and the ‘var/lib/postgresql/data/’ folder on the container. The physical path to the data on the machine is ‘/var/lib/docker/volumes/username_database-data’.</p><p>Now we can restart our database container and deploy updates without losing any data we have stored on it.</p><p>We define the volume at the bottom of the compose file.</p><p><strong>.NET Core Web Api</strong></p><p>The ASPNETCORE_ENVIRONMENT variable is set to ‘Production’ rather than ‘LocalDocker’. This will load the appsettings.Production.json file with the production database connection string rather than the local .</p><p>Also, we are no longer publishing the ports, in the local example the Angular application was directly calling the Api from our host machine. In our production example we’re using an NGINX reverse proxy to handle all incoming requests, this means call to the api are going to the same URL and port as our application code. This means we don’t need to expose the ports of our Api to the ourside world. More on this later in the NGINX section!</p><p>Looking further down the file we see two new services, certbot and nginx. Both of these deserve a proper explaination and are covered below.</p><p>Here’s a reminder of how it fits together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ks9W-E4-X1kQmHH1Dxn9bQ.png" /></figure><h3>Acessing Files on the VM Through WinSCP</h3><p>The next step in the process requires us to edit files on the server and we’ll shortly be needing to upload files too so it’s a great time to get WinSCP setup.</p><blockquote><strong>WinSCP</strong> (<strong><em>Win</em></strong><em>dows </em><strong><em>S</em></strong><em>ecure </em><strong><em>C</em></strong><em>o</em><strong><em>p</em></strong><em>y</em>) is a <a href="https://en.wikipedia.org/wiki/Free_and_open-source_software">free and open-source</a> <a href="https://en.wikipedia.org/wiki/SSH_File_Transfer_Protocol">SSH File Transfer Protocol</a> (SFTP), <a href="https://en.wikipedia.org/wiki/File_Transfer_Protocol">File Transfer Protocol</a> (FTP), <a href="https://en.wikipedia.org/wiki/WebDAV">WebDAV</a>, <a href="https://en.wikipedia.org/wiki/Amazon_S3">Amazon S3</a>, and <a href="https://en.wikipedia.org/wiki/Secure_copy_protocol">secure copy protocol</a> (SCP) client for <a href="https://en.wikipedia.org/wiki/Microsoft_Windows">Microsoft Windows</a>.</blockquote><p>WinScp let’s us upload, download and edit files on our VM. Download and install it from here.</p><p><a href="https://winscp.net/eng/download.php">WinSCP :: Official Site :: Download</a></p><p>We’re also going going to need to generate a public and a private SSH Key. PuTTYgen is a great tool for doing this so let’s get than downloaded and installed too.</p><p><a href="https://www.ssh.com/academy/ssh/putty/windows/puttygen">How to install and use puttygen to create new key pairs and change passphrases. Installing keys on server, managing SSH keys.</a></p><p>First let’s create the ssh keypair. Open up PuTTYgen and click generate. Then enter your Google account name into the Key Comment field. This is the same username shown in the SSH terminal we’ve been using on the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*xamNDmU0fW1diuZPKP518w.png" /><figcaption>GCP Username</figcaption></figure><p>We need to save two keys. First copy and paste the public key at the top of the box with the header ‘Public key for pasting into OpenSSH authorised_keys file:’ into a text file and keep it safe. Next click save private key and save this in the same location you have your public key from the previous step and select the option to NOT password protect it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*Rj41iAuFZLFS2Z6ssjYf3A.png" /><figcaption>PuTTY Key Generator</figcaption></figure><p>Now we have our key pair it’s time to put enter the public one on the Google Cloud Platform. Select metadata from the Compute Engine section of the GCP left hand menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*9UXI56NF8oQYdRHqu-is3g.png" /></figure><p>Now select SSH from in the top nav and add the public key we just saved in the previous step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tUC2ZJAkcWKVxRunB2FQqA.png" /></figure><p>With the public ssh key setup on our Compute instance we can now access the files on our VM using WinSCP and the private key.</p><p>Open up WinSCP annd select ‘New Session’. Click new site and enter a name and add the IP address of the VM into the the ‘Host Name’ section and enter you’re GCP username into the username field.</p><p>We are using the private key to access our VM, select ‘Advanced’, then select ‘Authentication’ from the window that comes up. Next, select the private key file and hit ‘Ok’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SqlPfAyOZ553qoawiT4vnw.png" /></figure><p>The setup is complete. Hit save and then after selecting the site hit login and we’ll be able to access and upload files onto the server!</p><h3>NGINX</h3><p>NGINX is a free and extremely fast web server we’ll be using to host our application and act as a reverse proxy. The ‘command’ in the docker-compose file above ensures that every 6 hours it reloads the SSL certificate that may have been updated by certbot.</p><p>Along with the volumes pointing to the certificate and the challange request data we also point to the configuration file to run our application. Let’s dive into that now.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe6ac35835546ed74867ae3f0b20add8/href">https://medium.com/media/fe6ac35835546ed74867ae3f0b20add8/href</a></iframe><p>The first part of the configuration is the upstream statement. This is used to define groups of servers that can be referenced by the proxy_pass. Here we’re referencing the container running the api. Within the the set of services running within our docker compose we can address them using their service name, in this case ‘api’ running on port 880. We use this at the bottom of the second server to proxy requests coming into our domain matching the following pattern ‘gcpblog.dev/api’ to our api application.</p><p>Next we have our first server block, these are analogous to Apache’s VirtualHosts. Here we are listining for incoming http requests on port 80 to gcpblog.dev. The first location block handles return the challange data required by Let’s Encrypt to prove the ownership of the domain. We need to provide this over http as we won’t have setup our SSL cert at this point.</p><p>The following statement ensures any other requests for the http version of the site are redirected using a 301 code to the https version of the site.</p><p>The following server block handles the https requests coming in on port 443. We include the paths to the ssl certificate we’ll be setting up int the next step and other associated ssl configuration.</p><p>Now we setup the proxy configuration to the website files we uploaded to the gcp bucket in the preivous step. The specific our location statement is the higher priority it is given.</p><p>The first statement uses a special syntax, this means any requests coming directly to our gcpblog.dev domain are forwarded to the index.html file on our bucket and loading our angular application.</p><pre>location = / {     <br>proxy_pass <a href="https://storage.googleapis.com/gcpblog-bucket/index.html;">https://storage.googleapis.com/gcpblog-bucket/index.html;</a>    <br>}</pre><p>This statement serves up the files we need, mapping any css, javascript and images files we have hosted on our bucket.</p><pre>location / { <br>proxy_pass <a href="https://storage.googleapis.com/gcpblog-bucket/;">https://storage.googleapis.com/gcpblog-bucket/;</a> <br>}</pre><p>We do have a problem with paths now, if we navigate through the application using Angular to the <a href="https://www.gcpblog.dev/add-article">https://www.gcpblog.dev/add-article</a> page then hit F5 to refresh the page then the GCP bucket will have no idea what to do with that path as it doesn’t exist on the server. What we need to do is redirect it, and all other routes on the application to the index.html file and let Angular handle the routing.</p><pre>location /add-post { <br>proxy_pass <a href="https://storage.googleapis.com/gcpblog-bucket/index.html;">https://storage.googleapis.com/gcpblog-bucket/index.html;</a> }</pre><p>If you remember from the first article, our articles have an seo friendly url with the title being turned into a slug and used to identity them such as ‘<a href="https://www.gcpblog.dev/add-article">https://www.gcpblog.dev/</a>article/angular-11/’?</p><p>The line below matches any incoming requests which match the pattern ‘/article/’ followed by any characters. We then use a re-write rule to take that path and re-write it to /index.html and pass it to the proxy_pass directive. The last statement it used to stop processing and pass the result on.</p><p>If we didnn’t take these steps then all parts of the path after the domain would be passed on through the proxy pass directive to the storage bucket and we’d get an error.</p><pre>location /article { <br>rewrite ^/blog/(.*)$ /index.html last; <br>proxy_pass <a href="https://storage.googleapis.com/gcpblog-bucket/index.html;">https://storage.googleapis.com/gcpblog-bucket/index.html;</a> }</pre><p>Finally the last location statement is used to take any requests to the api and pass them along with any parts of the path over to our api which we defined earlier in the upstream directive.</p><pre>location /api/ { <br>   proxy_pass <a href="http://web-api/;">http://web-api/;</a> <br>}</pre><h3>Let’s Encrypt, Certbot and enabling HTTPS</h3><p>Ideally all sites should be running https, for security, seo and for the peace of mind it gives your users. Here we dive into how to get a free SSL certficatate for your site and automate the process of retrieving new certificates when your current one expires.</p><p>I want to take this opportunity to thank <a href="https://medium.com/u/524783b33278">Philipp</a> for his excellent article on the subject which I used to figure all this out. While I’ll be running over this, I strongly suggest you read through his article which goes into plenty of depth and will help you work through any issues you may have.</p><p><a href="https://pentacent.medium.com/nginx-and-lets-encrypt-with-docker-in-less-than-5-minutes-b4b8a60d3a71">Nginx and Let’s Encrypt with Docker in Less Than 5 Minutes</a></p><p>Let’s Encrypt is a free, automated, and open certificate authority. In order to use this service and automate much of the process we’ll be using a certbot image.</p><blockquote>Certbot is a free, open source software tool for automatically using <a href="https://letsencrypt.org/">Let’s Encrypt</a> certificates on manually-administrated websites to enable HTTPS.</blockquote><p><a href="https://certbot.eff.org/about/">https://certbot.eff.org/about/</a></p><p>First let’s look over the the docker compose file again to see what we’ve needed to add to get this working.</p><pre>certbot:<br>  image: certbot/certbot<br>  restart: unless-stopped<br>  volumes:<br>    — ./data/certbot/conf:/etc/letsencrypt<br>    — ./data/certbot/www:/var/www/certbot <br>  entrypoint: “/bin/sh -c ‘trap exit TERM; while :; do certbot renew; sleep 12h &amp; wait $${!}; done;’”<br> nginx:<br>   image: nginx:1.15-alpine<br>   restart: unless-stopped<br>   volumes:<br>     — ./data/nginx:/etc/nginx/conf.d<br>     — ./data/certbot/conf:/etc/letsencrypt<br>     — ./data/certbot/www:/var/www/certbot<br>   ports:<br>     — “80:80”<br>     — “443:443”<br>    command: ‘/bin/sh -c ‘’while :; do sleep 6h &amp; wait $${!}; nginx -s reload; done &amp; nginx -g “daemon off;”’’’</pre><p>First we specify the certbot service image and make sure that we restart it if it errors. Next we create two shared volumes which are used by both the certbot and nginx.</p><p>In order for Let’s Encrypt to to verify you have control of a domain it issues a challange request. This challange data needs to be created by the certbot and served by our NGINX server. We also need to serve up our SSL certificate via NGINX. This is why we have the two volumes both shared by NGINX and the certbot service.</p><p>The next line to cover is the ‘entrypoint’ in the certbot service. By default the certbot service won’t automatically renew our certficate, this line fixes this by checking if our certficate is about to expire every 12 hours and renewing it if it is.</p><p>We do have a problem however we need to create a dummy certificate. From <a href="https://medium.com/u/524783b33278">Philipp</a> article.</p><blockquote>Now for the tricky part. We need nginx to perform the Let’s Encrypt validation But nginx won’t start if the certificates are missing.</blockquote><blockquote>So what do we do? Create a dummy certificate, start nginx, delete the dummy and request the real certificates.<br>Luckily, you don’t have to do all this manually, I have created a convenient script for this.</blockquote><p>SSH onto our vm and execute the following statement to pull down his script.</p><pre>curl -L <a href="https://raw.githubusercontent.com/wmnnd/nginx-certbot/master/init-letsencrypt.sh">https://raw.githubusercontent.com/wmnnd/nginx-certbot/master/init-letsencrypt.sh</a> &gt; init-letsencrypt.sh</pre><h3>Putting it Live!</h3><p>Now we need to use WinSCP to edit the init-letsencrypt.sh shell script file that’s now on our server.</p><p>Open up the site in WinSCP and right click ‘edit’ on the ‘init-letsencrypt.sh’ file. Now find the domains line and add your domain rather than example.com. For Example.</p><pre>domains=(gcpblog.dev <a href="http://www.example.org)/">www.gcpblog.dev)</a></pre><p>Now upload all of the files and the data folder in the ‘vm-files’ folder to the the default folder on the VM using WinSCP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H8otuwKv5QR8a9tv3Dp3kQ.png" /></figure><p>Next edit the app.conf file in the following folder and change the two instances of server_name to the domain you’re using.</p><pre>GcpBlog\vm-files\data\nginx\app.conf</pre><p>Then update the SSL certificate paths to match the domain name too. For example.</p><pre>ssl_certificate /etc/letsencrypt/live/gcpblog.dev/fullchain.pem;<br>ssl_certificate_key /etc/letsencrypt/live/gcpblog.dev/privkey.pem;</pre><p>Now point your domain A record at the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dw5QXpd5lqIXsQVhxWfBSA.png" /></figure><p>Once we have waited for our A record update to propagate, it’s time to get our SSL certificate.</p><p>First login to docker on the vm so we can pull down our api image.</p><pre>docker login</pre><p>Now set execute permissions on the script file.</p><pre>chmod +x init-letsencrypt.sh.</pre><p>Then get our cert by running the following.</p><pre>sudo ./init-letsencrypt.sh</pre><p>You should now get a success message stating that a certificate has been correctly generated for your domain.</p><p>Now we just need to start the site by bringing up our containers though Docker Compose.</p><pre>docker-compose up</pre><p>Now when you navigate to your domain you should see the site!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P7F6achX8JOCzUwFPMdLBQ.png" /></figure><h3>References and further reading</h3><ul><li><a href="https://chrisjean.com/fix-apt-get-update-the-following-signatures-couldnt-be-verified-because-the-public-key-is-not-available/">Fix apt-get update &quot;the following signatures couldn&#39;t be verified because the public key is not available&quot;</a></li><li><a href="https://pentacent.medium.com/nginx-and-lets-encrypt-with-docker-in-less-than-5-minutes-b4b8a60d3a71">Nginx and Let’s Encrypt with Docker in Less Than 5 Minutes</a></li><li><a href="https://medium.com/@hbmy289/how-to-set-up-a-free-micro-vps-on-google-cloud-platform-bddee893ac09">How to set up a free micro VPS on Google Cloud Platform</a></li><li><a href="https://redstapler.co/cost-of-hosting-wordpress-website-on-google-cloud/">How Much Traffic Google Cloud f1-micro Instance can Handle | Red Stapler</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8b32167e183" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/docker-net-core-5-0-angular-11-nginx-and-postgres-on-the-google-cloud-platform-pt-2-a8b32167e183">Docker, .NET Core 5.0, Angular 11, Nginx and Postgres on the Google Cloud Platform — Pt 2</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker, .NET Core 5.0, Angular 11, Nginx and Postgres on the Google Cloud Platform — Pt 1]]></title>
            <link>https://medium.com/geekculture/docker-net-core-5-0-angular-11-nginx-and-postgres-on-the-google-cloud-platform-pt-1-363160e34439?source=rss-ae04f4d0e60------2</link>
            <guid isPermaLink="false">https://medium.com/p/363160e34439</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Stephen Robert James Adam]]></dc:creator>
            <pubDate>Thu, 15 Apr 2021 21:47:50 GMT</pubDate>
            <atom:updated>2021-06-01T06:40:32.503Z</atom:updated>
            <content:encoded><![CDATA[<h3>Docker, .NET Core 5.0, Angular 11, Nginx and Postgres on the Google Cloud Platform — Pt 1</h3><p>A complete guide to writing, configuring and deploying a dockerized CRUD application to the Google Cloud Platform.</p><p><a href="https://stephen-adam.medium.com/docker-net-core-5-0-angular-11-nginx-and-postgres-on-the-google-cloud-platform-pt-2-a8b32167e183">Skip over to part 2</a> if you just want help with the process of going live on GCP.</p><p><a href="https://github.com/Pastafarian/GcpBlog">The source code for the example can be found here.</a></p><p>There is a lot to learn when deploying your first fully fledged application to the cloud using Docker. In fact, it can be overwhelming. How do you know where to start?</p><p>I recenly launched my <a href="https://stephenadam.dev/">blog</a> and used it as an excuse to learn docker and have a play with GCP.</p><p>There were a few stumling blocks along the way and while there are plenty of good tutorials out there for each technology, it took some some to put them all together and launch the site.</p><p>Here I’ll combine all this information in one place and walk you through the process. By the end we’ll have a site secured using https, a containerized database and api along with a static site being served from a Google storage bucket. With Google’s generous 3 month trial we can do all of this for free!</p><p>I’ll move quickly and provide all the information required to get this up and running. I have included a list of references at the end if you want to dig deeper into any of the technologies used.</p><p>There’s a lot to cover so let’s dive in!</p><h3>Architecture Overview</h3><p>The solution architecture has been kept as simple as possible. The VM instance hosts docker which runs the containers for our applications.</p><p>Incoming requests are served by Nginx which then proxies them to either the .NET Core Web Api or to the GCP hosted Bucket. The web api connects to the Postgres database within the Docker host.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ks9W-E4-X1kQmHH1Dxn9bQ.png" /></figure><h3>The Sample Application</h3><p>We are going to be working with a simple blog application which allows us to add, view and delete articles. The articles will have an seo friendly slug to identify them.</p><p>This article assumes the reader already has a working knowledge of .NET, Angular and writing CRUD applications.</p><p>We’ll start off by getting the project running locally and going over the Docker configuration required to make this happen. Then we’ll update the project to get it running in the cloud, followed by setting up the GCP virtual machine and finally — deploying it to Google Cloud.</p><h3>Running It Up Locally</h3><p>In order to run the application locally you’ll need to ensure you have the following pre-requisites installed on your system.</p><p>Docker Desktop. <a href="https://www.docker.com/products/docker-desktop">https://www.docker.com/products/docker-desktop</a>.</p><p>Node.js. <a href="https://nodejs.org/en/download/">https://nodejs.org/en/download/</a>.</p><p>Git. <a href="https://git-scm.com/download">https://git-scm.com/download</a>.</p><p>Angular CLI. Once you have Node installed run the following command to install it.</p><pre>npm install -g <a href="http://twitter.com/angular/cli">@angular/cli</a></pre><p>Next, clone the sample application repository.</p><pre>$ git clone <a href="https://github.com/Pastafarian/GcpBlog">https://github.com/Pastafarian/GcpBlog</a></pre><p>Now have the the source code on our machine we are ready to build to the Angular application.</p><p>Navigate to the the application (where the docker-compose.yml residies) in powershell and run the following command.</p><pre>docker-compose build</pre><p>This will run the docker-compose.yml script. It’s job is to build our images and run containers based on them for our Postgres database the Web Api and the Angular application. The Postgres database is based on an image and can be spun up quickly, however the Web Api and the Angular application both need to be built from source code before generating an container from them.</p><p>Now we have the images ready it’s time to launch them with the following command.</p><pre>docker-compose up</pre><p>Now when we navigate to the following url we should see our application running.</p><pre><a href="http://localhost:8080/">http://localhost:8080/</a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*1K666OI-3yBsLZeX1W6mKA.png" /></figure><h3>Application Overview</h3><p>Next I want to gointo a bit more detail on the project, going over configuration required to get things running locally before we look at moving our solution to the cloud.</p><p>First let’s tackle the docker-compose.yml to see the structure of the solution and explain how it has been configured. The compose file allows us to configure all of the services required by the application and to define the containers which it will be made up of.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2a1050f64d18f0f1b18975f2d7ce694/href">https://medium.com/media/f2a1050f64d18f0f1b18975f2d7ce694/href</a></iframe><p>A couple of minor points on the docker-compose file. We are using the default naming convention of ‘Dockerfile’ for each of our projects so we don’t need to specify these in the build option. Docker will also create a default network for us when we run our ‘docker-compose up’ command so I have left out any networking options in this example.</p><p><strong>Postgres Database</strong></p><p>The first service in the docker compose file is the Postgres database. As with all the other services we specify the restart policy to ‘unless-stopped’. This will ensure the container is restarted automatically unless manually stopped by a user. The image is specified with no tag so it will default to using the ‘latest’ version of Postgres. This can be risky in a production environment but is fine for our simple demo.</p><p>Next we specify the database.env file. This will configure the credentials the database uses and will be used by the connection string in the Web Api. This file lives in the root of the solution along with the docker compose file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65177c85942a1b667870ea371caab103/href">https://medium.com/media/65177c85942a1b667870ea371caab103/href</a></iframe><p>The two ports given in the ports cofiguration map to the external and internal ports to be used by the container. To access the Prostgres database from outside the Docker host, for example, by using <a href="https://www.pgadmin.org/">pgAdmin</a> on your local machine, you would use localhost:5439 as we are ‘publishing’ this to the outside world. Note, we’d likely not want to publish an external port in a production system for security reasons.</p><p>To access the Postgres container from another service within the docker compose we would use the service name alias along with the internal port.</p><p>For example, here is the connection string used by the Web Api.</p><pre>“Host=database;Port=5432;Username=BlogUser;Password=BlogPassword;Database=GcpBlog”</pre><p><strong>.NET Core Web Api</strong></p><p>The Web Api service is next. Unlike database service which is specified by an existing image on <a href="https://hub.docker.com/">dockerhub</a>, this image needs to be built using a docker file.</p><p>To do this we use the build configuration option. Here we specify ‘context’ which is a path to the build context and where it will look for the Dockerfile which contains the instructions on how to create the image.</p><p>We pass in an environmental variable to the image context in the form of ‘ASPNETCORE_ENVIRONMENT=LocalDocker’. This ensures that the .NET Web Api uses the correct ‘appsettings.LocalDocker.json’ file to load its configuration from, we also pass in the ASPNETCORE_URLS environmental variable which sets up the Api to run on port 8800.</p><p>In order for the Api to startup sucessfully the database needs to be running first. We achieve this by using the ‘depends_on’ configuration option which ensures our Postgres container is up and running before the api container is started.</p><p>Now let’s look at the Dockerfile in the server directory along with the Web Api code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55da282966a917f6aa5c519dffec9fb6/href">https://medium.com/media/55da282966a917f6aa5c519dffec9fb6/href</a></iframe><p>This uses Dockers <a href="https://docs.docker.com/develop/develop-images/multistage-build/">multi-stage builds</a> to keep the size of the final image as small as possible. The last FROM statement is the one that creates the final base image, this allows us to use the larger sdk image with all its tooling to build the .NET Core application but to then copy those build artifacts to the the far slimmer aspnet runtime image we have specified at the start of the file.</p><p>Let’s step through each step in turn.</p><p>First we specify the the .NET Core 5.0 SDK as the build image. This is a large image which contains all the tooling required to build our application.</p><p>We set our WORKDIR to app, which is the folder all our work takes place in.</p><p>The next part is to copy the solution file and each of the csproj files over and run the restore command. We could simply copy the entire application over before building but copy seperating out the the files this way, Docker is able to this cache layer. Essentially, it will rely on a cached image for restore step for all subsequent builds until you update a NuGet package. The whole restore step can be skipped when you have only updated a .cs file. For more information on this and a more elegant way of pulling thisoff check out <a href="https://andrewlock.net/optimising-asp-net-core-apps-in-docker-avoiding-manually-copying-csproj-files-part-2/">Andrew Locks great post</a> on the subject.</p><p>Now we have run the restore step it time to copy the rest of the application cope and publish the application in release mode.</p><p>We don’t want to use the sdk image as a base for our final application image as its large and contains lot’s of tooling we don’t need to run the application.</p><p>The final FROM statement selects the much slimmer asp.net core runtime image which is far smaller and will result in much faster startups for our application.</p><p>We copy the contents of our build from the build image into our runtime image and set our ENTRYPOINT to the GcpBlog.Api.dll ro start running our application.</p><p><strong>Angular Application</strong></p><p>When we move to the cloud we’ll be using a CDN to serve the Angular application. Here I wanted use the local example to show how to run it in a container.</p><p>The docker-compose file has already setup the port we will be running on. Externally the app will be using 8080 and inside we’ll be using 80.</p><p>Let’s run through the Angular docker file to start with and then look at the changes made to the application to get the configuration working.</p><p>We’re using a multi-stage build again to keep the size of the application small. First we use the latest version of the node image to build our application. The package.json and package-lock.json files are copied to the /user/src/app folder and we run an npm install command to pull down the packages we require, we then copy the application code across to the same directory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5d19701ac5945988e83a90387e5cfb1/href">https://medium.com/media/c5d19701ac5945988e83a90387e5cfb1/href</a></iframe><p>Next we use the ‘npm run localdocker’ command which runs a custom script in the package.json file. This runs the ‘ng build’ command and passes in the configuration argument ‘localdocker’ to it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a1c192b75089767e67352aec3852da7/href">https://medium.com/media/1a1c192b75089767e67352aec3852da7/href</a></iframe><p>By passing the configuration argument whe Angular is built, it will look in the ‘configurations’ block shown below and apply the file replacement we have specified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*VF2JPDGuTGVvHLWgstjIaQ.png" /></figure><p>Rather than using the default ‘environment.ts’ file we’ll be using ‘environment.dockerlocal.ts’ file. This contains the address of the Web Api we will be connecting to locally, in this case ‘http://localhost:6578/’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*cmIlJhvxv0Gwg2YimilHUw.png" /></figure><p>Once the application has been built with the correct configuration values we specify the the final image ‘nginx:alpine’. <a href="https://www.nginx.com/">NGINX</a> is an extremely fast web server that we’ll be using to serve our Angular application.</p><p>We copy over the nginx.config file from the config folder in our client folder to overwrite the existing one.</p><p>The config file is given below. It’s outside of the scope of the article to into detail on NGINX configuration options but it’s worth looking at line 14. Given this is an SPA and it’s the Angular application that will be handling all of our routing, we want all requests for a given path to resolve to our index.html file. The last part of the ‘try_files’ command ensures if NGINX is unable to find a file and we would have recieved a 404 then route to the index.html file instead. This means when we hit F5 to refresh the page then Angular will still be able to show the page no matter what route we are currently on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7dfa579af32641af33d9ceb71e8bf2b/href">https://medium.com/media/b7dfa579af32641af33d9ceb71e8bf2b/href</a></iframe><p>Now we have the app running locally and have covered the docker configuration it’s time to move onto moving it to the cloud in part 2!</p><p><a href="https://medium.com/p/a8b32167e183">Docker, .NET Core 5.0, Angular 11, Nginx and Postgres on the Google Cloud Platform — Pt 2</a></p><h3><strong>References and further reading</strong></h3><p><a href="https://wkrzywiec.medium.com/build-and-run-angular-application-in-a-docker-container-b65dbbc50be8">https://wkrzywiec.medium.com/build-and-run-angular-application-in-a-docker-container-b65dbbc50be8</a></p><ul><li><a href="https://blog.codewithdan.com/video-building-and-running-custom-asp-net-core-containers/">Video: Building and Running Custom ASP.NET Core Containers</a></li><li><a href="https://redstapler.co/cost-of-hosting-wordpress-website-on-google-cloud/">How Much Traffic Google Cloud f1-micro Instance can Handle | Red Stapler</a></li><li><a href="https://andrewlock.net/optimising-asp-net-core-apps-in-docker-avoiding-manually-copying-csproj-files-part-2/">Optimising ASP.NET Core apps in Docker - avoiding manually copying csproj files (Part 2)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=363160e34439" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/docker-net-core-5-0-angular-11-nginx-and-postgres-on-the-google-cloud-platform-pt-1-363160e34439">Docker, .NET Core 5.0, Angular 11, Nginx and Postgres on the Google Cloud Platform — Pt 1</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns Made Easy with C# — Pt 1]]></title>
            <link>https://stephen-adam.medium.com/design-patterns-made-easy-with-c-pt-1-95d297a277fe?source=rss-ae04f4d0e60------2</link>
            <guid isPermaLink="false">https://medium.com/p/95d297a277fe</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Stephen Robert James Adam]]></dc:creator>
            <pubDate>Sun, 21 Mar 2021 21:12:06 GMT</pubDate>
            <atom:updated>2021-03-22T16:24:00.057Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Patterns Made Easy with C# — Pt 1</h3><h4><strong>Harnessing the power of d</strong>esign patterns makes your code readable, elegent and efficient.</h4><p>There are lots of great articles on design patterns; unfortunately many of them make them far more complicated than than they need to be.</p><p>My aim with this series is to demystify them, refresh my memory of a few and give some real world applications in a concise, code based and approachable way.</p><blockquote>A pattern is an idea that has been useful in one practical context and will probably be useful in others.<br>Martin Fowler</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aEezrVXWbGbBoSrpIqs2uQ.jpeg" /></figure><h3>The Adapter Pattern</h3><h4>Description</h4><p>The adapter pattern is used adapt one class to fit the signature of another. In the example below we have service expecting a Person object with a Name property. How do we handle a FrenchPerson with a Nom property?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a4661fd714471025208d8b5b7f38e37/href">https://medium.com/media/0a4661fd714471025208d8b5b7f38e37/href</a></iframe><h4>Real world uses</h4><p>A good example would be using a third party dependency injection framework such as Simple Injector with Web Api.</p><p>MVC Core comes with its own baked in dependency injection framework, in order to use simple injector with it needs to have a class which implements the frameworks IDependencyResolver. This way SimpleInjector can be treated in exactly the same way as the framework DI container.</p><h3>The Decorator Pattern</h3><h4>Description</h4><p>You can think of the decorator as a russian doll, where a class can have it’s behaviour extended and modified at run time. The behaviour have be shared between classes and doesn’t require the modification of the class itself.</p><p>Often we’ll want to augment the behaviour of a given set of classes in our system. In the example below we have a QueryExecutor which has logging and caching functionality added at runtime.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e5b137269115859856ef00f27fd6570/href">https://medium.com/media/3e5b137269115859856ef00f27fd6570/href</a></iframe><h4>Real world uses</h4><p>The above example was inspired by a very similar real world implemention I wrote for a <a href="https://github.com/jbogard/MediatR">MediatR</a> implementation. <a href="https://github.com/jbogard/MediatR">MediatR</a> is a library which can be used to wire a set of commands (or queries) to handlers. Much like the example above I had a number of query handlers I wanted to add logging and error handling to in a generic way.</p><h3>The Chain of Responsibility Pattern</h3><p>Similar to the decorator pattern, it differs in that it allows the forwarding of a request until a condition is met or the end of the chain is reached.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d5c8f29ddb838adfeea7b25cf935c20/href">https://medium.com/media/6d5c8f29ddb838adfeea7b25cf935c20/href</a></iframe><h4>Real world uses</h4><p>The request processing pipeline for ASP.NET Core MVC uses exactly this pattern to handle Http requests and responses.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95d297a277fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NuGet — Targeting both .NET Standard and the .NET Framework]]></title>
            <link>https://stephen-adam.medium.com/nuget-targeting-both-net-standard-and-the-net-framework-326a16266ca4?source=rss-ae04f4d0e60------2</link>
            <guid isPermaLink="false">https://medium.com/p/326a16266ca4</guid>
            <category><![CDATA[nuget]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Stephen Robert James Adam]]></dc:creator>
            <pubDate>Wed, 19 Jul 2017 17:05:11 GMT</pubDate>
            <atom:updated>2017-08-12T12:42:31.073Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently we’ve been moving over to .NET Core for new projects at work. This has been fairly straightforward in most respects, though we have large number of NuGet packages which we use to share utilities, claims, API libraries and a variety of other components between our applications.</p><p>Given we want to avoid creating .NET Core versions of all of our libraries I decided to take a look at the story around creating packages which could target both our new .NET Core applications and .NET Standard libraries along with our legacy .NET Framework applications.</p><p>We’re going to learn about this by getting an old Framework package written for the .NET Framework working with a new .NET Core App.</p><p>Example source code on Github can be found <a href="https://github.com/Pastafarian/NuGetMultitargetPackage">here</a>.</p><h4><strong>Compatibility Matrix</strong></h4><p>There has always been some understandable confusion regarding compatibility between new .NET Standard and legacy Framework applications. It’s understandable with the myriad of names, name changes and Microsoft <a href="https://www.theregister.co.uk/2017/05/11/microsoft_asp_net_core_2_0/">getting confused and flip flopping on the issue</a>.</p><p>The matrix below shows which versions of the .NET standard are compatible with which version of the .NET Framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*aPS2JbP61fczgl5BF7sUyQ.png" /></figure><p>Unfortunately it isn’t quite that simple as there a large number of Api’s which are present in the .NET Framework which are NOT present in the .NET standard. You can think of the .NET standard as an interface which defines a set of features, in our case we’ll be using 1.3. Which can (roughly) be described as a subset of 4.6.</p><p>i.e.</p><pre>IFramework46 : INetStandard13 { }</pre><p>Let’s get started and see what challenges we run into!</p><h3><strong>Using a .NET Framework NuGet package with a .NET Core application</strong></h3><p>For this example I created a new .NET Core console application in Visual Studio and tried adding a utility package we use internally via NuGet. This generated the following error message.</p><pre>Package MyCompany.Utility 1.2.5 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1). Package MyCompany.Utility 1.2.5 supports: net35 (.NETFramework,Version=v3.5)</pre><p>This error comes as no surprise as by default our Core App will target the platform independent .NET Standard; our package on the other hand could be using all sorts of classes and Api’s which are only available in the .NET Framework.</p><p>The easiest way of getting up and running if you want to use legacy Framework libraries with new Core apps is to set the target Framework of your consuming Core app.</p><pre>&lt;PropertyGroup&gt;<br> &lt;OutputType&gt;Exe&lt;/OutputType&gt;<br> &lt;! — &lt;TargetFramework&gt;netcoreapp1.1&lt;/TargetFramework&gt; →<br> &lt;TargetFramework&gt;net461&lt;/TargetFramework&gt;<br>&lt;/PropertyGroup&gt;</pre><p>This is not an ideal solution as our package can still only be run by clients running the .NET Framework. If you want to really harness the flexibility of .NET Core then read on for a better way!</p><h3><strong>Creating a NuGet package which targets multiple platforms</strong></h3><p>A more flexible and clean way of handling the issue is to update the package so it supports both our old .NET Framework applications and our new Core Apps.</p><p>This will require some work as many of the .NET Framework Api’s are either not available in .NET Standard or have been moved to a separate package.</p><p>To illustrate this process I have created a new .NET Standard library and have copied the Framework code from the old utility library across.</p><p>The first step is to update the csproj file and tell it we want to target both version 1.3 of the Standard Library and 4.6 of the Framework.</p><pre>&lt;Project Sdk=”Microsoft.NET.Sdk”&gt; <br> &lt;PropertyGroup&gt;<br> &lt;TargetFrameworks&gt;netstandard1.3;net46&lt;/TargetFrameworks&gt;<br> &lt;/PropertyGroup&gt;<br>&lt;/Project&gt;</pre><p><strong>Fixing our first method</strong></p><p>Let’s start of with this DeserializeXmlDocument method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*4srYzBBlfufnxmO5Gb0dww.png" /></figure><p>Prior to .NET Core the XmlSerializer lived in the System.Xml library which was automatically added to new projects. The push with Core was to break out functionality into separate packages to make applications faster and smaller and leaner.</p><p>After a quick google the I found the .NET Standard package for the System.Xml.XmlSerializer package and installed it via NuGet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*0VaE4bleJpzYRTjP6pr-Kw.png" /></figure><p>After installing that we still have a couple of issues to address. The signature for the StreamReader has changed and now only accepts a Stream rather than a path and the close method is missing from the StreamReader.</p><p>This all makes sense, the StreamReader now follows the <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility principle</a> and no longer handles file access, the close method was superfluous as the reader implements the IDisposable interface which allows us to wrap it in a using statement.</p><p>Fixing these means we need to refactor the code a bit, but the changes are trivial. Given the System.Xml.XmlSerializer package supports both the .NET Standard 1.3 and the .NET Framework 4.61. We now have a method of serializing Xml which will work across platforms!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*J5QmeXrLjcuiXAN_O_kayQ.png" /></figure><h3>Conditional Compilation</h3><p>The next issue I ran into was the ConfigurationHelper class. This is a set of methods which work on the ConfigurationManager manager.</p><p>The ConfgurationManager has been with us since .NET 2.0 and is tightly coupled to the standard framework Xml configuration files (web.config / app.config).</p><p>With these gone and replaced with a totally new configuration system in Core we have a problem. Our existing legacy applications still need to make use of this class but our new Core apps simply wouldn’t be able to run with this code still present.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*By6gQoWlvjl-3RpVfPSwHg.png" /></figure><p>Conditional compilation allows us to target different blocks for different frameworks. Below is the update which was required on the csproj file.</p><p>We conditionally load in dependencies setup constants we can use in the library to specify which code to compile based on the framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*Z_CvTbkl7jj5Vjy_MTezkA.png" /></figure><p>With our new conditional constants defined we get this drop down menu to select which platform to interpret the code from. Below we are looking at the code using the .NET Standard 1.3 and as such the code is grayed out as it will not be compiled for that Framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*LzO_f2Mqv41MXD9m1Dgp_A.png" /></figure><p>Here we can see the same class with the 4.6 Framework option selected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*zHm9tz06oY0O6H2JZg_Myg.png" /></figure><h3><strong>Building the package</strong></h3><p>The tooling has also moved on from the previous method of invoking ‘nuget pack’ at the command to the <a href="https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-pack">new dotnet-pack command</a>.</p><pre>C:\Projects\NuGetExample\Standard.Utils&gt;dotnet pack</pre><p>This creates the nuget package in the ‘bin\Debug’ folder.</p><p>An alternative is to use msbuild. To use this method we need to open up the Visual Studio Developer Command Prompt and run the following command in the project directory.</p><pre>msbuild /t:pack /p:Configuration=Release</pre><p>Note: if you want to execute the msbuild command above from the standard command line then you’ll need to add the following to your Path variables.</p><p>C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=326a16266ca4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>