Wednesday, April 29, 2015

Filters In Angular JS

Filters are the way to format data in certain order, type to be displayed on the View. Angular filters are one of the cool concepts to work with. They are great; they're very powerful for transforming our data so easily into reusable and scalable little chunks. Filters help in picking out the data in our style or format. The API for the filters in Angular JS is filterProvider.

How To Add Filters:

A filter can be added in the Expression using the Pipe (|) symbol.  It is a reserved operator which denoted that we are applying filters for the expression.

<p>The name is {{ UserName | uppercase }}</p>


We can Use the filter either in HTML Expression on using Javascript. Here are the samples for them
 {{ expression | filter : expression : comparator}}

In Javascript

$filter('filter') (array, expression, comparator)

Using Multiple Filters

Multiple filters can be applied using PIPE (|) separation as below

                {{ expression | filter1 | filter2 | ... }}

If we have to pass arguments to these filters then we can pass them using the Colon (:) Symbol

{{ expression | filter:argument1:argument2:... }}

Some Common Filter used for data transformation are

  1. Currency : Used to format data in currency format.
<div ng-app="" ng-controller="currencyCtrl">
<input type="number" ng-model="quantity">
<input type="number" ng-model="price">
<p> Total = {{ (quantity * price) | currency }} </p>

  1. Data Filter :  These filter are used to filter some subset of data from a given set of data.
<body ng-app="TestApp">
  <div ng-controller="TestCtrl">
    <form class="form-inline">
      <input ng-model="Search" type="text"
        placeholder="Filter by" autofocus>
    <ul ng-repeat="customers in customers | filter:search | orderBy: 'name' ">

  1. Upper and Lower case filter
<div ng-app="" ng-controller=" TestCtrl ">
<p>The name is {{ Name | uppercase }}</p>

<div ng-app="" ng-controller=" TestCtrl ">
<p>The name is {{ Name | lowercase }}</p>

  1. Order by :  These can be applied to sort the filter data
<body ng-app="TestApp">
  <div ng-controller="TestCtrl">
    <form class="form-inline">
      <input ng-model="Search" type="text"  placeholder="Filter by" autofocus>
    <ul ng-repeat="customers in customers | filter:search | orderBy: 'name' ">

  1. LimitTo :  These are used to restrict the value in the expression for example if we want to display only 10 items from collection we can use
<div ng-controller="TestCtrl">
 <li ng-repeat="customer in customers | limitTo:10 ">

  1. Date
   <p class="OrderDate">Items Order On: {{item.dateOrdered | date:'dd/MM/yy'}}</p>

  1. Number:  To restrict the decimal value to certain place we set this filter so that the No of decimal will appear accordingly.
        <p class="itemPrice">{{item.price | number:2 }}</p>
                <p> {{item.description}}</p>

  1. Custom Filter :   We can create custom filter by adding and using existing filters in combination. Here is a sample code for it.
<div ng-controller="TestController">
  <input ng-model="CustomTest" type="text"><br> 
  Reverse String: {{CustomTest|reverse}}<br>
  Reverse string in uppercase: {{CustomTest|reverse:true}}<br>

Hope you all like this piece of information. Filter is very powerful way for the data formatting using Angular JS. Please provide your feedback or comment so that I can improve further. I will come up with some more points in Angular JS soon.

Thanks & Regards
Anil Kumar Pandey
Microsoft MVP, Microsoft MCC, DNS MVM

Wednesday, March 11, 2015

Visual Studio 2015 CTP 5

Visual Studio 2015

Last week the Preview for Visual studio 2015 for Community user is released. Multiple innovative Ideas and featured has been included in it. Which include update in ASP.Net as well. I have tried to summarize some of the Key feature for this CTP release. Some of the key features are listed below.
  1. UI Debugging  :       There are 2 new tools are added for XAML UI debugging named as
    1.  Live Visual Tree
            This feature allows us to view the complete visual tree while we are debugging a code. We can select any element from the visual tree and use the live property to view respective property of that control or element.
    1.  Live Property Explorer
This feature enables us view the property of the element in XAML while we are debugging the code. We can set some changes immediately and can view the effect.
  1. Single Sign On :      This is mainly deals when we are using any cloud environment for example either for our data base or our code base. In this situation we would require to sign on all the application. With this new Single Sign On feature the single signing in in application will allows us smooth access for all our application and environments.

  1. CodeLense :            This is a very interesting tool added in VS 2015, with the help of CodeLense we can any time check the History or version of our C++, SQL and JavaScript file, while we are working on the Editor. The Information related to work items associated with code in TFS can also be viewed with this.

  1. Code Maps:             Maps are the best way to navigate among the dependency for the code. With this feature you can jump between them quickly and even can drag drop, create links between them. You can show or hide code elements on a map based on their category, as well as group code elements by solution folders, assemblies, namespaces, project folders, and types.

  1. Diagnostic Tools:  The Improvement for the Diagnostic tool debugger is done  with 64 bit Windows store app and zoom for most recent event break.

  1. Exception Settings:          The exception related settings can be done using this tool which will not impact in the code and will improve the performance.

7.     Java script Editor:                          As requested earlier there will be a Java script editor which will allows us to use the TASK LIST feature  and the more advanced Intellisence will be available.

  1. Unit Test:                 The improvement towards the Unit testing side is also done. Now we can create Parameterized Unit test means there will be an API available for test data generation and correcting the properties. The Library for this is Microsoft.Pex.Framework.  The Context menu Smart Unit Test will be available.
Along with that the “Create Unit Text” context menu will also be available which will improve the performance by faster addition of test class or test stub.

  1. Android Emulator:            The Emulator will come up with some additional features like  Android 4.3 and 4.4. Along with that the IOS 6, 7 and 8 will also be supported.  Windows Mobile 8.1 will also be supported.

  1. Mobile Development for Cross platform:                Now Visual studio can be used to create mobile application for across the platform with a single solution only.  Android Lollipop API, Android Logcat support is added, using which we can search log message, scroll messaged, can clear previous message and move between various log levels.  We will also get precompiled headers in the template.

  1. ASP.NET :     various new enhancement are done in ASP.NET as well like Run and Debug setting are now captured in debugSetting.jsonIntellisense is more advanced, lot new API templates, Windows PowerShell script can be used and customized for ASP.NET 5. And the long required debugging option for debugger window for LAMBDA expression.

I hope you will enjoy these features. Microsoft has request the community members to use the Windows 2015 and provide there valuable suggestion and feedback along with reporting option for Bug if at all any you find while using visual studio 2015.  You can download the Visual Studio 2015 from the below location. Download.  Please provide your suggestion for the above article and please feel free to share your comments and any question if you are having.

Saturday, February 21, 2015

Code Quality and Test Coverage using NCover

For any Developer the code quality is at most important, every organization put emphasis and focus on a very good code quality whether it is a Product based company or a service organization. All the process which we follow to improve the Quality are mainly focused on finding defect if at all any present in the code and fixing them ASAP.

Now days everyone is going for agile methodology, which is one of the best methodology to improve the code quality and deliver highly efficient code. Agile also force to make most of the automation test so that in a quick time limit we can have maximum code tested.

Then the Question arises:-

How much code is covered in or test case?

How Can I Cover entire code in test case?

What can be done to reduce less tested code?

In this case we go for a Test coverage tool or option which will give some figures and facts that how much percentage of the code is tested, covered and left untouched. There are a l lot of statistics and measurement required to baseline the approach and finalize that we are having maximum code coverage.

There are a lot of test coverage tools are present in the market. Recently I came across one of them and I was really happy with the result it has given to me. That tool is NCover. NCover provides a very powerful and flexible tool set which can integrate into your build process and help you deliver higher quality code. The flexibility provided by the NCover tools may seem a little intimidating at first, but with a little experimentation it is easy integrate NCover with any build process. 

The latest version of NCover is NCover 5. I have tried this application with some of my application and I am pleased with the kind of response it has given to me. Some of the latest features added in NCover 5 are

      1.       Improved static analysis for expanded merging

2.       Public browsing of code central projects

3.       Enhancements to ncover user interface
4.       Pre-instrumentation
5.       Coverage for windows store apps
6.       Condition coverage
7.       Baseline executions
8.       Self-contained html report
9.       Expanded coverage data exporting
10.   Visual studio theme support
11.   Expanded test runner support
12.   Improved bolt performance

Implementing Code Coverage using NCover.

NCover performs analysis on code by instrumenting it behind the scenes while the tests are running. If using NUnit as the unit testing tool, simply prefix the NUnit command line with the NCover command.
NUnit command line:

nunit-console MyTests.dll

NUnit with NCover:

NCover.Console nunit-console MyTests.dll

It's easy enough to create code coverage data, but analysis is where you actually begin to improve your tests. We include NCoverExplorer with NCover for this purpose. NCoverExplorer highlights those lines of your code that are uncovered, and does statistical analysis of your coverage data as well. It can even run a program and collect coverage data for you, so many developers never touch the command line version of NCover. NCover also includes an HTML reporting feature for teams that want to generate analysis reports including highlighted code directly from their continuous integration server

Some of the GUI option for NCover are

You can download the Trail version from Below location. NCover Download. For more details Please visit the below location.  I  hope you will like using this tool and improve the quality of the code. Please provide your feed back for this article or any more support on the NCover tool. I will try to resolve them or will take them directly to the NCover team.

Thanks & Regards
Anil Kumar Pandey
Microsoft MVP, Microsoft MCC, DNS MVM

Wednesday, October 1, 2014

Constraints in Attribute Based Routing MVC5

In the previous article we have discussed about the attribute based Routing where the Routes can be specified directly above the Action method or Controller class itself. Now going ahead we will discuss about the Constrained that can be used in the Route.

Constraints are nothing but the validation which we can directly apply on the action methods using the Attribute based routing. With this you also gain the ability to validate your actions more like function overrides, a route will only be matched if the data type matches or the validation we have applied otherwise the request will fall through to the next route matching the pattern, looking for a supported data type.

Some of the common and widely used Constraints are as follows.

Data Type Related

[Route("MyRoute/{x:int}")]  // Matches 32 Bit integer value
public User GetUserById(int id) { ... }

[Route("MyRoute/{x:long}")]  // Matches 64 Bit integer value
public User GetUserById(long id) { ... }

[Route("MyRoute/{x:float}")]  // Matches 32 Bit floating point value
public User GetUserById(float id) { ... }

 [Route("MyRoute/{x:double}")]  // Matches 64 Bit floating point value
public User GetUserById(double id) { ... }

[Route("MyRoute/{x:decimal}")]  // Matches a decimal value
public User GetUserById(decimal id) { ... }

[Route("MyRoute/{x:bool}")]  // Matches a boolean value
public User GetUserByCondition(bool id) { ... }

[Route("MyRoute/{x:guid}")] // Matches a Unique Identifier value
public User GetUserById(GUID id) { ... }

[Route("MyRoute/{x:datetime}")]  // Matches a datetime value
public User GetUserByIdLoginTime(datetime id) { ... }

String Related Constraints 

[Route("MyRoute/{x:alpha}")]  // Matches upper and lower case value from a-z
public User GetUserByName(string id) { ... }
[Route("MyRoute/{x:length(5)}")]  // Matchesstring value with specified length
public User GetUserByName(string id) { ... }
[Route("MyRoute/{x:length(2,100)}")]  // Matches string value with specified length range
public User SetUserByName(string id) { .. }

[Route("MyRoute/{x:minlength(8)}")]  // Matches a string with minimum specified length
public User SetUserByName(string id) { ... }

[Route("MyRoute/{x:maxlength(20)}")]  // Matches a string value with specified maximum length
public User SetUserByName(string id) { ... }

Other Common Constraints

[Route("MyRoute/{x:min(1)}")]  // Matches integer value with minimum specified value
public Product GetAmount(int id) { ... }

[Route("MyRoute/{x:max (100)}")]  // Matches integer with specified maximum value
public Product GetAmount(int id) { ... }

[Route("MyRoute/{x:range(1, 100)}")]  // Matches integer with specified range of value
public Product GetProducts(int id) { ... }

[Route("MyRoute/{x:regex(^[a-z][0-9]$)}")]  // Matches value with specified regular expression
public Product GetProducts(int id) { ... }

[Route("QuerystringParameterExists?{X})]  // Matched Query string parameter if it exist or not
public Product GetProducts(int id) { ... }

[Route("QuerystringParameterConstraints{x:int}&{y:int}")]  // Matched Query string parameter if they are of specified type or not
public Product GetProducts(int id) { ... }

Custom Route Constraints

You can create custom route constraints by implementing the IHttpRouteConstraint interface. For example, the following constraint restricts a parameter to a set of predefined values.

public class CorrectConstraint: IRouteConstraint
   private readonly string[] correctOptions;
   public CorrectConstraint(string strOptions)
        correctOptions = strOptions.Split('#');

p        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
                 object value;
                 if (values.TryGetValue(parameterName, out value) && value != null)
                  return correctOptions.Contains(value.ToString(), StringComparer.OrdinalIgnoreCase);
                  return false;

     To register this value in the Constraint we have to add the code in the Route config as below.

      public static void RegisterRoutes(RouteCollection routes)
        var constraintsResolver = new DefaultInlineConstraintResolver();
        constraintsResolver.ConstraintMap.Add("values", typeof(ValuesConstraint));

And the Route can be called as  below.

     public class BusinessController : Controller
             public ActionResult Show(string scale)
                 return Content("Valid set of value is " + scale);

Hope you now Understand that how the constraints in the Attribute based route can be used and applied and how can we create a custom base Route.  Please feel free to provide your valuable comment on the same.

Thanks & Regards
Anil Kumar Pandey
Microsoft MVP, Microsoft MCC, DNS MVM