Monday, 10 August 2020

Create a C# Core REST API

I started my career working with Visual Basic 6.0... soon after I Switched to win-forms in visual studio, then to web-forms, then to UWP's and XAMARIN forms with each transition relying less frequently on the WYSIWYG to such a point were I just stopped using it, in the same way that a drug addict weens him or herself (wouldn't want to be accused of sexism) off of crack once they hit rock bottom, my rock bottom was SharePoint... 

Anyway enough of my autobiography "Sucking SharePoint for money", it's time to start a second volume; currently my working title is "Stealing candy from babies, making a living the merican way".

So lets get started, in this post we are going to set up a simple out of the box rest API, open up your windows terminal 

one can create a dotnet project using any terminal, i just prefer the "windows terminal" because it brings me back to DOS and I'm getting nostalgic in my final years...

for a bonus type in "dotnet new" to see all the initial templates available to you.

once you hit enter it should take about 10 seconds and voila you have your first API.

keep in mind that we manually created our file folder, we could have done something along the lines of "donet new webapi -n <project name>"

now to take a look at what you have created, ether type in the "dir" command to view a listing of the directory in your terminal or "explorer ." to open it up in your windows explorer.

and the explorer view

now that is probably not all that exciting, however you can see that it is there, next lets open this sucker in VS Code; type in "code ."

now that our project is open VS Code

notice the dialog in the bottom right, make sure to click yes on it; you may be wondering what happens if you don't, well the answer is simple... henchmen from the Microsoft corporation come to your house and buy you out.

with our template created, lets test it to see what happens; in your terminal of choice type in dotnet run (assuming that you are in your project folder).

now your api is up and running locally on your machine, you can navigate to https://localhost:5001/weatherforecast on your local machine and you should see something like the following.

It's just some simple JSON output coming from our weatherforecast controller, and if you are wondering WTF is that, well lets head back to our project in VS code and take a look.

 

in the left hand column you can see our WeatherForcastController file, you can think of this as our webpage, but instead of returning HTML that our browser renders, it contains functions that return data, generally as JSON but way back when I first started with SOAP service they were returning XML, why the change you may ask, well because in the early 2000's the internet hated Microsoft and apparently JSON was far superior due to the fact that it was far less verbose, meaning that it was shorter and you have to transfer less data, how much less you may ask? well it depends on the payload, but compared to an audio file the difference was competently insignificant, that being said it was also a time when mobile data was very expensive so it did serve a purpose.

I'm not shitting on JSON, I think it is just fine, but by no means is it the game changer that it has been made out to be. in short JSON is shorter than XML, XML is more human readable, 99% of the time it wouldn't make a difference which you use, however 99.9% of the time you will be made fun of for using XML, thus save yourself ridicule and use JSON, but just be aware that in a legacy system if you hear the words SOAP Service it will most likely be passing data around as XML.

But i degress, lets take a look at our Controller

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace pav.Controllers {
  [ApiController]
  [Route("[controller]")]
  public class WeatherForecastController : ControllerBase {
    private static readonly string[] Summaries = new[] {
      "Freezing", "Bracing", "Chilly", "Cool", "Mild", 
      "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger) {
      _logger = logger;
    }

    [HttpGet]
    public IEnumerable<WeatherForecast> Get() {
      var rng = new Random();

      return Enumerable.Range(1, 5).Select(index => new WeatherForecast {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = rng.Next(-20, 55),
        Summary = Summaries[rng.Next(Summaries.Length)]
      }).ToArray();
    }
  }
}

notice the two attributes on our class [ApiController] and [Route("[controller]")] the first marks our class as an API Controller and then through the magic of Reflection our API Application "knows" that this class contains api endpoints. the second is the route, this specifies the url path after our domain address, so if we changed it from 

namespace pav.Controllers {
  [ApiController]
  [Route("[controller]")]
  public class WeatherForecastController : ControllerBase {
   //removed for brevity
  }
}

to 

namespace pav.Controllers {
  [ApiController]
  [Route("api/v1/[controller]")]
  public class WeatherForecastController : ControllerBase {
   //removed for brevity
  }
}

and we restarted our api but clicking ctrl+C in our terminal and executing dotnet run again we now would have to modify our url accordingly.

 

if we update our URL to https://localhost:5001/api/v1/weatherforecast

we are up and running once again, now the reason why we appended this api route with a version number is because often times your api will be supporting multiple versions of consumers. so for example you may have a web application that uses version 1 then you may add a mobile app that uses a newer version say version 2 that needs some new endpoints, that do the same thing but slightly differently. anyway save your future self some headaches and version your API right from the get go.

It also would make sense for you to adjust your folder structure accordingly, so just add a v1 folder to your controllers and move your weatherforecast controller into it, notice that Code give you this horizontal display when you have just one child folder

Should you add a second V2 folder it will look more familiar

now if you rerun your application everything will work as before, keep in mind that your folder structure and your namespaces are usually aligned out of convention, by no means do they need to be.

anyway I think that is enough for today.


Friday, 17 July 2020

MSAL localhost

So let's say that you have MSAL configured and it works perfectly in production however it fails in your development (localhost) environment. As a matter of fact you get a javascript error message such as the following.

Unsafe JavaScript attempt to initiate navigation for frame with origin 'https://myurl.azurewebsites.net' from frame with URL 'http://localhost:8080/login'. The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.

well my dear friend odds are you most likely made the same bonehead move that I did, especially if on your older laptop it worked perfectly, but fails on your new one. I'll cut to the chase, you need to specify the correct redirect url when defining your IdentityContext:

  IdentityService: new IdentityService(
    new IdentityContext(
      process.env.VUE_APP_CLIENT_ID, 
      process.env.VUE_APP_REDIRECT_URL,                   
      `https://login.microsoftonline.com/${process.env.VUE_APP_TENANT_ID}`))

as you can most like deduce i am using vue.js environment variables to hold my values, but you know which files do not get pushed to your repo, the ones that end in .local, and which ones does your local machine use? the ones that end in .local. 

trust me if this solved your problem you are feeling a lot less silly than I did when I figured it out.

all i had to do was open my .env.dev file

VUE_APP_TITLE=DEV-remote
VUE_APP_CLIENT_ID=00000000-957e-4ae1-a64a-ab186e161727
VUE_APP_REDIRECT_URL=https://myurl.azurewebsites.net
VUE_APP_PROFILE_MATCHCER_API_URL=https://myurl.azurewebsites.net/api/v1

and change it to

VUE_APP_TITLE=DEV-remote
VUE_APP_CLIENT_ID=00000000-957e-4ae1-a64a-ab186e161727
VUE_APP_REDIRECT_URL=https://localhost:8080
VUE_APP_PROFILE_MATCHCER_API_URL=https://myurl.azurewebsites.net/api/v1

and all was well in the world again

Saturday, 30 November 2019

Closing: Closure Plan

There are various reasons of why a project would close
  • It has completed the objectives as stated in the project plan.
  • Management has pulled the plug for one reason or another
regardless the reason there needs to be a project closure plan. The goal of the closure plan is to ensure that all of the project objective have been achieved, the deliverables where delivered, resources reassigned to other projects or operations, lessons learned and best practices are captured. Project closure can be viewed as a mini sub project. The closure plan consists of
  • Confirm all work of the project has been completed 
  • Update project documents to indicate the final status, and store them in a shared repository 
  • Turn over deliverables to the customer and/or to operations, and obtain approval to close the project 
  • Assign resources to other project or operational work 
  • Capture lessons learned and best practices for the benefit of future projects 
  • Celebrate the team and project success

Thursday, 21 November 2019

Execution: Change Control Process

Changes to a project can occur:

  • Scope
    • Add/Remove features or functions
    • Add/Remove deliverables 
    • Add/Remove requirements 
    • Add/Remove activities 
  • Budget
    • Add/Remove money to budget 
  • Schedule 
    • Extra time to deliver project
    • extra time for deliverables 
    • extra time for milestones
Change order is a form that details the change, the buiness impact and reason for the change, its approval or rejection follows a procedure:
  1. Change Order comes from any source internal or external to team
  2. Change order is submitted to the PM or Change Control Board
  3. Change order is logged in the Change control log
  4. Change order is reviewed by PM and Change Control Board
  5. If Change order is rejected or put on hold
    1. Rejection is logged 
    2. Change order initiator is notified 
  6. If change order is considered
    1. PM & Team analyse the change and impact to
      • Scope
      • Work Effort
      • Time Required 
      • Resources
      • Quality
      • Risks
    2. Change Control board reviews analysis and decides to accept or reject chang
      • Rejected
        • initiator notified
        • change logged
      • Accepted
        • initiator notified 
        • baseline changed
        • project docs updated
        • new baseline communicated to stakeholders

Monday, 18 November 2019

Execution: Control

the goal of controlling a project is to pay attention to the various metrics of the project and ensure that the project is being delivered as closely as possible to the baselined plan. if the performance begins to veer off the original plan then the PM must institute corrective measures. If process improvements are identified they should be implemented money and time saved for one activity could be needed by another.

If poor project health is identified using the CPI or SPI then the PM needs to analyse what the cause is:

  • Poor original estimates
  • Personal lack expertise 
  • Unforeseen Risks or issues
  • More expensive resources then anticipated 
  • Scope Creep
  • etc
any number of things could veering the project off kilter, however when the culprit is identified the PM must implement corrective measures, if these corrective measures bring the budget or schedule outside the acceptable variance levels then a change order has to be requested to the Project sponsor and stakeholders. 

Change orders are not a cure all for poor planning or performance, each change order takes personnel away from their tasks costing more time and money on the project. they should be used sparsely and only when necessary. an abundance of change orders is generally a sign of poor planning.

to keep the project on track the PM must review project KPI's regularly and handle discrepancies sooner rather then later.

Thursday, 7 November 2019

Execution: Calculations

Now that we've established:

  • Planned Value: is the amount we planned to spend up until the current point in time
  • Actual Cost: is the amount we spent up to the current point in time
  • Earned Value: is the amount we planned to spend on the completed activities.
  • Budget at Completion: is the amount we spent when to project is completed

we can use these values to calculate values that indicate project health

Cost Variance = EV - AC indicates the budget surplus or deficit.

  • CV >  0 we've earned more value than expected for the cost we incurred; budget surplus
  • CV  = 0 we've earned as much value as we planned for the cost; budget is on-target
  • CV < 0 we've earned less value then expected for the cost we incurred; budget-deficit

Schedule Variance = EV - PV indicates if the project is ahead or behind schedule

  • SV > 0 we've earned more value than expected: ahead of schedule
  • SV = 0 we've earned the planned value: on-schedule
  • SV < 0 we've earned less value than expected: behind-schedule

Cost performance index = EV / AC indicates the health of our budget

  • CPI > 1 we've earned more value than expected meaning we're under-budget
  • CPI = 1 we've earned as much as we planned meaning we're on-budget
  • CPI < 1 we've earned less value than expected meaning we're over-budget.
Schedule performance index = EV / PV indicates the health of our schedule 
  • SPI > 1 we've earned more value than expected up to this point in time: ahead of schedule
  • SPI = 0 we've earned the panned value up to this point in time: on-schedule
  • SPI < 1 we've earend less value than expected up to this point in time: behind-schedule
The CPI and SPI can be used to forecast the expected project cost based on our current performance, if the projected cost is within the variance all is well, if it's not then corrective measures must be implemented.

Estimate to complete = (BAC - EV) / CPI how much money is required to complete the project

Estimate at completion = ETC + AC how much money the entire project will cost.

Tuesday, 5 November 2019

Execution: Earned Value

Earned Value
is the the industry standard for measuring progress, earned value is the Actual cost of the activities that we've completed. It gives us an accurate depiction of how much money we've spent accomplishing our tasks. Earned value provides us with:

  • Progress of status of work being done 
  • Comparison of planned schedule and cost to, actual schedule and cost based on the work completed 
  • Objective data from the baseline compared to actual progress 
  • A forecasting method for estimating project completion 
  • Comprehensive insight into cost and schedule portions of the project
Earned Value Terminology 
  • Planned Value (PV): the amount you planned to spend based on your baseline estimates up to the current point in time.
  • Budget at Completion (BAC): the amount you planned to spend on the entire project.
  • Actual Cost (AC): the amount you've actually spent on the project up to the current point in time.
  • Earned Value: the value of what you've accomplished based on your original estimates, what the cost should be based on how much work is accomplished. 
the relationships between these values will indicate the health of a project
  • EV = PV: on schedule, earned the value planed up to this point in time
  • EV = AC: on budget, earned the value for the cost planned up to this point in time
  • EV < PV: Behind schedule, accomplished less then planned up to this point in time
  • EV < AC: Over budget, paid more for the value than planned up to this point in time
  • EV > PC: Ahead of schedule, earned more then planned up to this point in time
  • EV > AC: Under budget, earned more value for our cost then planned up to this point in time
there are various methods for determining "Earned Value", the one(s) selected should be defined in the Quality plan. 
  • 0/100 Rule: an activity is either complete, or not complete. You've earned 100% of the value or 0% of the value.
  • 50/50 Rule: the project earns 50% of the value when the activity starts and 100% when it's complete.
  • Proportional rule: the value earned is based on the activity status, so if an activity is 25% done then you earn 25% of it's value.