| Comments

Reflecting back on this blog I realized it’s been 16 years of life here.  It hasn’t always been consistent content focus on tech over the early years versus a more random outlet of my thoughts (and apparent lack of concern over punctuation and capitalization).  Some months had more volume and as my career (and perhaps passions) changed some had lower volume.

Month comparison of blog post quantity

I’ve enjoyed getting back in to posting more recently and finding more time (and again, perhaps the passion) to do so.  I think also with newer various outlets of social media, my personal passions are posted elsewhere now like Instagram (if you want to follow my escapades on the bike mostly).  Recently this summer in 2019 I switched job roles at Microsoft back into program management with the .NET team.  I’m focusing on a few different things but having spent so much time in UI frameworks on the client side for so long, I missed some waves of changes in ASP.NET and needed to re-learn.  I spent the first month of my new role doing this and exploring the end-to-end experiences.  Instead of building a To-do app, I wanted to have some real scenario for me to work with so I set off to migrate my blog…it was time anyway as just that week I had received warnings on my server about some errors.  I could avoid this no longer.  It wasn’t an easy path, but here was my journey.

Existing website frameworks

My blog started in 20-Aug-2003 and was built using Community Server (from Telligent) initially.  That quickly forked into a product called .TEXT from Scott Watermasysk and I moved to using that as it was solely content management and not forums or other things I didn’t need.  I stayed on .TEXT for as long as it lived until again another fork happened.  This time the .NET ecosystem around Open Source was improving and this fork was one of those projects.  Phil Haack, along with others, created SubText which was initially a pretty direct fork, but quickly evolved.  I wasn’t much interested in the code at this point, but wanted to follow ‘current’ frameworks so I moved to SubText.  All along this path it was easy because these migrations were similar, using the same frameworks and similar (if not same) data structures.  The SubText site was an ASP.NET 2.0 site using SQL Server as the data store.  Over time this moved to .NET 3.5 but not much more after that (for me at least). 

Over time I made a few adjustments to the SubText environment for me, never really concerning myself about the source, but just patching crap in random binaries that I’d inject into the web.config.  My last one was in 2013 to support Twitter cards and it was a painful reminder at the time that this site was fragile.   By this time as well the SubText project itself was fragile and not really being maintained as ASP.NET had moved to newer things like MVC and such.  The writing was on the wall for me but I ignored it.

Hosting environment

In addition to the platform/framework used, I was using an interesting hosting setup.  Well, not abnormal really considering at the time in 2003 there was no ‘cloud’ as we know it today.  I had a dedicated box (1U server) hosted at my own data center (I was managing, among other things, a data center rack at the time).  This was running Windows Server 2000 and whatever goop that came with.  Additionally this was SQL Server Express [insert some old version here].  I had moved on to another job and after a period of time I needed to move that server.  I was using the server for more than just my site, running about 10 other WordPress blogs for my community, my wife’s business, and various other things.  WordPress sites were constantly being attacked/hacked due to vulnerabilities in WordPress and leading to my server being filled with massive video porn files and me not knowing until my site was down then I had to login remotely and clean crap up.  Loads of fun.  I eventually moved that server to a co-located environment at GoDaddy still maintaining a dedicated 1U server for me.  It was nice having direct access to the server to do whatever I wanted, but I was quickly not needing that type of hands-on configuration anymore…but still dealing with the management.

During each of these moves I was just moving folders around.  I had no builds, no original source code reliably, etc.  “Fixing” things was me writing new code and finding interesting ways to redirect some SubText functionality as I didn’t have the source nor was interested in digging up tooling to get the source to work.  I never upgraded from Windows 2000 server and was well beyond support for things I was doing.  When I wanted to upgrade the OS at GoDaddy, I was faced with “Sure we’ll set up a new server for you and you migrate your apps” approach.  So again I was going to have to re-configure everything.  Another nightmare waiting and I just put it off.

To the Cloud!

My first step was moving data to the cloud.  I wrote about this when I did this task back in 2012.  I quickly learned that if my site wasn’t on Azure as well and with the traffic I was still getting, the egress costs were not going to be attractive for me.  A few years ago I went about moving just my blog app to Azure App Service as well.  Not having anything to build, this was going to be a fun ‘deployment’ where I needed to copy a lot of things manually to my App Service environment.  I felt dirty just FTP-ing in to the environment and continually trying things until it worked.  But it eventually did.  I had my .NET Framework SubText app running on App Service and using Azure SQL.  The cool thing about Azure SQL is the monitoring and diagnostics it provides.  I immediately was met with a few recommendations and configuration changes I should make and/or it automatically made on my behalf.  That was awesome.  I did have one stored procedure from SubText that was causing all kinds of performance havoc and contributing to me hitting capacity with my chosen SQL plan requiring me to bump up to the next plan and more costs.  Neither of which I wanted to do.  And due to what I mentioned prior about not having SubText buildable I couldn’t reliably make a change to the stored proc without really changing the code that called it.  Just another dent in the plan.  I needed a real migration plan.

Migrate to ASP.NET Core

I mentioned that in my new role I needed to spend time re-learning ASP.NET and this was a perfect opportunity.  I decided to dedicate the time and ‘migrate’ to ASP.NET Core.  Why the air quotes?  Because realistically I couldn’t migrate anything but data.  I did not have reliably building source for SubText and despite that it was WebForms and I didn’t know what I might be getting myself in to.  I needed a new plan, which meant a new framework and I went looking.  Immediately I was met with recommendations that I should go static sites, that Jekyll and GitHub pages are the new hotness and why would I want anything else.  I don’t know, for me, I still wanted some flexibility in the way I worked and I wasn’t seeing that I’d be able to get what I want out of a static site approach.  I wanted to move to ASP.NET Core solutions and found a few frameworks that looked attractive.  Most were in varying states and others felt just too verbose for my needs.  I landed on a recommendation to look at miniblogcore.  This was the smallest, simplest, most understandable solution to my needs that I found.  No frills, just render posts with some dynamicism.

I did not even attempt to migrate any of my existing ASP.NET WebForms code or styling as modern platforms were using Bootstrap and other things to do the site, so that was where I needed to start.  I spent a good amount of time working on the simple styling structure for a few things and learning MVC in the process to componentize some of the areas.  I added a few pieces of customization on the miniblog source, adding search routing (using Google site search), a timeline/calendar view thanks to Telerik controls, category browsing (although mine is horrendous due to waaay too many categories used over the years), using Disquss for commenting, adding SyntaxHighlighter for code formatting support, an image provider for my embedded images during authoring, and a few other random things.  I wrote a little MVC controller to do the data migration once from SQL to the XML file-based storage that MiniBlog uses.  That was a lot simpler than I thought it would take to migrate the data to the new structure.  Luckily my old blog had ‘slug’ support and this new one had it as well, so the URI mapping worked fine, but now I had to ensure the old routing would work.  I had to play around with some RegEx skills to accomplish this but in the end I found a pattern that would match and implemented that in my routing, using proper redirect response codes:

// This is for redirecting potential existing URLs from the old Miniblog URL format
// old subtext non-slugged & slugged
// https://timheuer.com/blog/archive/2003/08/19/145.aspx
// https://timheuer.com/blog/archive/2015/04/21/join-windows-engineers-at-free-build-events-around-the-world-xaml.aspx
[Route("/post/{slug}")]
[Route("/blog/archive/{year:regex(\\d{{4}})}/{month:regex(\\d{{2}})}/{day:regex(\\d{{2}})}/{slug}.aspx")]
[HttpGet]
public IActionResult Redirects(string slug)
{
    // if the post was a non-named one we need to append some text to it otherwise it will think it is a page
    // if (slug doesn't contain letters) { redirect to $"post-{slug}" }
    var newSlug = slug;
    var isMatch = Regex.IsMatch(slug, "^[0-9]*$");
    if (isMatch) newSlug = $"post-{slug}";

    return LocalRedirectPermanent($"/blog/{newSlug}");
}

That ended up being remarkably simpler than I thought it would be as well.  This alone was causing me stress to maintain the URIs that had existed over time and using ASP.NET routing with RegEx I got what I needed quickly.

Moving to Azure App Service once this was all done was simple.  When I first moved ASP.NET Core 3.0 wasn’t yet available so I had to deploy as a self-contained app.  This isn’t difficult though and in some cases may be more explicitly what you want to do.  I wrote how to Deploy .NET apps as self-contained so you can follow the steps.  This basically is a ‘bring the framework with you’ approach when the runtime might not be there.  Azure App Service now has .NET Core 3.1 available though so I no longer have to do that, but good to know I can test future versions of .NET by using this mechanism.

Summary

So what did I learn?  Well, not having source for your apps you care about hurts.  I didn’t even get a chance to actually attempt to truly migrate SubText to ASP.NET Core because I had let my implementation rot for so long.  I have become such a huge believer in DevOps now it’s unreal.  I won’t do a simple project even without it.  The confidence you gain when your projects have continuity through automation is amazing.  My new blog app is fully run on DevOps and deploys using that as well…I just commit changes and they are deployed when I approve them.  I learned that even though this was ‘just a blog’ it was a fairly involved app with separation of user controls and things.  It didn’t need to be so complex, but it was and I’m glad for MiniBlog not being so complex.  The performance of my content site and costs are much more manageable now and my stress is reduced knowing that should anything happen I’m in a better place for restoring a good state.  My biggest TODO task I think is re-thinking the XML-based data store though.  This actually is the one thing causing me some DevOps pain because the ‘data’ is content within the web app and when using slot-staging deployment that doesn’t work well.  Azure has a way to use Azure Storage as a mounted point to serve content from in your App Service though and I’ve started to try that with some mixed results so far.  Using this approach separates my app from my data and allows for more meaningful deployment flows and data backup.  I’ve also explored using an Azure Storage provider for my data layer, but the method for how the initial cache is build in MiniBlog right now makes this not a great story due to startup latency when you have 2,000 posts to retrieve from blob container.  I’m still playing around with ideas here, so if you have some I’d love to hear (dasBlog users would hit similar concerns).

I’m happy with where I landed and hope this keeps me on a path for a while.  I’ve got a simple design, responsive design, easy-to-maintain source code, all the features I want (for now), no broken links (I think), works with my editing flow (Open Live Writer), and less stress worrying about a server.  I’ve already updated to ASP.NET Core 3.1 and it was a simple config change to do that now that my setup is so streamlined. 

What are your migration stories?

| Comments

I’ve been spending a lot of time looking at the GitHub Actions experience for .NET developers.  Right now I’m still using Azure Pipelines for my project, Alexa.NET, in building, testing, and deploying to NuGet.  As the tools and process for using DevOps tools for CI/CD have so vastly improved over the years, I’ve become a huge advocate for this being the means for your build/deploy steps…YES, even as a single developer or a smaller team.  It simply really helps you get to a purer sense of preserving the ability for your code to live on, for others to accurately build it, and for you to have peace of mind that your code works as intended.  I’m just such a huge fan now.  That said, I still think there is a place for ‘right-click publish’ activities in inner-loop development.  In fact, I use it regularly for a few internal apps I’ve written.  For simple solutions that method works well, but I certainly don’t think I can right-click-publish a full solution to a Kubernetes environment though.  I’m currently researching new tooling ways to help those ‘publish to CI/CD’ from Visual Studio (would love your opinions here) so I’ve been spending a lot more time in GitHub Actions.  I decided to look at publishing a Blazor app to Azure Storage as a static site…here’s what I did.

Setting up the Storage endpoint

The first thing you need is an Azure Storage account.  Don’t have an Azure account, no worries you can get a Free Azure account easily which includes up to 5GB of Azure Blob Storage free for the first 12 months.  Worried about pricing afterwards?  Well check out the storage pricing calculator and I’m sure you’ll see that even at 1TB storage it is cost-effective means of storage.  But any rate, you need a storage account and here are the configuration you need.

First, you may already have one.  As a developer do you create your infrastructure resources or are these provisioned for you by infra/devops roles in your company (leave comments)?  Earlier this year at Build we enabled static website hosting in Azure Storage.  You first create a Storage resource (ensuring you choose v2 which is the default, but that is the version that enables this feature).  After you create your resource scroll on the left and you’ll see ‘Static website' section.  Here’s what the configuration looks like and let me explain a few areas here:

Screenshot of the Static website configuration
All of this configuration is under the Static website area.  First you obviously need to enable it…that’s just toggling the enabled/disabled capability.  Enabling this now gets you two things: 2 endpoints (basically the URI to the website) and a specific blob contianer named $web where your static content needs to live.  The endpoints default map to this blob container without having to add a container name to the root URI.  Remember the resource group you’ve given to your storage instance here, you will need that later.

NOTE: You can later add CDN/custom domain to these endpoints, but I’m not covering those here.

The second thing you need is to set a default document and error page.  The default document for your SPA is your root entry point, and for most frameworks I’ve seen this is indeed index.html.  For Blazor WebAssembly (WASM) apps, this is also the default if you are using the template.  So you set the default document as ‘index.html’ and move on.  The error document path is another interesting one…you need to set this for SPA apps because right now the static website capability of Azure Storage does not account for custom routing rules.  What this means is that storage will throw an HTTP 404 error message when you go to something like /somepage where it actually doesn’t exist but your SPA framework knows how to handle it.  Until custom routing works on Azure Storage your error document becomes your route entry point.  So for this set the error document path to also be index.html for Blazor WASM.

NOTE: Yes this isn’t ideal for routing.  On top of that it still does show an HTTP 404 actual network message even though your route is being handled.  Azure Storage team has heard this request…working on advocating for y’all.

That’s it.  Now you have a storage endpoint with a blob container that you can begin putting your content in and browse to using your endpoint URI provided from the portal.  For a simple tool to navigate your storage, I’ve been using Azure Storage Explorer and it is intuitive to me and works well to quickly navigate your storage account and containers (and supports multi-account!). 

Setting up your Azure Service Principal credentials

The next thing you will need is a service principal credential.  This will be used to authenticate with your Azure account to be able to use DevOps tools to work on your behalf in your account.  It’s a simple process if you have a standard account.  I say this only because I know there might be some configurations for environments where you yourself don’t have access to create service principals and may need someone to create one on your behalf, or also there might be credentials you can already use.  Either way here is the process I used.

I used the Azure CLI so if you don’t have that installed go ahead and grab that and install it.  This should now be in your PATH environment and using your favorite terminal you should be able to start executing commands.  To start out, login to the CLI using `az login` – this will launch a browser for you to authenticate via your account and then issue the token in your environment so that for the remainder of your session you’ll be authenticated.  After logging in successfully running `az account show` will emit what subscription you are using and you’ll need the subscription ID later so grab that and put it somewhere on your scratch notepad for later command usage.

NOTE: If you have more than one subscription and have not set a default subscription you should set that using the `az account set` command.

Now you can use the CLI to create a new service principal.  To do that issue this command:

az ad sp create-for-rbac --name "myApp" --role contributor \
                            --scopes /subscriptions/{subscription-id}/resourceGroups/{resource-group} \
                            --sdk-auth

Note on line 2 here that you need to replace {subscription-id} with your own actual subscription id (the GUID) and {resource-group} with the resource group name where your storage account is located.  On line 1 the “myApp” can be anything but I recommend making it meaningful as this is basically the account name of the principal.  The output of this command is your service principal.  The full JSON output.  Save this off in a place for now as we’ll need that later to configure GitHub Actions properly.  Great now to move on to the app!

Create your Blazor WASM app

I assume since you may be reading this far you aren’t new to Blazor and probably already have the tools.  As of this writing, Blazor WASM is still in preview so you have to install the templates separately to acquire them to show up in `dotnet new` and in Visual Studio File…New Project.  To do that from a terminal run:

dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.1.0-preview4.19579.2

Then you will be able to create a new project.  I’m showing Visual Studio here and this is the WASM template:

Screenshot of Blazor new project dialog

In the dialog here you will see Blazor WebAssembly App and that’s what you will use.  Now you have a choice to have it ASP.NET Core hosted using that checkbox, which if you were going to do other things in ASP.NET maybe that’s what you want.  For the purposes of this article we are talking about just having the WASM app and having a place to host it that isn’t a web server with other content…just hosting static content and using storage to do so…so we aren’t checking that box.  The result will be a Blazor WASM app with no host.  Now let’s add that to GitHub.  If you are using Visual Studio 16.4+ you’ll be able to take advantage of an improved flow for pushing to GitHub.  Once you have your project, in the lower right click ‘Add to Source Control’ choosing Git and then you’ll see the panel to choose GitHub and create/push a repo right away.  You don’t have to go to GitHub site first and clone later…all in one step:

Animation of Visual Studio GitHub flow

Great!  Now we have our WASM project and we’ve created and pushed the current bits to a new GitHub repository.  Now to create the workflow.

Setup the GitHub Action Workflow

Now we’ve got an Azure Storage blob container, a service principal, a Blazor WASM project, and a GitHub repository…all set to configure the CI/CD flow now.  First let’s put that service principal as a secret in our repository.  In the settings of your repository navigate to the Secrets section and add a secret named AZURE_CREDENTIALS.  The content of this is the full content of your service principal (the JSON blob) that we generated earlier:

Screenshot of GitHub Secrets configuration

This saves the secret for us to use in the workflow and reference as a variable.  You can add more secrets here if you’d like if you wanted to add your resource storage account name as well (probably a good idea).  Secrets are isolated to the original repository so no forks get the secrets at all.  Now that we have these let’s create the workflow file.

Today, Visual Studio isn’t too helpful in authoring the YAML files (would love your feedback here too!) but a GitHub Action is just a YAML file in a specific location in your repository: .github/workflows/azure-storage-deploy.yaml.  The file name can be anything but putting it in this folder structure is what is required.  You can start in the GitHub repo itself using the Actions tab and through the online editor get some level of completion assistance to help you navigate the YAML editing.  Go to the Actions tab in your repository and create a new workflow.  You’ll be offered a starter workflow based on what GitHub thinks your project is like.  As of this writing it thinks Blazor apps are Jekyll workflows so you’ll need to expand and either find the .NET Core one or just start from a blank workflow yourself.

Screenshot of GitHub Actions config

Four my workflow I want to build, publish and deploy my app.  I’ve separated it into a build and deploy jobs.  You can read all about the various aspects of GitHub Actions in their docs with regard to jobs and other syntax as I won’t try to expound upon that in this article.  Here is my full YAML for the entire workflow with some key areas highlighted:

name: .NET Core Build and Deploy

on: [push]

env:
  AZURE_RESOURCE_GROUP: blazor-deployment-samples
  BLOB_STORAGE_ACCOUNT_NAME: timheuerblazorwasm

jobs:
  build:
    name: Build
    runs-on: ubuntu-latest
    steps:
    - uses: actions/[email protected]
    - name: Setup .NET Core
      uses: actions/[email protected]
      with:
        dotnet-version: 3.1.100

    - name: Build with dotnet
      run: dotnet build --configuration Release
    
    - name: Publish with dotnet
      run: dotnet publish --configuration Release 
    
    - name: Publish artifacts
      uses: actions/[email protected]
      with:
        name: webapp
        path: bin/Release/netstandard2.1/publish/BlazorApp27/dist

  deploy:
    needs: build
    name: Deploy
    runs-on: ubuntu-latest
    steps:

    # Download artifacts
    - name: Download artifacts
      uses: actions/[email protected]
      with:
        name: webapp

    # Authentication
    - name: Authenticate with Azure
      uses: azure/[email protected]
      with:
        creds: ${{ secrets.AZURE_CREDENTIALS  }}

    # Deploy to storage using CLI
    - name: Deploy to storage using CLI
      uses: azure/[email protected]
      with:
        azcliversion: latest
        inlineScript: | 
          # show azure account being used
          az account show
          # az storage account upload
          az storage blob upload-batch --account-name ${{ env.BLOB_STORAGE_ACCOUNT_NAME }} -s webapp -d \$web
          # az set content type of wasm file until this is fixed by default from Azure Storage
          az storage blob update --account-name ${{ env.BLOB_STORAGE_ACCOUNT_NAME }} -c \$web -n _framework/wasm/mono.wasm --content-type application/wasm

So a few things going on here, let’s talk about them.

  • Lines 5-7: these are ‘local’ environment variables I set up.  The storage account name is NOT the blob container name but the actual storage account name.  This ideally probably should be a Secret as mentioned above.  Environment variables can be set here and then placeholders reference them later.
  • Starting at line 9 is where the ‘build’ portion is here.  We checkout the code, acquire the SDK and run the build and publish commands.  On line 26-30 is a step where we put the publish output to a specific artifact location for later retrieval of steps.  This is good practice.
  • Lines 40-42 is where we are now in the ‘deploy’ step of our CD and we retrieve those artifacts we previously pushed and we set them as a name ‘webapp’ that the later will use in deployment
  • Line 45 is where we are going to first authenticate to Azure using our service principal retrieved from the Secrets.  The ‘secrets’ object is not something you have to define and is part of the workflow so you just add the property you want to retrieve
  • Line 51 is where we start the deployment to Azure using the CLI commands and our param ‘webapp’ as the source.  This is the CLI command for uploading batch to storage as described in the docs for `az storage blob upload-batch`
  • Line 61 is an additional step that we need for .wasm files.  I believe this to be a bug because there is logic in the CLI to correctly map the content-type but for some reason it is not working…so for now you need to set the content-type for .wasm to `application/wasm` or the Blazor app will not work

This is made possible through a series of actions: checkout, dotnetcore, azure…all brining their functionality we can draw on and configure.  There are a bunch of Azure GitHub Actions we just released for specific tasks like deploying to App Service and such.  These don’t require CLI commands but rather just provide parameters to configure.  Because there is no Storage specific Action as of now, we can use the default CLI action to script what we want.  It is an enabler in lieu of a more strongly-typed action.  Now that we have this workflow YAML file complete we can commit and push to the repository.  In doing that we now have a CI/CD action that will trigger on any push (because that’s how we configured it).  We can see this action happening in my sample repo and you can see since we separate it in two jobs it will show them separately:

Screenshot of action deployment log

Summary

So now we have it complete end-to-end.  And subsequent check-in will trigger the workflow and deploy the bits to my storage account and I can now use my Azure Storage account as a host for my static website built on Blazor WASM.  This full YAML sample flow is available on my repo for this and you can examine it in more detail.

I would love to know how y’all are coming along using GitHub Actions with your .NET projects.  Please comment below! 

| Comments

Yay! .NET Core 3.0 is now available!  You now are migrating your apps and want to get it to your favorite cloud hosting solution.  But they may not have it quite ready yet and you are still eager to deploy to production.  No worries, we have a solution for you.

As our documentation explains on different deployment models we have for .NET Core apps (simplified);

  • Framework-dependent (FDD): you are expecting the required framework to be where you are deploying…you are just deploying your code.
  • Self-contained (SCD) : you are packaging the required libraries and runtimes needed for your code to run, not expecting any shared runtime on your endpoint.
  • Framework-dependent executable (FDE): similar to FDD, but packaged as an executable, but expects a shared runtime to exist where you are deploying

Ideally your favorite cloud host provider will have your desired runtime available to you in their PaaS offerings.  But we’ve already established you are eager and want to get your new app there sooner.  No worries, then SCD is for you.  So how do you do that?  Here’s some helpful hints to get you going.

Producing the bits for SCD deployment is a part of the ‘publish’ pipeline to get the fully functional bits in all the right formats/places for you.  Here’s how you get it going in a few different environments.  First, though all of these require the understanding of runtime identifier values, or RID as we affectionately call it.  RIDs identify the target platform where the app will run.  You can see a list of all possible values in the RID catalog.  Understanding your value is key first.  For this, I’m going to deploy to Azure App Service for Linux and going to use linux-64 as my RID in all samples below.  This would vary based on what/where you are deploying.  I am also assuming in my samples that I’m executing these commands where they know the context of where my csproj file exists.  You can, of course, specify the path to your project files explicitly.

dotnet CLI

From the dotnet CLI you would first want to build and then publish using the RID.  Why build?  Well, it’s valuable to ensure your building against the RID that you will publish.  Catch any build errors in advance, ya know?  So from the CLI:

dotnet build -r linux-x64
dotnet publish --self-contained -r linux-x64

The key here is the ‘-r’ and ‘--self-contained’ arguments.  I’m using ‘-r’ but you can also use ‘--runtime’ for the long form.  What this will produce (unless you specified a different output argument) is a folder with your RID and then the publish folder within that.  So for me above in my project directory it would be in \bin\release\netcoreapp3.0\linux-x64\publish and everything in that \publish is what is needed for SCD. 

Using the CLI is the basic you can do.  Now it’s on your own to push the bits where they need to be, specify startup commands, etc.  But better, you can use some tools that build on top of this CLI goodness.

Azure DevOps 

Let’s first talk about DevOps.  You should be using this.  No let’s be real clear – USE CI/CD!!! “But I’m only myself as a developer!” So what, you should still use this.  I’m a believer now and it is so simple to set up and you then just worry about committing your code and your DevOps flow/pipelines take care of build/test/publish/release for you…it’s awesome.  With that out of the way, let’s show you how to do it in Azure DevOps. 

Honestly, if you haven’t gotten the hang of CI/CD you really should spend the time in one day and get your project configured.  Whether it is Azure DevOps, GitHub Actions, AppVeyor, Jenkins, whatever, you will be better off.  Azure DevOps is basically free and you’ll be happier once you’ve got it done.  You owe it to yourself.  But don’t worry, I explain the other ways below too.

In your pipeline you would add the .NET Core task and configure it for publish (assuming you also have the build/test).  This task basically calls the CLI so you put the same arguments as we just went through.  Here is my task in part one:

Screenshot of Azure DevOps pipeline showing publish arguments

Observe the ‘Zip Published Projects’ – I enabled this because this is what will be used for Azure App Service deploy next.

SPECIAL NOTE: When using the ‘Use .NET Core’ task in Azure DevOps, I recommend using the major.minor.x pattern to specify the version, so in this case 3.0.x.  This will ensure you get the latest patch updates for your specified major.minor version.  For self-contained this is smart since you are bringing the platform runtime with you and not getting auto-updates from the platform.

Then you want to deploy it, and for me to Azure App Service, I add the Azure App Service Deploy task and configure it using my published bits from the previous step.  Notice I’m still specifying the Runtime Stack value (even though at the time of this writing I need to use SCD) and specifying the startup command as the folder path to my app.

Screenshot of Azure DevOps pipeline showing deployment

And that’s it…now when I commit a change, these pipelines run and build/publish/deploy my app to my cloud provider without me having to worry if they have the runtime available yet or not.  You should be able to do this with Azure, AWS, wherever, and still use Azure DevOps to manage your workflow (or GitHub Actions).

Oh you’re a YAML person?  Sorry about that…here’s basically what it looks like using Azure DevOps tasks:

steps:
    # task for publish CLI command
    - task: [email protected]
    displayName: Publish
    inputs:
    command: publish
    publishWebProjects: True
    arguments: '--configuration $(BuildConfiguration) --output $(build.artifactstagingdirectory) --self-contained -r linux-x64'
    zipAfterPublish: True

    #task for deploy to Azure App Service
    - task: [email protected]
    displayName: 'Azure App Service Deploy: tacticview'
    inputs:
    azureSubscription: 'Azure-Microsoft'
    appType: webAppLinux
    WebAppName: tacticview
    deployToSlotOrASE: true
    ResourceGroupName: 'timheuer-linuxappsvc'
    SlotName: staging
    RuntimeStack: 'DOTNETCORE|3.0'
    StartupCommand: /home/site/wwwroot/TacticView
    

So there you have it for Azure DevOps!

GitHub Actions

For GitHub Actions, it is very similar to Azure DevOps using the CLI.  Here’s the relevant snippet for those steps (minus the deploy part):

name: ASP.NET Core CI

    on: [push]

    jobs:
    build:

    runs-on: ubuntu-latest

    steps:
    - uses: actions/[email protected]
    - name: Setup .NET Core
    uses: actions/[email protected]
    with:
    dotnet-version: 2.2.108
    - name: Build with dotnet
    run: dotnet build --configuration Release
    - name: Publish with dotnet
    run: dotnet build --configuration Release -r linux-x64 --self-contained

    

You would them want to add the deploy pieces in GitHub Actions and you can follow along with that from Abel’s blog post.

Visual Studio

I STRONGLY recommend you adopt a full CI/CD workflow for all your projects.  This has gotten so simple for most cases that it would be a shame not to do that.  But we do also provide means in Visual Studio tools to publish as well.  In your ASP.NET Core application if you right-click and choose Publish, you’ll see the options.  You first create a publish profile which walks you through where you want to publish.  I won’t show that part because it can be different depending on your selection.  But once complete you’ll be presented with this view:

Screenshot of Visual Studio showing deployment mode option

In that view you click on the area highlighted that is labeled Deployment Mode and will be presented with the dialog to change:

Screenshot of Visual Studio showing deployment mode and target runtime options

Once those two things are changed, then when you click Publish it will use the self-contained version of your app and push to whichever endpoint you chose.  And you are done for Visual Studio.

VS Code

What about if you use Visual Studio Code, VS Code?  With the latest release of the Azure App Service extension, .NET projects got better support for deploying to Azure App Service.  The default flow for this is simpler and doesn’t assume you want to deploy using SCD, so you have to do a bit more setup.  When you have a C# project in VS Code you should get prompted (and you should accept) the option to add assets to your project.

Screenshot of Visual Studio Code dialog requesting to add assets

This adds a .vscode foler with a tasks.json file in it that looks like this:

{
    "version": "2.0.0",
    "tasks": [
    {
    "label": "build",
    "command": "dotnet",
    "type": "process",
    "args": [
    "build",
    "${workspaceFolder}/testwebdeploy.csproj",
    "/property:GenerateFullPaths=true",
    "/consoleloggerparameters:NoSummary"
    ],
    "problemMatcher": "$msCompile"
    },
    {
    "label": "publish",
    "command": "dotnet",
    "type": "process",
    "args": [
    "publish",
    "${workspaceFolder}/testwebdeploy.csproj",
    "/property:GenerateFullPaths=true",
    "/consoleloggerparameters:NoSummary"
    ],
    "problemMatcher": "$msCompile"
    },
    {
    "label": "watch",
    "command": "dotnet",
    "type": "process",
    "args": [
    "watch",
    "run",
    "${workspaceFolder}/testwebdeploy.csproj",
    "/property:GenerateFullPaths=true",
    "/consoleloggerparameters:NoSummary"
    ],
    "problemMatcher": "$msCompile"
    }
    ]
    }
    

Note lines 17-24 which show the CLI commands we’ve already been talking about here.  So these you’d have to change to add arguments.  For brevity I’m only showing the modified publish lines here to what you would need:

{
    "label": "publish",
    "command": "dotnet",
    "type": "process",
    "args": [
    "publish",
    "${workspaceFolder}",
    "--configuration",
    "Release",
    "/property:GenerateFullPaths=true",
    "/consoleloggerparameters:NoSummary",
    "--runtime",
    "linux-x64",
    "--output",
    "bin/release/netcoreapp3.0/publish",
    "--self-contained",
    ],
    "problemMatcher": "$msCompile",
    "dependsOn": "clean"
    }
    

But that’s not it.  Remember when we talked about how the CLI publishes to a /netcoreapp3.0/<RID>/publish folder?  You’ll need to know that for the Azure App Service deploy.  Notice I added an explicit output argument here.  Why?  Well laziness for one.  The App Service Extension when you deploy will also add a settings.json file in your .vscode folder that looks like this:

{
    "appService.preDeployTask": "publish",
    "appService.deploySubpath": "bin/Release/netcoreapp3.0/publish"
    }
    

Notice the appService.deploySubpath argument?  Well I just didn’t want to change that to /linuxx64/publish.  Either way, you could have changed the argument here or in tasks.json but the bottom line is they need to match paths so the extension knows what you want to publish!  With these two complete, when you choose to publish using the extension you’ll be publishing a self-contained app to your provisioned Azure App Service instance.

I hope this helps get an idea of the different ways you can publish and how to use the SCD option.  Realistically you don’t need to use this in cloud environments which support your framework version.  In fact, as soon as they do support your version, go back in to your DevOps flow and remove the SCD argument and kick off a new release…no need to change code in your project or use your dev tools…another benefit of using DevOps – you can even do it from your phone!

Thanks for reading this far!

| Comments

I run my site on Subtext which has been around for 6+ years in some form (Subtext is a fork of .Text from way back).  As a part of the framework, there was initially built-in capabilities for tracking referral traffic.  On each view of the application, it would tick a referral note and you could see this in the statistics view of the admin pages.

As the standards (for lack of a better term) of tracking Page Views, Referrals, etc. moved to more proven/consistent reporting like Google Analytics (or other platforms) these type of platform tracking became worthless to me.  I never checked them because, frankly, I didn’t believe them anyway.  The problem is that Subtext is still tracking this information for me and taking up valuable little bytes in my database.

For Subtext, specifically, contributors have created scripts and maintenance pages to help manage some of these referrals that may not matter to folks and are just taking up space.  I am one of those people.  In my recent migration to SQL Azure I wanted to take advantage of 100MB pricing.  Surely my blog was not bigger than that.  To my surprise my blog was 650MB in size. 

What!?

I hadn’t run my database maintenance script in a while and decided to run that which purges the referral tracking.  It got down to 35MB.  Yeah baby.  In fact this topic has been discussed on a few times on the Subtext developer mailing list and even tracking as a issue for the project.  In the meantime I wanted to solve it myself for my blog.

In Subtext there is a stored proc that runs to get some of the entry tracking data called subtext_TrackEntry.  Within that proc is where it looks to see if it is a referral and adds that data.  I simply altered my proc on my end to be like this (keeping in the old function just so that I know what I did in case I needed to revert back):

   1: ALTER PROCEDURE [dbo].[subtext_TrackEntry]
   2: @EntryID INT, @BlogId INT, @Url NVARCHAR (255)=NULL, @IsWeb BIT
   3: WITH EXECUTE AS CALLER
   4: AS
   5: -- Removing the referral tracking
   6: -- if(@Url is not NULL AND @IsWeb = 1)
   7: -- BEGIN
   8: --    EXEC [dbo].[subtext_InsertReferral] @EntryID, @BlogId, @Url
   9: -- END
  10: EXEC [dbo].[subtext_InsertEntryViewCount] @EntryID, @BlogId, @IsWeb

Now I’m no longer tracking referrals because my analytics package is doing that for me already.  My database is now representative of things that matter to me, rather than things I just want to clean up.  If you are a Subtext user and never knew that referral logging was wasting your database (and you are using an analytic package to track that anyway), then I hope this helps! 

| Comments

One of the nice little additions to the data client services in Silverlight 2 is the removal of the need to drop out of Visual Studio to do some proxy code generation.  Prior to Silverlight 2 release, if you wanted to consume an ADO.NET Data Service (the artist formerly known as Astoria), you had to drop into a command line and execute something like:

   1: datasvcutil.exe /out:"MyDataService.cs" /uri:"http://foo.com/MyDataServiceEndpoint.svc"

While that isn’t difficult, it just wasn’t convenient as a developer productivity workflow.  I mean who wants to have to click and type more than you have to, right?  After all, ADO.NET Data Service (alright forget it, I’m calling it Astoria) endpoints are services right?  And Visual Studio does have this thing called Add Service Reference?

Alas, now we don’t have to use a command-line anymore.  With Silverlight 2 and Visual Studio tools, you now can use the service reference capability I’d like to show you a screenshot, but it’s not like the dialog window is any different than other service references, so I’ll save me and you the bandwidth.  But try it out.  Take your project, add a reference to your Astoria service.