Monthly Archives: August 2016

Exposing ASP.Net Core Web API Documentation with Swagger

Exposing ASP.Net Core Web API Documentation with Swagger
Swagger is one of the available options for API documentation and code generation. In this post, we are going to build swagger specification on top of the Student Service built in the last post [http://www.alternatestack.com/development/app-development/creating-web-apis-with-aspnet-core/] using ASP.Net Core.

Let’s first add the required nuget packages. Here we are using SwaggerGen and SwaggerUI packages. Here the former is used to generate swagger spec for the API and latter is used to expose the specification through a pretty UI. The packages are still in beta for ASP.Net Core.

After adding the above to project.json, let’s run dotnet restore command to download these packages to universal packages folder.

The packages provide a number of extension methods to IServiceCollection and IApplicationBuilder. Now we can use the functionality exposed by these packages in Startup class. Let’s first look at ConfigureService method. Here we are adding certain metadata to the service using ConfigureSwaggerGen method. This metadata would be part of specification, also exposed through ui.

Another is Configure method. Here we are using both Swagger specification generation and UI functionality by using UseSwagger() and UseSwaggerUI() methods.

Service Spec
Let’s run this using dotnet run. Here we are hosting it on localhost:5000 (default) so the url for the spec would be http://localhost:5000/swagger/v1/swagger.json. Here are the contents for the spec.

swagger spec

swagger spec

You can copy and paste this in the editor of your choice and format it as pretty json to understand the API.

Service Documentation
Service documentation can be viewed using Swagger UI. It lists all the operations exposed by the service alongside their signatures. Our service should be available at http://localhost:5000/swagger/ui/index.html

swagger ui

swagger ui

Swagger-ui also allows us to test the API as a client. Here we can specify different parameters to the service to test the service response.

service signature

service signature

Using Code’s XML Comments

Swagger also supports the code’s xml comments to be used for documentation of our API. You just need to enable it like this in project.json.

Here is how we have added the xml comments to the service and its operations:

Please notice the operation summary being used as description for service operations.

xml comments

xml comments

Using Swashbuckle’s attributes

Swashbuckle also provides attributes for decorating our operations. These attributes are available in Swashbuckle.SwaggerGen.Annotations namespace. Let’s add these attributes to our Students service. Here we are adding SwaggerOperation attribute to all our operations. Additionally, we have added SwaggerResponse attribute to Get() method. Here we can list all the possible responses with HTTP status codes.

Please notice how SwaggerOperation translates in swagger spec for get-students-list operation. You can also notice Exception response for Unauthorized.

swagger-json-updated

swagger-json-updated

Here is how Swagger UI displays it.

swagger-response-with-annotations

swagger-response-with-annotations

Code Repository

code repository

code repository

Creating Web APIs with ASPNet Core

Creating Web APIs with ASPNet Core
We have seen how we can setup our mac environment for .net based development. Here we discussed how we created a sample application using Visual Studio and Dotnet CLI tools.

http://www.alternatestack.com/development/developing-c-applications-on-mac-os-using-vs-code/

In this post we are going to see how we can use command line tools to create our first Web API using ASP.NET Core. Here we are going to use Yeoman for code generation and DOTNET CLI to build and run it. We have discussed Yeoman before for building AngularJs applications [http://www.alternatestack.com/development/rest-service-in-angular-js/].

After setting up your machine for .net core development, let’s first install asp.net generator for yeoman using npm.

Now we can just use this generator to create a web api project using yo aspnet command. The generator gives an option to select the project type. Here we have selected Web API Application. Let’s name our API as StudentService.

yo-aspnet

yo-aspnet

As we remember, the first thing we do after generating a project is to restore all the dependencies. Just run dotnet restore and it would restore all dependencies for you.

dotnet restore

dotnet restore

The most amazing thing about asp.net core project is its reduced project contents. I have always been amazed by the number of folders and their contents just to host a simple Web API. Just compare it to some golang or javascript node based service. Here is the project structure.

aspnet core folders

aspnet core folders

A yeoman generator can also have sub-generators. Let’s explore these sub-generators using yo aspnet –help command. Here is the list:

aspnet sub-generators

aspnet sub-generators

Let’s use WebApiController sub-generator to generate StudentsController. Here we are naming our controller as StudentsController. It would be generated in Controllers folder by default.

WebApiController

WebApiController

Now let’s use Class sub-generator to create Student class. This would be used to describe a Student entity. We are creating it in model folder.

Class Sub-Generator

Class Sub-Generator

Now let’s build and run the service using dotnet build and dotnet run commands.

Let’s hit it using Postman. Here we we have the response for GET request from the service.

student-service-get

student-service-get

If this is the first time you are developing a .net core project, and you are curious like a cat then you must be wondering where the packages folder is. Actually, this has been optimized for the framework. Now we just have one packages folder for the user and all applications use the same folder. This reduces the disk usage on a developer’s machine. The packages are in .nuget\packages folder. The default nuget configuration is in .nuget\Nuget.config file.

packages .nuget

packages .nuget

You can always create a local Nuget.Config file for a different nuget repository to be used for a project.

Code Repository

code repository

code repository

Simple Http Server with Templated Response in Go

Simple Http Server with Templated Response in Go

In this post we are going to see how easy it is to host an Http Server in go (GoLang). As we discussed in the previous post we have to use specialized packages for any go app. In order to host an Http server, we need to use net/http package.

In the following code, we are using the package. The package provides methods to listen to Http requests. It also allows to define simple routes. Here we are just defining main route for the app.

Building and running the app is as easy as ever. Here we are building to create the executable. We are then simply running the executable.

Simple Http Server

Simple Http Server

The request is handled by SimpleIndexHandler method. It just respond with a simple message. It also add any sub-route specified in the request. Here we are just requesting the app. Since there are no sub-path, it just returns a hello message in the response.

go server index

go server index

If we do specify a sub-path, it is added to the response.

go server path

go server path

Serving HTML Response

Serving Html response is also very easy. Let’s add a simple Html file to the same folder. Let’s name it index.html.

http package provides ServerFile method. Here we can provide a file name with any necessary path information. It picks up the file and serve the html content of the file.

When we build and run the application again. The request to index sub-path is served with the contents of index.html.

Serving Html file

Serving Html file

Templated Html Response

We can also serve Html response built from a template. The template does support variables passed, which is then used and formatted inside the template. Here we are defining a Student type. It has an Id (int) and Name (string) field.

We can use this type to build up our response. Here we have defined a new function to build up the response. Here we would be needing html/template package. The package provides necessary methods to parse the template, pass arguments and rendering a response.

This can be served up simply by using HandleFunc provided by http package.

And here is the response in the client browser when top-student route is requested.

templated html response

templated html response

Using Template Files

We can also keep the template in a file. Here we are adding IndexTemplated.html file. The file assumes certain parameter with properties Id and Name.

The same html/template package provides functionality to load template from a list of files. We can then pass arguments to the template and then build up the rendered response. Here we are serving up the response using /top-student-from-file sub-path.

When we build and run it, the response is provided as follows:

templated response

templated response

GitHub Repository

https://github.com/msiddiqi/AlternateStack-GitApp

Setting Your Mac for Go Development (GoLang)

Setting Your Mac for Go Development (GoLang)

In this post we are going to see how we can setup your Mac machine for development using GoLang. Go is an open source programming language from Google, which is very efficient for writing platform independent, highly scalable and concurrent code. Let’s first download Go. You can download the installer which should provide the necessary tools for development using the language.

go installer download

go installer download

The installer should also add go in your PATH. If it is successfully installed, you can verify it from the terminal. Just type go in your terminal.

go terminal

go terminal

In order to check which version of go is installed, you can use go version command in the terminal.

go version

go version

Setting $GOPATH

The Go installer just installs the necessary base for development but you need additional packages for developing a go application. They are separately downloaded. This requires GOPATH environment variable to be set. You can just create this bash_profile in your User folder.

touch .bash_profile

touch .bash_profile

We update .bash_profile as follows:

Setting VSCode for Go Development

In order to develop Go applications in VSCode, we have to set it up first. Ideally, it should pick up the system’s settings, but it doesn’t. We need to update settings to specify the folder used to download packages.

go settings

go settings

Let’s update the settings.json with the following settings:

For debugging support, we are not done yet with Visual Studio Code. As we try to hit Debug, we get the following message:

go debug vscode

go debug vscode

We can install this using Integrated Visual Studio Code terminal:

First Go App

Let’s write our first Go app. This is actually the skeleton of any Go App. This has a simple main function, which uses PrintLn function from fmt package to print a simple message to the console.

Go application can be built using go build command. It creates an executable in the same folder, which can be run directly. You can notice that the message written using fmt is printed on the console.

building go

building go

GitHub Repository:

https://github.com/msiddiqi/AlternateStack-GitApp

Angular2 – Using Images, CSS and other assets

Angular2 – Using Images, CSS and other assets:

In this post, we are going to learn how we can use assets including image and CSS style in an angular 2 application. Let’s use the banner of our blog site as the image:

alternate-stack

alternate-stack

In order to keep our example simple, we are using a very basic style setting the width and height of an image to a specific value.

All the assets in an angular 2 app are created in public folder. Here we have created two sub-folders; images and stylesheets. Both of these folders just have one component corresponding to their folder names.

image-styles

image-styles

As we build the project using ng b command. All the constituents of the folder are copied directly to disk directory. Please notice stylesheets and images folder in the dist folder below.

dist-asssets

dist-asssets

In order to use them, we can simply use relative path from dist folder. Here we are adding a reference for stylesheet app-styles.css.

And here we are adding image to our application. We are using the class as-banner which we defined above.

As we ng serve the app, the image is displayed with the style applied correctly.

as-image

GitHub Repository

Screen Shot 2016-08-05 at 1.19.34 AM

Angular2- Environment Specific Configuration

Angular2- Environment Specific Configuration

Angular2 makes development and release workflows a lot easier than other javascript frameworks. One such ease is the ease of environment specific settings and configuration. In this post, we are going to see how we can keep environment specific configurations in an angular2 application developed using Angular CLI. We will be using the project we have been building so far. You can download all source code from GitHub.

In order to support environment configuration, Angular2 provides environment.ts file in the app folder. Here we can have all the configurations we want.

There are also environment specific configurations in config folder. Here we have two different files environment.dev.ts and environment.prod.ts for dev and prod environments respectively. In these configs, we can do environment specific overrides of our choice.

env config

env configs

Of course, we can still build the project using ng’s build command.

(default) ng b

(default) ng b

Building the project, generates the finalized environment.js file for a particular environment. By default, it uses dev environment.

environment.js

envionrment.js

In order to use prod’s environment configuration file, we can just use –environment=prod. Running the build with just [ng build –prod] should also have the same effect.

(prod) ng build

(prod) ng build

We can verify that correct config values are generated. The difference is that they get generated in main.js file instead of environment.js file.

mainjs for env=prod

mainjs for env=prod

Using Environment Configs

And we can definitely use it in our template file.

Just make sure that you run it again with ng serve -prod.