Building Real time application with SignalR – Part 1

HTTP protocol is the basis for all communication over the web, and it has catered to our needs since the early days. HTTP works in a request and response model, where a request needs to be sent to the server to get any update from there. This creates challenges in handling a few scenarios where we need real time data: when a user opens a web page then it needs to be updated, and when there is a change on the server but as per the HTTP architecture, a new request must be sent to get an update from the server. This creates a bad experience for the user and multiple requests may throttle…Read complete post on Infragistics blog.

Cheers,
Brij

Presented on REST and ASP.NET Web API in C# Corner South India Meet : 31st Jan 16

Hello All,

On 31st Jan 2016, C# corner organized a major event named as South India Meet in Hyderabad. This event got an awesome response from the developer community where more than 500 people registered for the event and was attended by 200+ developers. A series of hot topics were discussed including REST, ASP.NET Web API. AngularJS, Phonegap etc which was very much appreciated by the audience. I presented on Building Rest Services using ASP.NET Web API and audience enjoyed the talk with full of enthusiasm and energy in spite of the last session of the day.  For the popular demand, I am attaching the slides and sample at the end of this Post. Some snaps of the event

Brij_stage

attendees

CaBySP-UEAAlbY7We also announced the North India’s largest conference C# Corner Annual Conference which will be taking place in Noida during 18-19 April 2016.

For complete details of C# Corner Conference Click here.

Sample code

Please note that the solution was built using Visual Studio 2015 Update1 and ASP.NET RC1. You can download the community edition of Visual Studio to get going and exploring more features.

Thanks a lot to all attendees and hope you all have enjoyed the day.

Do share you feedback and let us know if you want to hear any specific topic

You may like to download AngularJS book from here

Cheers,
Brij

 

Unspecified Error while installing ASP.NET 5 RC1 Update 1 : Solution

Hello All,

Recently I installed Visual Studio update 1 on few new azure VMs but when I started installing ASP.NET 5 RC1 Update 1, I got the below error.

error

I tried to find the details on internet but not much information regrading this information. I saw some people find another Hash problem with this package but after looking it closely I found it different. Later when I looked into the log, I found the below details

Log files shows that it is not able to download DotNetVersionManager_x64 from https://go.microsoft.com/fwlink/?LinkId=708515. However, when I try from browser, it is downloading the msi. The error looks in the log as
[1124:12AC][2015-12-20T19:10:08]w343: Prompt for source of package: DotNetVersionManager_x64, payload: DotNetVersionManager_x64, path: C:\Users\WinS12R2Brij\Desktop\DotNetVersionManager-x64_rc1.msi
[1124:12AC][2015-12-20T19:10:08]i338: Acquiring package: DotNetVersionManager_x64, payload: DotNetVersionManager_x64, download from:https://go.microsoft.com/fwlink/?LinkId=708515
[1124:12AC][2015-12-20T19:10:08]e000: Error 0x80072f08: Failed to send request to URL: https://go.microsoft.com/fwlink/?LinkId=708515, trying to process HTTP status code anyway.
[1124:12AC][2015-12-20T19:10:08]e000: Error 0x80072f76: Failed attempt to download URL: ‘https://go.microsoft.com/fwlink/?LinkId=708515‘ to: ‘C:\Users\WINS12~1\AppData\Local\Temp\2\{782d25e1-8377-4417-a491-3013700fe300}\DotNetVersionManager_x64’

The error shows that it is preparing to download some packages but failing to send the request to the URL and returning some crazy HTTP status code anyway . I checked quickly internet connectivity as soon as I saw this error but it was working fine and even I tried to download from the requested URL directly from browser and it was downloading the package correctly.

After spending some more time and doing here n there, I downloaded the packages from all the URLs where it was failing and installed directly on my machine. I had to install three packages in the same to all the machines where I was getting the issue. Then I installed the original package and it ran smoothly. You can find the URLs from the log by looking specific line where you have Error 0x80072f08: Failed to send request to URL .

Before wrapping up, let me tell you that I didn’t find this issue on one of my machines but got the same on rest four VMs and some were having Windows Server 2012 R2 and 2016 technical preview. Two were having SQL 2014 and VS 2013 installed before installing VS 2015 update 1 and the above 1. On the machine where It went smooth without any issue that was also having similar configuration but I was using it from long time. Just provided this information for completeness as all the environment were quite similar.

Cheers
Brij

 

ASP.NET 5 RC1 Web API always returns JSON – Why ?


Hello All,

Note – For this example, I am have used Visual Studio 2015 Update 1 for IDE and ASP.NET 5 RC1.

Recently I started working on an ASP.NET Web API application but I got stuck at one point for few hours. Let’s start from scratch and create the application first then we will see the behavior and various options. As I (most of us) like to start from clean slate so I created an empty ASP.NET application and followed the below stuff

  1. Added Microsoft.AspNet.Mvc as dependency in project.json.
  2. In ConfigureServices method of startup.cs, added services.AddMvc()
  3. In Configure method of startup.cs, added app.UseMvc();
  4. Added a Controllers folder in solution and added a controller class with name as PeopleController which inherits from Controller.
  5. Added the attribute route on the controller as
  6. Now we have done all the necessary set up and added a Controller for Web API. I have added a DataHelper class in Models folder (which I added) which returns a list of persons.

Now when I run that application and call the API using Fiddler as

request

I get the response in JSON format

response

Although we didn’t send any Accept header in request. It means now the default response format is JSON only. Now I added the Accept header as

acceptrequest

Then also the response was same as earlier.

As per earlier understanding that the returned content type should be as per the Accept header which is not the case when I did some research, I found that now by default only JSON formatter is included. Refer the below link for detailed discussion.

https://github.com/aspnet/Mvc/issues/1765

And this was implemented in beta 3 release and it says that to add the XML formatter, we need to include the package Microsoft.AspNet.Mvc.Xml but I got an error while including this package because the latest version available is beta5 and the version of MVC we are using is rc1. After spending few hours, I discovered that the package Microsoft.AspNet.Mvc.Xml is not the correct one now and there was no update in it since 30th Jun’15. Two new packages for formatting XML and JSON format got introduced as

  1. Microsoft.AspNet.Mvc.Formatters.Xml
  2. Microsoft.AspNet.Mvc.Formatters.Json

Currently there is no details available on earlier package  that now some new packages are available instead of Microsoft.AspNet.Mvc.Xml  which made it bit tough to find the right one.

As we realized, JSON is included by default with MVC package, I added Xml package and configureed it in services as

public void ConfigureServices(IServiceCollection services)
{
    var mvcBuilder = services.AddMvc();
    mvcBuilder.AddXmlDataContractSerializerFormatters();
}

Now when I ran the package with Accept header as text/xml, it return the response in XML format as

xmlresponse

But default is JSON only so we don’t need to send any information in header if we just want the result in JSON format.

Cheers
Brij

 

Wish you all a very Happy New Year : 2016

Happy-New-Year-2016

Hello All,

As the 2015 is now past, I want to wish you and your family a Very Happy New Year. May this year become one the best years and you achieve new heights in your career. As saying Good health is True Wealth , be healthy throughout the year and enjoy each moment.

First I want to say all of you a BIG THANK YOU for all of elders, friends, blog readers, event audiences for your support and candid feedback throughout the year. This year was again one of the best years where I received my 5th MVP award in a row .I also presented to India’s largest developer’s conference (GIDS) and it was an awesome experience. I would like to thank some of the legends Pinal Dave, Vinod Kumar,  Balmukund, Mahesh Chand, Gaurav mantri sir and many more for there valuable suggestions and motivation. This year, I also moved to new city Hyderabad and enjoying interacting with the developers here and I am really enjoying this place. Hope we will see you all in many other events and if you stay nearby.

In the New Year 2016, I will give more time to my blog and community events to make myself more helpful. Also I have many plans for few new things that I will be working and sharing at right time. I am sure my posts, community events will add more value in coming year too.  You can connect me through my blog, twitter, facebook page, Linkedin, email. I’ll try to respond as early as possible.

Again, Thanks a lot and A very happy new year to all of you and keep learning n keep growing.

Happy New Year
Brij

AngularJS in 19 Days : Download the free eBook with samples

Hello All,

As you might be following the series of posts on AngularJS from last couple of months and that I completed 20 post and covered range of topics. Based on many suggestions, I have updated all those posts with current version 1.4, since initial posts were using other using 1.0+, added navigation links etc. Now I have incorporated compiled all the posts, refined the content and sample a bit and happy to present it in a format of eBook. I am sure it will be very handy and easy to read and follow till end.

About the ebook :

ebookcoverFor those who were not following the series of post, As the name suggests this book in divided in 19 days from Introduction to covering most of the core topics including unit tests. The sample of each day can be downloaded from GitHub. This is not just another e book which covers the basics of AngularJS or cover everything, but it is a unique combination of basics and details description of core concepts with sample. If you are ASP.NET MVC developer then it will become more fruitful to you as some of days it covers that how and what are best ways to use Angular in ASP.NET MVC project. I am sure you will enjoy the book and will share your feedback that will help in upcoming new version.

 

Download the book from here

Thanks
Brij

Leveraging HTTP/2 with ASP.NET 4.6 and IIS10

In the last decade, the Web has taken multiple long strides. From basic HTML, web pages developed a richer look and feel, and are getting more intuitive, user friendly and glossier every day. The key contributors to these changes are some new and revamped technologies, supported by the latest hardware and better internet connectivity. But performance has always been an area of concern with web applications since the beginning…Read the complete post on Infragistics blog

Getting started Unit Testing in {{AngularJS}} Contd. – Part 20

This post is in continuation of my previous post on Unit Testing in AngularJS where we discussed about the basics of Unit Test in AngularJS, setting up the infrastructure and then wrote couple of unit tests. First we started with test for plain JavaScript method then we wrote an angular application and added unit test for Angular controller. While writing unit test, we also learned basics of Jasmine framework. The link of my previous post is given below

Getting started with Unit Testing in {{AngularJS}} – Part 19

Today we will write unit tests for following components.

  • Angular Service
  • Custom Filters
  • Custom Directive

Note – This post is a part of series of posts on AngularJS and it is 20th one. Click here to view all the post. Apart from that you can also use the navigation links for next and previous post in each post at the bottom to check all.

Testing your Service

As we know that service is an independent object which does some specific work and can be reused at multiple places. We normally used to have many services in our application which does various tasks. These services are the first candidates which should be considered for writing unit tests. Broadly in our service, we do two type of tasks, first where we take some input, write some logic and return the output accordingly. Second, where we connect some third party services via AJAX, process the response and return it. First type of service can be tested easily as normal JavaScript function. We are going to write Unit Test for second type.

We will extend our previous application where we hard coded the values in Angular Controller. Now instead, we will be creating an Angular service which will get the data from server and return that. Let’s see our service

homeModule.factory("TalksService", function ($http, $q) {
    return {
        getTalks: function () {
            // Get the deferred object
            var deferred = $q.defer();
            // Initiates the AJAX call
            $http({ method: 'GET', url: '/home/GetTalkDetails' }).success(deferred.resolve).error(deferred.reject);
            // Returns the promise - Contains result once request completes
            return deferred.promise;
        }
    }
});

Note – In this series of posts on AngularJS, I have written following post where we discussed about Angular Services. To learn more about services, you can refer that

Learning {{AngularJS}} with ASP.NET MVC – Part 4

We have added our service using Factory which uses $http service to get the data from the server. One of the key points is that we are returning a promise here. Now let’s make the required changes in the controller

After these changes, our application would run same as we are now returning the same data server via Web API. Now it’s time to write the Unit Test

Writing Unit Test

There are two new things here, usage of $http Service and returning promise. To test $http service, AngularJS provides a Fake implementation as $httpBackend which helps in mocking the service and setting up the response. To write the test, we need to initialize TalkService and httpBackend that we can inject at before each. Also we need to initialize homeModule as

var TalksServiceFactory, httpBackend;

beforeEach(module("homeModule"));

beforeEach(inject(function($httpBackend, TalksService) {
    httpBackend = $httpBackend;
    TalksServiceFactory = TalksService;
}));

And unit test

    it("Should Return four Talks", function () {
    var talks;
    
        // Setting the mock up mock http response 
        httpBackend
        .expect('GET', '/home/GetTalkDetails')
        .respond(200, [
            { id: '1001', name: 'Real Time Web Applications with SignalR', speaker: 'Brij Bhushan Mishra', venue: 'Hall 1', duration: '45' },
            { id: '1002', name: 'Power of Node.js', speaker: 'Dhananjay Kumar', venue: 'Hall 2', duration: '75' },
            { id: '1003', name: 'Getting started with AngularJS', speaker: 'Brij Bhushan Mishra', venue: 'Hall 1', duration: '60' },
            { id: '1004', name: 'Microsoft Azure - Your cloud destination', speaker: 'Gaurav mantri', venue: 'Hall 1', duration: '45' }
        ]);

        // calling service
        TalksServiceFactory.getTalks().then(function (response) {
            talks = response;
        });

        // Flushing httpBackend
        httpBackend.flush();

        // verification
        expect(talks.length).toBe(4);
    });

Above code is self-explanatory. First we are initializing the mock service, calling the service and finally verifying the response. We can configure httpBackend for different scenarios based on usage of $http in actual service.

Custom Filter

Filter is another one of the most used features of AngularJS. Here we are going to use one custom filter that we wrote in one of previous post where we discussed about Custom Filters. So let’s quickly see the Filter first

homeModule.filter('ConvertoPhone', function () {
    return function (item) {
        var temp = ("" + item).replace(/\D/g, '');
        var temparr = temp.match(/^(\d{3})(\d{3})(\d{4})$/);
        return (!temparr) ? null : "(" + temparr[1] + ") " + temparr[2] + "-" + temparr[3];
    };
});

Note – In this series of posts on AngularJS, I have written following posts where we discussed about Filters and writing custom one. To learn more about it, you can refer the following links

Now to write unit test, we need to inject the $filter and then instantiate our custom filter in the init test. Let’s see our unit test

describe("Filter Tests ->;", function () {

    var filter;
    beforeEach(module('homeModule'));

    beforeEach(inject(function (_$filter_) {
        filter = _$filter_;
    }));

    it('if the number formatted', function () {
        var phoneFilter = filter('ConvertoPhone');

       expect(phoneFilter('1234567891')).toEqual('(123) 456-7891');
    });

});

Custom Directive

Directives are again one of the most important components for AngularJS. Writing Custom Directive is a complex task because it is not just another function which can be injected and called from anywhere. Custom Directives are declaratively used in HTML. As it directly changes the view and also designed in a way to be reused at different views, provided the scope is properly isolated based on requirement, these should be properly tested.

We are going to write two Custom Directives : First would be a simple one and another using isolate scope and we will write unit test for both the cases. First directive is an element directive which reads some information from scope and replaces the directive with the provide html in directive as

homeModule.directive('myelementdirective', function () {
    var directive = {};
    directive.restrict = 'E'; //restrict this directive to elements
    directive.template = "Hello {{name}} !! Welcome to this Angular App";
    return directive;
});

Note – In this series of posts on AngularJS, I have written following posts where we discussed about writing custom directives. To learn more about it, you can refer the following links

Writing Unit Test

Writing unit test is tricky for directives because every custom directive is first complied which renders the html then other actions like binding, any user actions are performed. There is a digest cycle which runs and responsible for any binding or any other initialization before a directive appears on page.  So when writing unit test we ourself need to compile the directive using compile service and create a specific scope if required. Then run the digest cycle to make it in similar state as on UI. For that we need to initialize the scope, compile service by injecting it using beforeEach. Now let’s see our test

 var compileService, rootScope;
       
    beforeEach(module('homeModule'));

    // Store references to $compile and $rootScope so they can
    // be uses in all tests in this describe block
    beforeEach(inject(function (_$compile_, _$rootScope_) {
        compileService = _$compile_;
        rootScope = _$rootScope_;
        rootScope.talk = {
            name: 'abc', duration: '25m'
        };
        rootScope.name = 'Brij' ;
    }))

    it('My element Custom Directive defined', function () {

        var compiledDirective = compileService(angular.element('<myelementdirective/>'))(rootScope);

        rootScope.$digest();

        expect(compiledDirective).toBeDefined();

    });

Here we are compiling the directive and running the digest cycle and checking whether it is defines. Then we can write another test which checks whether the correct html is rendered or not as


    it('My element Custom Directive renders proper html', function () {

        var compiledDirective = compileService(angular.element('<myelementdirective/>'))(rootScope);

        rootScope.$digest();

        expect(compiledDirective.html()).toContain("Hello Brij !! Welcome to this Angular App");
    });
Angular App");
    });

Testing Custom Directive with isolated scope

Now we are going to write another directive with isolate scope. If you know or referred my previous post then we find that three types of isolated scope are available in Custom Directives which is also known as Local scope properties. We are going to write two way binding scope where the data is always in sync with parent regardless where it is getting changed. So let’s see the custom directive first


homeModule.directive('bindcustomdirective', function () {
    var directive = {
        restrict: 'E', // restrict this directive to elements
        scope: { talkinfo: '=' },
        template: "<input type='text' ng-model='talkinfo.name'/>" +
            "


<div>{{talkinfo.name}} : {{talkinfo.duration}}</div>



",
    };
    return directive;
});

Here talkinfo gets initialize with the scope passed via an attribute while using Directive as

 <bindcustomdirective talkdetails="talk" />

As in the template, we have input which allows to change the scope object, this reflects in the parent scope as well.

Writing Unit Test

To write the unit test, most of things would be same as above like initialization of compiler service, scope and assign some initial value to talk object in parent scope. So lets move to the test itself

 it('Bind Custom Directive defined', function () {

    var compiledDirective = compileService(angular.element(' <bindcustomdirective talkinfo="talk" />'))(rootScope);

    rootScope.$digest();

    var isolatedScope = compiledDirective.isolateScope();

    expect(isolatedScope.talkinfo).toBeDefined();
});

Here we got the compiled directive using compiler service and run the digest cycle same as earlier one. One extra line added to get the isolate scope from the compiled directive and checking whether talkInfo is defined.

We will write another test and here we will check that if we change the isolated object’s property whether that get reflected in parent scope or not as

it('Bind Custom Directive two way binding check', function () {
    var compiledDirective = compileService(angular.element(' <bindcustomdirective talkinfo="talk" />'))(rootScope);

    rootScope.$digest();

    compiledDirective.isolateScope().talkinfo.name = "Building modern web apps with ASP.NET2";

    expect(rootScope.talk.name).toEqual("Building modern web apps with ASP.NET2");
});

Conclusion

We have written the unit tests few very important components of AngularJS. Although many more test could be written and even these components vary based on requirement, accordingly different unit test may be required. But in this post, I tried to provide the basics of writing unit test for these test. Do share your feedback or face any difficulty for writing unit test for any specific component. I will try to answer that.

Cheers,
Brij

Next Post ==>