Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

Why You Should Use AngularJS

Introduction:

One of my friend told me why you are using old JavaScript and JQuery, why not tried angular JS.

After reading some tutorials and googling my opinions is for Single Page Applications the crazy new AngularJS framework can do a lot more than classic old JavaScript and JQuery.

AngularJS:

AngularJS Is a free open source framework developed by Google Employee and presently maintained by Google and by a community of individuals and corporations to address many of the challenges encountered in developing single-page applications.

Why AngularJS?


If you haven’t tried AngularJS then you are really missing actual JavaScript magic’s.
According to me JavaScript is most dynamic and flexible language for web development.

Here are some advantages that tells you why you should be using Angular.

1. Testability Advantage 

a. Inbuilt support:

Inbuilt Unit testing Support provided with AngularJS.

b. Dependency injection:

AngularJS was designed considering testable environment, it fully supports dependency injection and encourages behavior-view separation, comes pre-bundled with mocks.

Dependency injection is also a core to AngularJS. This means that any component which does not fit your needs can easily be replaced.

2. Directive Advantages 

Directives is a unique and powerful feature available only in Angular. Directives let you invent new HTML syntax, specific to your application.

a. Reusable components

You can use AngularJS directives to create reusable components; these components hide complex DOM structures, CSS and behavior.

b. Localization

Each and every important application is available all local languages, and all successful and famous framework provides localization features.

Localization is the process of adapting internationalized software for a specific region or language by adding locale-specific components and translating text.

AngularJS filters and stemming directives provides features to make your application available in all local languages.

3. Dom and HTML Markup 

a. Easy and quick to use:

You can use angularJS with local basic html file, not required web server like Asp.net require always IIS.

Simply add angularJS in HTML page and rune one any browsers it works.

Easy, readable and quick to develop application.

b. Dynamic and integration with existing App:

AngularJS starts evaluating the page at the end of the loading process (i.e. once HTML is in the DOM), it is easy to attach your small angularJS code in existing application.

Example:

If you want to add small functionality on page, for example leave summery of employee you can easily add this functionality without major changes in existing pages.

c. Extensibility:

AngularJS is fully extensible and works well with other libraries. 

You can modify and replace existing features according to your need that is allowed in AngularJS Framework. 

4. Data-Binding Advantage

AngularJS applications provide automatic synchronization of data between the model and view components.

There are two types of binding used:

1. One way data binding (Model to View)

2. Two way data binding (Model to View and View to model continues update)

When model changes the view reflects the change and vice versa, here model is real data and view is projection on model.

Example:

You can create your new webpages, you can add data binding whenever you feel that you have some dynamic data.

Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).

5. DOM Manipulation Advantage

In MVC application using angular DOM is not manipulated in VIEW, DOM manipulation code is available inside directive.

Angular consider view is projection on model to place data and a simple html page.

Advantage of this feature is your view is clean and easy to maintain and change.

6. Data validation and data filtering advantage

a. Data validation

AngularJS provide client side form validation rules without writing any JavaScript code, additionally you can use HTML5 data validation rules easily.

Write less code and have “Girlfriend/Boyfriend “and Beer Sooner.

b. Filters:

A filter formats the value of an expression for display to the user.

C# provide nice feature called LINQ to filter data with less code, with angularJS you can filter data with existing and custom filters using lesser code than LINQ.

You can also use filters in controllers, services, and directives.

Writing your own filter is very easy: just register a new filter factory function with your module. Internally, this uses the filterProvider.

7. MVC Advantages

Existing other MVC firework you have to divide your code in MVC components and again you require to write code to bind together.

With angualarJS in first stage write your code in MVC component, then rest angularJS will do for you.

8. Data models are Plain JavaScript (POJO)

 Models in angualarJS are classic old JavaScript objects (POJO) and don’t require extraneous getter and setter functions. You can add and change properties directly on it and loop over objects and arrays at will.

Your code is clean, simple and readable using these natural old JavaScript objects (POJO).

This makes your code easy to test, maintain, reuse, and again free from boilerplate.

9. AngularJS inbuilt services and Server Communication

Angular provides a rich built in support for communication with the server, it not only provides the low level mechanism which acts as building block to communicate with the servers, but it also provides built-in wrappers for communication with services.

AngularJS provides built-in services on top of XHR as well as various other backends using third party libraries. Promises further simplify your code by handling asynchronous return of data.

Example:

You can use the AngularFire library to wire up a Firebase backend to create real world a simple Angular app.

Conclusion:

My suggestion is for single page web application,CRUD based web applications and responsive web application prefer AngularJS then old JQuery or JavaScript.

Angular JS is like Messi of “Football” and “Kolhi” of Cricket for single page web application.

Reference:

https://angularjs.org/

 

Linq to XML

Introduction:

For any application common approach is use database or XML documents to store backend data.

a. LINQ provides LINQ to SQL component to directly manipulate relational data, you can perform linq queries on Data directly.

b. For XML document .net framework provided LINQ to XML interface that enables In-memory XML document modification.

In this article I will describe LINQ to XML in detail with some sample examples.

What is LINQ to XML?

LINQ to XML is a LINQ-enabled, in-memory XML programming interface that enables you to work with XML from within the .NET Framework programming languages.

LINQ to XML is like the Document Object Model (DOM) in that it brings the XML document into memory. You can query and modify the document, and after you modify it you can save it to a file or serialize it and send it over the Internet. However, LINQ to XML different from DOM.

Using LINQ to XML, you can

a. Load XML from files or streams.
b. Serialize XML to files or streams.
c. Create XML from scratch by using functional construction.
d. Query XML using XPath-like axes.
e. Manipulate the in-memory XML tree by using methods such as Add, Remove, ReplaceWith, and SetValue.
f. Validate XML trees using XSD.
g. Use a combination of these features to transform XML trees from one shape into another.

Reference: https://msdn.microsoft.com

Why LINQ to XML?

LINQ to XML enables you to create and modify XML documents easily by using LINQ query expressions instead of XPath or XQuery.

Compared with classic complex XML parsing approach LINQ to XML expressions are easy to read xml document and modify XML document.

Advantages using LINQ to XML:

1. LINQ to XML makes XML easier by providing a query experience that is similar to SQL.
2.   Allows to use query result as parameters to XElement and XAttribute object constructors enables a powerful approach to creating XML trees.
This approach, called functional construction, enables developers to easily transform XML trees from one shape to another.
3. Main advantage of LINQ to XML is its integration with LINQ, This integration allows you to write queries on the in-memory XML document to retrieve collections of elements and attributes.
   var result = xdoc.Descendants("Types")
                 .Descendants("Animals")
                 .Descendants("Tab")
                 .Elements("Dogs")
                 .Where(n => n.Attribute("id").Value == "1");
4. Easy to create XML trees with LINQ to XML.
5. Compiled and in memory use, so it runs faster.
6. Allows for better string manipulation.
7. Ability to work directly with XML elements instead of creating a container XML document, as required with W3C DOM.
8. In-memory XML document modification that is powerful, yet simpler to use than XPath or XQuery.
9. You can perform sorting, grouping on xml data.

LINQ to XML Example with Sorting Data:

Following example LINQ to xml query sort’s student’s xml data by year in ascending order.

XML:

<?xml version="1.0" encoding="UTF-8"?>
<
Collage>
  <
Students>
    <
Student>Shourya</Student>
    <
Year>2014</Year>
    <
teacher>Nagnath</teacher>
  </
Students>
  <
Students>
    <
Student>Shrad</Student>
    <
Year>2015</Year>
    <
teacher>Girish</teacher>
  </
Students>
  </
Collage>

LINQ to XML Query:

IEnumerable<decimal> Students =
 
         from el in doc.Elements("Students")
 
         let year = (decimal)el.Element("Year")
 
         orderby year
 
         select year;
           foreach (decimal student in Students)
               Console.WriteLine(student);

 

LINQ to XML methods with use of extension method:

In following example count method is used with XML document  

var doc = XDocument.Load("~/nmk/students.xml");
int descendantsNodes =doc.Descendants().Count(); // counts ALL descendants elements
int childNodes = doc.Root.Elements().Count(); //counts direct children of the root element


User Defined Extension methods with LINQ to XML:

In following example I have created extension methods for data casting, those methods I used with LINQ to XML query.

  var products =
               from elem in xElem.Descendants("Product")
               orderby elem.Attribute("ProductName").Value
               select new Product
               {
                   ProductId = elem.Attribute("ProductId").GetAsInteger(),
                   ProductName = elem.Attribute("ProductName").GetAsString(),
                   Category =
                      elem.Attribute("Category").GetAsString(),
                   Price = elem.Attribute("Price").GetAsDecimal()
               };


User Defined Extension method:

public static string GetAsString(this XAttribute attrbute)
  {
    string ret = string.Empty;
 
    if (attrbute != null && !string.IsNullOrEmpty(attrbute.Value))
    {
      ret = attrbute.Value;
    }
 
    return ret;
  }

 

Using existing .net Framework provided extension methods with LINQ to XML:

Following LINQ to XML query example returns valid products data for existing categories only

var ValidProductsDeatils = xElem
 .Element("Products")
 .Elements("Product")
 .Where
 (
     x =>  x .Elements("Category")
     .Where
     (
         z => z.Attribute("Id").Value !="0"
     )
     .Select
     (
         z =>
         z.Attribute("Name").Value
     ).SingleOrDefault()=="true"
 );
 

Linq to Dataset

Introduction:

Previously I written two articles on linq features LINQ to SQL and Linq to Objects, I specified in first article I will continue writing some more articles on LINQ features.

In this article I will describe in detail LINQ to Dataset in detail with some sample examples.

 What is LINQ to dataset?

LINQ to Dataset provides the easier and faster approach to query over data cached in a DataSet object.

LINQ to DataSet can also be used to query over data that has been consolidated from one or more data sources.

For example querying data on actual data and intermediate cached data source in financial web application, such scenarios required to create financial reports.

Following diagram explain relationship between LINQ to Dataset to ADO.NET 2.0 and Database.

                       

Why LINQ to Dataset?

LINQ to Dataset allows developers to write queries from the programming language itself, instead of using separate query language.

Programming query languages who can now take advantage of the compile-time syntax checking, static typing, and IntelliSense support provided by the Visual Studio in their queries,this is especially useful for Visual Studio developers.

Advantages using Linq to Dataset:

1. Easy and readable.

2. No need to learn separate query languages like SQL (Structured query language), you can use visual studio programming language.
3.  You can use linq on two different datasets or you can retrieve some distinct values from dataset using Linq To Dataset.
4. You can use Sql queries to retrieve dataset but you can’t use SQL queries to retrieve value from dataset, in classic programming .net provides ado.net objects but with Linq to Dataset approach you can retrieve some distinct values from dataset.

 LINQ to Dataset Single table Queries:

The following obtains valid Products from the “C4Test” sample database using LINQ to dataset query.

  DataSet ProductsData = ProductDataAccess.GetProductDetails();  
  DataTable Products = ProductsData.Tables["Products"];

 

          var ValidProducts =
              from product in Products.AsEnumerable()
              where product.Field<string>("ProductName") != string.Empty
              && product.Field<int>("CategoryId") != 0
              select new
              {
                  ID =
                      product.Field<int>("ID"),
                  Name =
                      product.Field<int>("ProductName"),
                  Price =
                      product.Field<int>("Price")
              };

 

LINQ to Dataset Cross table query Example:

The following example performs a classic join (SQL join) of the Products and Categories tables from the “C4Test” sample database to obtain valid product details with categories.
LINQ framework provides two join operators, Join and GroupJoin. These operators perform equi-joins: that is, joins that match two data sources only when their keys are equal.
DataSet ProductsData = ProductDataAccess.GetProductDetails();
DataSet CategoriiesData = ProductDataAccess.GetProductCategories();
 
DataTable Products = ProductsData.Tables["Products"];
DataTable Categories = CategoriiesData.Tables["Categories"];

 

           var query =
               from product in Products.AsEnumerable()
               join category in Categories.AsEnumerable()
               on product.Field<int>("CategoryId") equals
                   category.Field<int>("ID")
               where product.Field<string>("ProductName") != string.Empty
               && product.Field<int>("CategoryId") != 0
               select new
               {
                   ID =
                       product.Field<int>("ID"),
                   Name =
                       product.Field<int>("ProductName"),
                   Category =
                       category.Field<string>("CategoryName"),
                   Price =
                       product.Field<int>("Price")
               };

 

Creating a DataTable from a Query (LINQ to Dataset):

The following example queries the Categories table for valid categories and uses the CopyToDataTable method to create a DataTable from that query.
 DataSet CategoriiesData = ProductDataAccess.GetProductCategories();
 DataTable Categories = CategoriiesData.Tables["Categories"];

 

  // Query the Categories table for only valid categories
  IEnumerable<DataRow> ValidCategories =
           from category in Categories.AsEnumerable()
           where category.Field<string>("CategoryName")!=string.Empty
           select category;
 
   // create a table from the query.
   DataTable NewValidDataTable = ValidCategories.CopyToDataTable<DataRow>();

 

Conclusion:

LINQ to Dataset allows developers to write queries from the programming language itself, instead of using separate query language.

 You can perform joins on different tables and you can retrieve only required data from different data sources.