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

Group Query Results using LINQ

Introduction

Grouping on data is common requirement in finance and data applications, programmers write Frequently code to perform these operations. In old applications architects prefer grouping logic in database programming only and they use front end coding to display grouped data.

              Now LINQ provides easier and faster approach to query over data using LINQ to entities and LINQ to Data-set.

In this article I will explains in detail,

  a. How I can Group data using LINQ?
  b. How I can group data with multiple columns using lambda?
  c. How I can group data with multiple columns using linq but not using any extension method? 

Group by in LINQ

Grouping is one of the most powerful capabilities of LINQ. In this example I will explain grouping using LINQ with following sample examples.

            1.   Groping List data with single property.
       2.   Grouping List data with multiple properties.
       3.   Grouping Data Table data with single columns.
       4.  Grouping Data Table data with multiple columns.
       5. Grouping Data with Bool Value

You can perform grouping using group clause and GroupBy() extension method same I performed with following examples.

group clause

The group clause returns a sequence of IGrouping<TKey, TElement> objects that contain zero or more items that match the key value for the group.

GroupBy() Method

Groups the elements of a sequence according to a specified key selector function and projects the elements for each group by using a specified function.

Groping List data with single property

Using group clause (Grouping by string)

The following example shows how to group source elements by using a single property of the element as the group key. In this case the key is a string “UserName”.

  var GroupUserByNames =
                from user in activeUsers
                group user by user.UserName;

Using Group by Method

The following example shows how to use GroupBy() extension method to group results with single property. In this case the single group property is the UserName.

List<User> CheckDuplicateUsers= activeUsers.GroupBy(U => 
                 U.UserName).Where(gr => gr.Count() > 1).SelectMany(dupRec => dupRec).ToList();

Grouping List data with multiple properties

Using group clause (Group data by numeric range)

In this example we used expression to create numeric group keys that represent a percentile range. Note the use of let as a convenient location to store a method call result, so that you do not have to call the method two times in the group clause.

     var GroupProductByProfit=from product in products
      let profitPercentage=GetProductProfit (product)
      group new { product.Name, product.Type } by profitPercentage into ProfitPercentGroup orderby ProfitPercentGroup.Key
      select ProfitPercentGroup;

Using Group by Extension Method

          List<BasicProduct> CheckDuplicateProducts = activeProducts.GroupBy(u =>
                 new { productCode=u.ProductCode,Type=u.ProductType}
            ).Where(gr => gr.Count() >1).SelectMany(dupRec => dupRec).ToList();

Grouping Data Table data with single columns:

Using group clause

Following example explains how to use group by clause to group data with single column value (key value).

var GroupUserByNames = from user in UsersTablle.AsEnumerable()
                group user by Field<string>("UserName") into newGroup
                orderby newGroup.Key
                select newGroup;

Using Group by Extension Method

Following example explains how to use GrouBy() method to group data with single column value (key value).

DataTable duplicatesUsers =UsersTablle.AsEnumerable().GroupBy(x
=> x.Field<string>("UserName"))
    .Where(gr => gr.Count() >1).SelectMany(dupRec => dupRec).ToList().CopyToDataTable();

 

Grouping Data Table data with multiple columns   

Using group clause (Grouping by Composite Keys)

Use a composite key when you want to group elements according to more than one key. You create a composite key by using an anonymous type or a named type to hold the key element.

In this example grouping is performed with two composite keys name and address.

var GroupUserByNames =
                from user in UserTable.AsEnumerable()
                group user by new
                {
                    Name = user.Field<string >("Name"),
                    Address = user.Field< string >("Address")
                } into newGroup
                orderby newGroup.Key
                select newGroup;

Using Group by Extension Method

  //LINQ query retrieves duplicate records from data table
on two columns and save result in another table
        DataTable resultTable = Data.AsEnumerable()
                          .GroupBy(row => new
                         {
                              UserName = row.Field<string>("UserName"),
                              OrignalAuthor = row.Field<string>("OrignalAuthor")                           }).Where(gr => gr.Count() > 1).SelectMany(dupRec => dupRec).ToList().CopyToDataTable();

 

Grouping Data by using Bool Value

Following example group employees those eligible for taxable income and not eligible for taxable income, Grouping is performed with bool values.

  // Group by true or false.
   Var GroupEmployeByPackage=
        from employee in employees
       group employee by employee.package >=500000;//taxable or nontaxable!

 

 धन्यवाद मित्रानोआपला प्रत्येक दिवस आनंदी आणि सुखी जावो  

AngularJS Routing

Introduction

When I started writing on AngularJS I shared following tow posts on AnjularJS 

http://codechef4u.com/post/2016/04/02/angularjs-introduction
http://codechef4u.com/post/2016/04/01/why-you-should-use-angularjs

In both posts I mentioned AngularJS is a Single Page Applications(SPA) framework,

I think that is a wrong assumption you can use AnjularJS for creating multi page applications also easily and efficiently.

AngularJS is a Single Page Applications (SPA) framework is only Hype?

AngularJS does not enforce developers to create SPAs. It makes it easy to write SPAs, hence people created hype about AngularJS it is Single Page Applications (SPA) framework.

You can create easily AngularJS choose Multi Pages Applications (MPAs) using $Route Module,routing service provider $routeProvider, ng-View directive and  inbuilt AngularJS Dependency Injection feature.

Always choosing single page application is not good- especially if you are looking into highly complex, Module based, pluggable UI architecture in that case my suggestions Is choose Multi Pages Application (MPA).

MPAs Required Terms Explained:

ngRoute Module

The ngRoute module provides routing and deeplinking services and directives for angular apps.

Syntax:

angular.module('YourModule', ['ngRoute'])

$routeProvider

Provider is Used for configuring routes, Requires the ngRoute module to be installed.
Application routes in Angular are declared via the $routeProvider, which is the provider of the $route service. This service makes it easy to wire together controllers, view templates, and the current URL location in the browser.

$Route

$route is used for deep-linking URLs to controllers and views (HTML partials). It watches $location.url() and tries to map the path to an existing route definition

The $route service is typically used in conjunction with the ngView directive and the $routeParams service.

 ng-View Directive

ngView is a directive that complements the $route service by including the rendered template of the current route into the main layout (index.html) file. Every time the current route changes, the included view changes with it according to the configuration of the $route service.

Syntax

  <[html tag]  ng-view>your html view code</[html tag]>

AngularJS Multi Pages Application Example

I will create sample AngularJS application with two views,

1. employee.html

2. contact.html

And I will explain this example following steps.

Step 1:

A. Create a module named mainApp and load ngRoute as a dependent module.

B. Configure the routes using $routeProvider.

C. We use three paths in the example, /home ,/viewEmplyees,/viewContacts with EmployeeController and

    ContactController this is initialized with an array of employees and a contact message.

E. We will be showing the message in the home page and the employees list in employee page, and contact details in contact page.

F. Save this file as AppRouteExample.js.

AngularJS Controller and Model code

var mainApp = angular.module("mainApp", ['ngRoute']);
 
mainApp.config(function ($routeProvider) {
    $routeProvider
        .when('/home', {
            templateUrl: 'home.html',
            controller: 'EmployeeController'
        })
        .when('/viewEmployees', {
            templateUrl: 'employees.html',
            controller: 'EmployeeController'
        })
 
        .when('/viewContacts', {
            templateUrl: 'contact.html',
            controller: 'ContactController'
        })
 
        .otherwise({
            redirectTo: '/home'
        });
});
 
mainApp.controller('EmployeeController', function ($scope) {
    $scope.employees = [
        { name: 'Shourya Kendre',designation:'CEO',company:'CodeChef4u', city: 'Pune' },
        { name: 'Sanskruti Kendre', designation: 'Director', company: 'Aditya Enterprises', city: 'Riagad' },
        { name: 'Anushka Kendre', designation: 'Chairman', company: 'KCS', city: 'Latur' }
    ];
 
    $scope.message = "Click on the hyper link to view the employess list.";
});
 
mainApp.controller('ContactController', function ($scope) {
    $scope.message = 'Please contact us at www.codechef4u.com contact page or admin@codechef4u.com';
});

Step 2:

Now we can create our views and save as home.html, employee.html, contact.html

Home.html

<div class="container">
          <div class="row">
          <div class="col-md-3">
              <ul class="nav">
                  <li><a href="#/viewEmployees"> View Employees List</a></li>
                  <li><a href="#/viewContacts"> Contact Us </a></li>
               </ul>
           </div>
      </div>
  </div>

Employees.html

<div class="container">
    <h2> View Employees </h2>
    Search:
    <br/>
        <input type="text" ng-model="name" />
    <br/>
    <ul>
        <li ng-repeat="employee in employees | filter:name">{{employee.name}},{{employee.designation}} ,{{employee.company}}, {{employee.city}}</li>
    </ul>
 
    <a href="#/home"> Back</a>
</div>

Contact.html

<div class="container">
{{message}}
 
 <a href="#/home"> Back</a>
</div>

Step 3:

1. The ng-app  auto-bootstraps our application mainApp

2. The ngView directive is the placeholder of the views ( home.html, employee.html and contact.html).

3. Include angular.min.js and angular-route.min.js

4. Include AppRouteExample.js which we have created in the first step.

5. Save the file as index.html

index.html

<!DOCTYPE html>
<html>
    <head lang="en">
      <meta charset="utf-8">
      <title>AngularJS Routing</title>
        <script src="Content/js/angular.min..js"></script>
        <script src="Content/js/angular-route.js"></script>
        <script src="Content/js/AppRouteExample.js"></script>
    </head>
    <body>
 
      <div ng-app="mainApp">
        <ng-view></ng-view>
      </div>
 
    </body>
</html>

Step 4

Save all files in same location.

Open index.html with your browser or type the URL in your browser, For example: yourLocationURL/index.html

 धन्यवाद मित्रानोआपला प्रत्येक दिवस आनंदी आणि सुखी जावो  

AngularJS Dependency Injection

In this article I will explain AngularJS Dependency injection with some sample examples; first I will share definition of dependency injection.

Wiki Definition

In software engineering, dependency injection is a software design pattern that implements inversion of control for resolving dependencies. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it.

MSDN explanation of Dependency Injection

Dependency Injection (DI) is a design pattern that demonstrates how to create loosely coupled classes. The term "loosely coupled" deserves clarification and sometimes the best way to explain something is by first describing its opposite, which in this case is "tight coupling."

AngularJS Dependency Injection (DI)

The Angular injector subsystem is in charge of creating components, resolving their dependencies, and providing them to other components as requested.

AngualrJS provides following core components which can be injected into each other as dependencies.

1. Factory methods

Factory methods are functions registered with modules and used to return some value.

Following code sample explains how to use factory methods in AngularJS

Example:

var DoctorService = angular.module('DoctorService', [])
DoctorService.factory('DoctorsDataOp', ['$http'function ($http) {
 
    var urlBase = 'http://localhost:54393/Service1.svc';
    var DoctorDataOp= {};
   DoctorDataOp.getDoctors = function () {
        return $http.get(urlBase + '/GetallDoctors');
    };
 
    return DoctorDataOp;
 
}]);

In this example we retrieve data using $http.get(),to use the $http service we have to pass this as dependency to the service factory.

2. Module methods

You can use functions to run at configuration and run time for a module by calling the config and run methods. These functions are used same like factory methods with your module, following code sample explains how to use module methods.

angular.module('myDcotAppModule', [])
.config(['appDepProvider'function (appDepProvider) {
    // ...
}])
.run(['doctorService'function (doctorService) {
    // ...
}]);

3. Value

Here we consider value is simple JavaScript object used to pass value as parameter.

You can use this to pass controller or inject some vale to angularJS service.

Example:

var myTestModule =angular.module("myTestModule", []);
myTestModule.value("myValue"  , "nk1985");
function MyService(myValue) {
    this.doIt = function() {
        //perform some task with myValue
    }
}
myModule.service("myService", MyService);

4. Service

A service in AngularJS is a singleton JavaScript object which contains a set of functions, here set of functions contain logic to complete task you want.

AngularJS services are created using the service() function on a module.

Example:

var app = angular.module("EmpApp", []);
app.service("EmployeeService"function ($http) {
 
    // Get Employee data
    this.getEmployee = function () {
        debugger;
        return $http.get("/Home/GetAllEmployees");
    };
    // Update Employee
    this.UpdateEmployee = function (Id, Name, Email, Address) {
        var response = $http({
            method: "post",
            url: "Home/Update",
            params: {
                id: Id, name: JSON.stringify(Name), email: JSON.stringify(Email), address: JSON.stringify(Address)
            }
        });
        return response;
    }
});

5. Provider

Providers are most flexible in AngularJS you can use providers to create custom services, factory etc, providers tells angular how to create injectable things we can call these things services in technical term.
Services are defined by things called providers, which is what you're creating when you use $provide.

You can use Factory,value,service shortcuts to define provider , I will explain value in next section with current example I will define $provide with factory and service.

Example

ProviderTestModule.config(function ($provide) {
    $provide.provider('AppConfig',function () {
        this.$get = function () {
            return function () {
                //here some configuration code
            };
        };
    });
});

$provide with factory

ProviderTestModule.config(function ($provide) {
    $provide.factory('WebAppConfig', function () {
        return function (settingVal1, setttingVal2) {
            //here some configuration code
        };
    });
});

$provide with service

 

ProviderSampleModule.service('WebAppConfig', function () {
    return function (configSettingsValues) {
        //here some configuration code
    };
});

$provide with value

ProviderSampleModule.config(function ($provide) {
    $provide.value('WebAppConfig', function (settings) {
        //here some configuration code
    });
});

The Injector ($injector)

The injector is responsible for actually creating instances of our services using the code we provided via $provide.

You can get an instance of a defined service by calling get on it with the name of the service.

Sample Code

var myTestInjector =$injector.get('myTestInjector');
myTestInjector('Injected successfully');

Using injector you can inject services into any function you have using the injector's invoke method

Sample Code

var mySampleFunction = function (SomeVal) {
    //perform some task with SomeVal
};
$injector.invoke(mySampleFunction);

6. Constant

You can create config provider using AngularJS module.config() function, Unfortunately you cannot inject values into the module.config() function but you can inject constants here.

Constants in AngularJS are defined using the module.constants() function.

Example

var appModule = angular.module("EmpApp", []);
 
appModule.constant("configValue", "some constant config value");
 
myservices.config(function (mySecondServiceProvider, configValue) {
    mySecondServiceProvider.doConfig(configValue);
});

7. Controllers

You can inject things (i.e Service, method, value) into controllers but you can't inject controllers into things, reason controllers aren't created via the provider.

Example

Angular App

var app= angular.module("EmpApp", []);

Angular Service

app.service("EmployeeService", function ($http) {
    // Get Employee data
    this.getEmployee = function () {
        debugger;
        return $http.get("/Home/GetAllEmployees");
    };    
});

Angular Controller injects Service

app.controller("EmpCntrlr", function ($scope, EmployeeService) {
    GetAllEmployee();
    function GetAllEmployee() {
        debugger;
        var getAllEmployee = EmployeeService.getEmployee();
        getAllEmployee.then(function (empls) {
            $scope.employees = empls.data;
        }, function () {
            alert('Employee data not found');
        });
    }
});

References used

1. Dependency injection article shared on website https://github.com
2. Tutorial shared by https://docs.angularjs.org
3. https://en.wikipedia.org/
4. https://msdn.microsoft.com/

 धन्यवाद मित्रानो, आपला प्रत्येक दिवस आनंदी आणि सुखी जावो