Saturday, January 9, 2016

AngularJS – Controllers

Controllers in AngularJS exists to augment the views of an AnuglarJS applications. The controller in AngularJS is a function that functionality to the scope of the view. We use it to set up the initial state and to add custom behavior to the scope object.

When we create the controller on a page, Angular passes it a new $scope. This new $scope is where we can set up the initial state of the scope on our controller. Since Angular takes care of handling the controller for us, we only need to write the constructor function.
Setting up the initial controller looks like this:

function FirstController($scope) {
    $scope.message = “Hello”;
}

Doing so is usually poor form, as we don’t want to dirty the global namespace. To create it more properly, we’ll create a module and then create the controller on top of our module, like so:

var app = angular.module(‘app’, []);
app.controller(‘FirstController’, function($scope) {
    $scope.message = “Hello”;
}

To create custom actions we can call in our views, we can simply create functions on the scope of the controller. Luckily for us, AngularJs allows our views to call functions on the $scope, just as if we were calling the data.

To bind buttons or links (or any DOM element, really), we’ll use another built-in directive, ng-click.
The ng-click directive binds the mouseup browser click event to the method handler, which calls
the method specified on the DOM element (i.e., when the browser fires a click event on the DOM
element, the method is called). Similar to our previous example, the binding looks like:

<div ng-controller="FirstController">
<h4>The simplest adding machine ever</h4>
<button ng-click="add(1)" class="button">Add</button>
<a ng-click="subtract(1)" class="button alert">Subtract</a>
<h4>Current count: {{ counter }}</h4>
</div>

Both the button and the link are bound to an action on the containing $scope, so when they are
pressed (clicked), Angular calls the method. Note that when we tell Angular what method to call,
we’re putting it in a string with the parentheses (add(1)).
Now, let’s create an action on our FirstController.

app.controller('FirstController', function($scope) {
    $scope.counter = 0;
    $scope.add = function(amount) { $scope.counter += amount; };
    $scope.subtract = function(amount) { $scope.counter -= amount; };
});


Setting our FirstController in this manner allows us to call add or subtract functions (as we’ve
seen above) that are defined on the FirstController scope or a containing parent $scope.
Using controllers allows us to contain the logic of a single view in a single container. It’s good
practice to keep slim controllers. One way that we as AngularJS developers can do so is by using the
dependency injection feature of AngularJS to access services

AngularJS – Scopes

The $scope object is where we create the business functionality of the application, methods in our controllers, and properties in the views. Scopes serve as the glue between the controller and the view.
Scopes provide the ability to watch for the model changes. They give the developer the ability to propagate the model changes throughout the application by using the apply mechanism available on the scope.

It is ideal to contain the application logic in controller and model working data on the scope of the controller.

When Angular starts to run and generates the view, it will create a binding from the root ng-app element to the $rootScope. This scope is the eventually parent of all the $scope objects. The $rootScope object is the closest object we have to the global context in the Angular app. It’s a bad idea to attach too much logic to this global context, in the similar way that it’s not a good idea to dirty the JavaScript global scope.

Scopes have the following basic functions:
  •          They provide observers to watch for model changes.
  •         They provide the ability to propagate model changes through the applications as well as outside the systems to other components.
  •         They can be nested such that they can isolate functionality and model properties.
  •         They provide an execution environment in which expressions are evaluated.

    Example



Output

In the above example notice that the Mycontroller assigns the value “Jatin” to the username property on the scope. The Scope then notifies the input of the assignment, which then renders the input with the username pre-filled. This demonstrates how controller can write data to the scope.

Similarly the controller can assign behavior to the scope as seen by the sayHello method, which is involved when the user clicks on the ‘greet’ button. The sayHello method reads the username property and creates the greeting property. This demonstrates that the properties on scope update automatically when they are bound to the HTML input widgets.

 


AngularJS – Module

In Angular, a module is the main way to define an AngularJS app. The module of an app is where we’ll contain all of our application code. An app can contain several modules, each one containing code that pertains to specific functionality. You can think of a module as container for the different parts of your app – controllers, services, filters, directives etc.

Modules provide us a lot of advantages, such as
  •        Keeping our global namespace clean.
  •         Making testing easier as independent modules can be tested separately.
  •         Making it easy to share code between applications.
  •          Allowing our app to load different parts of code in any order.


The angular modules API allows us to declare a module using the angular.module() method.
When declaring a module, we need to pass two parameters to the method. First is the module name and second one is the list of Dependencies also known as injectable.

angular.module(‘moduleName’, []);

However we can also use the overloaded method with single parameter as shown below,

angular.module(‘ModuleName,);

Example


In following example we going to create two modules
  •          Application Module – used to initialize an application with controllers.
  •         Controller Module – used to define a controller.
MyApp.js

Var app  =  angular.module(“myApp”, []);

MyController.js

App.Controller(“myController”, function($scope) {
                $scope.firstName = “Jatin”;
                $scope.lastName = “Patil”;
});

AngularJSModule.html

 


Output


AngularJS - Introduction

AngularJS is the client-side technology, written entirely in JavaScript. It works with the long-established technologies of the web (HTML, CSS and JavaScript) to make the development of web apps easier and faster than even before.

AngularJS extends HTML with new attributes. It is a framework that is primarily used to build single-page web applications. AngularJS makes it incredibly easy to build web applications; it also makes easy to build complex applications.

Features
  •  Separation of application logic, data models and view
  •  Ajax Services
  • Dependency Injections
  •  Browser history ( makes bookmarking and back/forward buttons work like normal web apps )
  • Testing
  •  Cross browser compliant. AngularJS automatically handles JavaScript code suitable for each browser.
  • And more…

Data binding and First AngularJS Web Application


Data binding is one of the most basic and impressive features of the AngularJS. Many classic Web frameworks combine data form the model and mashes them together with templates to deliver a view to the user. This combination produces a single way view, the view only reflect the data the model exposes at the time of the view rendering.

AngularJS takes different approach. Instead of merging the data in to the template and replacing a DOM element, AngularJS creates a live template as a view. Automatic data binding gives us the ability to consider the view to be a projection of the model state. Any time the model is changed in the client-side model, the view reflects these changes without writing any custom code.

Hello World example



Output



In above example we have just included angular.js in our HTML and explicitly setting the ng-app attribute on an element in the DOM. The ng-app attribute declares everything inside of it belongs to the Angular app; that’s how we can nest an Angular app inside of a web app. The only components that will be affected by the Angular are the DOM elements that we declare inside of the one with the ng-app attribute. Views are interpolated when the view is evaluated with one or more variable substitutions; the results is that the variables in our string are replaced with the values. For instance, if there is variable named name and it is equal to “Jatin”, string interpolation on a view of “Hello { { name } }” will return “Hello Jatin”.

Saturday, September 19, 2015

SharePoint 2013 CSR

Introduction

In SharePoint 2013 the Client Side Rendering (CSR) is nothing more than a JavaScript framework used to customize the interface of the List and forms. CSR is used to render the display templates at client side using JavaScript. Prior versions of SharePoint used to handle the display templates at Server side using XSLT in 2010 and CAML in 2007.
SharePoint 2013 itself uses CSR framework in many places like Search Results, Lists and Document Libraries. Therefore CSR is the best way to modify the user Experience (UX).

How it works

Unlike Previous versions where the rendering was handled at Server side using the XSLT or CAML, In SharePoint 2013 the only step performed by the Server side webparts is to dump the raw data in JSON format in the page. And when the Page Loads the CSR framework actually forms the HTML with help of CSR templates and the raw data.
Therefore the HTML is the result of the combination of CSR templates and raw data,
HTML => CSR + Raw data

Customizing with CSR

To use this framework we need to define and override the template. The template is nothing but the JavaScript object containing various options for rendering the template. 

Following is the basic structure of the template.
(function () {
    var ctx = {};
    ctx.Templates = {};
    ctx.Templates.Header = undefined;
    ctx.Templates.Footer = undefined;
    ctx.Templates.Item = undefined;
    ctx.Templates.OnPreRender = undefined;
    ctx.Templates.OnPostRender = undefined;
    ctx.Templates.Fields = {};
    ctx.ListTemplateType = undefined;
    ctx.BaseViewID = undefined;

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctx);
})();

The line "SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctx)" , actually inserts our custom template on the SharePoint 2013 rendering stack. Note that the call to this function must be inserted in self-invoking JavaScript function so that it gets called on the page load and parameter to this function are the various override options .

Example

Let’s have a look at a simple example where we have a list called car details which contains 3 columns Title, Price and Color. In this example we will override the field color in list view where the text in the color column will be actually rendered in the color entered by the user.


1. Create JS Override template file as shown in the following figure



2. Upload the file to Master page library





3. While uploading select content type as “JavaScript Display Template”, Target Control type as “View”, Standalone as “Override”, Target Scope as “/”.







4. Edit the List view webpart and enter the JavaScript file path created in step 1 under JSLink Property.

The Full path is “~site/_Catalogs/masterpage/CSRCarDetails.js”.

5. Output

a. Before Applying Custom CSR Template

b. After Applying Custom CSR Template

Thursday, April 3, 2014

Designing claims-based tokens using Security Assertion Markup Language(SAML)

The Security Assertion Markup Language (SAML) specification is an open security standard envisioned by Organization for the Advancement of Structured Information Standards (OASIS) Technical Committee for the exchange of security context across service boundaries. The SAML tokens are XML-based (can be transmitted using SOAP/HTTP) and provide a way of implementing claims-based identity that is particularly useful in interoperable scenarios across the identity providers and the service providers.

Following example shows how to create the SAML security tokens using the System.IdentityModel assembly in .NET Framework 4.0.

    Create a new Visual C# Console Application project in Visual Studio
  1. Create a new Visual C# Console Application project in Visual Studio
  2. Add a reference to System.IdentityModel and System.ServiceModel assembly
  3. Open the Program.cs file, and include the System.IdentityModel.Claims, System.IdentityModel.Tokens, System.ServiceModel   and the System.Security.Principal namespaces.
  4. Before we can create SamlSecurityToken, we need to create an instance of the SamlAssertion object that holds the claims information abstracted from the current windows identity. We will write a private static method that accepts a collection of the Claim objects and returns a SamlAssertion object.


  5. Note that SAML v1.1 specification puts a restriction that only resources identifiable by a named string can be used as a SamlAttribute value. In our example, we are using a helper method to translate SecurityIdentifier into readable NTAccount named permissions:


  6. Now, In main method create instance of SamlSecurityToken using the SamlAssertion instance returned from the method “CreateSamlAssertionFromWindowsIdentityClaims()”.


  7. Now Run the program and put debugger on token generation line to see the token.


Tuesday, March 25, 2014

Claims Based Identity Model

Claims based security is based on the concept that the identity of a person can be represented by a set of claims about that person. A claim is a bit of information that describes the person in a way that is digitally useful. Claims typically contain the usual user name, or email, but they can include much more. Information such as roles, phone numbers, zip codes, addresses, anything that is typically used by applications to customize the user experience.
Claims-based identity provides a standard way of acquiring identity information by heterogeneous applications to validate service requests within and outside an organization and also over the Web.

Abstracting Identity with Claims:
Authentication and authorization are two of the most common aspects of the application security. In Windows, security is generally handled using the Kerberos or the NTLM security tokens.
This works well within the boundaries of the Windows ecosystem; however, it gets difficult if the application has to support the users that do not have Windows Active Directory credentials. In the real world, the applications spanning multiple platforms interact with each other and require the security context to be shared. Using a claims-based identity model provides a robust way of handling authentication and authorization across the discrete systems.

Claims Base Authentication:
Claims-Based architecture allows you to delegate authentication logic into another entity. This entity is a “some” layer which abstracts all authentication related coding and gives your application what it needs: is the user authenticated or not, and some information about the user (called claims or assertions) that lets your application take authorization decisions.
How to do it…
Following example demonstrate how you can create a collection of claims from a WindowsIdentity object,

1.    Create a new Visual C# Console Application project in Visual Studio



2.       Add a reference to System.IdentityModel assembly

3.       Open the Program.cs file, and include the System.IdentityModel.Claims and the System.Security.Principal namespaces.

4.       In the Main method, create a new instance of the WindowsClaimSet class, and pass the current context identity as a parameter to the constructor. And then Loop through the ClaimSet object and print the claim information into the console output



5.       Compile and run the project. The result is displayed in the console window:


How it works…

The WindowsClaimSet class inherits from the System.IdentityModel.Claims.ClaimSet. ClaimSet represents a collection of claims (System.IdentityModel.Claims.Claim) associated with an entity. The WindowsClaimSet constructor accepts the current Windows user identity as a parameter and returns a ClaimSet object containing the collection of claims that represent the Windows Active Directory groups of the user. The current Windows user identity is fetched using the WindowsIdentity.GetCurrent method. Generated ClaimSet can be used to create a signed security token that can be passed on to a service to create a security context and implement role-based access control.

A claim is used to identify a user or provide access to a particular resource requested by the user. There are three properties exposed by the Claim class:

ClaimType: It identifies the type of claim. In our example, Sid (security identifier) and Name are the two claim types displayed in the console window.

               Resource: It identifies the resource associated with the claim.

Right: It is a URI representing the Identity or PossessProperty right associated with the claim. PossessProperty determines whether the user has the access to Resource.

Both the Claim and the ClaimSet classes are serialization-friendly, which allows them to be transmitted over service boundaries.