Lets Have a fun with Technology.

BTemplates.com

Follow by Email

Friday, September 9, 2016

npm install command fails in Angular2


Hello,

Recently I am working on Angular2 application.

My Client provided application. I have to extend the functionality. I have to run npm install. In my machine I have new environment. I have to run "npm install" command in node.js command prompt. But it's fail every time.

I have double check the version and lots other thing but didn't work.

Then I have run below command which set the registry. And after setting this registry "npm install" works successfully.

Command is

npm set registry https://registry.npmjs.org/


Please don't forgot to comment if this article help you.


Saturday, August 27, 2016

How to Run Angular2 Application in local environment.


Hello,

Below steps need to follow to run Angular2 Application on local machine.

1. First Install node.js from below location.
    https://nodejs.org/en/download/

2. You will see below installed command prompt in your system
    
    



3.  Now we are going to install web server. Run below command in  nodejs command prompt.

    npm install live-server -g

    We will use live-server package. This server written in Node, update the        
    package automatic when changes the source code.

4.  Now we install typescript. Typescript is languae which used to write angular 
     2 application. 

    npm install typescript

5.  I am using Visual studio code as a editor. Install it from below location.
     https://code.visualstudio.com/Download

6. Now you can run your first application. Below is sample application which I         have created. 

     


I know above screen shot is not enough for first example. We will see details code of First Example later. Here I have only shown How to run Angular 2 application.

Let me know if you have query.


Sunday, July 17, 2016

How to do paging in AngularJS


The paging is most usefull feature of web appliation.

Below is code block to achive Paging in AngularJS.


<html ng-app="todos"/>

<head>
  <link data-require="bootstrap-css@3.3.4" data-semver="3.3.4" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"></link>
  <script data-require="angular.js@1.3.15" data-semver="1.3.15" src="http://code.angularjs.org/1.3.15/angular.min.js"></script>
  <script data-require="angular-ui-bootstrap@0.12.1" data-semver="0.12.1" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.1.min.js"></script>
  <link href="style.css" rel="stylesheet"></link>
  <script src="script.js"></script>
</head>

<body ng-controller="TodoController">
  <h1>
Todos</h1>
<h4>
{{todos.length}} remain</h4>
<ul>
<li ng-repeat="todo in filteredTodos">{{todo.text}}</li>
</ul>
<pagination boundary-links="true" class="pagination-sm" max-size="maxSize" ng-model="currentPage" total-items="todos.length">
  </pagination>
</body>


Running Example

Tuesday, June 28, 2016

Call Web API From AngularJS


WebAPI support below HTTP verbs

POST, GET, PUT, DELETE, PATCH.

Lets make a sample application on that we pass some data from AngularJS to Web API and retrieve some data from Web API to AngularJS.


Create a Web API with simple steps.

Select Empty Project template. You can also select Web API templates.



Create a Model School class. In this class, define some property of the school.



Now, in controller folder, create a SchoolController. In this controller, define two methods, Get and Post.


You can give any name, but you have to use HTTP verbs over the method name.


Now, our WEB API is ready. To check if Web API is working or not, just run the solution.



We can see the Get method that returns proper data. So our Web API development is done.

Now, we have to create a HTML page with the help of AngularJS. Through this page, we pass the data and retrieve the data.

So, let's start doing the coding of our HTML page.

I am creating two folders- UI and scripts. In UI folder, I kept all my HTML pages and in Scripts Folder, all JS Files.


Create a School.html page and in this page, take reference of Angular.js file and my script file and two buttons, where one is for Get and another for Post.



Now, we have to do Angular coding.

Create a module and a controller. In the controller, we inject $http service, which is used to pass and retrieve the data from Web API. In this controller, we will create two functions, getData and postData.

It will look  as shown below:




Run the solution and when we click on Get Button, the data comes from Web API and binds  to all the text boxes.




When we give some value to text box and click Post button, the controller data shows:


In SchoolController, the data is being displayed as:








Monday, May 30, 2016

ui-router Benefits (ui-router advantage)


ui-router Benefits (ui-router advantage)

ui-router is a 3rd-party module and is very powerful. 
It supports everything the normal ngRoute can do as well as many extra functions.

Here are some common reason ui-router is chosen over ngRoute:

1. ui-router allows for nested views and multiple named views. This is very useful with larger app where you may have pages that inherit from other sections.

2. ui-router allows for you to have strong-type linking between states based on state names. Change the url in one place will update every link to that state when you build your links with ui-sref. Very useful for larger projects where URLs might change.

3. There is also the concept of the decorator which could be used to allow your routes to be dynamically created based on the URL that is trying to be accessed. This could mean that you will not need to specify all of your routes before hand.

4. states allow you to map and access different information about different states and you can easily pass information between states via $stateParams.

5. You can easily determine if you are in a state or parent of a state to adjust UI element (highlighting the navigation of the current state) within your templates via $state provided by ui-router which you can expose via setting it in $rootScope on run.
In essence, ui-router is ngRouter with more features, under the sheets it is quite different. These additional features are very useful for larger applications.

Below is more information details.

Github: https://github.com/angular-ui/ui-router
Documentation:
API Reference: http://angular-ui.github.io/ui-router/site/#/api
Guide: https://github.com/angular-ui/ui-router/wiki
FAQs: https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions
Sample Application: http://angular-ui.github.io/ui-router/sample/#/

Thursday, May 26, 2016

AngularJS Interview Question -2


What are expressions in AngularJS?

Angular expressions are unit of code which resolves to value. This code is written inside curly braces “{“.


AngularJS expressions are much like JavaScript expressions: They can contain literals, operators, and variables.






Example {{ 5 + 5 }} or {{ firstName + " " + lastName }}
<div ng-app="">
  <p>My first expression: {{ 5 + 5 }}</p>
</div>


The below expression displays a controller scoped variable.



<div ng-controller="CustomerVM">
The value of Customer code is {{CustomerCode}} 
</div>

Difference between AngularJS Expressions and JavaScript Expressions


Like JavaScript expressions, AngularJS expressions can contain literals, operators, and variables.


Unlike JavaScript expressions, AngularJS expressions can be written inside HTML.


AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript expressions do.


AngularJS expressions support filters, while JavaScript expressions do not.



What is the digest cycle, watchers and dirty checking?

Digest cycle: - It is a simple loop which updates the model and view.
Watchers :- They are listeners which are attached to expression and angular directives and fire when the model data changes.
Dirty check :- This is a extra digest loop which runs to check any cascading left over updates due to the first digest cycle.

Lets look in details.


Angular is a MVW framework. It helps us to bind the model and the view. 

In other words when any change happens in the model the view gets updated. 
This updation of the model and the view is done by a loop called as digest cycle.
Digest cycle follows four important steps:-

Step 1:- Some kind of event is triggered by the end user like typing (onchange), button click etc and due to this activity model value changes.

Step 2:- Angular first checks if the new value and old values are same. If they are same he does not do anything. If they are not it then it invokes the digest cycle.
Step 3:- Digest cycle then runs through the scope objects to check which objects are getting affected because of this change. Every object in the scope have watchers. Watchers as the name says it listens whether the model has changed or not. Digest cycle informs the watchers about the model change and then watchers synchronize the view with the model data.
Step 4 :- In step 3 watchers update the view and due that update its very much possible that the model changes again. Now due to this model change we have to reevaulate the view again. So the digest loop runs once again to ensure that all things are synched up. This second loop which runs is termed as dirty check loop.
Below is the figure where in we have highlighted all the four steps.






How do you reset a “$timeout”, and disable a “$watch()”?

The key to both is assigning the result of the function to a variable.

To cleanup the timeout, just “.cancel()” it:




var customTimeout = $timeout(function () {
  // arbitrary code
}, 55);
$timeout.cancel(customTimeout);

The same applies to “$interval()”.


To disable a watch, just call it.




// .$watch() returns a deregistration function that we store to a variable
var deregisterWatchFn = $rootScope.$watch(‘someGloballyAvailableProperty’, function (newVal) {
  if (newVal) {
    // we invoke that deregistration function, to disable the watch
    deregisterWatchFn();
    ...
  }
});


List at least three ways to communicate between modules of your application using core AngularJS functionality.


Common ways to communicate between modules of your application using core AngularJS functionality include:


Using services

Using events
By assigning models on $rootScope
Directly between controllers, using $parent, $$childHead, $$nextSibling, etc.
Directly between controllers, using ControllerAs, or other forms of inheritance



Do I need Jquery for AngularJS?
No , you do not need Jquery for Angular. It’s independent of Jquery.

How is the data binding in AngularJS ?

Its two way binding. So whenever you make changes in one entity the other entity also gets updated.

Mention what are the styling form that ngModel adds to CSS classes ?


ngModel adds these CSS classes to allow styling of form as well as control

ng- valid
ng- invalid
ng-pristine
ng-dirty

Difference between angular-route and angular-ui-router
See below description

Explain AngularJS boot process.

When the page is loaded in the browser, following things happen:

• HTML document is loaded into the browser, and evaluated by the browser. AngularJS JavaScript file is loaded; the angular global object is created. Next, JavaScript which registers controller functions is executed.

• Next AngularJS scans through the HTML to look for AngularJS apps and views. Once view is located, it connects that view to the corresponding controller function.

• Next, AngularJS executes the controller functions. It then renders the views with data from the model populated by the controller. The page gets ready.



AngularJS Interview Question        


AngularJS Interview Question -1


What is the Singl Page Application (SPA)
Single Page Application is one in which we have a shell page and we can load multiple views into that.
Traditional application, as you know you typically blink and load everything again. It’s not very efficient on the bandwidth, especially in the mobile world.

In a SPA we can load the initial content upfront and then the different views or the little kind of miniweb pages can be loaded on the fly and embedded into the shell.



What is AngularJS?

AngularJS is a javascript framework used for creating single web page applications. 
AngularJS is a structural framework for dynamic web apps. 
It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly. 
Angular's data binding and dependency injection eliminate much of the code you would otherwise have to write.

Explain Directives in AngularJS

Directives are attributes decorated on the HTML elements. All directives start with the word “ng”. As the name says directive it directs Angular what to do.

For example below is a simple “ng-model” directive which tells angular that the HTML textbox 

“txtAgentName” has to be binded with the “AgentName” property.

<input type=text id="txtAgentName"  ng-model="AgentName"/>


Some of the most commonly used directives are ng-app,ng-controller and ng-repeat.


List out Main Features of AngularJS.



  1.   Data-binding It is the automatic synchronization of data between        model and view components.
  2.   Scope  These are objects that refer to the model. They act as a glue between controller and view
  3.   Services AngularJS come with several built-in services for example $http to make a XMLHttpRequests. These are singleton objects which are instantiated only once in app.
  4.   Controller These are JavaScript functions that are bound to a particular scope.
  5.   Filters These select a subset of items from an array and returns a new array.
  6.   Directives Directives are markers on DOM elements (such as elements, attributes, css,and more). These can be used to create custom HTML tags that serve as new,custom widgets.AngularJS has built-in directives (ngBind, ngModel...)
  7.   Templates These are the rendered view with information from the controller and model.These can be a single file (like index.html) or multiple views in one page using "partials"
  8.   Routing  It is concept of switching views.
  9.   Deep Linking Deep linking allows you to encode the state of application in the URL so that it can be bookmarked. The application can then be restored from the URL to the same state.
  10.   Dependency Injection AngularJS has a built-in dependency injection subsystem that helps the developer by making the application easier to develop, understand, and test






What are controllers and need of ng-controller and ng-model in AngularJS?
Controllers are simple javascript function which provides data and logic to HTML UI.
As the name says controller they control how data flows from the server to HTML UI.

For example below is simple “Customer” controller which provides data via “CustomerName” and “CustomerCode” property 

and Add/ Update logic to save the data to database.



function Customer($scope)

{

        $scope.CustomerName = "Shiv";

        $scope.CustomerCode = "1001";

        $scope.Add = function () {

        }

        $scope.Update = function () {

        }

}



“ng-controller” is a directive.Controllers are attached to the HTML UI by using the “ng-controller” 
directive tag and the properties of the controller are attached by using “ng-model” directive. 
For example below is a simple HTML UI which is attached to the “Customer” controller via the “ng-controller” 
directive and the properties are binded using “ng-model” directive.




<div ng-controller="Customer">

<input type=text id="CustomerName"  ng-model="CustomerName"/><br />

<input type=text id="CustomerCode"  ng-model="CustomerCode"/>

</div>



What is $scope in AngularJS?


'$scope' is an object instance of a controller. 

'$scope' object instance get’s created when 'ng-controller' directive is encountered.
Every controller has an associated $scope object
A controller (constructor) function is responsible for setting model properties and functions. 
This can be done only through $scope. Whatever function or model you apply in View (html file), 
that is accessed in controller using scope.

Only methods defined on this $scope object are accessible from the HTML/view. 


Example - from ng-click, filters, etc.


Now See the below examples –




 function MyController($scope) {

 $scope.username = 'World';

 };



In the above example we are defining any attribute named username with its value as “World”. 

Suppose in the html file you have the following line of code –



<div ng-controller="MyController">

<h1>{{data.username}}</h1></div>




This will automatically pick up the value from controller and display it on screen.


Now see below example





$scope.sayHello = function() {

$scope.greeting = 'Hello ' + $scope.username + '!';

};



This is a function defined in a controller which you can access in view by following code –




<div ng-controller="MyController">

<h1>{{data.greeting}}</h1></div>



Here, data.greeting will automatically pick value from sayHello function 

i.e. the value displayed will be "Hello World". "World" from username concatenated with “Hello” before.


What is the ng-app directive in AngularJS

ng-app directive starts an AngularJS Application. It defines the root element. 
It automatically initializes or bootstraps the application when web page containing AngularJS Application is loaded. 
It is also used to load various AngularJS modules in AngularJS Application. 

In following example, we've defined a default AngularJS application using ng-app attribute of a div element.




<div ng-app="">
</div>

What is the ng-init in AngularJS 

ng-init directive initializes an AngularJS Application data. 
It is used to put values to the variables to be used in the application.
In following example, we'll initialize an array of countries. We're using JSON syntax to define array of countries.



<div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'}, {locale:'en-GB',name:'United Kingdom'},
 {locale:'en-FR',name:'France'}]">
</div>

What is the ng-model directive in AngularJS

ng-model directive defines the model/variable to be used in AngularJS Application. 
In following example, we've defined a model named "name".



<div ng-app = "">
   <p>Enter your Name: <input type = "text" ng-model = "name"></p>
</div>


What is the ng-repeat directive

ng-repeat directive repeats html elements for each item in a collection. 
In following example, we've iterated over array of countries.


<div ng-app = "">
   <p>List of Countries with locale:</p>
   <ol>
      <li ng-repeat = "country in countries">
         {{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
      </li>
   </ol>
</div>





AngularJS Interview Question       AngularJS Interview Question -1

Sunday, May 8, 2016

Disable/Enable All Triggers in SQL Server.



To disable Triggers Run below code.

sp_msforeachtable 'ALTER TABLE ? DISABLE TRIGGER all'

To enable all triggers, you can use following statement

sp_msforeachtable 'ALTER TABLE ? ENABLE TRIGGER all'

Tuesday, April 19, 2016

MVC Interview Question - 4


What is HTML Helpers in MVC

The ASP.NET MVC framework includes helper methods that provide an easy way to render HTML in a view.


Below render CheckBox in MVC Application

<%= Html.CheckBox("bookType") %>

TextBox Helper

Enter your name: <%= Html.TextBox("name") %>

List out the HTML Helpers Available in MVC


ActionLink — Links to an action method.

BeginForm * — Marks the start of a form and links to the action method that renders the form.
CheckBox * — Renders a check box.
DropDownList * — Renders a drop-down list.
Hidden — Embeds information in the form that is not rendered for the user to see.
ListBox — Renders a list box.
Password — Renders a text box for entering a password.
RadioButton * — Renders a radio button.
TextArea — Renders a text area (multi-line text box).
TextBox * — Renders a text box

What is the AJAX Helpers in ASP.Net


AJAX Helpers are used to create AJAX enabled elements like as Ajax enabled forms and links which performs request asynchronously. AJAX Helpers are extension methods of AJAXHelper class which exist in System.Web.Mvc namespace.


Following example shows how to use AJAX action link using action and controller in Asp.Net MVC.


@Ajax.ActionLink("Fatch Data", "GetData", new AjaxOptions {UpdateTargetId = "Data-container", HttpMethod = "GET" })


Here is the html output of above code block.


<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#Data-container" href="/Home/GetData"> Fatch Data </a>




What is JSON Binding in MVC?

JavaScript Object Notation (JSON) binding support started from ASP.Net MVC3 onwards via the new JsonValueProviderFactory, which allows the action methods to accept and model-bind data in JSON format. This is useful in Ajax scenarios like client templates and data binding that need to post data back to the server.


What is Dependency Resolution in MVC?

Dependency Resolver again has been introduced in ASP.Net MVC3 and it is greatly simplified the use of dependency injection in your applications. This turn to be easier and useful for decoupling the application components and making them easier to test and more configurable.


Explain Bundle.Config in ASP.Net MVC4?

"BundleConfig.cs" in ASP.Net MVC4 is used to register the bundles by the bundling and minification system. Many bundles are added by default including jQuery libraries like - jquery.validate, Modernizr, and default CSS references.

What is the difference between View and Partial View



View Partial View
It contains the layout page It does not contain the layout page
Before any view is rendered, viewstart page is rendered Partial view does not verify for a viewstart.cshtml. We cannot put common code for a partial view within the viewStart.cshtml.page
View might have markup tags like body, html, head, title, meta etc. Partial view is designed specially to render within the view and just because of that it does not consist any mark up
View is not lightweight as compare to Partial View We can pass a regular view to the RenderPartial method


How to perform validation in MVC ?

one of the way to do validation in MVC using data annotations.
it is attributes whih can be applied to model peoperties.

See the below example.





public class Customer

{

    [Required(ErrorMessage="Customer code is required")]

    public string CustomerCode

    {

        set;

        get;

    } 

}  



In order to display the validation error message we need to use the ValidateMessageFor method which belongs to the Html helper class.




<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))

{ %>

<%=Html.TextBoxFor(m => m.CustomerCode)%>

<%=Html.ValidationMessageFor(m => m.CustomerCode)%>

<input type="submit" value="Submit customer data" />

<%}%> 




How can we enable data annotation validation on client side?

It’s a two-step process: 
first reference the necessary jQuery files.



<script src="<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>" type="text/javascript"></script>



The second step is to call the EnableClientValidation method.








<% Html.EnableClientValidation(); %> 



How to use Jquery Plugins in ASP.Net MVC validation?

We can use dataannotations for validation in ASP.Net MVC. If we want to use validation during runtime using Jquery then we can use Jquery plugins for validation. Eg: If validation is to be done on customer name textbox then we can do as :




$('#CustomerName').rules("add", {

required: true,

minlength: 2,

messages: {

required: "Please enter name",

minlength: "Minimum length is 2"

}



});






MVC Interview Question                          MVC Interview Question - 1