Click here to Skip to main content
13,634,776 members
Click here to Skip to main content
Add your own
alternative version

Stats

10.3K views
6 bookmarked
Posted 22 Feb 2017
Licenced CPOL

Build Realtime Clock Using Angular2, TypeScript, ASP.Net and SignalR

, 23 Feb 2017
Rate this:
Please Sign up or sign in to vote.
In this article we will see how we can create real time clock using SignalR and Angular2 and integrate the angualr2 app inside ASP.Net and see its results.

Introduction

Before proceeding to the step wise progress of creating real time clock, it’s better to understand few of the important terms and things.

First of all we talk about,

What is mean by real time communication?

Real time communication (RTC) is a term which means a communication which does not have delays, as the clients connected each other through server when anyone client send a message as soon as server receives it pushed it towards another connected or all connected clients without any delay. Just like Instant Messaging Services we use like popular services are WhatsApp, IMO and Facebook Messenger.

It uses Peer-to-peer connection with minimum latency, RTC data and messages are not stored between transmissions.

I think it’s enough to have an information on real time communication, if you are willing to deep dive you can check out the available content on the web.

Next we will discuss about,

What is ASP.Net SignalR?

It is an ASP.Net library that add real time functionality to the web apps. As we already discuss that in real time communication as the server receives data it without storing pushes towards the connected clients.

SignalR Provides simple API for generating server to client Remote Procedure Calls (RPC) that hits with the JavaScript functions on the client from server side or the same is the reciprocal from client to server as it supports bi-directional communication.

SignalR contains built in rich mechanism for management of connections and methods to connect, disconnect or reconnect are available to override, grouping and authorization.

And the last but not least technology we used to create app is angular2.

What is Angular2?

Angular 2 is a rich UI Framework for building mobile and web applications. It is built using JavaScript. It has many enhancements over its 1st Version Angular 1. It is recreated and now it is better to develop applications with angular2 as it has extended set of features mentioned below.

  •           Cross Browser and Cross Platform Compatibility
  •           Two way Data Binding
  •           Enhanced Routing Support
  •           Modular Structure to Manage your code
  •          ·Excellent community support
  •           High Speed and Performance
  •           Fully Productive tools to fast pace your work
  •          Unit Testing

Implementation Using Code

Step 1:

Go to File è New è Project and select Asp.Net Web Application, after name the project and the destination Press Ok.

 

After Pressing Ok Button it will open new window to select the Template of the New Project.

In our case we are using Empty Template with MVC check box checked.

 

Now press OK Button again to create the project.

We have successfully created our web application.

Step 2:

Now we will first install SignalR to the created app.

For this we would Right click the project and select Manage Nuget Packages.

 

Nuget Package Manager Window Opens, Search SignalR and Press Install Button to install packages.

 

Now Review Changes window opens and these changes reflected on your solution after installing it.

 

Press OK button to continue.

After this License Acceptance window opens Click on I accept to accept the license other Press I Decline.

 

As this the final step towards installing SignalR through nugget package manger and it can install all the dependencies and Scripts needed for the project and it opens the Project folder in which change has occurred.

You can verify the package installed or not by verifying the tick mark on the package you installed in the Nuget Package Manger window.

 

Step 3:

Download and Install NodeJS for windows.

Go to https://nodejs.org/en/ and click on the recommended version to install for windows.

 

After downloading install the Microsoft installer file and follow the steps to install in your local machine.

To check either it is successfully installed on your local machine open Command Prompt Window and Type node –v and hit enter if it return the node version as shown in image it has been successfully installed.

 

Also verify the npm installed by typing the command npm –v

 

Step 4:

Add OWIN Startup class to the project by Adding New Item to the root of the project.

 

After the file is created add the following code to the file inside Configuration method.

app.MapSignalR();  

 

 

Step 5:

Add SignalR Hub Class to the Project better approach is to Make a Folder with the Name of Hubs and add Hub Class Inside it.

We first create the folder namely Hubs, and create a Hub Class by right click on the folder select Add è SignalR Hub Class, name it and it will add hub class to the folder.

 

I have created Hub class with the name of Clock. By default it will created with Hello method.

Copy and paste the below method to follow this tutorial.

 

public void GetRealTime()   
{  
Clients.Caller.setRealTime(DateTime.Now.ToString("h:mm:ss tt"));  
}  

 

Now let’s elaborate this method, as you can see GetRealTime is a hub method and it is server side method. From client we hit this server side event and on the result it make remote procedure call and send response back to the client by calling Clients.Caller.setRealTime method which is then used in the client side to accept the response and show to the client.

Caller means the calling client which is connected to the hub.

setRealTime function is used in the client end to broadcast and show the response.

Step 6:

Now we will move to setup the angular2 environment for your project.

If you want to quick start your project. You can use the ready made available project of the angular2 from official github account of Angular2 and clone the project to quick start.

I have enlisted the steps below to setup for your local development environment.

      1. Make sure you have installed node and npm. Node is for client side applications and build tools and npm package manager installs the javascript libraries.

      2. Create the angular2 folder on the root of your project and then app folder where we place only the angular2 code and in angular2 folder we place the configuration and other files required at the root.

      3. Create the Configuration files.

                                  i. First, create the tsconfig.json file. For this Press Ctrl + Shift + A or right click the angular2 folder and Select Add New Item from context menu, new windows appears select the json file and name it tsconfig.json and Press Add to create the file. The basic purpose of this file is to set the environment for typescript compilation configuration. Through this file all the typescript files transpiles to Javascript. Add the following code to the file.

{
"compilerOptions": {  
"target""es5",  
"module""system",  
"moduleResolution""node",  
"sourceMap": true,  
"emitDecoratorMetadata": true,  
"experimentalDecorators": true,  
"removeComments": false,  
"noImplicitAny": false  
},  
"exclude": [
"node_modules",  
"typings/main",  
"typings/main.d.ts"  
   ]  
} 

                                ii. Second, create the file through above procedure namely typings.json which can identity the typescript definition’s file in your angular application. There are three types of typing files defined in file. A) core-js b) jasmine and c) node. Copy the below code to the file.

{  
 "globalDependencies": {  
    "core-js": "registry:dt/core-js#0.0.0+20160602141332",  
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",  
    "node": "registry:dt/node#6.0.0+20160621231320"  
 }  
}  

                                iii. Third, create package.json file, this file contain the packages required by our app. The packages are installed and maintained using node package manager. Copy the below code the file.

{  
    "name": "angular2realtimeclock",  
    "version": "1.0.0",  
    "scripts": {  
        "start": "concurrent \"npm run tsc:w\" \"npm run lite\" ",  
        "tsc": "tsc",  
        "tsc:w": "tsc -w",  
        "lite": "lite-server",  
        "typings": "typings",  
        "postinstall": "typings install"  
    },  
    "license": "ISC",  
    "dependencies": {  
        "angular2": "2.0.0-beta.7",  
        "systemjs": "0.19.22",  
        "es6-promise": "^3.0.2",  
        "es6-shim": "^0.33.3",  
        "reflect-metadata": "0.1.2",  
        "rxjs": "5.0.0-beta.2",  
        "zone.js": "0.5.15"  
    },  
    "devDependencies": {  
        "concurrently": "^2.0.0",  
        "lite-server": "^2.1.0",  
        "typescript": "^1.7.5",  
        "typings": "^0.6.8"  
    }  
}  

      4. After creating the files now open the angular2 folder in window explorer and Press Shift + Right Key combination and select “Open Command Window Here” Option or alternatively point to this folder using command and write npm install and press Enter.

 

After packages installed, it will create the node_modules and typings folder inside your folder where you have installed.

      5. After the packages has been successfully installed, Now we will create the directory structure for residing the source code of angular2 as in angular2 every things is made up of component, so we will make basic and generic folder structure site which consists of Components, Classes, Services, Modules, Routing, Common and Shared folders so create them all on the project. It’s not necessary to create all the folder start it with per your requirement and then extend the functionality with creating folders as per need.

      6. We will start with the first of all the creating the base component inside app folder and their template as well. Create new typescript file with the name of app.component.ts in the root of app folder.

Inside file first import component from anglar core.

import {Component} from '@angular/core'

Then create @component decorator and add selector in which selector we bind our component to and then template for simple html inside file or to use the external template attach a template via templateUrl like this.

@Component({  
    selector: 'my-app',  
    templateUrl: './app/app.component.html'  
})  

And in the last export the class to be usable in other class to import.

export class AppComponent { } 

      7. Next we will create the template of app component with the name of app.component.html and put this code inside it.

<div id="wrapper"><router-outlet></router-outlet></div>

 

Basically router-outlet act as a placeholder for component that depends on current router state.

     8. Next Create app.module which act a base of all the modules used and it which you can export the component class, values and functions to be used in other modules. Copy and paste the code in the app.module file.

import {  NgModule  } from '@angular/core';  
import {  BrowserModule } from '@angular/platform-browser';  
import {  AppComponent  } from './app.component';  
import {  routing } from './app.routes';  
import {  HttpModule,  JsonpModule  } from '@angular/http';  
import {  ClockComponent } from './components/clock/clock.component';  
import {  SignalRService  } from './services/signalRService';  
import { FormsModule  } from '@angular/forms';  
@NgModule({  
    imports: [  
        BrowserModule,  
        routing,  
        HttpModule,  
        JsonpModule,  
        FormsModule  
    ],  
    declarations: [  
        AppComponent,  
        ClockComponent  
    ],  
    providers: [  
        SignalRService  
    ],  
    bootstrap: [AppComponent]  
})  
export class AppModule {}

     9. Next we will create the main.ts file in the root of the angular app folder which can bootstrap the app module , paste the following code.

import {  
    platformBrowserDynamic  
} from '@angular/platform-browser-dynamic';  
import {  
    AppModule  
} from './app.module';  
platformBrowserDynamic().bootstrapModule(AppModule);  

     10. Move to the other step in which we can create the systemjs .config.js file which can map the app folder files( transpile files to js) of your app, load the packages from certain path, and set the configuration and finally we place on the main entry point of our app page which is mainly index.html.

     11. Finally we will create the index.html file which is the main entry point of the app where we register the files like shim, reflect, zone, system js files and also Import the files generated previously to the main entry point using statement System.import(‘path of youor mapped app folder’. Inside index.html place this line of code.

    <meta charset="UTF-8">  
    <meta name="viewport" content="width=device-width, initial-scale=1">  
    <link rel="stylesheet" href="styles.css">  
    <link href="app/app.component.css" rel="stylesheet" />  
    <!-- 1. Load libraries -->  
    <!-- Polyfill(s) for older browsers -->  
    <script src="node_modules/core-js/client/shim.min.js"></script>  
    <script src="node_modules/zone.js/dist/zone.js"></script>  
    <script src="node_modules/reflect-metadata/Reflect.js"></script>  
    <script src="node_modules/systemjs/dist/system.src.js"></script>  
    <!-- 2. Configure SystemJS -->  
    <script src="systemjs.config.js"></script>  
    <title>Angular 2 Realtime Clock</title>  
    <script src="../Scripts/jquery-1.10.2.min.js"></script>  
    <script src="../Scripts/jquery.signalR.js" type="text/javascript"></script>  
    <script>  
        System.import('app');  
    </script>  
 
<!-- 3. Display the application -->  
  

    <!-- headers -->  
    <!-- body -->  
    <my-app>Loading the app...</my-app>  
    <!-- footers-->  

In our case also attach the signlaR and jquery client files required to fulfill our requirement.

      12. After finishing the basic configuration and settle down the things we will now create the functionality for creating the realtime clock using signalr like our component, model and service.

      13. So First we will create the model component. Name the component GetClockTime.ts and place them in the Model folder of your app and past the following code inside it.

export class GetClockTime {  
    public Time: string;  
    constructor(time: string) {  
        this.Time = time;  
    }  
}  

In this code block we have firstly created exported class which is reusable in other components and define a class member and initialize in the constructor.

      14. Now next we will create some global constant files as constants are those variable which value cannot be changed through the application execution life cycle. Name the file as app.constants.ts and place in the generic folder and paste the following code.

export let CONFIGURATION = {  
    baseUrls: {  
        server: 'http://localhost:50347/'  
    },  
}  

In this file we have created the exported variable and add the url of our server to be used in the signalR service. The basic purpose of using these files is that once we have list of all constants that are too frequently used can be changed in one place not on separately all the files.

      15. In the next step we will create the signalR Service, which is the backbone of all the process.

 Create the service in the service folder and paste the following code inside it.

// import the packages  
import {  
    Injectable,  
    EventEmitter  
} from '@angular/core';  
import {  
    CONFIGURATION  
} from '../generic/app.constants';  
import {  
    GetClockTime  
} from '../models/getclocktime';  
// declare the global variables  
declare  
var $: any;  
@Injectable()  
export class SignalRService {  
    // Declare the variables  
    private proxy: any;  
    private proxyName: string = 'clock';  
    private connection: any;  
    // create the Event Emitter  
    public messageReceived: EventEmitter < GetClockTime > ;  
    public connectionEstablished: EventEmitter < Boolean > ;  
    public connectionExists: Boolean;  
    constructor() {  
        debugger;  
        // Constructor initialization  
        this.connectionEstablished = new EventEmitter < Boolean > ();  
        this.messageReceived = new EventEmitter < GetClockTime > ();  
        this.connectionExists = false;  
        // create hub connection  
        this.connection = $.hubConnection(CONFIGURATION.baseUrls.server);  
        // create new proxy as name already given in top  
        this.proxy = this.connection.createHubProxy(this.proxyName);  
        // register on server events  
        this.registerOnServerEvents();  
        // call the connecion start method to start the connection to send and receive events.  
        this.startConnection();  
    }  
    // method to hit from client  
    public sendTime() {  
        // server side hub method using proxy.invoke with method name pass as param  
        this.proxy.invoke('GetRealTime');  
    }  
    // check in the browser console for either signalr connected or not  
    private startConnection(): void {  
        this.connection.start().done((data: any) => {  
            console.log('Now connected ' + data.transport.name + ', connection ID= ' + data.id);  
            this.connectionEstablished.emit(true);  
            this.connectionExists = true;  
        }).fail((error: any) => {  
            console.log('Could not connect ' + error);  
            this.connectionEstablished.emit(false);  
        });  
    }  
    private registerOnServerEvents(): void {  
        debugger;  
        this.proxy.on('setRealTime', (data: GetClockTime) => {  
            console.log('received in SignalRService: ' + JSON.stringify(data));  
            this.messageReceived.emit(data);  
        });  
    }  
}  

  I have commented each section for easiness.

      16. Further we will create the main component of the realtime clock.

  Create the new component by firstly creating the folder of the module than create component file namely clock.component.ts.

  Place this line of code inside it.

import {  
    Component,  
    NgZone  
} from '@angular/core';  
import {  
    SignalRService  
} from '../../services/signalRService';  
import {  
    GetClockTime  
} from '../../models/getclocktime';  
// decorator section comprised of selector and view template  
@Component({  
    selector: 'clock-component',  
    templateUrl: './app/components/clock/clock.component.html'  
})  
export class ClockComponent {  
    // public variables declaration  
    public currentMessage: GetClockTime;  
    public allMessages: GetClockTime;  
    public canSendMessage: Boolean;  
    // constructor of the class to inject the service in the constuctor and call events.  
    constructor(private _signalRService: SignalRService, private _ngZone: NgZone) {  
        // this can subscribe for events  
        this.subscribeToEvents();  
        // this can check for conenction exist or not.  
        this.canSendMessage = _signalRService.connectionExists;  
        // this method call every second to tick and respone tansfered to client.  
        setInterval(() => {  
            this._signalRService.sendTime();  
        }, 1000);  
    }  
    private subscribeToEvents(): void {  
        // if connection exists it can call of method.  
        this._signalRService.connectionEstablished.subscribe(() => {  
            this.canSendMessage = true;  
        });  
        // finally our service method to call when response received from server event and transfer response to some variable to be shwon on the browser.  
        this._signalRService.messageReceived.subscribe((message: GetClockTime) => {  
            debugger;  
            this._ngZone.run(() => {  
                this.allMessages = message;  
            });  
        });  
    }  
}  

      17. Last but not least we will create a view template against component in which we will place the clock to show in the browser.

  Create the clock.component.html file as a view to show the data to the browser.

<style type="text/css">p {  
        color: #000;  
        font-size: 8.7em;  
        font-family: Helvetica, Arial;  
        padding-top: 0%;  
        margin-left: 25%;  
    }</style> 
    <div id="timediv">
<p>{{allMessages}}</p>
</div>

Step 6: Launch the project on the browser by using command prompt npm start statement or launch the browser by using visual studio f5 and type the angular2 to point to the angular2 app.

Finally the output is here.

  

Points of Interest

The best thing in all this is to try to create the same thing using new technoloies and the best thing is to setup the angular2 for development.

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

M,AqibShehzad
Software Developer (Senior)
Pakistan Pakistan
No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
Questionsome pieces missing Pin
Member 913162927-Feb-17 10:14
memberMember 913162927-Feb-17 10:14 
AnswerRe: some pieces missing Pin
M,AqibShehzad27-Feb-17 16:57
professionalM,AqibShehzad27-Feb-17 16:57 
GeneralMy vote of 5 Pin
Ehsan Sajjad24-Feb-17 4:11
professionalEhsan Sajjad24-Feb-17 4:11 
QuestionSource Code Pin
Ehsan Sajjad24-Feb-17 4:10
professionalEhsan Sajjad24-Feb-17 4:10 
AnswerRe: Source Code Pin
M,AqibShehzad24-Feb-17 6:39
professionalM,AqibShehzad24-Feb-17 6:39 
AnswerRe: Source Code Pin
M,AqibShehzad5-Mar-17 20:36
professionalM,AqibShehzad5-Mar-17 20:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04-2016 | 2.8.180712.1 | Last Updated 23 Feb 2017
Article Copyright 2017 by M,AqibShehzad
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid