ClientSide – Suraj | Coding Passion Tue, 09 Oct 2018 07:03:49 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.8 Unobstrusive ajax and handle unauthorized request in MVC /unobstrusive-ajax-and-handle-unauthorized-request-in-mvc/ /unobstrusive-ajax-and-handle-unauthorized-request-in-mvc/#respond Tue, 05 Apr 2016 10:18:26 +0000 /?p=580 Introduction

In this article I will be sharing a basic stuff which comes handy in MVC applications. The HTML helpers provided by the Razor are smart enough to understand and process the work as required.
We will be discussing in brief about the Ajax.BeginForm, which has few concepts hidden within. When we face the difficulty or the issue, we explore and resolve. Same has happened recently with me. So lets start exploring what the hidden secrets are, which actually are very few.

Adding Unobstrusive- Ajax JS

This can be added from the Nuget package manager directly. I find adding from the Package Manager console easy. The script goes like below:

Install-Package jQuery.Ajax.Unobtrusive

Snippet & Learning

AjaxExtensions.BeginForm is a part of System.Web.Mvc.Ajax namespace under the System.Web.MVC assembly. When used in the response it writes the HTML

tag. Ajax, as we know is Asynchronous Javascript and XML, the word asynchronous plays the trick actually. That means the call will be done asynchronously in some other thread, without hampering or halting the current executing thread for better user experience and performance. Thus, the ajax call we used to write through jQuery, can be done by the MVC HTML helpers now.
One important point to remember here is we need to have the unobstrusive-ajax.js file in order for the Ajax.BeginForm to work in the actual manner.
The Ajax.BeginForm has three options attached to it.
@using (Ajax.BeginForm("ACTION", "CONTROLLER", new AjaxOptions { UpdateTargetId = "TARGETID" ,OnSuccess="PostSuccess"}))
{
   <div id="TARGETID"></div>
   // Do anything you would like to.
}

Lets understand the properties it possesses.
The first param to the Ajax.BeginForm is Action Method, the action to which we will be posting or getting the results.
The second param is Controller, the route controller in which the Action Method is specified. The route table in turn configures accordingly.
The third is the important property of the Ajax.BeginForm as it gives us the different options in order to track and show the response, even manipulate the response as well.

  • UpdateTargetId:- This property is used to track the ‘id’ where the ajax response will be displayed.
  • OnSuccess, OnFailure, OnComplete, OnBegin:- The second part of the option is the track functions. We can use the the functions to track the event and update the UI accordingly. The methods are self explanatory so, I not being stupid to explain the same. πŸ˜›
  • HttpMethod:- This again is self explanatory, it allows the POST GET to be specified explicitly.
  • AllowCache:- This method in ajax allows to either cache the response or not. By default it caches the identical request’s response. So to avoid any kind of caching, we can use the Attribute [OutputCache(NoStore = true, Duration = 0, VaryByParam = “*”)]

These were few of the important properties discussed, which are frequently used.
Now another issue we face is when we have a session ended for any user, but the user is still on the web page, then we find that the login page loads in the partial part of the page only, not the whole page is reloaded to the Login page, which is really weird from any user point of view. This can easily be done and accomplished by changing the UpdateTargetId to the body or supplying any id to the body tag.
But sometimes we have to handle the unauthorized access from the user during any ajax calls. So, incase (everytime now in MVC projects Authorize attribute and its virtual methods are overridden), inside the Custom Authorize attribute, we modify/override the HandleUnauthorizedRequest and handle the Ajax calls that are unauthorized. The code goes below:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { redirectTo = FormsAuthentication.LoginUrl }
                };
            }
            else
            {
                base.HandleUnauthorizedRequest(filterContext);
            }
        }

filterContext.HttpContext.Request.IsAjaxRequest() is doing the trick here, tracking whether the request coming from the client is Ajax request or the normal request.
redirectTo = FormsAuthentication.LoginUrl This takes the default login URL from the app settings in Web.config file. Thus now the result of the context will be present in the current context and can be tracked by the Onsuccess method. The code can be seen below:

function PostSuccess(result) {
    if (result.redirectTo) {
        window.location.href = result.redirectTo;
    }
}

This is a simple part, we can also do the same tracking the reference of the result context and manipulate.

Conclusion

I tried to cover a basic stuff in the MVC application, which we use frequently in our application, sometimes scratch our head to get a proper understanding and solution to a simple problem. I hope this has helped some way. Any suggestions or more interesting facts are more than welcome.
Keep learning and keep sharing.

]]> /unobstrusive-ajax-and-handle-unauthorized-request-in-mvc/feed/ 0 Overview of MVC6 & Deploy application to Azure /overview-of-mvc6-deploy-application-to-azure/ /overview-of-mvc6-deploy-application-to-azure/#respond Sat, 02 Apr 2016 19:04:35 +0000 /?p=558 Introduction

With an anticipation and hope, this article would be an interesting and effective somehow. This article will be covering the Asp.Net 5’s MVC6 Welcome application. a brief about the all new concepts of MVC6 and the new structure it beholds. Then we create our first Welcome application and then have a walk through of the new Azure Portal and deploy our first web application.
Collage

The above image is all that we will be covering in our article.

Get Started

A perfect blend of cloud and web application is what Asp.Net 5 is intended for. Asp.Net 5 is now being called off as .NET core is what that stands out today. It is a framework with open source & cross platform for building cloud based web applications. Here Azure comes integrated to the Visual Studio applications. Web applications either can be deployed to cloud or be running on On-premise. .Net core is available on Visual Studio 2015 build. You can download the community edition of the Visual Studio which is actually free. πŸ™‚
Community Edition Download. Give a try for sure!
.Net 5 core contains a small optimized run time environment called “CoreCLR” One more important point to note is, .Net Core is opensource and the progress can be updated on Github. They have the code exposed and the build can be tracked easily. .Net core is said to contain a set of libraries known as “CoreFx”. Below are the links to the Github. Just have a look:

Another important benefit is termed as “Portability”. What this means is, we can package and deploy the Core CLR which can in turn help you eliminate the dependency on the installed version of .Net framework. Multiple application running on different versions of CLR can be set ups well. This is the magic the team wanted to result out, which is great!
With .NET 5 and VS 2015 comes MVC6 into picture. Microsoft builds are moving faster than the world! πŸ˜€
When I first looked at the structure of the Solution when i added a new MVC project, I was like What!!
thinkzoo
Where is Global.asax.cs? Where is Web.config, App_Start?. Did I download the correct files and selected the correct template. These sort of questions were flickering in my mind. When ran the application it ran successfully as well. Strange!!

Let’s have a small trip into the MVC6

Unified MVC Controllers

MVC6, the merger, the blend of three frameworks, i.e. MVC, Web API2 & Web Pages. Previous versions of MVC, while adding a new template would prompt to check whether we want Web API along with MVC. Here we select the MVC project and we get the opportunity to work with API as well.
In previous versions there were two base controller classes, separate for normal controller and also for the Api controller, i.e. ApiController

public class TestController: Controller {

}

public class ApiTestController ; ApiController {

}

In earlier version as shown above, the controller base class were from System.Web.MVC.Controller and for API, System.Web.Http.ApiController. But in MVC6 it is only one, i.e. Microsoft.AspNet.Mvc.Controller.

Different style of HTML helpers

In MVC6 there comes a new title termed as Tag Helpers. They make life much more simpler. How! We will get to know once we see the code snippet.
For normal web pages, as we know the HTML helpers are defined within the System.Web.WebPages.Html under System.Web.WebPages
, whereas in MVC6, it is under the System.Web.MVC assembly..
The HTML helpers which we used to use in Razor or ASPX, were quite difficult for normal HTML developers to understand (suppose designers). Now i MVC6 that has been simplifies using the Tag Helpers.

@using (Html.BeginForm())
{
        @Html.LabelFor(m =&gt; p.EmpName, "Employee Name:")
        @Html.TextBoxFor(m =&gt; p.EmpName)
        
        <input type="submit" value="Create" />
}

But in MVC6 ,

@model AzureDemoProject.Models.Employee
@addtaghelper "Microsoft.AspNet.Mvc.TagHelpers" 
<form method="post">
<div><label>Employee Name:</label> <input type="text" /></div>
<input type="submit" value="Save" />

</form>

Now the second snippet looks more like HTML friendly and also a bit simple.
Mr. Damian Edwards, has posted the source code on Github which has examples of Tag Helpers. Please go through for better live understanding
Git Hub Tag Helpers Download and play around.

Support for Grunt, NPM & Bower

These are the latest trending front end development tools. These are quite new to me as well, πŸ˜› but will be learning and posting articles on these as well in coming days. Stay tuned!!
Ok branding apart, πŸ˜‰ lets have a brief idea on what these are.
gnpmbower
Bower:-This is a client side item added by default to MVC6 project. If not added, then Right click on the project-> Add->New Item
->Installed(Client Side)-> Bower.json
. You can find then the file is already installed. The file is inside the wwwroot->lib->bootsrap->bower.json. As you open up the file, you can find the client side tool packages added to the project and their versions. Thus, we got to know that the bower is a client side package manager which is used to add the front-end packages like bootstrap, jQuery, angular, etc.
Grunt:-In MVC6 project when we add, we can find the gulpfile.js, this is kind of an alternative to the Grunt as both perform the same kind of functions. The operations they perform is minification, cleaning, concatenation, etc. of both js & css files.
NPM:- Node Package Manager is present under the project with the name project.json. This holds the dependencies and their versions required by the web application we have set up.

"dependencies": {
    "EntityFramework.Commands": "7.0.0-rc1-final",
    "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
    "Microsoft.ApplicationInsights.AspNet": "1.0.0-rc1",
    "Microsoft.AspNet.Authentication.Cookies": "1.0.0-rc1-final",
    "Microsoft.AspNet.Diagnostics.Entity": "7.0.0-rc1-final",
    "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final",
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
    "Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
    "Microsoft.Extensions.CodeGenerators.Mvc": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.FileProviderExtensions" : "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final"
  },
 "scripts": {
    "prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ]
  }

As we can see in the above snippet, which is just a part of the project.json file. This is to show the default dependencies added to the project and the pre publish scripts mentioned. When we suppose add a new dependency, suppose I try and add System.Linq, it will list up the Nuget package as intellisense and then we add the version which also comes under the intellisense. Like below image:
projectjson
Then after hitting Ctrl+S, the restoring of the references packages starts.
restor
Then we see the references added. For more information on the project.json file and its contents, please visit the below link:
Project.json
Integration to Cloud & optimized: This is another major boost feature added to MVC6 application. Now it comes integrated to the cloud with Microsoft Azure and also the optimizing and monitoring tool provided by Azure, i.e. Application Insights.
We will have a walk through of adding the cloud Web application and then a brief on Application insights as well.
Boosted Dependency Injection: Now MVC6 application has in built and integrated dependency injection facility. There is no more need for the packages like, Ninject, Unity, Structure Map3 and all. The code for the configuration setting for the dependency injection is added inside the StartUp.cs class file as below:

// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);

            services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext(options =&gt;
                    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

            services.AddIdentity&lt;ApplicationUser, IdentityRole&gt;()
                .AddEntityFrameworkStores()
                .AddDefaultTokenProviders();

            services.AddMvc();

            // Add application services.
            //Dependency Injection as well
            services.AddTransient&lt;IEmailSender, AuthMessageSender&gt;();
            services.AddTransient&lt;ISmsSender, AuthMessageSender&gt;();
        }

The we normally inject the services into the constructor of the controllers. Is’nt that great!!
appsettings.json: As we know there is no Web.config file in our application, but we need to have a place where we have the settings required by the application at all stages. This is this place. In MVC6, they have had a upper hand over the JSON than the XML. πŸ˜›
The connection strings, the other app settings file we used to add inside the Web.config will now be contained here, that to in Json format. An example like below:

"Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-AzureWebAppDemo-XXXXXXXXXXXXXXXXXXX-XXX;Trusted_Connection=True;MultipleActiveResultSets=true"
    }
  }

global.json: This is a separate folder named Solution Items. here is the global.json file, which contains the solutions’s project references and their dependencies as well. Loos like below:

{
  "projects": [ "src", "test" ],
  "sdk": {
    "version": "1.0.0-rc1-update1"
  }
}

The appsettings is initialized into the project in the Startup.cs file as below:

var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

The App_Start which had the RouteConfig.cs file also goes missing. In MVC is present inside the Startup.cs file as below:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
               app.UseMvc(routes =&gt;
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

Thus, lets have a look at the entry point of the application:

// Entry point for the application.
        public static void Main(string[] args) =&gt; WebApplication.Run(args);

Another nice feature is the segregation of the Models & View Models. The Model now only will deal with the Db Entities and the context, where as the ViewModel will deal with the model classes which are required in the View binding.
This was just a brief about MVC6, more information and application building will be shown in the upcoming articles on MVC6. Now lets jump start the deployment to azure.

done

Head start Deployment

Now lets discuss creating a new MVC6 project from VS 2015 and then deploying to Azure, mostly I will pictorially explain you which will help understand better.

    • Step 1: Create a brand new project from the Visual Studio 2015 templates. Select the cloud directly and then the Web project as we will be deploying our application to azure.
      1
    • Step 2: Then after giving name for the project, another window will prompt which will ask for the Microsoft Azure configurations. Web App Name, which will actually be the URL for the application after hosted on cloud.
      Then asks for the Application Service under which the application will be registered and deployed.
      Region is another important factor which might come handy in the performance of the application. Thus, we select East Asia here.
      If asked for the Database server and the application required we add a new database server or use any existing database. We skip for now the database integration.
      2
    • Step 3: After setting up, we land in creating our first web application and the structure is like below:
      3
    • Step 4: Lets have a look at project structure which gets created.
    • 4
    • Step 5: Lets now publish and deploy our web application. Right click on the project and click ‘Publish’. We then see a window pop up like below:8
    • Step 6: This will now create an Application Service(Webservice) on Azure portal and also deploy our Web Application as a new Website. The status can be seen under Azure Activity :
      10Β 1112
      The above images are the over all status and the name of the publish package that got deployed.
    • Step 7: Then navigate to the Azure portal, already notifications would be highlighted to let you know that web site is now hosted and you can browse.
      15
      The status app type and the app status will update in a few minutes.

    Conclusion

    Thus, once the website is hosted on Azure, we can browse and run our application and share with anyone to navigate through our application. We came to know in this article how easy it is to deploy to cloud in the latest builds, making the lives of developers much easier. I will be sharing and covering the Application Insights in the next article which will follow this up. I hope this has helped in learning some facts about MVC6 and please post your feedback. Application Insights– upcoming. πŸ™‚

    References

    MVC6
    MVC6 Features

    ]]> /overview-of-mvc6-deploy-application-to-azure/feed/ 0 Working with JSON in MVC /working-with-json-in-mvc/ /working-with-json-in-mvc/#respond Fri, 01 Apr 2016 19:05:10 +0000 /?p=547 Introduction

    JSON Java Script Object Notation , a very familiar and commonly used concept. It is a data interchange medium and is very lightweight. It is one kind of a syntax for storing and passing data. Since it is Java script object notation, it uses the java script style of syntax, but actually is text only. It also is language independent. The format would look like below:

    {"Books":[
        {"name":"Asp.Net Mvc", "code":"111"},
        {"name":"Angular Js", "code":"112"},
        {"name":"Javascript", "code":"113"},
        {"name":"CLR", "code":"114"}
    ]}

    Now this, JSON object can be created and used to POST or GET in MVC application. Usually, when we do an ajax call, we get the HTML fragments and send them to the browser or append to any DOM elements. That is acceptable, but sending HTML elements with data is not advisable, so would not that be great to send data in a specific format and the browser assigns the data into the HTML. Here, JSON comes in handy. Lets see how. I will explain in simple terms and snippets for better understanding as this topic is not complex at all.

    Peek into Snippets!!

    I will proceed with an anticipation that readers are aware of MVC (Model, View & Controller), as I will not be sharing the steps to create an MVC project. So, Lets start.
    When we create a controller in an MVC project, we know the default type added is ActionResult, which is generic to other types of method types pre-defined like: ViewResult, JsonResult, etc.. Thus, for returning a JSON data, we can use either ActionResult or JsonResult,but preferably use JsonResult as we already know the type, the method will return. JsonResult, is actually a special ActionResult, which suggests the ViewEngine that an object of JSON type will be returned rather than normal HTML.
    Lets see the snippet and then try and understand.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.MVC;
    using DemoJsonTest.Models;
    
    namespace DemoJsonTest.Controllers {
        public class EmployeeController : Controller {
            private Employee[] employeeData = {
                new Employee {Name:"Suraj Sahoo",EmpCode:"EMP042"},
                new Employee {Name:"Suraj Sharma",EmpCode:"EMP044"},
                new Employee {Name:"Suraj Ray",EmpCode:"EMP041"}
            };
    
        public ActionResult Index() {
            return View();
        }
       
        public JsonResult GetEmployeeDataJson(string empCode) {
            var employee = employeeData.Where(emp =&gt; emp.EmpCode == empCode).SingleOrDefault();
            return Json(employee, JsonRequestBehaviour.AllowGet);
        }

    Thus,in the above code, we have shown a normal controller, in whose constructor we have explicitly initialized a model named Employee with few dummy data. Then the main part is the JsonReult method using which, we are filtering the data based on the parameter passed, here EmpCode and then returning the Json object. Mark here, we have used JsonRequestBehaviour.AllowGet. Now whats this. This has an interesting concept behind it. Usually, the browsers to avoid malicious sites trying to intercept JSON data returned, in response to a GET request, it does not respond to GET requests by default.

    System.InvalidOperationException: This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.

    The above is a part of the error thrown when we miss AllowGet. That is self explanatory actually. πŸ˜›
    We usually us ajax options, i.e. success method to process the JSON data received from the GET request and append or set to the HTML DOM elements.

    <script type="text/javascript">
    $.ajax({
        url: "GET REQUEST URL",
        type:"GET",
        success: function(empData) {
                var trgt = $("#tblEmployee");
                target.append("<tr><td>" + empData.Name + "</td><td>" + empData.EmpCode + "</td></tr>");
            },
        error: function() {
          //Do something..
            }
    
    });
    // ]]></script>

    Thus, in the above snippet, we are fetching the data in JSON format from the GET response and binding to the table html dom.
    A point to note here is that, when we assign/cast (actually) a model into JSON object and we explicitly specify few properties of the model and miss out on others, MVC framework is clever enough to first convert the model with each property into JSON and then assign default values to those properties which we have missed. Lets see an example of conversion:

    { "EmployeeId":0, "Name":"Suraj Sahoo", "EmpCode":"042",
         "IsActiveEmployee": false, "DepartmentId": null }

    Mark here,that we have only specified the values of Name and the EmpCode, all other values assigned after JSON conversion by the MVC smart framework.

    Conclusion

    We saw and discussed a very simple and interesting topic regarding the JSON in MVC and how smartly MVC handles the conversion. This helps when we use API and then return JSON,XML to interchange and expose our data. JSON is actually an alternative to XML form of data exchange. For angular JS now a dayswhich is in demand,we use the API controller, return JSON data and take the advantage of Angular two-way binding.
    I hope this helps the beginners out there learning MVC. This is a part of it. Enjoy coding. Open to suggestions. Don’t miss to add your feedback. πŸ™‚

    ]]>
    /working-with-json-in-mvc/feed/ 0
    Hands on Angular Js-III /hands-on-angular-js-iii/ /hands-on-angular-js-iii/#respond Fri, 25 Mar 2016 09:33:51 +0000 /?p=482 Introduction

    Hello folks!! Lets continue our journey of learning Angular JS. We have seen & discussed few topics already!

    In this article we will discuss few concepts that are very essential to build an MVC project with Angular.
    thinkzooLets see the topics we will be covering in thisΒ article:

    • Angular Model
    • Angular Scopes
    • Angular Services
    • Angular Http
    • Angular Dependency Injection

    Angular Model

    This as the name suggests binds the values to the model associated to an element. This shows a two-way binding, i.e. when the value suppose in the textbox changes, the value for the model also binds and changes. The attribute used is ng-model, the code would be like:

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <div>Name : <input type="text" />
    <h1>Welcome {{name}}</h1>
    </div>

    This will update the value of text entered inside the text box and gets displayed in real time.
    1
    Interesting fact about the ng-model directive is that, the directive watches the model by reference not by value. It also provides validation to the particular field.

    Angular Scopes

    Angular scopes are the execution-context generated during the creation of a controller. We pass the scope object to the controller function. The scope is generally denoted as $scope. This is actually an object to which we add the properties to be accessed in the HTML page using the controller reference.
    As the angular doc rightly says, it is actually the glue between the controller and the view. It comes with two referring API i.e. $watch (used to observe the model mutations) and $apply (used to propagate the changes done to the scope object property) Lets have a glance at the snippet:

    angular.module('scopeTest', []).controller('TestController', function($scope) {
      $scope.username = Suraj;
     });

    This is how the scope object is passed and initialized and assigned properties to be used inside the view.
    Interesting Facts:
    Controller function in Angular is a constructor function. Now what is a constructor function?
    A constructor function in simple terms is when the new keyword is used before a function.

    var constructorFunction = new Funciton(Parameters..);

    Thus everytime a controller is instantiated it gets associated with a new Scope.

    Angular Services

    There are many in-built services provided by the Angular and also we can explicitly create our own services to have a loose coupling while using the Http Get Post services. These are actually singleton functions that are required to perform certain specified tasks. What singleton means is restricting the instantiation to a single object only.
    As in MVC we follow Separation of concern, here also these services can be used to follow the loose coupling and binding.
    2
    As we can see here the reuse of the services can also be followed here. This is done using the injection of dependency into the controller function. We will look into the dependency in the next points.
    Lets see how we declare a service in Angular.

    var module = angular.module('TestApp', []); 
    module.service('TestService', function(){
        this.users = ['Suraj', 'CsharpCorner', 'Angular'];
    });

    Here comes another concept known as Factory, which also behaves as a service function only.

    var module = angular.module('TestApp', []); 
    module.factory('TestFactory', function(){     
        var testFactory = {};     
        testFactory.users = ['Suraj', 'CsharpCorner', 'Angular'];
        return testFactory; 
    });

    The behavior is the same for both service and factory, but the difference is interesting. For the difference, take a closer look at the snippets mentioned above. In the first snippet where we have declared the service and we have added the ‘users’ to the reference of the service i.e. this keyword. Whereas, in the .factory declaration, we have used the testFactory object and assigned property users to it. While using the Services in the injection, we will have the object instance of the service becomes the reference to the methods and can be used in the injection for other controllers or services, while in case of factory, when that is injected, the value is directly provided which is returned by the function within.
    The above discussed are explicit or user-defined services, now lets see the in-built services provided by the Angular. (Some of them)

    • $http:- This is the Http server requesting service, which is one of the most commonly used and important service.
      var app = angular.module('TestApp', []);
      app.controller('TestCtrl', function($scope, $http) {
          $http.get("url").then(function (response) {
              $scope.testData= response.data;
          });
      });

      As we see in the above snippet, the $http service used to make a get request to the URL specified and then the data retrieved is assigned to the scope. As we see the $http is passed into the controller function as an argument. It is recommended to use the $http, server request inside the service as we are in a way interacting with the data. Then the service is injected into the Controller.
    • $interval:- This as the name suggests, is an angular type for window.setInterval
      var app = angular.module('TestApp', []);
      app.controller('TestCtrl', function($scope, $interval) {
          $scope.theTime = new Date().toLocaleTimeString();
          $interval(function () {
              $scope.theTime = new Date().toLocaleTimeString();
          }, 1000);
      }); //reference for use from https://www.w3schools.com/angular/tryit.asp?filename=try_ng_services_interval
    • $location:- Same as above, angular version of window.location.
    • $timeOut:- Same as above, angular version of window.setTimeOut.

    Dependency Injection

    This is an interesting and most debated topic and angular provides this out of the box concept.
    3Β Out of the box.. πŸ˜€
    Dependency is required when we are looking for the loosely coupled codes, i.e. without directly exposing our services. The separation of concern is the major concern when DI comes into picture. Once our service is ready, we can inject to any other service or controller in Angular. The best example would be a Bakery shop. πŸ˜€
    Lets chalk out the plan with a simple snippet:

    var app = angular.module('BakeryApp', []);
     
    app.service('BakeryService', function() {
        //Declare or pass the prices as arg 
        this.Pizza = function(quantity) { return quantity * pizzaPrice };     
        this.Pastries =function(quantity) { return quantity * pastriesPrice };     
        this.Cakes= function(quantity) { return quantity * cakePrice};
    });
    
    //Injected Bakery Service to the 'BakeryCalculateService'
    app.service('BakeryCalculateService', function(BakeryService){     
        this.PizzaPrice = function(qty) { return BakeryService.Pizza(qty); };
        this.CakePrice= function(qty) { return BakeryService.Cakes(qty); };
     
    });
    
    //Injected BakeryCalculateService.
    app.controller('BakeryPriceController', function($scope, BakeryCalculateService) { 
        $scope.CalcPizzaRate= function() {
            $scope.PizzaRate = BakeryCalculateService.PizzaPrice ($scope.quantity);
        } 
        $scope.CalcCakeRate= function() {
            $scope.answer = BakeryCalculateService.CakePrice($scope.quantity);
        }
    });

    We can very well in the above example see the Dependency Injection and the separation of the main service, the layering that is set between the controller and the actual operations. This is very handy during maintenance as well. This is by law which every developer should abide by πŸ˜›

    Do’s & Dont’s

    Another interesting fact when we use the injection is the minification breakage. The angular code breaks when the injection is not done properly when the script files are usually bundled and minified.
    The above Dependency Injection snippet we discussed, will break when the script is minified, bundled & deployed. The reason being, when minification takes place, it re-frames the variable names as ‘a’,’b’,’c’.., thus the parameters injected as $scope,$http will be now treated as a, b. Thus this will break as there is no meaning injecting a b, may it be a controller or a service.
    To avoid that, we usually modify the snippet and use the Angular attribute $inject, wherever Dependency is injected.

    var testController= function(myCtrlScope, $http) {
      //We included $scope and the $http service into our controller.
      }
    testController.$inject = ['$scope', '$http']

    Since we are using $inject attribute on our controller,it would not be an issue using any name of the parameters to it.

    Conclusion

    Thus, we have discussed few interesting concepts this time and work around with live snippets. Still we have not discussed the integration of angular with an MVC app using API. We will discuss in the upcoming articles of the series, before that we will be clear on the basic stuffs that needs to be covered. πŸ™‚
    I hope this article helps. I am always open for corrections and suggestions.
    Lets learn and share together.

    ]]>
    /hands-on-angular-js-iii/feed/ 0