Add an Asp.Net Core MVC UI

Continuing the MyReverie Solution, I would like to add a UI to begin displaying data.

The UI will be quite basic for now injecting a simple dummy service in to our controller returning mock data to expose to to the View.

Okay, let’s go…

Create a new Solution Folder under the src folder called ‘Web App’ within this folder create the new Asp.Net Core MVC project and name it ‘WebMVC’

Template

Change the Authentication to be ‘Individual User Accounts’ –  we will be adding Authentication later on.

Auth

Select Ok and Ok again to create the new project

Okay, now we will go and create new ViewModels.

ViewModels are a View perspective of our underlying data – seperating out Models or DB Structure from our view.

Let’s create a new folder we will call ViewModels within the same project and within it create a new folder called GoalViewModel and within this folder create a new class called IndexViewModel, Also within the ViewModels folder create a new class called ‘Goal’ – the reason I am choosing this structure is to create a separate Goal object that will encompass the typical properties associated with a goal and then the IndexViewModel will be the grouping of ViewModels for the Goal View.

Within the Goal Class update as below

image

I am just creating one property name for now, I will build upon this later on.

Within the IndexViewModel class update as below

image

Now we will create a new controller selecting the ‘MVC Controller – Empty’ template and name it GoalController.

Now in the new GoalController class, we will want to call out to service methods in our new service class to return some mock data.

First lets Inject our service via Dependency Injection specifically Constructor Injection(we will create this service class after)

Create a new Constructor for our GoalController class and at the top of the class create a private readonly backing field called ‘_goalService’

Now create a Constructor injecting an IGoalService and assigning its goalService to our backing field – I am injecting an interface to decouple any dependencies of concrete classes making it more maintainable and testable.

The class should look something like below at this point

image

Okay we will go create our IGoalService interface in a new project folder we will call ‘Services’ within the WebMVC project

Within the newly created class change as below

image

Now let’s go ahead and implement this interface creating a new GoalService class

Create the new class within the Service folder and change as below

image

There will be warning saying there is no await in async method that is okay, we will be modifying this method to return something more meaningful after.

Go back to the controller class and and add the missing WebMVC.Services namespace

Do a build to ensure everything compiles correctly.

If you build successfully – Great… we are almost finished.

Now lets update the Index method in our GoalController class to return our Goal to display in our View.

image

Now lets update our View to display some information.

Within the Views Folder create a new Folder called Goal and within the Goal folder create a new view with the following settings

image

Now update this new view to be as below

image

Finally we need to update our ConfigureServcies  method in our Startup class

by adding the below:

services.AddTransient<IGoalService, GoalService>();

In order to resolve our injected dependency(IGoalService) in our Controller to GoalService

Now run your application, you should hopefully see the below to see the results

image

That’s it for now.

This code will be up pushed to the MyReverie GitHub repo under tag ‘UI’ for tracking.

Adding versioning to my Web API

Now I would like to add versioning to my MyReverie Web API, there are a few options available to me such as :

Query String, Url based as well as Http header.

For my purposes I am going to choose the Url based approach, purely a personal preference of being cleaner and more explicit.

First things first we will need to go ahead and install the Nuget package:

Microsoft.AspNetCore.Mvc.Versioning

Within the Startup class and ConfigureServices method, add:

services.AddApiVersioning(v =&gt;
     {
         v.ReportApiVersions = true;
         v.AssumeDefaultVersionWhenUnspecified = true;
         v.DefaultApiVersion = new ApiVersion(1, 0);
     }
 );

The above three properties are particularly useful in that they allow default versions to be set if none are explicitly set as well as providing header information on versioning that are supported.

In the above

ReportApiVersions: we are requesting the header to respond with supported API versions
AssumeDefaultVersionWhenUnspecified: set the default version if none are explicitly requested
DefaultApiVersion: Set the default version to 1.0 if default is used

To better illustrate point number one above see below. I used Postman to see the response header with supported versions listed, which I highlighted

Versioning_thumb7

Now all I have to do is simply add and update the controller attribute in my case

At the moment as I am still on version 1, I will add the attribute

 [ApiVersion("1.0")]

  and update the route attribute like so:

[Route("api/{v:apiVersion}/[controller]")]

So the result of the GoalsController class attributes should look like the below

Versioning_thumb1

Now let’s test our F5 and browse to our API endpoint with suffix : /api/1.0/goals, in my case below.

Versioning_thumb3

That’s it my API is now versioned v1.0

Adding Integration Testing with Xunit

I want to now add some test automation to my solution I’ve been working on MyReverie.

I plan on using xUnit and start off with some Integration testing for my API but will also be adding functional, unit down the line.

I will add testing through the Visual Studio IDE, I know I can do the same through the CLI, but I wont do that here.

Lets begin…

Note: Whilst I go I want to do some Solution restructuring/cleanup – I plan on taking in to consideration DDD(Domain Driven Design) concepts such as separating Bounded Contexts and continuing our micro services approach along the way.

So continuing from where we left last time

Lets create a new solution folder and call it ‘test’

Now under our new test folder create a new folder called ‘Services’

Now under under the Services folder under test create a new xUnit project like so

Right click on our Services folder select ‘Add’ and ‘New Project’

type xunit in the search field on the top right of the window, the results should be filtered and you should see  ‘xUnit Test Project(.Net Core)’

select it and name the project ‘IntegrationTest’

For some reason, the new test project ends up being added to our src/Services folder not our test/Services, so lets ensure we have our test project under test/Services

Lets delete the class auto created UnitTest1.cs

Under the IntegrationTest project create a new folder called ‘Services

Under the Services folder create a new folder called ‘Goals’

whilst we are at it lets move our Goals.API project under a new folder called ‘Goals’ under the ‘src/Services’ folder

The solution structure should look like below

Solution Structure

Lets rename the ValuesController class to GoalsController under our Goals.API project and change the class name to GoalsController

now lets create a new class under the Goals folder in our IntegrationTest project and call the class ‘GoalsScenarios’

We should now see something like below

Solution Structure Next

Let’s do a quick build to ensure we can still compile.

—-

Now what we need to do is to be able to fire up our API to perform an Integration test against.

Lets go ahead and create a new class under test/Services/IntegrationTest/Services/Goals and call is GoalsScenarioBase

and paste the below within the class

public TestServer CreateServer()
{
var webHostBuilder = WebHost.CreateDefaultBuilder();
webHostBuilder.UseStartup<Startup>();
var testServer = new TestServer(webHostBuilder);

return testServer;
}

let’s make the class public

We will want to add some references for correct namespace resolution

Lets go and add Microsoft.AspNetCore in my case v2.1.1 to our project through Nuget

Also lets add Microsoft.AspNetCore.TestHost again in my case v2.1.1

Note – Ensure you have Core v2.1.1 SDK and Runtime installed

We will want to add Goals.API , Microsoft.AspNetCore.TestHost, using Microsoft.AspNetCore.Hosting and Microsoft.AspNetCore through using statement on top of our class.

lets ensure we also have our Goals.API project references Microsoft.AspNetCore v2.1.1 also, otherwise we may get conflicts between versions.

Let’s build to ensure we are still good.

Our Base class should look something like the below once complete

Base

Now let’s perform a quick silly test to test Smile

In our Goals Scenarios class lets add the following code

[Fact]
public async Task Get_get_goal_by_id()
{
using (var server = CreateServer())
{
var response = await server.CreateClient()
.GetAsync($”api/values/5″);

Assert.Equal(“value”, await response.Content.ReadAsStringAsync());
}
}

Again this is a silly test but we just want to perform a simple integration test against our API.

We are calling our Get method passing in an arbitrary value(5) to receive a response back to compare – by default our method simply returns “value”

Let’s inherit form GoalsScenariosBase also so we have access to our server we created above and make our test class public

Lets add Xunit & System.Threading.Tasks namespaces to the top of our class

Run the test using the test runner and we should receive a Successful test run.

That’s it for now.

I will push all latest changes to GitHub to the MyReverie repo with tag xUnit for easy reference

Adding Swagger to my ASP.Net Core API

Continuing on the MyReverie solution building upon my last post on this My Reverie.

What I would now like to do is add some API documentation around the my API

The reason I am choosing swagger is simply that it is the largest framework of API developer tools for the OpenAPI specific which allows rapid documentation and testing my APIs with great ease.

For reference check out their website @ https://swagger.io/

Let’s get started

First we want to add the Swashbuckle package from Nuget

So right click the Goals.API project

Click Manage Nuget Packages

Nuget

Under Browse tab search for Swashbuckle.AspNetCore

Package

Once found click install

Once installed we want to add the Swashbuckle namespace ‘Swashbuckle.AspNetCore.Swagger’ to our Startup class

In the ConfigureServices method add:

services.AddSwaggerGen(c =>

{

c.SwaggerDoc(“v1”, new Info { Title = “My Reverie”, Version = “v1” });

});

ConfigureServices

Next, In the Configure method

In the cope of the env.IsDevelopment() check, add

app.UseSwagger();

app.UseSwaggerUI(options =>

{

options.SwaggerEndpoint(“/swagger/v1/swagger.json”, “My Reverie V1”);

});

Configure

Lets run it to see what it looks like, you should see something like below

image

To try it out simple select the Get button

Click the Try it out button on top right

Then hit execute

image

Summary:
We’ve just added swagger to the API to add a basic documentation and testing base in which to build upon.

My Reverie

MyReverie is a new simple side project I am working on. The idea is to build a goal tracking solution set target dates against those goals as well as set milestone markers to track progress. They could be long or short term goals – entirely up to the user.

I will routinely push the code at certain points to GitHub under MyReverie Repo.

I have a rough idea of some of the features to add which I will list under the Projects Tab of GitHub.

This is also a way to experiment and learn new technologies as I go, some technologies I will be looking to incorporate are Asp.Net Core, Swagger, Docker,  xUnit.Net and EF Core so far.

I would like to have this solution created in a Micro Services style architecture – so functionality abstracted to services.

I will break this solution out to different blog posts as the solution is going to continue to grow.

The solution is not intended to be a complete sample or starter app more of a reference or exploration on learning.

In this post I will begin with the Goals API

Okay, let’s get started.

Lets go to Visual Studio and create a new ASP.Net Core project.

I am using Visual Studio 2017 Community

After clicking File->New Project, I want to select ASP.NET Core Web Application

ASPNetCoreWebApp

Lets call the project name ‘Goal.API’ and Solution Name ‘MyReverie’ as below, I want to also also select ‘Create new Git repository’ to commit using Git

NameprojSol

Lets choose the API template and select ASP.Net Core 2.1 under the dropdown as well as uncheck ‘Enable Docker support’ for now and clock OK

Template

After restore of packages has completed, lets run the API to ensure it build and runs successfully,After launching add /api/values to the end of the URL and you should see something similar as below.

RunApp

Great, we have created our Solution as well as our Goal API.

Let’s go ahead and create 2 new folders in our solutions, src and Services, Services being a child of src and lets move the API project under Services as below.

SolStructure

That’s it for this post, next post will continue to build upon this solution

Getting Started with Azure Service Fabric

I wanted to show a simple example of using Azure Service Fabric to create a reliable & scalable micro service that would perform addition functionality on an input string for example “1+1” using a console application as the client.

The string is parsed out to two integers and calculates the result. Obviously this is extremely simplistic type of example. I wanted to really just do a quick test on passing input and expecting output.

The code is listed up on my GitHub account under the ServiceFabric Repo.

ASP.NET Core Web API with Docker

This post simply demonstrates creating a simple service called ‘AdditionMicroservice’ that adds two numbers provided as query string parameters.

I will add this code to my GitHub account under Getting started with Microservices repo

Pre-requisites:

Docker for Windows

1) Create a new ASP.NET Core Web Application project

image

Select the Web API Template

image

Check the Enable Docker Support checkbox

Select Windows as the OS

Click

Open Values Controller file under Controllers

image 

Remove all other methods except first Get method and change to below as below

image

The change  launchUrl’s from api/value to api/addition in launchsettngs.json file:

image

Run the app and append to the URL both the x and y parameters along with their set values to view the result:

image

Visual Studio 2015 debugging lambda expressions

Debugging Lambda expressions is certainly a very welcome feature of Visual Studio 2015. Before when trying to evaluate lambda expressions within either the watch or immediate windows we would see the message “Expression cannot contain lambda expressions”.

The great thing about this feature is that it really speeds up the diagnoses of possible bugs being faced within your application and being able to really dig in to your collections and query the data right there and then on the fly.

For instance if you are retrieving a result set from a collection but not getting the results you are expecting, you can now query the collection using lambda expressions within either the immediate or watch window during debug to give you a direct view of what data is resident within your collection that particular point in time, from there you can then dynamically make changes to your query within the immediate or watch windows necessary to confirm your hypothesis of why you are not seeing the results you were expecting – all while in debug mode without having to perform that oh so fun process of stop debugging –> make a change –> re-run –> confirm results if yes stop else go again.

Once you confirm that you are now getting the results expected from your changes you can then go ahead an make the necessary adjustments to your source code.

This is really well demonstrated by Andrew Hall in the below video.

 

Resources that helped me pass the 70-483 exam

Well a few weeks back I passed the 70-483 Programming in C# exam, it had been several years since I took an exam so I did not know how I would do.

I had worked in c# for quite some time now but all of my knowledge was pretty much self taught on the job so I knew there were some gaps in my knowledge so I thought going for the exam would at least highlight the areas in which I need to focus on. Indeed there were some areas I had touched on very little throughout my career so it was definitely a worthwhile cause from that perspective alone.

In my previous employment I had the opportunity to attend the Microsoft official course for this exam which lasted a week which was really beneficial and was a great resource, however it was expensive and not sure I personally would have attended I have had to foot the bill. Other resources that I took advantage of where pluralsight courses, virtual academy jumpstart videos as well as the MCSD Certification Toolkit.

To mention the pluralsight course there is blog post covering this exam course : http://blog.pluralsight.com/learning-path-c-microsoft-exam-70-483 which indicates the videos to check out that would be specific to the exam areas, I cannot rate pluralsight enough to be honest I truly believe it to be one of my best subscriptions I cannot tell you the amount of information I have learnt over the years using this resource as well as solving many technical issues that I had faced – if you do not have a subscription I would encourage you to take advantage of their free trial.

The virtual academy jump start videos were awesome too : http://www.microsoftvirtualacademy.com/training-courses/developer-training-with-programming-in-c, the videos were very entertaining and the presenters knew their stuff best of all it is free so definitely check them out. It is a great resource for some free training.

Other than this plenty of hands on coding there is really no substitute for actual coding I believe it is not only the best way to learn as it will quickly let you know when you hit an area you do not truly fully grasp but also the best way to retain what you learn for longer.

Reset WordPress admin password with MySql workbench

This post is particularly directed at a configuration of an Azure wordpress website with MySql as a linked resource.

Select your Azure wordpress website in your Azure portal then select dashboard

If you scroll to the bottom you will see a section titled ‘linked resources’ under here you should see your MySql database linked resource.

If you click on your MySql database name it will bring you to a clear db web portal.

If you click endpoint information from the top menu, note down your hostname along with your access credentials as you will need them to log in to a MySql client (MySql workbench)

Next click on the dashboard menu item on the clear db web portal and under the ‘Managing Your Database’ heading you should see a MySql workbench link which will bring you to a download page in which you can go and follow the instructions to download and install the client.

Once the client has been installed you should be able to run it and enter the hostname, username and password for your MySql database you noted earlier in the prompt that appears .

From here you should see a query windows open by default if you type in ‘SELECT * FROM [your database name].wp_users;’ and select the lightning bolt in the menu that will execute this sql statement you should see a list of users in your wp_users table in your database.

From here you can manually edit the ‘user_pass’ column that is associated with the admin account with an md5 hash(you will need to generate an MD5 hash of your new password, which you can utilize md5 hash online generators) of your newly chosen password and select the apply bottom near the bottom right of the table view.

That’s it – you can now go to back to your login page and enter your username with the new password and login.