Dynamic Query in LINQ using Predicate Builder


This tutorial explain how to create dynamic query using LINQ, Using Predicate Builder  LINQ to SQL dynamic query and Query with Entity Framework is easy. This concept first implement by albahari


Predicate Builder is power full LINQ expression which is mainly used when too many search filter parameter is there for querying data by writing dynamic query expression. We can write query like Dynamic SQL.

To know more about predicate delegate visit Predicate Delegate

How To Implement Predicate Builder


  public class PatientInfo
        public int PatientID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Nullable<System.DateTime> BirthDate { get; set; }
        public string Gender { get; set; }
        public string PatientType { get; set; }
        public string InsuranceNumber { get; set; }
        public Nullable<System.DateTime> AdmissionDate { get; set; }
        public bool IsHaveInsurence { get; set; }
using System;
using System.Data;
using System.Data.Objects;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;




   public ActionResult Index(string PatientName, string BirthDate, string Gender, string PatientType)
            ViewBag.PatientName = PatientName ?? "";
            ViewBag.BirthDate = BirthDate ?? "";
            ViewBag.Gender = Gender ?? "";
            ViewBag.PatientType = PatientType ?? "";

            var predicate = PredicateBuilder.True<Patient>();

            if (!string.IsNullOrEmpty(PatientName))
                predicate = predicate.And(i => i.FirstName.ToLower().StartsWith(PatientName) || i.LastName.ToLower().StartsWith(PatientName));

            if (!string.IsNullOrEmpty(Gender))
                int gender;
                Int32.TryParse(Gender, out gender);
                predicate = predicate.And(i => i.Gender == gender);
            if (!string.IsNullOrEmpty(PatientType))
                int type;
                Int32.TryParse(PatientType, out type);
                predicate = predicate.And(i => i.PatientType == type);

            if (!string.IsNullOrEmpty(BirthDate))
                DateTime dob;
                DateTime.TryParse(BirthDate, out dob);
                predicate = predicate.And(i => EntityFunctions.TruncateTime(i.BirthDate) == EntityFunctions.TruncateTime(dob));

            var patients = db.Patients.Where(predicate).Select(i => i).Include(p => p.DropDownOption).Include(p => p.DropDownOption1);
            ViewBag.Gender = new SelectList(db.DropDownOptions.Where(i => i.Item == "Gender").Select(i => i), "DropDownID", "Name", ViewBag.Gender);
            ViewBag.PatientType = new SelectList(db.DropDownOptions.Where(i => i.Item == "PatientType").Select(i => i), "DropDownID", "Name", ViewBag.PatientType);
            return View(patients.ToList());


In this example I have created instance of PredicateBuilder with PatientInfo Model and add multiple OR and AND Condition based on their value. Predicate Builder automatically create dynamic query with Linq and combined into one Expression.

When We have grid which filters record based on applied filter and filter parameter is in large number decision of use Dynamic LINQ result very high performance and minimize code writing while implementation otherwise it requires number of if else statement based on filter parameter.

In above code I have used entity framework Entity function which is very useful when we have to perform DateTime operation. It is internally worked as SQL DateTime function.



  /// <summary>
    /// Enables the efficient, dynamic composition of query predicates.
    /// </summary>
    public static class PredicateBuilder
        /// <summary>
        /// Creates a predicate that evaluates to true.
        /// </summary>
        public static Expression<Func<T, bool>> True<T>() { return param => true; }

        /// <summary>
        /// Creates a predicate that evaluates to false.
        /// </summary>
        public static Expression<Func<T, bool>> False<T>() { return param => false; }

        /// <summary>
        /// Creates a predicate expression from the specified lambda expression.
        /// </summary>
        public static Expression<Func<T, bool>> Create<T>(Expression<Func<T, bool>> predicate) { return predicate; }

        /// <summary>
        /// Combines the first predicate with the second using the logical "and".
        /// </summary>
        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
            return first.Compose(second, Expression.AndAlso);

        /// <summary>
        /// Combines the first predicate with the second using the logical "or".
        /// </summary>
        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
            return first.Compose(second, Expression.OrElse);

        /// <summary>
        /// Negates the predicate.
        /// </summary>
        public static Expression<Func<T, bool>> Not<T>(this Expression<Func<T, bool>> expression)
            var negated = Expression.Not(expression.Body);
            return Expression.Lambda<Func<T, bool>>(negated, expression.Parameters);

        /// <summary>
        /// Combines the first expression with the second using the specified merge function.
        /// </summary>
        static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
            // zip parameters (map from parameters of second to parameters of first)
            var map = first.Parameters
                .Select((f, i) => new { f, s = second.Parameters[i] })
                .ToDictionary(p => p.s, p => p.f);

            // replace parameters in the second lambda expression with the parameters in the first
            var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);

            // create a merged lambda expression with parameters from the first expression
            return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);

        class ParameterRebinder : ExpressionVisitor
            readonly Dictionary<ParameterExpression, ParameterExpression> map;

            ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
                this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();

            public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
                return new ParameterRebinder(map).Visit(exp);

            protected override Expression VisitParameter(ParameterExpression p)
                ParameterExpression replacement;

                if (map.TryGetValue(p, out replacement))
                    p = replacement;

                return base.VisitParameter(p);

Above Predicate builder helper method reference from albahari and from stackoverflow article and learn how powerful feature it is.predicate builder also work with IEnumerable and IQueryable.


This article explain implementation of Dynamic Linq query using Predicate Builder. Hope this article is useful while implementing dynamic query using LINQ.
Thanks to Pavel Valdov for C# code syntax highlighter.

Connect to TFS using C Sharp


In this article, we learn how to connect TFS (Team Foundation Server) or VSO (Visual Studio Online) using C#. We can create console application based on TFS API.



Before starting to working on authenticating TFS using C#, we required TFS Client library reference in the project. You can add required library using a command in NuGet Package Manager.
Install-Package Microsoft.TeamFoundationServer.Client -Version 14.95.3
Install-Package Microsoft.VisualStudio.Services.Client -Version 14.95.3
After adding reference library you can copy below code in your app and add a required reference in the project.

Source Code:

 NetworkCredential credential = new NetworkCredential("username", "password");
 BasicAuthCredential basicCred = new BasicAuthCredential(credential);
 TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(
                    new Uri("https://project.visualstudio.com/DefaultCollection"),

As per above code, we require valid username and password which is passed to NetworkCredential instance and also require valid TFS URL which you are trying to connect using C#.

We can authenticate a user with basic authentication mechanism without prompting for TFS login dialog, that’s why we have passed credential as an argument in a BasicAuthCredential object. Without basic authentication mechanism app prompt for login information.

TfsTeamProjectCollection instance accept two arguments 1) Default collection Url 2) Credential with basic authentication wrapper. 

TfsTeamProjectCollection instance has authenticate() method which actually requests for authentication and returns result or exception based on the credential.


In this article, we have explored Basic TFS API and authenticated TFS without prompt for username and password.

Login using Google API with C#


In this article, we learn about how to login using Google OAuth 2.0 with C#(.NET) or Authenticate Google API in Dot Net.


As we know Google OAuth 2.0 requires ClientId and ClientSecret before we proceeding to further step. So, first of all, we have to generate ClientId and ClientSecret from Google Developer Console by creating credential or generating a credential for Web Application or from Native Application.

I hope you have google account already if not then first create one before proceeding further.

Step 1: Create Credential for OAuth App.
Select credential type OAuth ClientID
Step 2: Select appropriate application type from available option.
Select application type

Based on where we are using login with google account we can select an application type. Here I have use other which works for a console app, Web application hosted on localhost as well as on domain.

Step 3: Copy and save generate ClientId and Client Secret
Save ClientId and Client Secret

Now, you have your ClientId and ClientSecret which will be used for authenticating with Google API using C#.

Once you have setup project you need Google API Reference you can install from Nuget


Install-Package Google.Apis -Version 1.32.1

Here is main logic for authenticating google API
public async Task<Usercredential> getUserCredential()
            UserCredential credential;
            string[] scopes = new string[] {  }; // view and manage your Google Analytics data

            //Read client id and client secret from json file

            credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                       new ClientSecrets
                           ClientId = ConfigurationManager.AppSettings["ClientId"],
                           ClientSecret = ConfigurationManager.AppSettings["ClientSecret"]
                       }, scopes,
                "user", CancellationToken.None, new FileDataStore("Auth.Api.Store"));

            return credential;
Hi, here I have created one single method

  • Which grabs ClientId and Client Secret from Web.Config App settings.
  • Passes scopes as a parameter. You can request more detail if you want while requesting from the user
  • Used await and task feature for thread safe and as performance improvement and it is already supported by Google API Library.
When you put above code in your project and run the app it will redirect to Google Account page for validating your credential and request for granting permission to use your basic profile information for login purpose.

If you receive any error it means permission is not given or ClientId or Client Secret key is not valid.


In this article, we have learned about how to create ClientId and Client Secret for a talk with Google API and Login with Google Account functionality using C#.Code.

Javascript Tips and Tricks

Javascript Tips and Tricks


In this article, we learn about import consideration while we are working with javascript.This information will help you to prevent most common mistake while development. JS tips and Tricks at one place.


Quick tips
  1. Use === while comparing two variable instead of ==
  2. Remember undefined is not null
  3. Remember javascript falsy value:   0, '', NaN, null, undefined
  4. Remember javascript truthy value:   '0', 'any string', [] (Empty array), {} (Empty object), 0 (any non-zero number)
  5.  Always declare all variables at the beginning of every scope
  6.  "use strict"; In javascript to avoid unwanted bug due to a variable.
  7. Avoid global variable declaration
  8. Reduce globals e.g var name='abc', isValid=false; Should be writen as var common={name:'abc', isValid:false};
  9. Always declare local variables
  10. Never declare Number, String or Boolean Objects ( e.g. Never use: new Number(1), new String("abc"), new Boolean() )
  11. Use {} instead of new Object()
  12. Use "" instead of new String()
  13. Use 0 instead of new Number()
  14. Use false instead of new Boolean()
  15. Use [] instead of new Array()
  16. Use /()/ instead of new RegExp()
  17. Use function (){} instead of new Function()
  18. Avoid Using eval()
  19. Don't use short hand  e.g Always use curly bracket with conditional operation
  20. Place scripts at the Bottom of page
  21. Declare Variables Outside of the from loops and conditionals (such as if, for, while, switch and try)
  22. Properly comment your code
  23. Never pass a string to SetInterval and SetTimeOut. Instead, pass a function name.
  24. Always, Always Use Semicolons
In this article we have get idea of lots of JavaScript tips and tricks and best practice consideration while development.

Add Event To Dynamically Added Control


Sometimes in real world project we require that we can add html control dynamically to after page successfully rendered on browser. We also require to perform certain task such as register event based on requirement.

In this article we learn about how we can register event on html control which was added dynamically using jquery.

Two implement this type of demo first of all we require jQuery library you can download from Here.

Html Snippet:
<div class="container">
<div class="body-container">
<input id="btnNew" type="button" value="Add New Button" />
<ul class="parent-ul"></ul>
JavaScript Snippet:
        $(function () {
            console.log("DOM is READy");
            // button handler which is responsible for 
            //adding new html control
           $('#btnNew').click(function () {
            var cnt = $('.parent-ul .item').length;
            //Below method register click event on dynamically
          // added control
            $('.parent-ul').on('click', '.item', function () {
             //Below commented code also worked
             //$(document).on('click', '.item', function () {
             //  console.log($(this));

You can test above code on jsfiddle link
As per above code we are adding new list item dynamically as child element of unorder list '.parent-ul'.

To achieve this we have register click event on all child element of specific parent element(here parent-ul class) as per the above code.

In some scenario we didn't know exact parent element or have multiple parent with same type of child control, in that type of condition below code work perfectly as document (DOM) is parent of all element rendered on browser so we can attach any event or perform some specific tasks for control which are added dynamically in page.
             //Below commented code also worked
             $(document).on('click', '.item', function () {


In this article we have learn about how we can access or register event on dynamically added control on page using jquery.

How to access Session in javascript


In this article we learn about how we can access ASP.NET server side session variable or data in client side JavaScript.
I have requirement for current user session variable in client side to perform some action based on user and its role.

Here are method or way to interact session variable in client side or in JavaScript.

1. Directly access session variable with mix code(Asp.net Server side)
as per the below code.
     //First way to access session 
     console.log("UserId:" + '<%=Session["UserId"] %>');
     console.log("UserRole:" + '<%=Session["UserRole"] %>');
2. Fetch session value from HiddenField
To fetch session value from hidden field first we have to set session data in server side and then we can access stored hidden value data in client side javascript.
//Set session value to hidden field for access this value in jquery 
     protected void setSessionToHiddenValue()
         Session.Add("UserId", "Arvind");
         Session.Add("UserRole", "Admin");
         hdnUserId.Value = Convert.ToString(Session["UserId"]);
         hdnUserRole.Value = Convert.ToString(Session["UserRole"]);
     //We can access hidden session data as below 
     console.log("UserId:" + '<%= hdnUserId.Value %>');
     console.log("UserRole:" + '<%= hdnUserRole.Value %>');


In this article we have learn about accessing server side session variable in client side for take action based on current session. 

Asp.Net Utility Functions


This article contains most useful utility function for Asp.Net WebForm as well as Asp.Net MVC project. All this method is collected from Internet sources like stackoverflow so it will be useful to many developer to find all useful method at one place.

See listed below most useful functions

1. Replace all special character in input string with '-' character

This method replace special characters using Regex function
  public static string ReplaceSpecialChar(string input)
        Regex rgx = new Regex("[^a-zA-Z0-9]");
        input = rgx.Replace(input, "-");
        return input;

2. Remove all special characters from string

This method remove all special characters and prepare new string which contains alpha numeric character along with underscore and space.
     public static string RemoveSpecialCharacters(string str)
      StringBuilder sb = new StringBuilder(); 
      for (int i = 0; i < str.Length; i++)
          if ((str[i] >= '0' && str[i]<='9')||(str[i]>='A'&&str[i]<='z'
|| (str[i] == '_' || str[i] == ' ')))
      return sb.ToString();

3. Convert Unix long timestamp to C# DateTime object

Most of system contains unix timestamp for storing date value,which is most REST API response datet as unix timestamp. So,Below method is very useful to convert timestamp to DateTime object.
public static DateTime ConvertUNIXTimeStampTODateTime(long date)
        DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0,System.DateTimeKind.Utc);
        dtDateTime = dtDateTime.AddSeconds(date).ToLocalTime();
        return dtDateTime;

4. Get short description from long length string value

In real world project many times this situation arise that we need to display on first 50 or 100 charcter from long string. This method trim long string value with ellipse format to display some short description.

public static string GetShortDescription(string Description)
            string strDesc = string.Empty;
                if (Convert.ToString(Description) != string.Empty)
                    if (Description.Trim().Length > 100)
                        strDesc = Description.Trim().Substring(0, 100) + "...";
                        strDesc = Description.Trim();
            catch (Exception)
            return strDesc;

5. Convert C# DateTime to Unix long timestamp

As we require converting unix timestamp to C# DateTime,we also required to convert C# DateTime to Unix timestamp.
     public static long ConvertToUnixTimestamp(this DateTime target)
            var date = new DateTime(1970, 1, 1, 0, 0, 0, target.Kind);
            var unixTimestamp = System.Convert.ToInt64((target - date).TotalSeconds);
            return unixTimestamp;




Fill free to contribute your own some useful functions in github repository which I have publish at Asp.Net-Utility-Functions


In this article we have seen most useful common utility function for Asp.Net, I will also updating this article in coming days, so we can get all common utility functions at one place.

Dynamic Query in LINQ using Predicate Builder

Introduction This tutorial explain how to create dynamic query using LINQ, Using Predicate Builder  LINQ to SQL dynamic query and Q...

Learn More