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

 

Advertisements

Leveraging the Power of Asynchrony in ASP.NET

Asynchronous programming has had a lot of attention in the last couple of years and there are two key reasons for this: First it helps in providing a better user experience by not blocking the UI thread which avoids the hanging of the UI screen until the processing is done and second, it helps in scaling up the system drastically without adding any extra hardware.

But writing asynchronous code and managing the thread gracefully was a tedious task. But as the benefits are tremendous.. Read complete post on Infragistics blog

User Name availability check with AngularJS, ASP.NET MVC and ASP.NET Web API


User Name availability check is required in most of the registration forms where we allow user to choose a user name that one can use to login later. In some other scenarios, we allow user to use his/her email as login id/user name. In both the scenarios, we require to make sure that user name or email is not used earlier. In this post, I am going to discuss, how to achieve this feature in an application which is developed using AngularJS, ASP.NET MVC and ASP.NET Web API. I wont discuss in detail the Data Access part, where one can use any approach like Entity Framework, Identity Framework , Membership provider or ADO.NET.

In this post, we will create an empty ASP.NET project with MVC and Web API. We’ll start working on Web API  part where an API will be exposed which will take user’s entry for user name as input and return true and false based on its existence. After that we will work on MVC part where we will create a registration form where user will put its information. In last, we will focus on AngularJS and create the basic infrastructure including a Service which will call the Web API to check the user name existence then how will do the check on view we will discuss at later section.

I created an API folder under Controller and created an empty Web API controller (RegistrationController) which exposed an API IsUserNameAvailable which takes an username and returns true if available else returns false. It is as

  [RoutePrefix("api/Register")]
    public class RegistrationController : ApiController
    {
        [Route("IsUserNameAvailable")]
        [HttpGet]
        public bool IsUserNameAvailable(string userName)
        {
            IRepository rep = new SQLRepository();
            IList<UserAccount> users = rep.GetUser(userName);
            return users.Count == 0;
        }
    }

 

Inside the API, I have used a SQLRepository which connects to the database and returns a list of users based on it. If there is no match then list contains no items. Let’s have a look that our table in database form where the account is getting matched.

table

Now let’s just quickly check that whether our API is working properly. The simplest way to check any API Get request via browsing the URL itself. So let’s check the URL

http://localhost:4077/api/Register/IsUserNameAvailable?userName=Brij

So as we see that Brij exists in the database so it returns false.

WebAPIResult

Now let’s create an empty MVC controller (UserRegistrationController) and View for the Index action which has an input control to enter the username.

Now its time to introduce the AngularJS into the application. Let’s see that what all the AngularJS components we need to create to implement the feature.

  1. Angular Module – To bootstrap the application.
  2. Service – This service will connect to exposed Web API to check the user name availability. It will initiate the AJAX (http) call and get the appropriate response accordingly.
  3. Angular Controller- To add some logic
  4. Custom Directive – We will discuss it in later section

I have created a new folder Registration in scripts folder to put all the angular resources. I created an angular module (file name as RegModule) which has currently

var registrationModule = angular.module('registrationModule', []);

Now it time create a service which will connect to the server to check the user availability and return true or false accordingly. I am using Factory method for creating service as

registrationModule.factory("RegService", function ($http, $q) {
    return {
        IsUserNameAvailablle: function (userName) {
            // Get the deferred object
            var deferred = $q.defer();
            // Initiates the AJAX call
            $http({ method: 'GET', url: 'api/Register/IsUserNameAvailable?userName=' + userName }).success(deferred.resolve).error(deferred.reject);
            // Returns the promise - Contains result once request completes
            return deferred.promise;
        }
    }
});

Now to handle the UI part, we have two options

1- Either we do all the UI manipulation using Angular controller and add the required code. Or

2- We can create an custom directive where all the logic will be put to check the uniqueness of the username and updating the UI.

Lets quickly see first option, where we will write the logic in Angular Controller  as

    $scope.checkUserAvailable = function () {
        RegService.IsUserNameAvailablle($scope.Registation.username).then(function (userstatus) {
            $scope.registrationForm.username.$setValidity('unique', userstatus);
        }, function () {
            alert('error while checking user from server');
        });
    };

Here we are using $setValidity of for the model and add the unique attribute and set it true/false based on the service response. This will set the validity of the input as true/false and we can show some messages based on that. So let’s see the form


<div class="container" ng-app="registrationModule">

<div class="row" ng-controller="regController">

<form name="registrationForm" role="form">
            <label for="username">User Name:</label>

<div class="form-group">
                <input type="text" name="username" id="username" ng-model="Registation.username" class="form-control" placeholder="Username" ng-blur="checkUserAvailable()" />
                <span class="alert alert-danger" ng-show="registrationForm.username.$dirty && registrationForm.username.$error.unique">
                    User name is not available
                </span>
            </div>

        </form>

    </div>

</div>

We are calling checkUserAvailable function in blur event so that it gets fired when user moves focus from the control after entering the data. We also added a span (p) to show the error message which checks the input control state and unique attribute that we added. Now let’s run the application and see

sample

As Brij is already exists in the database so it is not available and if you enter any other username which is not available in database, it wont show the message.

Second option is much cleaner so we will create a custom directive (I have written 19 posts on AngularJS, you can go here to learn all the topics or for custom directives refer the Part -9 and Part -10)

So let’s create our custom directive. Here it will use the RegService and add an onblur event to the input which will be fired once user goes out of the control after entering the some data as

registrationModule.directive('useravail', ['RegService', function (RegService) {
    var directive = {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            element.on('blur', function (evt) {
         
                if (!ngModel || !element.val()) return;
                var curValue = element.val();

                RegService.IsUserNameAvailablle(curValue)
                .then(function (response) {
                        ngModel.$setValidity('unique', response);
                }, function () {
                    //If there is an error while executing AJAX
                    ngModel.$setValidity('unique', true);
                });
            });
        }
    }
    return directive;
}]);

Here we have used similar code that we wrote in angular controller. Here we added blur event to the input control in directive. So let’s see the form


<div class="container" ng-app="registrationModule">

<div class="row">

<form name="registrationForm" role="form">
            <label for="username">User Name:</label>

<div class="form-group">
                <input type="text" name="username" id="username" ng-model="Registation.username" class="form-control" placeholder="Username" useravail />
               // later code is same as first option so removed forbrevity

We have set the ng-model and added our custom directive useravail as an attribute at the end in the input element. When we will run this application, it will have same as first option.
So we have implemented User name check using AngularJS, ASP.NET MVC and Web API. We can change the look n feel based on our need. Complete code is attached with this post.

Cheers
Brij

12 tips to increase the performance of ASP.NET application drastically – Part 2

This post is second part of my previous post where we discussed six tips to improve the performance of ASP.NET applications. In this post, we are going to discuss six more tips that could be another round a booster for your application performance. The link of previous post is below.

12 tips to increase the performance of ASP.NET application drastically – Part 1

  1.   Make your page asynchronous

IIS uses CLR thread pool to get a thread that processes a request that comes to the application. Say, if there are currently twenty threads available in pool, it means only twenty request can be served in parallel and if request processing takes some time then it could turn into disaster if hundred odd request are bombarded in few milliseconds. In this case…Read complete post on Infragistics blog

12 tips to increase the performance of ASP.NET application drastically – Part 1

Building web application and hosting it on a web server is insanely easy with ASP.NET and IIS. But there are lots of opportunities and hidden configurations which can be tweaked that can make it high performance web application. In this series post, we are going to discuss some of the most unused or ignored tricks which can be easily applied to any web application.

  1. Kernel mode cache – It is one of the primary tools widely used for writing making web application faster. But most of the times, we don’t use it optimally and just leave some major benefits. As each asp.net request goes through various stages, we can implement caching at various level as belowcachingoppWe can see that request is first received by http.sys so if it is cached at kernel level, then we can save most of the time spent on server as http.sys is a http listener which sits in OS kernel…Read complete post on Infragistics blog

Master Page, User Control, Custom Control and Content page : Order of page life cycle event

As we all know that while serving an asp.net request goes through many stages before it gets served. One of the important stages is, going through the page life cycle events. As a page can contain many other controls like User Control, Custom control etc and it can be a combination of master and content pages as well. As each control has its own life cycle so if they are inter weaved then it becomes very important to understand that how each event fits in complete lifecycle . Also this is one of the most asked question in asp.net interviews so I thought of explaining it.

Technically, Master page is nothing but a normal user control so you can treat it as user control used on a page and we will consider it same in our post. So we can say that there are two type of controls – User Control and Custom Control in a page. Content page is also nothing but a normal aspx page. Now to understand the order of events where all of these controls are available, lets first understand of the life cycle of each components individually.

Order

Note- I have not included all the events of life cycle only those are relevant at important to explain the topic. Continue reading

Concurrency vs Multi-threading vs Asynchronous Programming : Explained

Recently, I was speaking in an event and I asked a question about Asynchronous programming to the audience, I found that many were confused between multi-threading and asynchronous programming and for few, it was same. So, I thought of explaining these terms including an additional term Concurrency. Here, there are two completely different concepts involved, First – Synchronous and Asynchronous programming model and second – Single threaded and multi-threaded environments. Each programming model (Synchronous and Asynchronous) can run in single threaded and multi-threaded environment. Let’s discuss each in detail.

Synchronous Programming model – In this programming model, A thread is assigned to one task and starts working on it. Once the task completes then it is available for the next task. In this model, it cannot leave the executing task in mid to take up another task. Let’s discuss how this model works in single and multi-threaded environments.

Single Threaded – If we have couple of tasks to be worked on and the current system provides just a single thread, then tasks are assigned to the thread one by one. It can be pictorially depicted as

singlethreadedHere we can see that we have a thread (Thread 1 ) and four tasks to be completed. Thread starts workingon the tasks one by one and completes all. (The order in which tasks will be taken up, does not affect the execution, we can have different algorithm which can define the priorities of tasks)

Continue reading