Author Archives: Muhammad

Play Framework and CORS with Angular2 Client(Cross Origin Resource Sharing)

Play Framework and CORS with Angular2 Client(Cross Origin Resource Sharing)

Although Play framework allows us to write complete web application including UI. But we can just keep our REST based HTTP service in Play Framework and access them from any other application hosted on another server. But as soon as you do it, you start getting complaints about CORS issues. For our safety, we are not allowed to request the service from a web request started on another web server. In this post, we are going to see how we can enable CORS support in our Play framework based service.

You might first download Activator. It makes it easier to start with scala application by doing the necessary scaffolding to get you started. Please download it from the following if you don’t already have it. I am sure you wouldn’t regret.

Activator Download

Activator Download

It is downloaded as a zip package. We can extract it into a folder:

Open Activator

Open Activator

Running it for the first time can bring any required dependencies to run it.

Activator running

Activator running

Let’s first create a Play framework service using Activator. Let’s name it as Echo Service. You guessed it right, it would just echo the data sent to it. It accepts data with a Message field (string). It responds with the contents of the field as part of its web response.

Activator new

Activator new

Debugging the Service

Let’s now add the debug configuration for play framework based service. Here we are selecting Play from debug configuration to be used for our service.

Add Play Debug Config

Add Play Debug Config

We are running it on port 9000. It is the default port.

Screen Shot 2017-04-22 at 11.46.19 AM

Add EchoController
Let’s first add EchoController. It just has an action. The action accepts single parameter of type string. It just returns the message back in the form of Ok response.

Now we can update routes so that play framework can route the requests to our controller. We have commented all routes and just added a route for echo action for EchoController.

Let’s now hit the service using PostMan. Here we are passing the message as part of the query parameter, as expected by the EchoController. As expected, we are getting the same message echoed by the service.

Angular2 Client

Now let’s create a client to use our Echo Service. Since this would be hosted on a separate host, we can create a scenario of Cross Origin request for the service and discuss how we can resolve the issue. Here we are creating an Angular2 client. We are naming the Client as EchoServiceClient, which is certainly very intuitive 🙂

Echo Service Client

Echo Service Client

Let’s start by adding EchoRequestService in services folder in app.component. The service just has a method which accepts a message as an argument. It sends an Http request to our Echo Service running on port 9000. Angular2’s Http module returns an Observable<Response>. Here we are just extracting the response’s text from and returning Observable<String> from the method. The class is decorated as Injectable so that we could inject it to app.component.

Let’s turn our attention to app.component.ts. Since we just need EchoRequestService in this component, we are adding it to the providers section in the component’s decorator. We are also injecting the service in the component’s constructor. The component has two properties inputMessage: String and echoedMessage: Observable;. It also has sendEchoRequest() method which just uses EchoRequestService and assigns the result to the echoedMessage.

Now we just need to update the template to use the properties from the component. We are binding the inputMessage property to a text box. This is a two way binding. We are also using echoedMessage property. We are using async filter since this is an Observable.

Since we already have the play framework service running, we can just ng serve the angular2 project. This runs as localhost:4200 by default. We enter some message to the text box and click the button. To our surprise, we get the following error based response from play service.

Cross Origin Request Not Allowed

Cross Origin Request Not Allowed

CORS Resolution

This is actually a common problem when we request another service from another web application hosted separately. Here we need to build some kind of relationship between the two applications. This requires play framework service to recognize our Angular application running as localhost:4200 as one of the allowed origins. But this requires a bit of plumbing.

First we need to add filters as dependencies to build.sbt. This changes the build.sbt as follows:

This would add necessarily dependencies to our service by adding the necessary library references. This includes availability of CORSFilter. We need to just update Filters to use this filter. Now the request pipeline would use CORSFilter as one of the filter before serving the resource as specified by the route.

But this is not enough. We still need to add localhost:4200 as one of the allowed origins. Actually CorsFilter configuration is already added to application.conf. It’s just commented out. We can just uncomment the following section and add localhost:4200. In case we need to allow all origins, we can just assign null to it.

Now we can run the service again. We notice that the play framework service now honors the request from Angular application running on localhost:4200 and echoes the response as expected.

Echo Success

Echo Success

Code

Create In-Memory file & Downloading Data in HTML5 / Javascript

Create In-Memory file & Downloading Data

In this post we are going to add ability to create an in-memory file and add ability to download it using a link and a button.

In-Memory

Here is an HTML file. Here we are adding a Link with download attribute set as Download2.csv. This would download the file as Download2.csv as user clicks the link. We have also added a button. Clicking the button would call ExportData() function, defined later.

<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Create In-Memory file & Downloading Data</h1>
    
    <a id="aDownloadCsv" download="Download2.csv">Download Link</a>
    
    <p/>
    
    <button onclick="ExportData()">Download Button</button>
    <script>
      AssignDataToLink();
    </script>
  </body>

</html>

We have also call AssignDataToLink(), which should assign the code to the anchor tag to download the file. We have also added a script file reference script.js in the scripts section of the above HTML file.

We have defined AssignDataToLink() in script.js. It creates the data as comma separated values. We are also adding the data to href of the anchor tag.

function AssignDataToLink() {
  	var csv = "Id,Value\n1,Muhammad\n";
		var data = new Blob([csv]);
		var downloadLink = document.getElementById("aDownloadCsv");
		
		downloadLink.href = URL.createObjectURL(data);
}

Additionally, we are defining ExportData() function in script.js. It also creates some comma separated data, creates a link and add it to the DOM. We just call the click() for the anchor tag.

function ExportData() {
  	var csv = "Id, Value\n1,Muhammad\n";
		var data = new Blob([csv]);
		var downloadLink = document.getElementById("aDownloadCsv2");
		
		if (downloadLink == null) {
		  downloadLink = document.createElement('a');
		  downloadLink.setAttribute('download', 'DownloadedFile.csv');
		  downloadLink.setAttribute('id', 'aDownloadCsv2');
		  
      document.body.appendChild(downloadLink);
		}
		
		downloadLink.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(data));
		downloadLink.href = URL.createObjectURL(data);
		
		downloadLink.style.display = 'none';
		downloadLink.click();
}

Code

Plunkr

ng-content with Angular2 (Transclusion) – AngularCli

ng-content with Angular2 (Transclusion) – AngularCli

In this post we are going to look at a special feature in Angular2. The feature allows to create templates such that parent components can inject parts into the view of the child component. The child components use the injected part using ng-content.

When should we use ng-content?

  • ng-content is specially useful when you have pre-built components which you want to use throughout your application.
  • This are also suitable when a component needs to inject some elements into the display area of another component.

Let’s create a sample application Angular2TransclusionApp using Angular CLI.

ng new Angular2TransclusionApp

Here is how it generates the necessary files for our project:

ng new Angular2TransclusionApp

ng new Angular2TransclusionApp

Now we add another component to the app. Let’s call it MyCardComponent.

ng generate component MyCardComponent

Let’s just update the template of the card component. We are just using the content and decorating it using our best artistic skills. We are turning the background to yellow. Additionally, we are adding a border to it and coloring it lightgreen. Isn’t it beautiful…

Let’s just use the card component in our app component. We are just adding a div to the card’s content. The div just has some text inside. And yes I am using my name as the component, because I can…

Let’s run it using ng serve. This is certainly an amazing display of my craft.

ng-content display

ng-content display

Transclusion Using Selectors

We can also use multiple ng-content (s) within the same component. Let’s create a new component.

ng generate component my-special-card

ng generate component my-special-card

The component template has multiple ng-content (s). We use select to pick the relevant content. This also supports CSS classes by using DOT (.) notation.

Here we are using the component in the main App component. You can see that we are using the names for two contents while the third component is specified using CSS class.

Let’s run this now.

My Special card

My Special card

Source Code

Source code on github

Source code on github

AngularCli – Passing Data In / Out of Angular2 Components

AngularCli – Passing Data In / Out of Angular2 Components

In this post how we can pass data in and out of an angular2 component. Here we are creating an app to increment the input number. We have a textbox to enter a number. We are also creating a component. The number entered in the textbox is supposed to be passed to the component. Clicking the component should increment the number and the data should be passed from the component to outside.

Let’s first create an angular2 app using Angular-Cli. Let’s name it Angular2PassingData.

ng new Angular2PassingData

Now let’s create a component incrementer.

ng generate component incrementer

The new component is a simple component with just a button. As the button is clicked, increment() method is called for the component.

AngularCli has also generated incrementer.component.ts. Since we are planning to pass data in and out, so let’s import Input and Output from @angular/core. We also need to import EventEmitter from the same package which is to be used for the Output.

We have decorated inputNum and @Input and incremented as @Output. The inputNum has number type. The incremented is an EventEmitter to be used to emit output data through events.

In app.component, we have a textbox to enter a number. We are binding incrementInputNum property from component’s code behind to the textbox. We are binding another property incrementInputNum to incrementer.component’s inputNum property. Additionally, the incremented event from incrementer.component would trigger increment method to be called with event’s data. We also see another property being used here, which is incrementedNum, which is just displayed in a label. It would show the incremented number in the user interface.

As we have seen above, we are expecting two number based properties in app.component’s code behind. They are incrementInputNum and incrementedNum. In the incrementNum() method, we are just assigning the data from the event to incrementedNum property.

Now let’s run the application using ng serve. The app runs on localhost:4200 by default. As we enter a number and click Increment button, the data is passed to the incrementer component. It is incremented there and an event is emitted. The app.component is subscribing to that event and updates its own variable, which is then shown on the UI.

Incrementer App

Incrementer App

Assigning event data in template

Now let’s try to make it a little simpler. We are simply assigning the event’s data to one of the property in app.component’s code behind (other than writing to the console). Angular2 can make it a little easier for us. We can make it simpler by directly assigning the event’s data the property. Here we are updating incrementedNum to the data emitted by the component’s incremented event.

Repository

Github repo

Github repo

Angular2 – Using 3rd Party Libraries

Angular2 – Using 3rd Party Libraries:

We always need third party libraries to build any application. The same is true for applications built using Angular2. In this post, we are going to discuss how we can use 3rd party libraries in an Angular2 app. We have discussed adding these libraries to an Angular2 app with RC version. There are a few changes so it’s better that we discuss a complete new example.

Let’s use NumeralJs. The library is used to format numbers in javascript. Here we will be using the library to format an arbitrary number.

Installing Package

npm install --save numeral

npm install numeral

npm install numeral

Installing type definitions
There is also a @typedefinition package available for NumeralJs. This would allow it to be used in our typescript code without any editor squigglies.

npm install --save @types/numeral

numerals type definition

numerals type definition

Let’s first import the numeral into our component:

import * as numeral from 'numeral';

Now we can use the numeral library. Here we are formatting numbers using numeral library.

result = numeral(10000).format('0,0');

Here is the definition of component-one.component.ts

And let’s add it to the component’s HTML.

Now let’s run it using ng serve again. Here is how our ComponentOne looks like now:

app works formatted

app works formatted

Of course, I have highlighted the formatted result.

Using CSS Styles and JS Scripts from Libraries

Now try using a package which is a little more complex than numeralJs. Here we are using Angular2 Bootstrap (ng2-bootstrap). In order to use bootstrap, we need to use CSS styles and javascript code files. Let's first install ng2-bootstrap, which allows bootstrap to be used in Angular2 typescript code.

npm install –save ng2-bootstrap

Here we are running the above command:

ng2 bootstrap install

ng2 bootstrap install

We also need to install bootstrap package.

npm install --save bootstrap

bootstrap install

bootstrap install

We need to use styles and js files from the installed bootstrap packages. Let’s add the following css file to styles section of angular-cli.json.

"styles": [
  "styles.css",
  "../node_modules/bootstrap/dist/css/bootstrap.min.css"
]

We also need to add java script file to the scripts section.

"scripts": [
   "../node_modules/bootstrap/dist/js/bootstrap.min.js"
],

And the whole angular-cli.json file is as follows:

app.module.ts

Now we need to import ng2-bootstrap module. Let’s add it to app module (app.module.ts)

import { TabsModule } from 'ng2-bootstrap';

We need to add TabsModule now to the imports section of AppModule.

imports: [
  BrowserModule,
  FormsModule,
  HttpModule,
  RouterModule.forRoot(appRoutes),
  TabsModule.forRoot()
],

Now the app.module.ts has been updated as follows:

component-two.component.html

Now let’s add the tab to our component’s HTML. Here we are adding it to component-two.component.html

Now let’s run it. The tabs look as follows:

app works tabs

app works tabs

Angular2 Routes

Angular2 Routes:

In this post we are going to use how to use routes with Angular2 for your components. We are going to create two components and add routes for those components. Let’s first install angular-cli.

Install angular cli

Install angular cli

Let’s create a new project HelloWorld.

create project

create project

The command creates the following files:

files created

files created

The main folder structure looks like this:

main folder structure

main folder structure

The src folder looks like the following:

src folder structure

src folder structure

Let’s run the project using ng serve command:

ng serve

ng serve

And open the browser with http://localhost:4200

app works

app works

Adding Components

Let’s add components to our applications. Here we are adding two components ComponentOne and ComponentTwo.

>ng generate component ComponentOne
>ng generate component ComponentTwo


ng generate component

ng generate component

app.module.ts

Now we need to RouterModule from @angular/router. The good thing is angular-cli already adds the router when we created the project. First we need to import the RouterModule.

import { RouterModule, Routes } from '@angular/router';

Now let’s import the two components we created above i.e. ComponentOne and ComponentTwo.

import { ComponentOneComponent } from './component-one/component-one.component';
import { ComponentTwoComponent } from './component-two/component-two.component';

Now let’s add the routes to our components.

const appRoutes : Routes = [
  { path: "componentOne", component: ComponentOneComponent},
  { path: "componentTwo", component: ComponentTwoComponent}
]

We can add the routes to the RouterModule imported above. We also need to add the imported components to declarations section to the module. Please also notice that we are adding the routes to the imports section RouterModule.forRoot(appRoutes).

@NgModule({
  declarations: [
    AppComponent,
    ComponentOneComponent,
    ComponentTwoComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})

Let’s update the app.module.ts as follows:

app.component.html

Now we just need add where we need to decide where we need to display the components. We just need to add to app.component.html.

Running the project

Now we can run the project and see the routes in action. Let’ run it using ng serve. The main url displays the app component - http://localhost:4200/

app works main

app works main

The ComponentOne route can be used as http://localhost:4200/componentOne. Just see the contents of the components are displayed in the section where we added .

app works component one

app works component one

Here we have ComponentTwo with the url: http://localhost:4200/componentTwo

app works component two

app works component two

Swagger.ed for graphical visualization of APIs

Swagger.ed for graphical visualization of APIs
Swagger.ed is a chrome extension available for graphical display for our APIs exposed using swagger specification. The extension is directly available in Chrome Web Store. The package is offered by Chris Spiliotopoulos.

swagger.ed chrome extension

swagger.ed chrome extension

If the extension is successfully installed, it displays these message. Plus an icon is available in toolbar to show an API visualization if browser has a swagger description already loaded.

Screen Shot 2016-09-06 at 12.42.37 AM

Let’s use this extension to view graphical display of our Student API created in the last post [http://www.alternatestack.com/development/app-development/swagger/]. As we load the API in chrome, the extension’s toolbar button becomes enabled (turns green).

swagger.ed-enabled

swagger.ed-enabled

As we click the toolbar button, the following view is displayed:

swagger.ed

swagger.ed

This displays the list of API controllers available in the swagger specification. It also gives details about Model classes available through the APIs. Here we have StudentsController and ValuesController, so we see two services being available. Additionally, we are exposing two model classes Student and Exception. The view also supports panning. Clicking a node displays the details about the item. Here we have selected Student model class. Here is the description of Student type.

Student Model type

Student Model type

Here is the view when we selected Student service.

Student Service

Student Service

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