Category Archives: Uncategorized

ASP.NET Web API and Streaming Video Content

Below post explains how to stream video content through ASP.Net Web API’s, below is the code for Video Controller which inherits from API Controller. API show both GET and POST approaches.

Main thing to concentrate in the code is usage of Push Stream Content. PushStreamContent enables option to send data in small stream packets which then could be used on client side to stream videos, download large files etc.

    /// API Controller for streaming video files.
    public class VideoController : ApiController
    {
        private const string videoFilePath = "~/Movies/";

        /// Gets the live video.
        [HttpGet]
        [Route("api/video/live")]
        public IHttpActionResult GetLiveVideo(string videoFileId, string fileName)
        {
            string filePath = Path.Combine(HttpContext.Current.Server.MapPath(videoFilePath), fileName);
            return new VideoFileActionResult(filePath);
        }

        /// Gets the live video using post.
        /// The request.
        [HttpPost]
        [Route("api/video/live")]
        public IHttpActionResult GetLiveVideoPost(VideoFileDownloadRequest request)
        {
            string filePath = Path.Combine(HttpContext.Current.Server.MapPath(videoFilePath), request.FileName);
            return new VideoFileActionResult(filePath);
        }
    }

    /// Action Result for Returning Stream
    public class VideoFileActionResult : IHttpActionResult
    {
        private const long BufferLength = 65536;
        public VideoFileActionResult(string videoFilePath)
        {
            this.Filepath = videoFilePath;
        }

        public string Filepath { get; private set; }

        public Task ExecuteAsync(CancellationToken cancellationToken)
        {
            HttpResponseMessage response = new HttpResponseMessage();
            FileInfo fileInfo = new FileInfo(this.Filepath);
            long totalLength = fileInfo.Length;
            response.Content = new PushStreamContent((outputStream, httpContent, transportContext) =>
                {
                    OnStreamConnected(outputStream, httpContent, transportContext);
                });

            response.Content.Headers.ContentLength = totalLength;
            return Task.FromResult(response);
        }

        private async void OnStreamConnected(Stream outputStream, HttpContent content, TransportContext context)
        {
            try
            {
                var buffer = new byte[BufferLength];

                using (var nypdVideo = File.Open(this.Filepath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    var videoLength = (int)nypdVideo.Length;
                    var videoBytesRead = 1;

                    while (videoLength > 0 && videoBytesRead > 0)
                    {
                        videoBytesRead = nypdVideo.Read(buffer, 0, Math.Min(videoLength, buffer.Length));
                        await outputStream.WriteAsync(buffer, 0, videoBytesRead);
                        videoLength -= videoBytesRead;
                    }
                }
            }
            catch (HttpException ex)
            {
                return;
            }
            finally
            {
                // Close output stream as we are done
                outputStream.Close();
            }
        }
    }

 

On the client side you can view the video file using below code snippet

<video width="480" height="320" controls="controls" autoplay="autoplay">
        <source src="api/video/live?videoFileId=1001&fileName=sampleVideo.mp4" type="video/mp4">
    </video>

Signal R Load balancing Issue

If you are using Signal R and and Signal R Hub as part of an ASP.net application which sits behind the loadbalancer with more than one machine then there is possiblity that you will start seeing this below error

SignalR – The connection id is in the incorrect format.

Just like when load balancing an ASP.NET website that uses Session, SignalR instances which are load balanced requires that all servers which handle SignalR requests must share a machine key. This is not mentioned in any documentation for SignalR/. ConnectionToken is encrypted using the machine key, when an application hits server 1 it is assigned a connectionToken generated using that machine’s machine key. If the application then hits server 2 with that assigned connectionToken, machine 2 cannot decrypt the token unless is has a matching machine key.

To solve this issue in your application web.config file you can add the machine key configuration

    
    <machineKey decryptionKey="EF1E7D088734F1B53F6594DE015FA9950B1379E4F2C3261E"
                validationKey="26EAACEB1553F966A8EC1B0304131B9D63CB81970B9204A04380189E040A84C0DC97303552434261E9445434392413EF881CF54892851955461A826805A78AA0" />

Now you must be wondering how can generate these keys, IIS manager helps you to generate those keys

  • Open IIS Manager, host you are application website on the IIS, click on the site, then on the Features view tab, select machine key as shown below
    machinekey
  • After selecting machine keys you will see following default options MachineKey1.jpg
  • Uncheck all the checkboxes and on the right side tab click on the “Generate Keys” option. machinekey2
  • Post generating the keys, Click on apply, this will add the machine key configuration web site web.config file as shown above.

Observable’s in Angular 2 (RxJS)

Observables in Angular 2 can be achieved using RxJS(Reactive Extensions for JavaScript). Observables is an ES7 feature so you need to make use of an external library to use it today. RxJS is a library that allows you to work with asynchronous data streams. So what are asynchronous data streams?

  • Asynchronous – we can call a function and register a callback to be notified when results are available, so we can continue with execution and avoid the Web Page from being unresponsive. This is used for ajax calls, DOM-events, Promises, WebWorkers and WebSockets.
  • Data – raw information in the form of JavaScript data types as: Number, String, Objects (Arrays, Sets, Maps).
  • Streams – sequences of data made available over time. Technically everything is stream.

Observables can help manage async data and a few other useful patterns. Observables are similar to Promises but with a few key differences. The first is Observables emit multiple values over time. For example a Promise once called will always return one value or one error. This is great until you have multiple values over time. Web socket/real-time based data or event handlers can emit multiple values over any given time. This is where Observables really shine. Observables are used extensively in Angular 2.

 Observables  Promise
 Observables handle multiple values over time  Promises are only called once and will return a single value
 Observables are cancellable  Promises are not cancellable

The ability of observables being able to handle multiple values over time makes them a good candidate for working with real-time data, events and any sort of stream you can think of. Being able to cancel observables gives better control when working with in-flow of values from a stream. The common example is the auto-complete widget which sends a request for every key-stroke.

RxJS also provides Observable operators which you can use to manipulate the data being emitted. Some of common operators are:

  • Map
  • Filter
  • Take
  • Skip
  • Debounce
  • Retry

So in angular 2 now you services will start returns observables instead of promises like shown below for category service, getCategories returns an observable.

import { Injectable, Inject } from '@angular/core';
import { Http, Response} from '@angular/http';
import { OpaqueToken } from '@angular/core';

import {Category} from './category';
import {Observable} from 'rxjs/Observable';


export let INTERVIEW_APP_CONFIG = new OpaqueToken('app.config');
export interface ApplicationConfiguration{
    apiEndPoint : string,
    timeOut: number
}

export const INTERVIEW_APP_DI_CONFIG: ApplicationConfiguration = {
  apiEndPoint: 'http://app.cloudapp.net/api/Category',
  timeOut: 20
};


@Injectable()
export class CategoryService {
    categoryServiceUrl :string;
    constructor(private http: Http, @Inject(INTERVIEW_APP_CONFIG) config: ApplicationConfiguration){
        console.log(config.apiEndPoint);
        this.categoryServiceUrl = config.apiEndPoint;
    }
       
    getCategories (): Observable<Category[]>{
        console.log("Get Categories");
        return this.http.get(this.categoryServiceUrl)
                        .map(this.extractCategoryData)
                        .catch(this.handleError);
                        
    } 
    
    private extractCategoryData(res: Response){
        let body = res.json();
        return body || { };
    }
    
    private handleError (error: any) {
        let errMsg = (error.message) ? error.message : 
        error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
  }
}

 

An observable is only enabled when a first observer subscribes. This is a significant difference compared to promises. As a matter of fact, processing provided to initialize a promise is always executed even if no listener is registered. This means that promises don’t wait for subscribers to be ready to receive and handle the response. When creating the promise, the initialization processing is always immediately called.

Observables are lazy so we have to subscribe a callback to let them execute their initialization callback. below component defines the subscribe for the observable which has been returned,

import { Component, OnInit } from '@angular/core';
import { Category } from './category';
import './rxjs-operators';
import { CategoryService, INTERVIEW_APP_CONFIG, INTERVIEW_APP_DI_CONFIG } from './categoryService';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers:[CategoryService, { provide: INTERVIEW_APP_CONFIG, useValue: INTERVIEW_APP_DI_CONFIG }]
})
export class AppComponent {
  title = 'app works!';
  firstName="Aamol";
  errorMessage: string;
  categories: Category[];
  
 constructor(private categoryService: CategoryService){
   
 }
 ngOnInit(){
   this.getCategories();
   console.log("Getting categories");
  } 
 
 getCategories() {
   this.categoryService.getCategories()
                  .subscribe(
                    categories => this.categories = categories,
                    error => this.errorMessage = <any>error
                  );
 }
}

Observables allow you to register callbacks as shown above, the subscribe method three callbacks as parameters:

  • The onNext callback that will be called when an event is triggered.
  • The onError callback that will be called when an error is thrown.
  • The onCompleted callback that will be called when the observable completes.

Here is the way to register callbacks on an observable:

categoryService.getCategories.subscribe(
  (event) => {
    // handle events
  },
  (error) => {
    // handle error
  },
  () => {
    // handle completion
  }
);

The observable class provides a fromPromise method to create an observable from a promise. This allows you to make a promise part of an asynchronous data stream

Retrying requests – Observable allows you to repeat the source observable sequence the specified number of times or until it successfully terminates. In the context of HTTP requests, this allows you to transparently re-execute requests that failed.

getCategories (): Observable<Category[]>{
        console.log("Get Categories");
        return this.http.get(this.categoryServiceUrl)
                        .retry(4)
                        .map(this.extractCategoryData)
                        .catch(this.handleError);
                        
    } 

Enable RxJS Operators – The RxJS library is quite large. So Angular 2 exposes a stripped down version of Observable in the rxjs/Observable module, a version that lacks most of the operators including map, retry which we have used above, it’s up to us to add the operators we need. We could add every RxJS operators with a single import statement. but we’d pay a penalty in extended launch time and application size because the full library is so big. We only use a few operators in our app.

Instead, we’ll import each Observable operator one-by-one, we’ll put the import statements in one app/rxjs-operators.ts file.

// Statics
import 'rxjs/add/observable/throw';

// Operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/retry';

Your API’s and HAL

HAL – Hypertext Application Language

HAL is a simple format that gives a consistent and easy way to hyperlink between resources in your API. Adopting HAL will make your API explorable, and its documentation easily discoverable from within the API itself. In short, it will make your API easier to work with and therefore more attractive to client developers.

APIs that adopt HAL can be easily served and consumed using open source libraries available for most major programming languages. It’s also simple enough that you can just deal with it as you would any other JSON. HAL provides a set of conventions for expressing hyperlinks in either JSON or XML. The rest of a HAL document is just plain old JSON or XML. Instead of using ad-hoc structures, or spending valuable time designing your own format; you can adopt HAL’s conventions and focus on building and documenting the data and transitions that make up your API. Its conventions make the documentation for an API discoverable from the API messages themselves. This makes it possible for developers to jump straight into a HAL-based API and explore its capabilities, without the cognitive overhead of having to map some out-of-band documentation onto their journey.

The HAL conventions revolve around representing two simple concepts: Resources and Links.

Resources have: Links (to URIs), Embedded Resources (i.e. other resources contained within them), State (your standard JSON or XML data).

Links have: A target (a URI), A relation aka. ‘rel’ (the name of the link), a few other optional properties to help with deprecation, content negotiation, etc.

HAL is designed for building APIs in which clients navigate around the resources by following links. Links are identified by link relations. Link relations are the lifeblood of a hypermedia API: they are how you tell client developers about what resources are available and how they can be interacted with, and they are how the code they write will select which link to traverse.

@Injectables + Angular 2.0 + @Inject

@Injectable() is the decorator in Angular 2.0

Typically in Angular 2.0 services are simple classes and if these services require dependencies to be injected then you need this decorator.

DI (Dependency Injection) in Angular 2.0 is hierarchical in nature, for dependency injection to be able to create instances for you, you need to register providers for these classes (or other values) somewhere. and you can configure providers for DI at different levels

  • For the whole application when bootstrapping it. In this cases, all sub injectors (the component ones) will see this provider and share the instance associated with. When interacting, it will be the same instance
  • For a specific component and its sub components. Same as before but for à specific component. Other components won’t see this provider. If you redefine something defined above (when bootstrapping for example), this provider will be used instead. So you can override things. If a provider is registered in one of the child components a new (different) instance is provided for descendants of this component.
  • If a component requests an instance (by a constructor parameter), DI looks “upwards” the component tree (starting from leaf towards the root) and takes the first provider it finds. If an instance for this provider was already created previously, this instance is used, otherwise a new instance is created.

Angular 2.0 docs recommend adding @Injectable() to all services classes , even those that don’t have dependencies and, therefore, do not technically require it. Here’s why:

  • Future proofing: No need to remember @Injectable() when we add a dependency later.
  • Consistency: All services follow the same rules, and we don’t have to wonder why a decorator is missing.

Here is sample service (CategoryService) for my mobile app

import { Injectable } from '@angular/core';
import { Http, Response} from '@angular/http';

import {Category} from './category';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class CategoryService {
    constructor(private http: Http){
        
    }
    
    private categoryServiceUrl = "http://app.cloudapp.net/api/Category";
    
    getCategories (): Observable<Category[]>{
        return this.http.get(this.categoryServiceUrl)
                        .map(this.extractCategoryData)
                        .catch(this.handleError);
                        
    } 
    
    private extractCategoryData(res: Response){
        let body = res.json();
        return body || { };
    }
    
    private handleError (error: any) {
        let errMsg = (error.message) ? error.message : 
        error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); 
        return Observable.throw(errMsg);
  }
}

 

Here is how you register with provider this is at component level

import { Component, OnInit } from '@angular/core';
import { Category } from './category';
import { CategoryService } from './categoryService';
// Add the RxJS Observable operators we need in this app.
import './rxjs-operators';
@Component({
  moduleId: module.id,
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
  providers:[CategoryService]
})
export class AppComponent implements OnInit{
  title = 'app works!';
  firstName= "Aamol Gote";
  errorMessage: string;
  categories: Category[];
  
  constructor(private categoryService: CategoryService){
    
  }
  
  ngOnInit() {
    this.getCategories();
  }
  
  getCategories(){
    this.categoryService.getCategories()
                        .subscribe(
                          categories => this.categories = categories,
                          error => this.errorMessage = <any>error
                        );
  }
}

 

@Inject – This is manual way of letting angular know that this parameter must be injected. typically DI is implicit in nature for Angular 2.0 but for certain edge cases if there is need to specify dependency explicitly with its type then @Inject is used. One very good candidate for @Inject is for injecting non class dependencies. Suppose if you have an application configuration which includes API end point, then these configurations need not necessarily be instances of the classes these can be just object literals, for e.g. as shown below

export interface ApplicationConfiguration{
    apiEndPoint : string,
    timeOut: number
}

export const INTERVIEW_APP_CONFIG: ApplicationConfiguration = {
  apiEndPoint: 'http://app.cloudapp.net/api/Category',
  timeOut: 20
};

 

Now we need to inject INTERVIEW_APP_CONFIG in CategoryService, way we do it first need to register the Provider for INTERVIEW_APP_CONFIG,

[{ provide: InterviewAppConfig, useValue: INTERVIEW_APP_CONFIG  })]

constructor(private config:InterviewAppConfig){ }

 

But the above code snippet fails as INTERVIEW_APP_CONFIG constant has an interface, InterviewAppConfig. We cannot use a TypeScript interface as a token, to solve this we have to use Opaque tokens, here is the updated category service class with config value injected through @Inject()

import { Injectable, Inject } from '@angular/core';
import { Http, Response} from '@angular/http';
import { OpaqueToken } from '@angular/core';

import {Category} from './category';
import {Observable} from 'rxjs/Observable';

export let INTERVIEW_APP_CONFIG = new OpaqueToken('app.config');
export interface ApplicationConfiguration{
    apiEndPoint : string,
    timeOut: number
}

export const INTERVIEW_APP_DI_CONFIG: ApplicationConfiguration = {
  apiEndPoint: 'http://app.cloudapp.net/api/Category',
  timeOut: 20
};


@Injectable()
export class CategoryService {
    categoryServiceUrl :string;
    constructor(private http: Http, @Inject(INTERVIEW_APP_CONFIG) 
        config: ApplicationConfiguration){
        this.categoryServiceUrl = config.apiEndPoint;
    }
    
    
    
    getCategories (): Observable<Category[]>{
        console.log("Get Categories");
        return this.http.get(this.categoryServiceUrl)
                        .map(this.extractCategoryData)
                        .catch(this.handleError);
                        
    } 
    
    private extractCategoryData(res: Response){
        let body = res.json();
        return body || { };
    }
    
    private handleError (error: any) {
        let errMsg = (error.message) ? error.message : 
        error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
  }
}

 

We need register the provider in the component like shown below

@Component({
  moduleId: module.id,
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
  providers:[CategoryService, { provide: INTERVIEW_APP_CONFIG, 
                                useValue: INTERVIEW_APP_DI_CONFIG }]
})

Mystery of Transclusion – Angular JS

Definition of transclusion – The inclusion of a document or part of a document into another document by reference. example are including styles.css in html page, or server side include which injects HTML fragment in a document.

In angular JS you typically custom fragment through directives and that’s where transclusion is important from angular perspective.

Two key features are provided by AngularJS to support transclusion. The first is a property that is used in directives named transclude. When a directive supports transclusion this property is set to true. The second is a directive named ng-transclude that is used to define where external content will be placed in a directive’s template. The directive code that follows uses these two AngularJS features to enable transclusion.

Consider a directive called custom-directive-element in an element, and that element is enclosing some other content, let’s say:

Transclusion-1

var myCustomApp = angular.module('myApp',[]);
myCustomApp.directive('customDirectiveElement', function(){
    return {
        template: 'This is my custom directive element content'
    }
});

This will result in rendering
Transclusion-2

Notice that the content of your original element will be lost (or better said, replaced), button and href are gone

<button>Submit</button>
<a href="#">Home</a>

So, what if you want to keep your button… and href.. in the DOM? You’ll need something called transclusion. The concept is pretty simple: Include the content from one place into another.

So with transclusion the directive should look like this

myCustomApp.directive('customDirectiveElement', function(){
    return{
               restrict: 'E',
               transclusion: true,
               template: 'This is my custom directive element content 
                                         
'
} });

This would render:

Transclusion-3

In conclusion, you basically use transclude when you want to preserve the contents of an element when you’re using a directive.

ES6 let keyword

JavaScript ES6: the let keyword. let enables a new form of scoping. var is scoped to the nearest function block and let is scoped to the nearest enclosing block (both are global if outside any block), which can be smaller than a function block. Also, variables declared with let are not visible before they are declared in their enclosing block unlike var type in which case the variables get hoisted at the top of the function. For hoisting refer previous blogs if required. In its most basic form, let is a sibling to var. But declarations made with let are scoped to the blocks in which they occur, rather than being “hoisted” to the enclosing function’s scope as vars do

The let statement declares a block scope local variable, optionally initializing it to a value.

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

Scoping rules

Variables declared by let have as their scope the block in which they are defined, as well as in any contained sub-blocks . In this way, let works very much like var. The main difference is that the scope of a var variable is the entire enclosing function:

function oldES5varTest() {
    var x = 100;
    if (true) {
        var x = 200;  // same variable!
        console.log(x);  // 200
    }
    console.log(x);  // 200
}

function newES6letTest() {
    let x = 100;
    if (true) {
        let x = 200;  // different variable
        console.log(x);  // 200
    }
    console.log(x);  // 100
}

 

It makes inner function code much cleaner

var list = document.getElementById("list");

for (let i = 1; i <= 5; i++) {
    let item = document.createElement("li");
    item.appendChild(document.createTextNode("Item " + i));

    item.onclick = function (ev) {
        console.log("Item " + i + " is clicked.");
    };
    list.appendChild(item);
}

The example above works as intended because the five instances of the (anonymous) inner function refer to five different instances of the variable i. Note that it does not work as intended if you replace let with var, since all of the inner functions would then return the same final value of i: 6. Also, we can keep the scope around the loop cleaner by moving the code that creates the new elements into the scope of each loop.

At the top level of programs and functions, let, unlike var, does not create a property on the global object. For example:

var x = 'globalX';
let y = 'globalY';
console.log(this.x); // "globalX"
console.log(this.y); // undefined

 

Block scoping simply says, I want to be able to treat a { .. } block as a scope, without having to make a new function to encapsulate that scope.Other languages (e.g., Java, C++) have true block scoping, where you can declare a variable to belong to a specific block instead of to the surrounding scope/function.