[.NetWorld] CQRS: Command Query Responsibility Segregation Design Pattern

I was recently turned onto the Command Query Responsibility Segregation (CQRS) design pattern by a co-worker. One of the biggest benefits of CQRS is that is aids in implementing distributed, highly scalable system. This notion can be intimidating, but at the heart of CQRS there are rather simple guidelines to follow. Now let’s dive in and explore what this pattern is and some way of implementing it.

Purpose of Command Query Responsibility Segregation (SQRS)

The main purpose of CQRS is to assist in building high performance, scalable systems with large amounts of data.

Derives from Command Query Seperation (CQS)

The basis for the CQRS pattern is the Command Query Separation (CQS) design pattern devised by Bertrand Meyer. The pattern states there should be complete separation between “command” methods that perform actions and “query” methods that return data.

Here’s a really simplistic object oriented example of Command Query Separation in C#:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Simple CQS Example
public class DataStore {
    // Query Method
    public Person GetPerson(int id) {
        // query data storage for specific Person by Id
        // return Person
    }
    // Command Methods
    public void Insert(Person p) {
        // Insert Person into data storage
    }
    public void UpdateName(int id, string name) {
        // Find Person in data storage by Id
        // Update the name for this Person within the data storage
    }
}

The above example has clear separation between the Query method “GetPerson” that retrieves data, and the Command methods that insert or update data.

Adding Responsibility Segregation

Next, CQRS takes “Separation” from CQS and turns it into “Segregation” to completely pull apart the Responsibilities of Command and Query methods to place them in separate contexts.

Here’s a simple example in C# of taking the above CQS example and adding the “Responsibility Segregation” concept to it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Responsibility Segregation Example
public class QueryDataStore {
    public Person GetPerson(int id) {
        // query data storage for specific Person by Id
        // return Person
    }
}
public class CommandDataStore {
    public void Insert(Person p) {
        // Insert Person into data storage
    }
    public void UpdateName(int id, string name) {
        // Find Person in data storage by Id
        // Update the name for this Person within the data storage
    }
}

The seemingly simple change to completely separate Command and Query methods has some fairly big implications on the way you implement the Command and Query methods themselves. By breaking them apart to completely separate contexts, they must be able to function in isolation, completely independent from each other. What this means is that the Command object in the above example must not have a hard dependency on the Query object. If they were to depend on each other, then the design would still be CQS instead of CQRS.

Here’s a simple diagram to help clarify the separation of Command and Query how it pertains to CQRS:

Separate Models for Command and Query

The way CQRS enforces Responsibility Segregation is by requiring there to be separate models used for Command methods than for Query methods. The above responsibility segregation methods example would then be built out so that the Query class and Command class can operate completely independently without either one having dependencies on the other. One of the key principles for this in CQRS is that the pattern is really meant to allow for there to be multiple Query and/or Command classes, each with it’s own methods, that get used when it’s unique circumstance require. For example, there may be a Query class for simple data retrieval with a separate Query class used for a more complex, power user search.

CQRS + Event Sourcing

Event Sourcing is a separate design pattern itself, but it is necessary to integrate with CQRS when building systems that have distributed data along with the requirement of high performance and scalability; as these are the systems that CQRS was really developed for. Event Souring allows the CQRS implementation to have a separate data store (or database) for consistent, stable data with change tracking, while easily maintaining separate data stores (or databases) that have eventual consistency.

Here’s some example breakouts of systems that would benefit from a CQRS plus Event Sourcing architecture:

  1. A system that has the main database used for editing data, and a separate Reporting database that is synced with eventual consistency.
  2. A system that has the main database used for editing, with a separate database used for extremely specific query operations where searching and reporting have their own data models to facilitate higher query performance.

Here’s a simple diagram to help clarify how CQRS can be combined with Event Sourcing:

It is important to remember that Event Sourcing is not a requirement of CQRS unless the system architecture is utilizing distributed data. Event Sourcing gives the system the ability to maintain eventual consistency of the Query models while maintaining the Command model as the source of that consistency. Without Event Sourcing there really isn’t any way to effectively build a system using CQRS and Distributed Data.

Single Database for both Command and Query

Just because you have separate models for Command methods than Query methods doesn’t mean the data can’t be stored and queried in the same place. This is just an implementation detail for you to decide when using the pattern; however, the biggest benefits of CQRS come when using it to maintain completely separate data stores for Writing data (Command) than for Reading data (Query.) CQRS is really meant to be used for building systems with distributed data, and high performance and scalability.

New Paradigm in System Design

There’s a bit of mysticism in the industry as to what CQRS is. Some say it’s a philosophy and not even an architectural pattern. Before writing this article, I read through various different opinions on what CQRS is and how it relates to Event Sourcing. I have come to the conclusion that CQRS is an extremely simple design pattern, just as all design patterns should be. However, the level of abstraction that it facilitates really creates a huge shift in the way that software systems work with data. Instead of designing a single data access layer that utilizes a single, traditional data store, CQRS opens software architecture up to a new paradigm. This new paradigm breaks the software free from the restrictiveness of the vertical, monolithic data store thus allowing for the data store to be built in a similar modular fashion as the way clean code is. CQRS facilitates the storage, retrieval and editing of distributed data.

While the paradigm shift of distributed data is still fairly new to the software industry, it is most definitely the direction that things are moving. The “No SQL” movement of recent years is a testament to the fact that developers and architects abound are discovering the need to more effectively handle large amounts of data in a distributed fashion that allows for much greater flexibility and scalability.

ref: http://pietschsoft.com/post/2014/06/15/CQRS-Command-Query-Responsibility-Segregation-Design-Pattern

[Photograph] Bức ảnh tuyệt đẹp cho thấy khoảnh khắc khi một ngôi sao được sinh ra

IRAS1. Một bức ảnh ghi lại quá trình hình thành của một ngôi sao do kính viễn vọng Hubble mới chụp được gần đây đẹp đến nỗi mà có cảm giác như là nó không thật, trông giống như một bức tranh vẽ hoàn hảo cho các bộ phim khoa học viễn tưởng. Nhưng không có chút gì viễn tưởng ở đây – đó hoàn toàn là khoa học.

Bức ảnh mới từ kính Hubble cho thấy IRAS 14568-6304, một ngôi sao trẻ được choàng bên trong một đám khí gas và bụi màu vàng. Nó xuất hiện giữa vũ trụ đen tối đầy thích thú, với phần đuôi cong và nổi bật lên so với phần khoảng không đen đằng sau.

IRAS 14568-6340 khá đặc biệt vì nó được dẫn dắt bởi một “đám mây bụi tiền sao” (protostellar) xuất hiện trong ảnh như là phần “đuôi” phía sau ngôi sao. Đám mây bụi này là những thứ gồm khí gas và bụi mà IRAS lấy từ đám mây cha mẹ của nó để hình thành. Trong khi hầu hết vật chất để hình thành ngôi sao và phần quầng xung quanh – phần vật chất bao quanh ngôi sao mà một ngày nào đó nó có thể hình thành các hành tinh – tại một vài thời điểm trong quá trình hình thành của ngôi sau bắt đầu phóng ra một số thứ ở tốc độ siêu thanh vào trong vũ trụ. Hiện tượng này không chỉ đẹp mà nó còn cung cấp cho chúng ta những bằng chứng giá trị về quá trình hình thành của một ngôi sao. Mời các bạn cùng xem bức ảnh tuyệt đẹp ở bên dưới.

ref: http://www.tinhte.vn/threads/buc-anh-tuyet-dep-cho-thay-khoanh-khac-khi-mot-ngoi-sao-duoc-sinh-ra.2314397/

[Dev Tip] Set virtual directory in iis express


<site name="Hydra.Insurance.Web" id="126">
<application path="/" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="D:\tfs\Hydra\Dev\TeamA\Hydra\Insurance\Hydra.Insurance.Web" />
<virtualDirectory path="/brands" physicalPath="c:\temp\hydra\branch\brands\" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:49631:localhost" />
</bindings>
</site>

them /brands trong file applicationhost.config

[Dev Tip] Learning {{AngularJS}} with ASP.NET MVC – Part 4


This is fourth part in the series on AngularJS and till now we have discussed some basic components and used those in our examples.The links of my earlier post on this series are

Learning {{AngularJS}} with Examples–Part 1

Learning {{AngularJS}} with Examples–Part 2

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

So what will we be covering today. Let’s see our picture tracker

image

In our earlier posts in the series, we discussed five components. As we see in the above image, in this post, we will discuss services again. Angular services is vast topic but I am discussing the important concepts. One of the important technology that we use in a web applications is AJAX. So in today’s post our focus would that how AngularJS enables us to use AJAX.

In last post, we first created a simple ASP.NET MVC project and displayed data in tabular format. We provided our Angular application, a proper structure and used controller, module and services . In that example, we loaded data while page load. We also discussed that there are two ways to load the data on UI and these are

  1. Get the HTML and data from the server while the page loads itself.
  2. Load the page first, then get the data via an AJAX call and update the page accordingly.

In today’s post, we will be using second approach and see that how can we initiate the Asynchronous AJAX request via AngularJS.

tworequestFor our example, we’ll pick the sample that we created in last post. Please do read last post before continuing. Inn last sample, the data is passed with the view itself which will not be the case here. So let’s make few changes in EventController.cs.

1- Don’t send the data with view. So Index action would look like as

1
2
3
4
public ActionResult Index()
{
        return View();
}

2- Let’s create a repository class (say EventRepository) that returns the data as required. It’ll help us further while scaling up this application. This repository has GetTalks  that returns array of talks as

1
2
3
4
5
6
7
8
9
10
11
public TalkVM[] GetTalks()
{
        var talks = new[]
        {
                new TalkVM { Id= "T001", Name= "Real Time Web Applications with SignalR", Speaker= "Brij Bhushan Mishra", Venue= "Hall 1", Duration= "45m" },
                new TalkVM { Id= "T002", Name= "Power of Node.js", Speaker= "Dhananjay Kumar", Venue= "Hall 2", Duration= "45m" },
                new TalkVM { Id= "T003", Name= "Getting started with AngularJS", Speaker= "Brij Bhushan Mishra", Venue= "Hall 1", Duration= "60m" },
                new TalkVM { Id= "T004", Name= "Microsoft Azure - Your cloud destination", Speaker= "Gaurav", Venue= "Hall 1", Duration= "45m" }
         };
         return talks;
}

3- Let’s change the GetTalks method of controller to GetTalkDetails and mark it as public because we’ll call it using AJAX.  Also change the return type as ActionResult. For that we created an instance of type ContentResult and return that. It internally calls EventRepository to get the talks and convert it to type ContentResult. It looks like

1
2
3
4
5
6
7
8
9
10
11
12
public ActionResult GetTalkDetails()
{
        var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
        var jsonResult = new ContentResult
        {
                Content = JsonConvert.SerializeObject(eventsRepository.GetTalks(), settings),
                ContentType = "application/json"
        };
        return jsonResult;
}

Now we have made changes at server side. We have a method GetTalkDetails that is ready to be called via AJAX.

So let’s move to Index.cshtml. As here we created an Angular Service that just read the data passed to the view. Now we don’t want that so let’s delete it. We’ll still need a service but that will initiate an AJAX call to get the data from the server. So let’s create a new file named EventsService.js.

Here we are going to use two inbuilt angular services. These are

1 $http – As the name suggest, it enable to initiate the AJAX request to the server and get the response. This is a core angular service and uses XMLHTTPRequest. This API can be paired with $q service to handle the request asynchronously. It’s syntax is similar to jQuery ajax if you have used that.

2  $q – This service exposes deferred and promise APIs. Defer API is used to expose the Promise instance. Promise returns the result when the asynchronous request successfully completes. It has also APIs that tells us whether the request got successful or unsuccessful.

We’ll use it in our example. Now it’s time to write the code in Angular service file.

1
2
3
4
5
6
7
8
9
10
11
12
eventModule.factory("EventsService", function ($http, $q) {
    return {
        getTalks: function () {
            // Get the deferred object
            var deferred = $q.defer();
            // Initiates the AJAX call
            $http({ method: 'GET', url: '/events/GetTalkDetails' }).success(deferred.resolve).error(deferred.reject);
            // Returns the promise - Contains result once request completes
            return deferred.promise;
        }
    }
});

In the above code, we are using $http and $q services both. In getTalks, we have created a deferred object using $q . Then used $http services to initiate the asynchronous request to the server to get the data. Based on the request status success anderror callbacks are called. In success callback, we provided deferred.resolve and in case of error, deferred.reject.deferred.resolve resolves the derived promise with its value.

We also need to make changes in our controller.But why do we need to change the controller.?

Because the service method returns the Promise, not the actual value. While accessing the promise, response may not be received. So we cannot directly use it.To handle that, we need to use then, which gets fired once promise is resolved or rejected. It takes two functions as parameter, first gets called in case of success and second is called in case of error. Based on status of promise, it calls success or error one asynchronously. Let’s see the code

1
2
3
4
eventModule.controller("eventController", function ($scope, EventsService) {
    EventsService.getTalks().then(function (talks) { $scope.talks = talks }, function ()
    { alert('error while fetching talks from server') })
});

Now we have our application ready. So let’s run it
result
Great!! This is what we have expected.

Note – $http is a very powerful service and provide lots of features. I have just discussed the basic concept and feature around this.

The example application is attached with the post.

Happy Coding
Brij

[Dev Tip] Learning {{AngularJS}} with ASP.NET MVC – Part 3


This post is third part in the series on AngularJS. In first part, we created a simple Hello World application using AngularJS and in second part, we created a page which displays data in tabular format and used some directives to generate that. We also discussed one of the very important components, Module and provided a proper structure to our application. Please find the link of my earlier posts below

Learning {{AngularJS}} with Examples–Part 1

Learning {{AngularJS}} with Examples–Part 2

Let’s see that in last two post what have we covered and what will we be discussing today.

Structure

So we have covered three components in our earlier posts and will be using two more components in today’s post as in the above image.

In today’s example, we’ll use AngularJS in an ASP.NET MVC application. In our last post, we created a HTML page and initialized the data using ng-init directive. Now let’s think that how can we have the similar application in ASP.NET MVC . In that application, we provided the data at html page itself. In ASP.NET application, we may want to provide the initial data from server while initial load.

So the data can be provided in two ways.

1- Get the HTML and data from the server while the page loads itself.

one request2- Load the page first, then get the data via an ajax call and update the page accordingly.

tworequestSo we’ll take the first scenario,  because in a typical ASP.NET MVC application we provide data to the view via controller and use that model in the cshtml page.

For that I created an ASP.NET MVC empty application and created a Controller named EventsController.cs and it has just an index method. Then I have created an empty view for that.

Now In the view, lets copy the html that we created in our last post where we assigned data in ng-init. As, we don’t want to hard code the data in our view itself and want this to fetch from server. We can easily pass the data with view. Here we need the data in JSON format at client side so while sending the data, we can serialize the data in JSON format and pass it. So my controller looks like

image

Here, I have created a list of talks and converted it in JSON string format using the .NET library and passed it to the view. Here I have hard coded the data but in real implementation, we can get it from database or some web services. Anyways now we can use this data in our view and provide this to ng-init directive. Now my Index.cshtml looks like

image

Here talks is initialized with the model (refer the Red encircled area) and provided in ng-init directive.

I also provided the ng-app directive in _Layout.cshtml in body tag. Now let’s run this.

image

It displays the data as expected. This is a very simple ASP.NET MVC application with AngularJS.

Now let’s move further and convert this application in a structured application, similar to our last post. Let’s first remove the ng-init directive.

Now Let’s copy the module and controller js files. I also put  ng-app=”eventModule” in _Layout.cshtml as

1
<html ng-app="eventModule">

As we have used eventModule on  _Layout.cshtml  we need to include the eventModule.js file in this file itself.

In last post we hardcoded the data in the controller. Currently we have data at View so the next question is, how to pass it to the angular controller. So there could be multiple ways.

1- Create a JavaScript global variable and use that variable in controller. But that is not a good design

2- Another way, we can add a service that returns the data.

As we have data at our view (index.cshtml) so we need to read it from here and send it to controller in one or other way. For that purpose, we can use services and put it on the view only. But before using services, Let’s discuss what is AngularJS Service?

Angular Services are not like any other services which travels over the wire. But it is simple object which does some work for you. In specific words, Angular Services are like a singleton object which does some task for you and can be reused. The main benefits of the services is single responsibility, re-usability and. testability.

AngularJS has many in built services but it also provides us capability to write our own custom services. Once we create a service we need to inject in some controller.

To create a custom service, we’ve have to use another method Factory provided by AngularJS.  The syntax looks like as

1
2
3
4
5
eventModule.factory(“<ServiceName>”, function() {
// Do some task and return data
});

In our example, we have created a service named InitialLoadService  as

image

In the above code, we have created a service name InitialLoadService that has been registered with module using factory method.  This just simply returns the data that is read from the model.

Now we need to use this service. For that we can inject it in our controller (eventController.js) as

image

Here in our controller, we have injected the services (refer Red encircled Area) and read the data from the service.

Now we have created a custom service and injected the service in controller. Let’s run the application

image

Great!! Now we have successfully created an ASP.NET MVC and AngularJS application. It is same as earlier one in this post but here we used different components of AngularJS.

In this post, we learned some UI directives like ng-init, ng-repeat and used controllermodule and services. Sample application is attached with this post. Hope you have enjoyed the post.

Happy Coding
Brij

[Dev Tip] Learning {{AngularJS}} with Examples–Part 2


In the last post , we learnt about the basics of AngularJS and created a simple hello world application. You can refer the link of my earlier post.

Learning {{AngularJS}} with Examples–Part 1

We have discussed the basic components of AngularJS that we used in our last post. As we discussed that AngularJS is a complete framework for writing client side code that allows us to use latest design principles, there are many important components. Let’s see some of the important ones

StructureThere could be few other components and concepts of AngularJS that is not part of the above image but it includes all that we need to learn to built up the foundation on AngularJS. I’ll be discussing all the mentioned components in the series of posts with tons of examplea.

Let me tell you the color coding briefly. The dark blue color shows that we have discussed it that in our last posts. Other two highlighted items will be discussed in today’s post. And items with light blue color will be covered in coming post.

In today’s post, we’ll take a step further and discuss some more concepts of AngularJS. In our example , we’ll provide a structure to our application which is the beauty of AngularJS. In last post, we created a Hello World application,  which used a controller and  ng-app directive  was used to bootstrap the application.

One of the most common tasks in the web applications is,  to show the data the tabular format and angular does kept it in mind. If you’ve worked earlier on some client side templating features then you will find it similar to that. Else also it is very simple and easy to understand. Angular provides a way to repeat the some part of HTML based on the provided list of data. So we can have code like

image

So if we see here the red encircled area then we see ng-repeat directive. It actually repeat the element on which it is used based on the provide list of data . Here talks is an JSON object which contains list of talk. It says for every talk in talks, repeat the tr and evaluate the used expression based on the properties of talk. So if we have four items in the list then four rows will be created.

Now the next question is, how to provide the value to talks. As talks is being accessed here, it should be a global variable or a variable in the scope where it can be accessed. To fetch the data, There could be two ways

1- Initialize the value on the page

2- Or get the data from server/web services etc

Let’s take first scenario, initialize the value the on the page. AngularJS provides us a simple way to initialize using a directive that is called ng-init.

ng-init – This directive provides us a way to initialize a variable on the page. We can initialize the talks as

image

So here, put a div over the table and in div element, we initialized the variable talks using ng-init directive as above. So using this directive, we can provide some initial value to a variable.

I added the angular library on the page. Also I have used bootstrap.css for rendering the not so bad Smilelooking UI. Now let’s run the application.

image

So we have created an angular app. Now before providing it a structure, let’s discuss one very important component of Angular that we’ll use in todays post that is called Module.So, What is Module?

Modules – Modules are like containers . It is a top level element and contains all the part of AngularJS that are used on the page. So let’s see how does it fit into an application

image

Above image is for the basic understanding. It shows an AngularJS application can have multiple modules and every module contains controllers, views etc.

There are many other components which we’ll introduce in coming posts. As we discussed in last post that the main beauty of the an AngularJS application is it’s architecture so let’s restructure the code that we have written and we’ll use another component module in this example.

As now we have controller and module in our application. These should be put in different JavaScript file. So If you are working some enterprise level application which has lots of pages then one need to decide how is (s)he going manage or structure that. There are different views on that I’ll not discuss in detail on that. But In my code, I normally prefer having folders functionality wise, which makes very easy to find any file, add/remove any functionality at any point of time etc.

In this example, I have created a folder named as events . Now I have put all the angular JavaScript files associated to this feature in the same folder. As we discussed that the top level item is module. So lets create an module named aseventModule.

So I have created a file eventModule.js and here I registered this module with angular

1
var eventModule = angular.module("eventModule", []);

Now let’s create a controller named eventController as

image

So here controller also got registered with Module. In this method we initialized the talks in $scope variable which is a default parameter to the controller.

Now let’s move our HTML page and provide the controller name to the element. as..

1
<div class="row" ng-controller="eventController">

Now we have created a module and a controller. Controller is also registered with module and controller is assigned to the  UI element as well. Also we mapped module with angular. What else is left?

How the module that we created will get loaded. In last post, we discussed that when AngularJS loads it looks for the ng-appdirective and this is the place where we need to provide our module as

1
<html ng-app="eventModule">

We need to include all the controller and module JavaScript files to our page that we created. Now, we don’t have any JavaScript code on our page.

Now when we run the page, we get the similar output, that we got initially .Refer third figure from Top.

So in this post, we discussed about some new directive ng-initng-repeat. Then we discussed and new component module and converted the application in properly structured manner.

In next post, we will about ASP.NET MVC and AngularJS and create some examples using both.

Cheers,
Brij

[Dev Tip] Learning {{AngularJS}} with Examples–Part 1


Client side programming is becoming the one of the main parts of web applications. Now a days, We are seeing the explosion of JavaScript libraries. And the reason is that some JavaScript libraries got very popular and developers took them hand to hand because of its cool feature and almost negligible performance cost, Now in our projects,  count of JavaScript files (plugins and custom files) are increasing rapidly which is making it  unmanageable and unmaintainable. AngularJS provides best of the both the worlds and now a days, it is one of the most talked and used JavaScript framework in web applications. So I have thought to start a series of post on AngularJS. I’ll start from basics and gradually discuss all the features, keeping in mind the.NET Developers.  So let us start learning it. The first questions arises that

What is AngulalJS?

AngularJS is not just another JavaScript library but it provides a framework to write a proper architectured, maintainable and testable client side code. Some of the key points are

  • It follows MVC framework. If you don’t have Idea MVC framework, I’ll suggest you to get an Idea of MVC framework and then start learning AngularJS. You can refer below wiki page on MVC framework.
  • AngularJS is primarily aimed to develop SPAs (Single Page Applications), it means your single HTML document turns into application. But it is also used a lot in ASP.NET and other applications .
  • Allows you to write Unit and integration tests for JavaScript code. Testability is one of the main points, which was kept in mind while writing this framework so it has great support of it.
  • It provides it’s own and very rich list of attribute and properties for HTML controls which increases the usability of it exponentially.It is also called directives.
  • Supports two-way binding that means your data model and control’s data will be in sync.
  • Angular supports Dependency injection. Read more about dependency injection on wiki.
  • Angular library is also available on CDN so you just need to the url of the CDN and it available for use.

It is an Open Source

AngularJS is a open source library and developed and supported by Google. Being an open source, you can go through the code itself and customize it if required. There is lot of support from JavaScript community and even you can contribute to it.  Currently, more that 100 contributors have contributed and it is increasing day by day.

So let’s discuss the main components of AngularJS. These are

Controller – It is main component of AngularJS and contains the state and logic both. It acts as bridge between services and views.

Views/Directives –  Here we generate the UI. Directives extends the HTML element and enables us to generate the complex html easily. Controllers talks to view to both directions.

Services – It contains the core logic and state of the application. In it, we can communicate to server to get and post the data.

Now let’s see all the above components glued with each other.

image

Now you have got the basic explanation about the basics of AngularJS. So let’s jump to the coding. We need to learn two things mentioned below before writing the first application

1- {{expression}} – It is called expressions and JavaScript like code can be written inside. It should be used for mainly small operations in HTML page.

2- $scope – This is one of very important variable used in AngularJS. It provides and link between the data and views. It holds all the required data for the views and used with in the HTML template.

3- ng- – All the elements that are provided by angular starts from ng-. So if you see some attribute that ng- and angular library is also included in the page, then you can assume that this should be angular element only.

4- ng-app – This directive is used to bootstrap the application. Normally, it is put at in top level element like html or body tag. (That will be discussed in details in coming post).

Now lets write our first Hello World application with AngularJS. In this example, I’ll be using the basic construct of AngularJS. I have created Empty Project in Visual Studio and added an HTML page Home.html and written it as

NewExample

This is very simple page using AngularJS. I have encircled and numbered the specific part of the page that are relevant with AngularJS. Let’s discuss it one by one.

1- As discussed earlier that this attribute is required to bootstrap the AngularJS application so I have put it in body element. Here I have put it in body element so it AngularJS can be used inside the body tag. In the above application, I could have put it at h1 element as well because I am using AngularJS inside this tag only. The scope can be displayed pictorially as

image

2- Here I have included the angular library on the page using Google cdn.

3 – When ever we want to use the AngularJS , we need a controller. A JavaScript method HelloWorldCtrl is controller here. I appended Ctrl in the name as a naming convention

4- We already discussed what is $scope. This is a parameter in controller method and we can create dynamic properties and assign values to it, which can be later can be accessed in UI element. We can also create the controller in a new JS file that we’ll see in the coming posts.

image

5- Here we created a new property helloWorldMessage to $scope variable and assigns the message.

6- Now it’s time to use the controller. The controller can be defined over an element as ng-controller=<controller> given in the image as well.

7- Now we see the expression here. As we provided the controller in this element and we can access the property that we defined in the controller that we have used here.

Now it’s to run the application.

runningapp

We can see the message with date and time that we have provided.  Our page got rendered as per expectation. Now Let’s discuss the flow of the angular page. It can be depicted pictorially as

 

AngularFlow-New

 

So the above picture clearly illustrates that How does the flow of Angular page work at high level.

So In this post  we created a very simple page which has all the code on the same HTML page. In the next post, we’ll learn more concept and write a more detailed page and provide a better structure to the application.

Sample is attached with the application.

Hope you have enjoyed the post and will connect you again in next post.

Cheers,
Brij