Saturday, November 12, 2016

Consuming a RESful API with Angular 2 using angular-cli

Angular-cli is a command line interface used to scaffold and build angular2 apps using nodejs style (commonJs) modules. In this tutorial I will build a simple Angular 2 application that consumes a posts RESful API service located at https://jsonplaceholder.typicode.com/posts. This API service belongs to a handful APIs that are available for developers and testers at https://jsonplaceholder.typicode.com/.

Here’s a sample of what you will see if you point your browser to https://jsonplaceholder.typicode.com/posts:

image

The Post object looks like this:
{
  "userId": "number",
  "id": "number",
  "title": "string",
  "body": "string"
}
To continue with this tutorial, you will need to install node.js on your computer, If you do not already have it installed then download and install it from https://nodejs.org.

Once you have installed node.js, then go to a command prompt (or terminal window) and run the following command to globally install angular-cli:

npm install -g angular-cli

This may take some time so be patient. Although you can ignore warnings, if you get any red error messages then try the following:
  • run your command prompt in admin mode. If you are using linux or mac then use sudo
  • otherwise, try to upgrade to the latest version of node.js on tour computer.
Upon successful installation of angular-cli, you can now go ahead an scaffold an angular2 app that serves as a suitable starting point. Go to a convenient working directory and execute the following command to create an app named ng2-posts:

ng new ng2-posts

This also takes some time so patience is a good asset. Once the scaffolding process is complete, let’s see what it looks like. Change into the newly created ng2-posts directory:

cd ng2-posts

To build the application, run the following command:

ng build

To host the web application under a light-weight web server listening on port 4200, run the following command:
ng serve

Note: The ng serve command also builds the application so the ng build step is rather optional.

You can now view the web page in your browser by going to http://localhost:4200. This is what you will see:

image

Let us have a look at all the files that were generated. Load the contents of the ng2-posts folder into Visual Studio Code, which can be downloaded from http://code.visualstudio.com/. This is what the source code looks like:

image

Tip: You can load the application in Visual Studio Code by simply running the command “code .” from inside the main application directory within a terminal window.

Since we will need a Post class to represent our object, we can use angular-cli to create it for us. Type in the following command in a terminal window while in the main ng2-posts folder:

ng generate class Post

This results in the creation of a TypeScript file src\app\post.ts that has the following content:
export class Post {
}
Replace the content of post.ts with the following code:
export class Post {
  userId: number;
  id: number;
  title: string;
  body: string;
  constructor(obj?: any) {
    this.userId = obj && obj.userId || null;
    this.id = obj && obj.id || null;
    this.title = obj && obj.title || null;
    this.body = obj && obj.body || null;
  }
}
Next, we need to create a service that is responsible for all http requests to the RESTful API. Type in the following command in a terminal window while in the main ng2-posts folder:

ng generate service Post

This results in the creation of two TypeScript files:  src\app\post.service.spec.ts & src\app\post.service.ts.

Note:
  • The convention for naming a service is {service name}.service.ts. This is also applied to naming components as {component name}.component.ts.
  • The post.service.spec.ts is the unit test file.
The generated post.service.ts file looks like this:
import { Injectable } from '@angular/core';
@Injectable()
export class PostService {

  constructor() { }
}
Replace the contents of post.service.ts with the following:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class PostService {

  constructor(private http: Http) { }
  getAll() {
    return this.http.get('
https://jsonplaceholder.typicode.com/posts')
    .map((res: Response) => res.json());
  }
}
The above class is annotated with @Injectable() so that it can be used in dependency injection. In order for this to be possible, we will need to make it a provider at a higher level component. In this case, we will add it as a provider in the app.component.ts class. Edit app.component.ts and add the following import command in line 2:

import { PostService } from "./post.service";

Add the following to the @Component block:

providers: [PostService]

The AppComponent class then looks like this:
import { Component } from '@angular/core';
import { PostService } from "./post.service"

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [PostService]
})
export class AppComponent {
  title = 'app works!';
}
The next step is to create a Post component that actually uses the service that we created and displays some data in HTML. Create a PostComponent class by running the following command in a terminal window while in the main ng2-posts folder:

ng generate component Post

This results in the creation the following files:
src\app\post\post.component.css
src\app\post\post.component.html
src\app\post\post.component.spec.ts
src\app\post\post.component.ts
Note the following:
  • The component files follow the convention mentioned previously and are placed in a dedicated folder named post.
  • The third file (post.component.spec.ts) is for unit testing purposes.
Open the post.component.html and view its contents:
<p>
  post works!
</p>
Also, look at the contents of post.component.ts:
import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-post',
  templateUrl: './post.component.html',
  styleUrls: ['./post.component.css']
})
export class PostComponent implements OnInit {
  constructor() { }

  ngOnInit() { }
}
The above suggests that if we place the tag <app-post></app-post> in a consuming component class, then it will display “Post works!”. Let us test this out. Open app.component.ts in your editor and add the following import statement in line 3:

import { PostComponent } from "./post/post.component";

The app.component.ts would then look like this:
import { Component } from '@angular/core';
import { PostService } from "./post.service";
import { PostComponent } from "./post/post.component";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [PostService]
})
export class AppComponent {
  title = 'app works!';
}
Now let us add the <app-post></app-post> markup inside app.component.html so it looks like this:
<h1>
  {{title}}
</h1>
<app-post></app-post>
Have a peek at the web page. It should look like this:

image

What we just proved is that a custom component can be easily used by another component. Let us now enhance PostComponent so that it displays posts with real remote data coming from a RESTful service. Open post.component.ts in your editor and replace its contents with the following code:
import { Component, OnInit } from '@angular/core';
import {Post} from '../post';
import {PostService} from '../post.service';

@Component({
  selector: 'app-post',
  templateUrl: './post.component.html',
  styleUrls: ['./post.component.css']
})
export class PostComponent implements OnInit {
  results: Array<Post>;

  constructor(private postService: PostService) { }
  ngOnInit() {
    this.postService.getAll().subscribe(
      data => { this.results = data; },
      error => console.log(error)
    );
  }
}
Note the following about the above code:
  • Both Post class and PostService must first get imported.
  • PostService is being injected into the constructor making its instance available to the rest of the class. This is possible because of dependency injection and the fact that we previously added it as a provider inside app.component.ts.
  • The ngOnInit() method runs after the class is initialized. It calls the service’s getAll() method and hydrates the results array of Post objects with actual data coming from the RESTful API service.
The last step is to render data into our HTML view. Open post.component.html and replace its content with the following:
<table *ngIf="results" border="1">
  <thead>
    <tr>
      <th>User ID</th>
      <th>ID</th>
      <th>Title</th>
      <th>Body</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let p of results; let i=index">
      <td>{{p.userId}}</td>
      <td>{{p.id}}</td>
      <td>{{p.title}}</td>
      <td>{{p.body}}</td>
    </tr>
  </tbody>
</table>
The hour of truth is at hand. View the web page in your browser. It should resemble this:

image

This should be a great starting point for you to appreciate Angular 2 and do more interesting things with it.

References:

https://dzone.com/articles/getting-started-and-testing-with-angular-cli-and-angular-2-rc5-part-1
https://www.sitepoint.com/angular-2-tutorial/
http://www.mithunvp.com/build-angular-apps-using-angular-2-cli/

Saturday, November 5, 2016

Xamarin Forms Client for Azure ASP.NET Web API service

Xamarin Forms allows for the development of mobile apps using C# with a single code base for deployment to Android, iOS, and Windows.

It is advisable that you watch this video on Channel 9 in order to properly setup your Visual Studio 2015 environment for Xamarin development:

https://channel9.msdn.com/series/tendulkar-uvca/0102-Verify-Machine-Setup

Overview

The objective of this tutorial is to consume a Web API service. In this tutorial, we will use a service at http://cartoonapi.azurewebsites.net/api/cartoon. If you point your browser to this address, the JSON response will look like this:

[{"name":"Aladdin","pictureUrl":"images/aladdin.png"},
{"name":"Bambam Rubble","pictureUrl":"images/bambam_rubble.png"},
{"name":"Bambi","pictureUrl":"images/bambi.png"},
{"name":"Barney Rubble","pictureUrl":"images/barney_rubble.png"},
{"name":"Betty Flintstone","pictureUrl":"images/betty_flintstone.png"},
{"name":"Dino","pictureUrl":"images/dino.png"},
{"name":"Donald Duck","pictureUrl":"images/donald_duck.png"},
{"name":"Flintstone Family","pictureUrl":"images/flintstone_family.png"},
{"name":"Flounder","pictureUrl":"images/Flounder.png"},
{"name":"Fred Flinrstone","pictureUrl":"images/fred_flinrstone.png"},
{"name":"Goofy","pictureUrl":"images/Goofy.png"},
{"name":"Jasmine","pictureUrl":"images/jasmine.png"},
{"name":"Jumbo","pictureUrl":"images/jumbo.png"},
{"name":"Mermaid","pictureUrl":"images/mermaid.png"},
{"name":"Micky Mouse","pictureUrl":"images/micky_mouse.png"},
{"name":"Minnie Mouse","pictureUrl":"images/minnie_mouse.png"},
{"name":"Pebbles Flintstone","pictureUrl":"images/pebbles_flintstone.png"},
{"name":"Peter Pan","pictureUrl":"images/peter_pan.png"},
{"name":"Pinocchio","pictureUrl":"images/pinocchio.png"},
{"name":"Pluto","pictureUrl":"images/pluto.png"},
{"name":"Simba","pictureUrl":"images/simba.png"},
{"name":"Snow White","pictureUrl":"images/snow_white.png"},
{"name":"Tigger","pictureUrl":"images/tigger.png"},
{"name":"Tinkerbell","pictureUrl":"images/tinkerbell.png"},
{"name":"Tweety","pictureUrl":"images/tweety.png"},
{"name":"Wilma Flintstone","pictureUrl":"images/wilma_flintstone.png"},
{"name":"Winnie The Pooh","pictureUrl":"images/winnie_the_pooh.png"}]


The above JSON collection pertains to cartoon characters with only two properties: Name & PictureUrl.

Creating a Xamarin Forms portable application

Start Visual Studio 2015 then click on:

File >> New >> Project
Templates >> Visual C# >> Cross-Platform >> Blank Xaml App (Xamarin.Forms Portable)

image

Name the application “ComicMobile” then click on OK.

On the “New Universal Windows Project” dialog, choose Build 10586 for both Target and Minimum versions.

image

Be patient, it may take some time to create these six projects:

ComicMobile This is a shared solution
ComicMobile.Droid Android project
ComicMobile.iOS iOS project
ComicMobile.UWP UWP project
ComicMobile.Windows Windows 8.1 project
ComicMobile.WinPhone Windows Phone 8.1 project

Go ahead and remove the last two projects (ComicMobile.Windows & ComicMobile.WinPhone) from the Visual Studio solution in order to keep our project as small as possible. Also, delete the relevant folders for the two projects that you removed from the file system.

Open the configuration manager by selecting Build >> Configuration Manager…

image

Enable Build & Deploy for the UWP project then click on Close.

Right-click on the UWP project and select Build.

Then, right-click again on the UWP application and select “Set as StartUp Project”.

Hit F5 on the keyboard to run the UWP application in debug mode on the “Local Machine”. The application will run and the main window will look like this:

image

Adding a Web API client

Close the running application, then install the following two Nuget package to the “ComicMobile (Portable)” project:

Newtonsoft.Json
Microsoft.Net.Http

Add folders Models and ViewModels to the top “ComicMobile (Portable)” project.

Add a class named CartoonCharacter to the Models folder. In order to put  remote data into a C# collection, replace the CartoonCharacter class definition in the Models folder with the following code:

public class CartoonCharacter {
  public string Name { get; set; }
  public string PictureUrl { get; set; }
}


The code for actually connecting to the remote service and reading data will be placed in a View Model class. Add a class named CartoonViewModel to the ViewModels folder and replace the class definition with the following code:

public class CartoonViewModel : INotifyPropertyChanged {
  const string BASE_URL = "
http://cartoonapi.azurewebsites.net/";
  public event PropertyChangedEventHandler PropertyChanged;
  public Command GetCartoonCharactersCommand { get; set; }

  public ObservableCollection<CartoonCharacter> CartoonCharacters { get; set; }
  public CartoonViewModel() {
      CartoonCharacters = new ObservableCollection<CartoonCharacter>();

      GetCartoonCharactersCommand = new Command(
        async () => await GetCartoonCharacters(),
        () => !IsBusy);
  }

  private void OnPropertyChanged([CallerMemberName] string name = null) =>
      PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

  private bool busy;
  public bool IsBusy {
    get { return busy; }
    set {
      busy = value;
      OnPropertyChanged();
      //Update the can execute
      GetCartoonCharactersCommand.ChangeCanExecute();
    }
  }

  private async Task GetCartoonCharacters() {
    if (IsBusy)
        return;

    Exception error = null;
    try {
      IsBusy = true;

      using (var client = new HttpClient()) {
        //grab json from server
        var json = await client.GetStringAsync(BASE_URL + "api/cartoon");

        //Deserialize json
        var items = JsonConvert.DeserializeObject<List<CartoonCharacter>>(json);

        //Load speakers into list
        CartoonCharacters.Clear();
        foreach (var item in items) {
          CartoonCharacters.Add(new CartoonCharacter() {
            Name = item.Name,
            PictureUrl = BASE_URL + item.PictureUrl
          });
        }
      }
    } catch (Exception ex) {
      Debug.WriteLine("Error: " + ex);
      error = ex;
    } finally {
      IsBusy = false;
    }

    if (error != null)
      await Application.Current.MainPage.DisplayAlert("Error!", error.Message, "OK");
  }
}


Resolve any missing namespaces then compile your application to make sure you do not have any errors.

Adding UI to our application

We will need to add some UI to our portable project as follows:
  • Open MainPage.xaml and delete the <Label …> tag.
  • Put the following XAML markup between the opening and closing <ContentPage …> tags:
<StackLayout Spacing="0" Padding="20,20,0,0">
  <Button Text="Get Cartoon Characters"
    Style="{StaticResource buttonStyle}"
    Command="{Binding GetCartoonCharactersCommand}"/>
  <ActivityIndicator IsRunning="{Binding IsBusy}" IsVisible="{Binding IsBusy}"/>
  <ListView x:Name="ListViewCartoonCharacters"
       ItemsSource="{Binding CartoonCharacters}">
    <ListView.ItemTemplate>
      <DataTemplate>
        <TextCell Text="{Binding Name}"/>
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>
</StackLayout>


The above XAML markup just adds a button and a list. When the button is clicked, our application will retrieve data from a remote Web API service, then it will populate the list.
The button is bound to a method called GetCartoonCharactersCommand, which is already defined in our CartoonViewModel class.
  • Our UI uses a button style named buttonStyle. Add the following markup to App.xaml between the opening and closing <Application.Resources> tags:
<ResourceDictionary>
  <Style x:Key="buttonStyle" TargetType="Button">
    <Setter Property="HorizontalOptions" Value="Center" />
    <Setter Property="VerticalOptions" Value="CenterAndExpand" />
    <Setter Property="BorderColor" Value="Black" />
    <Setter Property="BorderRadius" Value="3" />
    <Setter Property="BorderWidth" Value="3" />
    <Setter Property="WidthRequest" Value="200" />
    <Setter Property="TextColor" Value="Black" />
    <Setter Property="BackgroundColor" Value="Silver" />
  </Style>
</ResourceDictionary>

  • To bind our MainPage.xaml UI to the CartoonViewModel , add the following code to bottom of the MainPage() constructor in MainPage.xaml.cs, right under InitializeComponent();
//Create the view model and set as binding context
CartoonViewModel vm = new CartoonViewModel();
BindingContext = vm;

  • Let’s test out the application. Build and run it. You should see a window that looks like this:
image
  • Click on the “Get Cartoon Characters” button. It will retrieve the names of cartoon characters on the server:
image

Adding a details page

To enhance our application, we will build the feature so that when a user click on a particular cartoon character, it displays an image of that character in a separate page. It addition, it will allow the user to go to a webpage that displays the image.
  • We need to add an event handled in MainPage.xaml.cs that handles the item selection process. Add the following code to the bottom of the MagePage() constructor in MainPage.xaml.cs:
ListViewCartoonCharacters.ItemSelected += ListViewCartoonCharacters_ItemSelected;
  • Next, add the code for handling the event by adding this method to the MainPage class in MainPage.xaml.cs:
private async void ListViewCartoonCharacters_ItemSelected(object sender, SelectedItemChangedEventArgs e) {
  var character = e.SelectedItem as CartoonCharacter;
  if (character == null)
      return;

  await Navigation.PushModalAsync(new DetailsPage(character));
  ListViewCartoonCharacters.SelectedItem = null;
}


Note that an object is being passed in the constructor of a page DetailsPage, which we are about to create.
  • To the ComicMobile project, add a “Forms Xaml Page” and name it DetailsPage.xaml.
image
  • In DetialsPage.xaml, replace the <Label …> tag with the following XAML markup:
<ScrollView Padding="10">
  <StackLayout Spacing="10" >
    <!-- Detail controls here -->
    <Image Source="{Binding PictureUrl}" HeightRequest="200" WidthRequest="200"/>

    <Label Text="{Binding Name}" FontSize="24" HorizontalTextAlignment="Center"/>
    <Button Text="Show image on Website" x:Name="ButtonWebsite" Style="{StaticResource buttonStyle}"/>
  </StackLayout>
</ScrollView>

  • Add the following instance variable to the DetailsPage class in DetailsPage.xaml.cs:
CartoonCharacter _cartoonCharacter;
  • Replace the DetailsPage() constructor with the following code that takes a CartoonCharacter as an argument:
public DetailsPage(CartoonCharacter cartoonCharacter) {
  InitializeComponent();

  //Set local instance of speaker and set BindingContext
  this._cartoonCharacter = cartoonCharacter;
  BindingContext = this._cartoonCharacter;

  ButtonWebsite.Clicked += ButtonWebsite_Clicked;
}

  • Add the following event handler method to the DetailsPage class to handle the button click for viewing a webpage:
private void ButtonWebsite_Clicked(object sender, EventArgs e) {
  if (_cartoonCharacter.PictureUrl.StartsWith("http"))
    Device.OpenUri(new Uri(_cartoonCharacter.PictureUrl));
}

  • Build and run your application.
image
  • Click on the “Get Cartoon Characters” button.
image
  • Click on a name like “Donald Duck”.
image
  • Click on the “Show image on Website” button. It will open a web page in your browser that just displays the image:
image

Android

Try running this same application in the Visualk Studio 2015 Android emulator by making the Android project (ComicMobile.Droid) your startup application.

image
image
image

a single code base, we were able to develop an app that runs on Android, iOS, and Windows. This is the power of Xamarin Forms.

Consuming a Swagger service in Visual Studio 2015

In a previous post I discuss how to add Swagger to an ASP.NET Core 1.0 application. In this post I will show you how to use it.

We will build a simple C# command-line console application to consume a Swagger service at http://cartoonapi.azurewebsites.net/api/cartoon. This service displays a list of cartoon characters and a link of their images. Point your browser to the above address and you will see this output:

[{"name":"Aladdin","pictureUrl":"images/aladdin.png"},
{"name":"Bambam Rubble","pictureUrl":"images/bambam_rubble.png"},
{"name":"Bambi","pictureUrl":"images/bambi.png"},
{"name":"Barney Rubble","pictureUrl":"images/barney_rubble.png"},
{"name":"Betty Flintstone","pictureUrl":"images/betty_flintstone.png"},
{"name":"Dino","pictureUrl":"images/dino.png"},
{"name":"Donald Duck","pictureUrl":"images/donald_duck.png"},
{"name":"Flintstone Family","pictureUrl":"images/flintstone_family.png"},
{"name":"Flounder","pictureUrl":"images/Flounder.png"},
{"name":"Fred Flintstone","pictureUrl":"images/fred_flinrstone.png"},
{"name":"Goofy","pictureUrl":"images/Goofy.png"},
{"name":"Jasmine","pictureUrl":"images/jasmine.png"},
{"name":"Jumbo","pictureUrl":"images/jumbo.png"},
{"name":"Mermaid","pictureUrl":"images/mermaid.png"},
{"name":"Micky Mouse","pictureUrl":"images/micky_mouse.png"},
{"name":"Minnie Mouse","pictureUrl":"images/minnie_mouse.png"},
{"name":"Pebbles Flintstone","pictureUrl":"images/pebbles_flintstone.png"},
{"name":"Peter Pan","pictureUrl":"images/peter_pan.png"},
{"name":"Pinocchio","pictureUrl":"images/pinocchio.png"},
{"name":"Pluto","pictureUrl":"images/pluto.png"},
{"name":"Simba","pictureUrl":"images/simba.png"},
{"name":"Snow White","pictureUrl":"images/snow_white.png"},
{"name":"Tigger","pictureUrl":"images/tigger.png"},
{"name":"Tinkerbell","pictureUrl":"images/tinkerbell.png"},
{"name":"Tweety","pictureUrl":"images/tweety.png"},
{"name":"Wilma Flintstone","pictureUrl":"images/wilma_flintstone.png"},
{"name":"Winnie The Pooh","pictureUrl":"images/winnie_the_pooh.png"}]


Note that there are two properties in the above object representing a cartoon character – name & pictureUrl.
The Swagger documentation is located at http://cartoonapi.azurewebsites.net/swagger/ui/. This URL displays the following page:

image

The swagger.json file contains the description of the serice and will be used later to create a C# client.

Creating a blank C# Console App

Let us start by creating our console application.
  • Start Visual Studio 2015
  • File >> New >> Project
  • Templates >> Visual C# >> Windows >> Console Application
  • Name the application MySwaggerClient

Adding Swagger client code to our console app

Point your browser to the address of your Swagger service. If you wish to go along with this example, access this page in your browser:

http://cartoonapi.azurewebsites.net/swagger/v1/swagger.json.

Copy all the contents of the JSON object on the page into the clipboard by hitting CTRL + A followed by CTRL + C on your keyboard.

Back in Visual Studio 2015, add a text file to your project and name it swagger.json. Paste the contents of your clipboard into swagger.json then save the file. You will notice that Visual Studio formats this file properly and it is possible to make sense of the content. Close inspection of the file reveals that this JSON file is a description of the remote service and it is intended for use by IDEs and code generators. We will next have Visual Studio 2015 interpret this description file and subsequently generate C# client code for us.

Right-click on the project node >> Add >> REST API Client…

image

image

Click on the second “Select an existing metadata file” radio button, then browse to the swagger.json file and select it. Click on OK when you are done.

Visual Studio 2015 will then generate client code for your project. You should see additional C# files added to your project as shown below:

image

Note two model classes: CartoonCharacter.cs and CartoonCharacterCollection.cs. These represent the model classes on the server.

Build your app to make sure that you do not have any errors.

Using the Swagger client code in our application

Since we will be making a remote call, it is best that we access the service asynchronously. Therefore we will use all the asynchronous versions of the calling methods.

Add the following async method to Program.cs:

static async Task<IEnumerable<CartoonCharacter>> GetAsync() {
  string baseUrl = "
http://cartoonapi.azurewebsites.net/";
  using (var client = new Auth0SwaggerSampleAPI(new Uri(baseUrl))) {
    var results = await client.ApiCartoonGetAsync();
    IEnumerable<CartoonCharacter> comic = results.Select(m => new CartoonCharacter
    {
      Name = m.Name,
      PictureUrl = m.PictureUrl
    });
    return comic;
  }
}


We first assign the base URL of our remote service to a variable named baseUrl. We then instantiate an instance of Auth0SwaggerSampleAPI. This is essentially the name of the class that Visual Studio created for us and represents the remote service. The instance of the Auth0SwaggerSampleAPI class is represented by the client object. With the client object we can call a method ApiCartoonGetAsync(), which returns all items into a variable results. Using a LINQ Lambda Expression, we can then populate a list of CartoonCharacter objects. We then return the list.

Add another async method that displays the contents of the collection to a terminal window:

static async Task RunAsync() {
  IEnumerable<CartoonCharacter> comic = await GetAsync();

  foreach (var item in comic) {
    Console.WriteLine("{0}, {1}",item.Name, item.PictureUrl);
  }
}


Lastly, we will add a method call to RunAsync() from within the Main() method that runs asynchronously. Add the following to the Main() method.

RunAsync().Wait();

If you now build and run your console application, you should see the following output:

Barney Rubble, images/barney_rubble.png
Betty Flintstone, images/betty_flintstone.png
Dino, images/dino.png
Donald Duck, images/donald_duck.png
Flintstone Family, images/flintstone_family.png
Flounder, images/Flounder.png
Fred Flinrstone, images/fred_flinrstone.png
Goofy, images/Goofy.png
Jasmine, images/jasmine.png
Jumbo, images/jumbo.png
Mermaid, images/mermaid.png
Micky Mouse, images/micky_mouse.png
Minnie Mouse, images/minnie_mouse.png
Pebbles Flintstone, images/pebbles_flintstone.png
Peter Pan, images/peter_pan.png
Pinocchio, images/pinocchio.png
Pluto, images/pluto.png
Simba, images/simba.png
Snow White, images/snow_white.png
Tigger, images/tigger.png
Tinkerbell, images/tinkerbell.png
Tweety, images/tweety.png
Wilma Flintstone, images/wilma_flintstone.png
Winnie The Pooh, images/winnie_the_pooh.png


Lesson leaned – Visual Studio 2015 offers a very easy way to consume a Swagger service that can be used in a variety of your applications.


Reference:

https://azure.microsoft.com/en-us/documentation/articles/app-service-api-dotnet-get-started/

Wednesday, November 2, 2016

Adding Swagger to ASP.NET Core 1.0 Web API app

Swagger is an API specification framework. It reminds me of WSDL in the SOAP days. In this article I will guide you in add Swagger documentation to an ASP.NET Core Web API app.

There are two components that we need to buckle-up in our Web API application. These are, not surprisingly, called Swashbuckle:
  1. Swashbuckle.SwaggerGen : provides functionality to generate JSON Swagger documents that describe the objects, methods, return types, etc.
  2. Swashbuckle.SwaggerUI : embedded version of Swagger UI tool which uses the above documents for a rich customizable experience for describing the Web API functionality and includes built in test harness capabilities for the public methods.
For starters, add the following package to your project.json:

"Swashbuckle": "6.0.0-beta902"

Next, add the SWaggerGen library to your middle-ware by adding the following line of code to the bottom of the ConfigureServices() method in Startup.cs:

services.AddSwaggerGen();

Also, add the following two lines of code to the bottom of the Cofigure() method in Startup.cs:

// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger();

// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUi();


Point your browser to http://localhost:{port number}/swagger/v1/swagger.json and you will see a JSON document that describes the endpoints of your service.

image

You can also see the Swagger UI at URL http://localhost{port number}/swagger/ui.

image

In the above example the API service is Studentapi. Your service will be under API V1. Click on it and you will see something similar to the following:

image

To test out GET, click on the first blue GET button and the section will expand describing to you the structure of your object:

image

Click on the “Try it out!” button to view the data coming back from the service for all items in the collection:

image

Click on the first blue GET button again to collapse the section. Now, click on the second blue GET button to test retrieval of an item by id.

image

Enter a value for ‘id’ then click the “Try it out!” button. It should get for you the item for that id.

image

In a similar manner, go ahead and test out all the other POST, DELETE, and PUT buttons.

The official Swagger website at http://swagger.io/. You can generate a Swagger client for most programming languages at http://editor.swagger.io/.

Monday, October 24, 2016

Configuring your Azure website to use a custom domain

Whenever you create an Azure website you are given a default domain azurewebsites.net to work with. If, for example, your website is named supersite then the fully qualified address for your site would be http://supersite.azurewebsites.net.

Suppose you wish to link your own custom domain to your azure website. As an example, let us assume that we wish to use a custom name like http://code.zift.ca instead of the default name of http://supersite.azurewebsites.net. This tutorial takes you through some very simple and short steps to achieve this.

Before we proceed, it is assumed that you have the following:
  • You must have a domain name that you already own.
  • You have an Azure subscription
1) Go to the Azure portal at http://portal.azure.com and login.

2) Click on your web application in Azure. In the example below, my azure website is named CodeFirstStuff2.

image

3) In the second blade, find and click on “Custom domains”.

image

If, in the third blade, you see a message “Click here to upgrade your App Service to assign custom hostnames to your app.”, then it means that you need to upgrade from the free tier to one that supports custom domains. Click on the above message and you will be reminded that your pricing tier is “F1 Free”, which does not support custom domains. The next tier up is pricing tier “D1 Shared”, which does support custom domains. It, however, costs $11.76 per month (at the time of writing). If you are OK with this additional cost then click on pricing tier “D1 Shared”, then click on the Select button.

image

4) If the third blade looks like below, then you are indeed able to create a custom domains for your Azure website:

image

Note the name at the bottom of the above blade. In this demo it is codefirststuff2.azurewebsites.net. You will need this address in the next important step where you will configure a CNAME DNS record to point to your {your web app name}.azurewebsites.net.

5) This next step involves your domain name registrar. Examples of some domain registrars are: godaddy.com, namecheap.com, fatcow.com, hostgator.com, etc …

Go to your domain registrar and add a CNAME host record that points to the hostname assigned to your Azure site. This is what my CNAME record looked like with my Canadian registrar, where I configured domain name zift.ca to use a host name code:

image

If you are unsure about how to configure the CNAME DNS record, then contact your domain registrar’s support desk and they will be happy to help you.
To prove that your DNS name change has indeed propagated, you can always use a website named https://www.whatsmydns.net/. Here’s what it looked like for me:

image

You can see from the above evidence that the CNAME DNS record change that was made has propagated across our planet (except for Paris, France). Now we can configure Azure with the new host name.

6) Return to Azure’s portal.

image

Click on “+ Add hostname”.

The following will appear in the fourth blade:

image

7) Enter the fully qualified custom address into the Hostname field (example: code.zift.ca), then click on the Validate button.

image

If you get two OKs at the bottom then you are good to go.

image

Click on the “Add hostname” to save your changes.

The real test comes by trying out your custom domain. Point your browser to your custom domain (Example: http://code.zift.ca) and make sure that your website is successfully loaded. I am happy to report that it worked for me when I pointed my Microsoft Edge browser to my custom domain name.

image



Sunday, October 23, 2016

Deploy UWP Windows app into Raspberry Pi 2 device running Windows 10 IoT Core

In a previous post, I discussed building a Windows 10 UWP app that uses EF Core and SQLite. In this post I will show you how to deploy the same application to the Raspberry Pi 2 device running Windows 10 IoT Core. These are the pre-requisites you need to fulfill before continuing with this tutorial:
  • Needless to say, you need to own a Raspberry PI, version 2 or 3, device
  • Your development computer needs to be running the Windows 10 operating system
  • Install Visual Studio 2015. The community edition is more than adequate.
  • A monitor is needed with HDMI input in order to view the UI on the Raspberry Pi device.
  • An Ethernet cable is necessary to connect your development computer to the Raspberry Pi device
  • An HDMI cable to connect the Raspberry Pi device to your monitor.
  • One microSD card that will contain the Windows 10 IoT Core operating system on the Raspberry PI. microSD cards need to be at least 8 GB in size. Slower and older cards are inconsistent when flashing and may fail to work. Class 4 SD cards are not supported and at a minimum Class 10 SD cards should be used.
    View the list of recommended cards.
  • A mouse with a USB connector
  • A keyboard with a USB connector

Installing Windows 10 IoT on your Raspberry Pi device

Once you have all the above in place we are ready to go. The first step is to install Windows 10 IoT Core on the microSD Card.

1) Insert the microSD card into the adapter on your computer.

2) Go to https://developer.microsoft.com/en-us/windows/iot

3) Click on the “Get started now” button.

image

4) Click on the device you have. In my case, I clicked on “Raspberry Pi 2”.

image

5) In step 2, click on “Install onto my blank microSD card”.

image

6) In step 3 click on “Windows 10 IoT Core”.

image

7) Click on Next.

image

8) Since you already have Windows 10 installed on your computer, on the “Get the tools” page, skip straight to step 2 then click on “Download Dashboard”. This will download a setup.exe file onto your computer . Run the setup.exe application to install an application named “Windows 10 IoT dashboard” on your connected microSD card.

image

9) Insert the microSD card into the adapter that is attached to your computer.

10) Start the “Windows 10 IoT dashboard” application on your computer.

image

11) Connect the mouse and keyboard to the Raspberry Pi.

12) Click "Set up a new device".

13) Select “Raspberry Pi” from the dropdown.

14) Enter device name, password and Wi-Fi network to connect to.

15) Download and install Windows 10 IoT Core onto your microSD card.

16) Power OFF your Raspberry Pi device.

17) Remove the microSD  card that is attached to your computer and insert it into the Raspberry Pi device.

18) Connect an HDMI cable between your Raspberry Pi device and monitor.

19) Connect an Ethernet network cable between the Raspberry Pi and your computer.

20) Power ON your Raspberry Pi device. You should see the Windows 10 operating system start screen on the Raspberry Pi device.

image

21) Back in the “Windows 10 IoT dashboard” application on your desktop computer, click on “My Devices”. Your device should get detected and you should see the name, model, and IP address:

image

22) To see that your Raspberry Pi device is indeed connected with your computer, click on your device.

image

23) On your device’s page, click on “Open Windows Device Portal in browser”. You may be asked to enter the administrator password that you previously entered.

image

Feel free to navigate around using the various links to get familiar with what is on your Raspberry Pi Windows 10 IoT device.

Deploy UWP .NET Core app onto your Raspberry Pi device

If you have done my building a Windows 10 UWP app that uses EF Core and SQLite tutorial, then you can deploy that application to your Raspberry Pi. Otherwise, you can create a UWP application from scratch and deploy that instead. For the purpose of this exercise, we will go ahead and create a brand new vanilla UWP app.
  • File >> New >> Project
  • Templates >> Visual C# >> Windows >> Universal
  • Choose the “Blank App (Universal Windows)” template
  • Give the application name IoTDemo then click OK
image
  • Choose minimum version to be same as target version then click OK.
  • Edit MainPage.xaml and add the following code between the opening and closing <Grid> tags:
<TextBlock Text="Hello UWP on Windows 10 IoT core" Margin="200,200,0,0"/>
  • Compile the application then hit Ctrl + F5 to run it on your local machine. You will see the following window appear on your screen:
image
  • Close the above window by clicking on the X in the top-right corner.
  • Choose the ARM processor in Visual Studio
image
  • Select “Remote Machine” for target device.
image
  • The following dialog will appear:
image
  • Go back into the “Windows 10 IoT dashboard” application on your desktop.
  • Click on “My devices” on the left side. Right-click on your Raspberry Pi device and select “Copy IP address”.
image
  • Paste the IP address in the Address field on the Visual Studio “Remote Connections” dialog.
  • For “Authentication Mode” leave it as “Universal (Unencrypted Protocol).
  • Click on the Select button.
  • Click on “Remote Machine” to deploy and run the application on the Raspberry Pi device.
image
  • You may see a warning message like the one below. If you do see such a message and the deployment does not error out, then you are good.
image
  • If all goes well, you should see the UWP app running on your Raspberry PI device:
20161023_180941
20161023_182117

The fact that you can put modern apps on a small and inexpensive networked device like the Raspberry PI opens up a lot of opportunities. I sincerely hope this demo makes you come up with some bright ideas that translate into production ready apps.