Wednesday, July 5, 2017

Javascript Tips and Tricks

Javascript Tips and Tricks

Introduction

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.

Description

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.

Monday, July 18, 2016

Add Event To Dynamically Added Control

Introduction

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>
</div>
</div>
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;
            $('.parent-ul').append($("<li/>").addClass('item').text("Item"+(cnt+1)));
       });
            //Below method register click event on dynamically
          // added control
            $('.parent-ul').on('click', '.item', function () {
                console.log($(this));
            });
             //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 () {
               console.log($(this));
             });

Conclusion

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

Sunday, July 17, 2016

How to access Session in javascript

Introduction

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 %>');

Conclusion

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

Introduction

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] == ' ')))
               sb.Append(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;
            try
            {
                if (Convert.ToString(Description) != string.Empty)
                {
                    if (Description.Trim().Length > 100)
                    {
                        strDesc = Description.Trim().Substring(0, 100) + "...";
                    }
                    else
                    {
                        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;
     }

Reference

    http://stackoverflow.com

Note

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

Conclusion

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.

Wednesday, May 11, 2016

Exception LINQ to Entities does not recognize the method ToString



Introduction


This is most common exception occurs while we working with entity framework and converting data inside IQueryable result for filtering.

Description

Mainly full exception message as “LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.”
var result=dc.Tests.Where(i=>i.status==status.ToString()).FirstOrDefault();
This exception mainly occurs, when we query SQL database using entity framework. The problem is that you are calling ToString in a LINQ to Entities query (IQueryable to IEnumrable). That means the parser is trying to convert the ToString call into its equivalent SQL (which isn't possible...hence the exception).
To solve this problem there is different solution.
Solution 1:  All you have to do is move the ToString call to a separate line.
String userStatus=status.ToString();
var result=dc.Tests.Where(i=>i.status== userStatus).FirstOrDefault();

Solution 2: Convert IQueryable result to IEnumrable before convert.

var result=dc.Tests.AsEnumerable().Where(i=>i.status==status.ToString())
.FirstOrDefault();
Note: This is only feasible for small entity collection as the above method first fetch all database result to in memory using AsEnumerable() method and then filtering result. Not feasible for large Db result.
Solution 3:  Use entity framework extension method SqlFunctions Class or DbFunctions Class
var result=dc.Tests.Where(i=>i.status==status.ToString()).FirstOrDefault();

Here SqlFunctions.StringConvert method converts Linq entities query to SQL query.
Note: Good when the solution with temporary variables is not desirable for whatever reasons.

Conclusion

In this article we learn different way to solve most common exception while working with Entity Framework.

Connect to TFS using C#



Introduction

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.

Description

Prerequisite

Before starting to working on authenticating TFS using C#, we required TFS Client library reference in the project. You can add required library using below command in NuGet Package Manger.
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 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"),
                    basicCred);
 tpc.Authenticate();
      
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.

Conclusion

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

Saturday, March 19, 2016

Getting started with data visualization using D3js


Introduction

As per https://d3js.org/ D3 allows you to bind arbitrary data to a Document Object Model (DOM), and then apply data-driven transformations to the document. For example, you can use D3 to generate an HTML table from an array of numbers. Or, use the same data to create an interactive SVG bar chart with smooth transitions and interaction.

Description

Here we learn basic usage of D3js and then moved to different type of visualization chart.

1. How Selections works

Modifying documents using the W3C DOM API is tedious
For example, to change the text color of paragraph elements:
var paragraphs = document.getElementsByTagName("p");
for (var i = 0; i < paragraphs.length; i++) {
  var paragraph = paragraphs.item(i);
  paragraph.style.setProperty("color", "white", null);
}
D3 uses new W3C Selectors API and supported natively by modern browsers. Elements may be selected using a variety of predicates, including containment, attribute values, class and ID. You can rewrite above code as below in single line:
d3.selectAll("p").style("color", "white");
D3 provides numerous methods for mutating nodes: setting attributes or styles; registering event listeners; adding, removing or sorting nodes; and changing HTML or text content.These operators can get or set attributes, styles, properties, HTML and text content.

I have implemented demo for selector example  in jsfiddle
Here is different way to use selector and append new element

 - d3.select(selector) 
 Select first element which match to selector and selector varies to tag,class,id etc.If no elements in the current document match the specified selector, returns the empty selection.This function traverse the DOM top to bottom order. 
 - d3.select(node):
Select specified node.This is useful if you already have a reference to a node, such as d3.select(this) within an event listener.This function does not traverse the DOM.
 - d3.selectAll(selector):
Select all elements which match to selector.If no elements in the current document match the specified selector, returns the empty selection.This function traverse the DOM top to bottom order.  
     e.g.
     
d3.selectAll("P");
d3.selectAll(".someclass>p");
  - d3.selectAll(node):
Select specified elements of array.This is useful if you already have a reference to a node, such as d3.selectAll(this.childNodes) within an event listener.This function does not traverse the DOM.

Selection also works with chaining method, this applied multiple operations to same elements. Let's see example
 e.g. Here first we have select all p tag and then set text color and background color. 
d3.selectAll("p")
.style("color","blue")
.style("background-color","yellow");

For more information you can refer this

2. Dynamic Properties

D3 provides many built-in reusable functions and function factories, such as graphical primitives for area, line and pie charts.
For example, to randomly color paragraphs:
d3.selectAll("p").style("color", function() {
  return "hsl(" + Math.random() * 360 + ",100%,50%)";
});
To alternate shades of gray for even and odd nodes: 
d3.selectAll("p").style("color", function(d, i) {
  return i % 2 ? "#fff" : "#eee";
});
Computed properties often refer to bound data. Data is specified as an array of values, and each value is passed as the first argument (d) to selection functions.
With the default join-by-index, the first element in the data array is passed to the first node in the selection, the second element to the second node, and so on.
For example, if you bind an array of numbers to paragraph elements, you can use these numbers to compute dynamic font sizes:
 d3.selectAll("p")
    .data([4, 8, 15, 16, 23, 42])
    .style("font-size", function(d) { return d + "px"; });
 You can test this code in jsfiddle by changing selector

3.Enter, Update and Exit

Using D3’s enter and exit selections, you can create new nodes for incoming data and remove outgoing nodes that are no longer needed.

When data is bound to a selection, each element in the data array is paired with the corresponding node in the selection. If there are fewer nodes than data, the extra data elements form the enter selection, which you can instantiate by appending to the enter selection.
For example:
d3.select("body").selectAll("p")
    .data([4, 8, 15, 16, 23, 42])
  .enter().append("p")
    .text(function(d) { return "I’m number " + d + "!"; });

Updating nodes are the default selection—the result of the data operator. Thus, if you forget about the enter and exit selections, you will automatically select only the elements for which there exists corresponding data.

A common pattern is to break the initial selection into three parts: the updating nodes to modify, the entering nodes to add, and the exiting nodes to remove.
// Update…
var p = d3.select("body").selectAll("p")
    .data([4, 8, 15, 16, 23, 42])
    .text(function(d) { return d; });
// Enter…
p.enter().append("p")
    .text(function(d) { return d; });
// Exit…
p.exit().remove();
By handling these three cases separately, you specify precisely which operations run on which nodes. This improves performance and offers greater control over transitions.

For example, with a bar chart you might initialize entering bars using the old scale, and then transition entering bars to the new scale along with the updating and exiting bars.
D3 lets you transform documents based on data; this includes both creating and destroying elements. D3 allows you to change an existing document in response to user interaction, animation over time, or even asynchronous notification from a third-party.
A hybrid approach is even possible, where the document is initially rendered on the server, and updated on the client via D3.

You can learn more from this article.

4.Transformation, not Representation

D3 does not introduce a new visual representation. Unlike Processing, Raphaël, or Protovis, D3’s vocabulary of graphical marks comes directly from web standards: HTML, SVG, and CSS. For example, you can create SVG elements using D3 and style them with external stylesheets.
You can use composite filter effects, dashed strokes and clipping. If browser vendors introduce new features tomorrow, you’ll be able to use them immediately—no toolkit update required.
And, if you decide in the future to use a toolkit other than D3, you can take your knowledge of standards with you!
Best of all, D3 is easy to debug using the browser’s built-in element inspector: the nodes that you manipulate with D3 are exactly those that the browser understands natively.

5. Transitions

D3’s focus on transformation extends naturally to animated transitions. Transitions gradually interpolate styles and attributes over time. Tweening can be controlled via easing functions such as “elastic”, “cubic-in-out” and “linear”.
 D3’s interpolators support both primitives, such as numbers and numbers embedded within strings (font sizes, path data, etc.), and compound values. You can even extend D3’s interpolator registry to support complex properties and data structures.
For example, to fade the background of the page to black:
d3.select("body").transition()
    .style("background-color", "black");
Or, to resize circles in a symbol map with a staggered delay:
d3.selectAll("circle").transition()
    .duration(750)
    .delay(function(d, i) { return i * 10; })
    .attr("r", function(d) { return Math.sqrt(d * scale); });
By modifying only the attributes that actually change, D3 reduces overhead and allows greater graphical complexity at high frame rates. D3 also allows sequencing of complex transitions via events. And, you can still use CSS3 transitions; D3 does not replace the browser’s toolbox, but exposes it in a way that is easier to use. 

Reference link: https://github.com/mbostock/d3/wiki

Conclusion

In this article we have learned basic concepts of D3 charting and feature. In next series of article we learn real chart example with customization.

Wednesday, July 5, 2017

Javascript Tips and Tricks

Javascript Tips and Tricks

Introduction

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.

Description

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.

Monday, July 18, 2016

Add Event To Dynamically Added Control

Introduction

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>
</div>
</div>
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;
            $('.parent-ul').append($("<li/>").addClass('item').text("Item"+(cnt+1)));
       });
            //Below method register click event on dynamically
          // added control
            $('.parent-ul').on('click', '.item', function () {
                console.log($(this));
            });
             //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 () {
               console.log($(this));
             });

Conclusion

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

Sunday, July 17, 2016

How to access Session in javascript

Introduction

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 %>');

Conclusion

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

Introduction

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] == ' ')))
               sb.Append(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;
            try
            {
                if (Convert.ToString(Description) != string.Empty)
                {
                    if (Description.Trim().Length > 100)
                    {
                        strDesc = Description.Trim().Substring(0, 100) + "...";
                    }
                    else
                    {
                        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;
     }

Reference

    http://stackoverflow.com

Note

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

Conclusion

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.

Wednesday, May 11, 2016

Exception LINQ to Entities does not recognize the method ToString



Introduction


This is most common exception occurs while we working with entity framework and converting data inside IQueryable result for filtering.

Description

Mainly full exception message as “LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.”
var result=dc.Tests.Where(i=>i.status==status.ToString()).FirstOrDefault();
This exception mainly occurs, when we query SQL database using entity framework. The problem is that you are calling ToString in a LINQ to Entities query (IQueryable to IEnumrable). That means the parser is trying to convert the ToString call into its equivalent SQL (which isn't possible...hence the exception).
To solve this problem there is different solution.
Solution 1:  All you have to do is move the ToString call to a separate line.
String userStatus=status.ToString();
var result=dc.Tests.Where(i=>i.status== userStatus).FirstOrDefault();

Solution 2: Convert IQueryable result to IEnumrable before convert.

var result=dc.Tests.AsEnumerable().Where(i=>i.status==status.ToString())
.FirstOrDefault();
Note: This is only feasible for small entity collection as the above method first fetch all database result to in memory using AsEnumerable() method and then filtering result. Not feasible for large Db result.
Solution 3:  Use entity framework extension method SqlFunctions Class or DbFunctions Class
var result=dc.Tests.Where(i=>i.status==status.ToString()).FirstOrDefault();

Here SqlFunctions.StringConvert method converts Linq entities query to SQL query.
Note: Good when the solution with temporary variables is not desirable for whatever reasons.

Conclusion

In this article we learn different way to solve most common exception while working with Entity Framework.

Connect to TFS using C#



Introduction

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.

Description

Prerequisite

Before starting to working on authenticating TFS using C#, we required TFS Client library reference in the project. You can add required library using below command in NuGet Package Manger.
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 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"),
                    basicCred);
 tpc.Authenticate();
      
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.

Conclusion

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

Saturday, March 19, 2016

Getting started with data visualization using D3js


Introduction

As per https://d3js.org/ D3 allows you to bind arbitrary data to a Document Object Model (DOM), and then apply data-driven transformations to the document. For example, you can use D3 to generate an HTML table from an array of numbers. Or, use the same data to create an interactive SVG bar chart with smooth transitions and interaction.

Description

Here we learn basic usage of D3js and then moved to different type of visualization chart.

1. How Selections works

Modifying documents using the W3C DOM API is tedious
For example, to change the text color of paragraph elements:
var paragraphs = document.getElementsByTagName("p");
for (var i = 0; i < paragraphs.length; i++) {
  var paragraph = paragraphs.item(i);
  paragraph.style.setProperty("color", "white", null);
}
D3 uses new W3C Selectors API and supported natively by modern browsers. Elements may be selected using a variety of predicates, including containment, attribute values, class and ID. You can rewrite above code as below in single line:
d3.selectAll("p").style("color", "white");
D3 provides numerous methods for mutating nodes: setting attributes or styles; registering event listeners; adding, removing or sorting nodes; and changing HTML or text content.These operators can get or set attributes, styles, properties, HTML and text content.

I have implemented demo for selector example  in jsfiddle
Here is different way to use selector and append new element

 - d3.select(selector) 
 Select first element which match to selector and selector varies to tag,class,id etc.If no elements in the current document match the specified selector, returns the empty selection.This function traverse the DOM top to bottom order. 
 - d3.select(node):
Select specified node.This is useful if you already have a reference to a node, such as d3.select(this) within an event listener.This function does not traverse the DOM.
 - d3.selectAll(selector):
Select all elements which match to selector.If no elements in the current document match the specified selector, returns the empty selection.This function traverse the DOM top to bottom order.  
     e.g.
     
d3.selectAll("P");
d3.selectAll(".someclass>p");
  - d3.selectAll(node):
Select specified elements of array.This is useful if you already have a reference to a node, such as d3.selectAll(this.childNodes) within an event listener.This function does not traverse the DOM.

Selection also works with chaining method, this applied multiple operations to same elements. Let's see example
 e.g. Here first we have select all p tag and then set text color and background color. 
d3.selectAll("p")
.style("color","blue")
.style("background-color","yellow");

For more information you can refer this

2. Dynamic Properties

D3 provides many built-in reusable functions and function factories, such as graphical primitives for area, line and pie charts.
For example, to randomly color paragraphs:
d3.selectAll("p").style("color", function() {
  return "hsl(" + Math.random() * 360 + ",100%,50%)";
});
To alternate shades of gray for even and odd nodes: 
d3.selectAll("p").style("color", function(d, i) {
  return i % 2 ? "#fff" : "#eee";
});
Computed properties often refer to bound data. Data is specified as an array of values, and each value is passed as the first argument (d) to selection functions.
With the default join-by-index, the first element in the data array is passed to the first node in the selection, the second element to the second node, and so on.
For example, if you bind an array of numbers to paragraph elements, you can use these numbers to compute dynamic font sizes:
 d3.selectAll("p")
    .data([4, 8, 15, 16, 23, 42])
    .style("font-size", function(d) { return d + "px"; });
 You can test this code in jsfiddle by changing selector

3.Enter, Update and Exit

Using D3’s enter and exit selections, you can create new nodes for incoming data and remove outgoing nodes that are no longer needed.

When data is bound to a selection, each element in the data array is paired with the corresponding node in the selection. If there are fewer nodes than data, the extra data elements form the enter selection, which you can instantiate by appending to the enter selection.
For example:
d3.select("body").selectAll("p")
    .data([4, 8, 15, 16, 23, 42])
  .enter().append("p")
    .text(function(d) { return "I’m number " + d + "!"; });

Updating nodes are the default selection—the result of the data operator. Thus, if you forget about the enter and exit selections, you will automatically select only the elements for which there exists corresponding data.

A common pattern is to break the initial selection into three parts: the updating nodes to modify, the entering nodes to add, and the exiting nodes to remove.
// Update…
var p = d3.select("body").selectAll("p")
    .data([4, 8, 15, 16, 23, 42])
    .text(function(d) { return d; });
// Enter…
p.enter().append("p")
    .text(function(d) { return d; });
// Exit…
p.exit().remove();
By handling these three cases separately, you specify precisely which operations run on which nodes. This improves performance and offers greater control over transitions.

For example, with a bar chart you might initialize entering bars using the old scale, and then transition entering bars to the new scale along with the updating and exiting bars.
D3 lets you transform documents based on data; this includes both creating and destroying elements. D3 allows you to change an existing document in response to user interaction, animation over time, or even asynchronous notification from a third-party.
A hybrid approach is even possible, where the document is initially rendered on the server, and updated on the client via D3.

You can learn more from this article.

4.Transformation, not Representation

D3 does not introduce a new visual representation. Unlike Processing, Raphaël, or Protovis, D3’s vocabulary of graphical marks comes directly from web standards: HTML, SVG, and CSS. For example, you can create SVG elements using D3 and style them with external stylesheets.
You can use composite filter effects, dashed strokes and clipping. If browser vendors introduce new features tomorrow, you’ll be able to use them immediately—no toolkit update required.
And, if you decide in the future to use a toolkit other than D3, you can take your knowledge of standards with you!
Best of all, D3 is easy to debug using the browser’s built-in element inspector: the nodes that you manipulate with D3 are exactly those that the browser understands natively.

5. Transitions

D3’s focus on transformation extends naturally to animated transitions. Transitions gradually interpolate styles and attributes over time. Tweening can be controlled via easing functions such as “elastic”, “cubic-in-out” and “linear”.
 D3’s interpolators support both primitives, such as numbers and numbers embedded within strings (font sizes, path data, etc.), and compound values. You can even extend D3’s interpolator registry to support complex properties and data structures.
For example, to fade the background of the page to black:
d3.select("body").transition()
    .style("background-color", "black");
Or, to resize circles in a symbol map with a staggered delay:
d3.selectAll("circle").transition()
    .duration(750)
    .delay(function(d, i) { return i * 10; })
    .attr("r", function(d) { return Math.sqrt(d * scale); });
By modifying only the attributes that actually change, D3 reduces overhead and allows greater graphical complexity at high frame rates. D3 also allows sequencing of complex transitions via events. And, you can still use CSS3 transitions; D3 does not replace the browser’s toolbox, but exposes it in a way that is easier to use. 

Reference link: https://github.com/mbostock/d3/wiki

Conclusion

In this article we have learned basic concepts of D3 charting and feature. In next series of article we learn real chart example with customization.