November 11, 2014

Working with NDepend


NDepend is a software tool which can be integrated with Visual Studio. After successful installation, you can see an NDepend menu option in your Visual Studio menu bar. Most of the sub-menu may be disabled. Here, I have integrated NDepend with MS Visual Studio 2010. To work with, select menu:


NDepend > NDepend Start Page


The start page will display solution analysis link and can be look like as shown in figure below.


To analyze your project and solution, click on link “Analysis VS Solutions and VS Projects”.

It will pop up a child window which will display all solution files available in your system. You can select any solution file or can browse a solution from “Browse” button and then click OK.

In next window, it may ask to choose an assembly from list of assemblies. For this just click on “Analyze .Net 4 assembly” button, now you can see all the sub-menus have been activated.



Dashboard:

The dashboard will display summary of your project solution including- lines of code, method complexity, code rules, rules violated, types, percentage of comment lines, third-party usages and related. A summary dashboard you can see in below image.






To be continued in next article, detail about working of NDepend.

October 24, 2014

Software Quality Assurance (QA) and NDepend

Background:

Software quality is not limited to testing for strong validations, security and vulnerabilities but also depends upon its architecture, coding standards, and defined business logics.

Quality assurance (QA) generally does by separate quality team in software industries and qualifies it after validations, security, vulnerabilities and performance testing. Testers do not have any idea about coding standards and business structures used behind the scene. Now the question arises, if coding guidelines and business structure are not defined properly then does the software will be really a quality product?

Object oriented (OO) concepts are not a piece of cake. Understanding, coding and managing software program in object oriented paradigm (OOPs) is really a big challenge in software development.

Consider you are the lead of a project and numbers of programmers are programming. Your assigned project is really big, then how you will assure about its quality in terms of coding standard, unless you do not have thorough knowledge about written codes? Second thing, is it an easy task for you to review entire project code lines and to decide whether the implemented concepts are write or wrong? Where the programmers have violated the rules? What could be the best approach? To find the variables defined but never been used? What are the dead codes? Rules violated, project dependencies, third party DLL(s) used in it? Not limited to these only, but numerous of similar challenges comes while handling large projects, because you can never assume all the programmers have same understandings.

Before, to overcome these problems, you need to do hard work to review and find all code logic written in assemblies or in project scope. But now a day’s tools are available in market those can really make your task easy and accurate.



NDepend: Your project review partner.

One of the tools I discovered is NDepend. This tool finds all the dependencies, assemblies used in project, reviews the code lines, classes & OOPs methodologies implemented and finally gives you a visual report from where you can easily monitor and track the limitations as well rules violated in your class libraries. Nevertheless, it has a user friendly dashboard which shows graphical representations of entire code activities, dependencies, code rules, rules violated, types, percentage of comment lines, third party tools used and similar.



October 16, 2014

Error: The type or namespace name 'Ajax' does not exist in the namespace System.Web.Mvc

ASP.Net MVC ERROR: The type or namespace name 'Ajax' does not exist in the namespace 'System.Web.Mvc' (are you missing an assembly reference?)


Solution:

Right click on respective referenced .dll, go to 'Properties', set property Copy Local = True, and then rebuild.

Error: Entity framework "Cannot convert from 'System.Data.Objects.ObjectParameter' to 'System.Data.Entity.Core.Objects.ObjectParameter"

Entity Framework ERROR: Cannot convert from 'System.Data.Objects.ObjectParameter' to 'System.Data.Entity.Core.Objects.ObjectParameter[]' entity framework 6


This is one of most frequent compile time error you may face in Entity Framework. This is because either of:

1. Version conflict or
2. Namespace used.


By default, while compiling project, framework includes namespace using System.Data.Objects;


Solution:

To fix this issue:

If version conflicts, install package for respective version of EF.

If version is same, change the above namespace to System.Data.Entity.Core.Objects 


July 17, 2014

Read excel file using C# and .NET

With C#, we can read excel file data and can store it into DataTable object easily. To do this, you may need to install and prepare development environment as well in the system wherever you want to deploy this application. This is one of the probable solution and is not limited to. Also, I have developed and tested this in Windows environment only, no idea about other OS. Development environment: OS Windows 7 32bit, VS 2012, Excel 2013.


Prerequisites:

1. Download and install "Data Connectivity Components".
2. Register msexcl40.dll located in C:\Windows\System32
3. Register oledb32.dll located in C:\Program Files\Common Files\System\Ole DB



Create an excel file. Here, I have created with name Test.xlsx as shown in figure below.





















Lets move to C# code. To work with excel file, you need an OledbConnection object to communicate with the .xls/.xlsx file. OLEDB (Object Linking and Embedding, Database) is an API designed by Microsoft to access data with variety of sources like excel, access etc. in a uniform manner.
Another object we need is OleDbDataAdapter, to fill data into DataTable object. The method is as simple as communicating database.

using System.Data.OleDb;

OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='file_path';Extended Properties='Excel 12.0;HDR=Yes'");
// file_path should be complete file path. Example: E:\\TestData\\Test.xlsx
// HDR = Yes/No. If Ist row is column name, set HDR = Yes.

DataTable tbl = new DataTable("Particulars");
OleDbDataAdapter adp = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", con);
// Sheet1$ : The name of sheet/tab in excel file, you want to read.


adp.Fill(tbl);


And the object "tbl" output has shown in figure below.

















Probable error(s) could be possible:

  1. 1. The 'Microsoft.Jet.OLEDB.12.0' provider is not registered on the local machine.
  2. 2. Could not find installable ISAM.
  3. 3. External table is not in the expected format.


The above error(s) can be possible if:-
  1. Connection string is incorrect or Microsoft.ACE.OLEDB.12.0 and Excel 12.0 are different version.
  2. msexcl40.dll and/or oledb32.dll are/is not registered properly.
  3. You are building your application with 64bit but application does not support it. If any of such issue(s) still persists, change platform target to 32bit. To do this, right click on project, click properties, navigate to Build tab, set Platform target to x86.



Hope this will help you and you enjoyed the codding.

July 16, 2014

Debugging windows service in .NET without process attachement

This concept is not developed by me. I got it over the net while working with my windows service and found really good. Therefore, I wish to share it with you. Hope you will love it and can debug your windows service without attaching any process. The complete article can be read here.

The same code, given below, I have pasted in Program.cs and I could debug my service as a normal application.


July 14, 2014

HTTP Error 500.21 - Internal Server Error: ExtensionlessUrlHandler-ISAPI-4.0_32 bit has a bad module

HTTP Error 500.21 - Internal Server Error
Handler "ExtensionlessUrlHandler-ISAPI-4.0_32bit" has a bad module "IsapiModule" in its module list














Solution:

By changing following settings with IIS and .config file, you can fix this issue.

Step: 1. Reorder the handlers in your .config file and make ExtensionlessUrlHandler-ISAPI-4.0_64bit as default.



     
 
     
 
           
     
         
 
   
Step: 2. Set framework version to "ASP.Net v4.0" in application pool it has assigned.


I could resolved my issue with these two changes.

June 17, 2014

Session management in ASP.Net MVC and C#

In ASP.NET MVC, we can manage session by four ways: Default, Disabled, ReadOnly and Required. By default, or if we do not provide a session mode, it is set to its Default mode. Session mode is defined in “SessionStateBehavior” class.
To set session mode of a controller, we can use “SessionState” attribute at the beginning of defined controller class. For example:


[SessionState(System.Web.SessionState.SessionStateBehavior.Default)]
public class HomeController : Controller
{

}


As we are defining the session mode of a particular controller, so its scope is limited to the respective controller only. Off course, for different controller we can set its different session mode.

Default mode has with its default and limited functionalities. Disabled mode restricts to store value in session. ReadOnly mode allows to read the session values but does not allow to write a value into session. Required mode allows to both read and write.

(This tutorial written under VS 2010, ASP.NET MVC 4)

June 11, 2014

Creating DOM in jQuery

Document Object Model in HTML or XML is a well-formed document with HTML tags or XML elements.
With jQuery, we can create DOM using ‘createElement()’ method. Many times, while programming, there may situations arise when you have part of HTML in string format and need to query it to find a particular value of tag, defined in it. In such cases DOM plays a vital role to achieve it.
Mechanism is simple, first create a DOM object with HTML string and then find for the element in the DOM object. In jQuery, you can create DOM object as:

var dom = document.createElement('div');

While programming, I got trapped in a situation where I need to find ‘span’ tag value on click event of a ‘div’ element. The scenario was, it was bound with a nested ‘div’ and was returning complete element having multiple HTML tags and I had to find single value – Transaction Number, to display the corresponding detailed information. The same I am sharing here with you.




Now, you can easily find element from the above, using simple jQuery syntax.

var val = $(dom).find("span").text();

And the above code will return: ‘TRANS00007’ without worrying about to manipulate long string.

Hope, it will be useful for you somewhere.

March 6, 2014

C# Most FAQ in Interview

  1. What is the difference between Abstract class & Interface? When to use Interface and when to use Abstract class?
  2. What is the scenario for multiple inheritances? Can you give an example?
  3. What are differences between IQueryable & IEnumerable?
  4. What are the difference between List & IEnumerable? Which is better?
  5. What is anonymous type? What is the difference between ‘var’ & ‘dynamic’?
  6. Can you explain about dependency injection?
  7. What are delegate and multi-cast delegate?
  8. What is anonymous method? 
  9. What is the lamda expression and expression tree?
  10. What is Lazy loading in C#?
  11. What is generation mechanism in memory management?
  12. What is extension method?
  13. What is the difference between finally and finalize?
  14. What is a strong name in assembly? What is satellite assembly?
  15.  What is delay signing? What are the type of signing in assembly & whats the difference?
  16. What are the types of inheritance? Describe all.
  17. What is the difference between a class & structure?
  18. What is a virtual class? Why we use virtual class?
  19. Suppose I need to use an DLL & I want to overwrite DLL method. What are the steps to achieve this?
  20. What is serialization? Why we use it? What are the types of serialization?
  21. What is a threading? What are its different types?

FAQs in ASP.NET MVC

  1. What is the benefit of Razor w.r.t. ASPX view engine?
  2. What are Action Link and Action Result in MVC? Can you list out the different types of action results returned by action method?
  3. What are areas in MVC?
  4. Does MVC support view state? If not, how can we can manage the same?
  5. What are Html helpers?
  6. How to create custom data annotation?
  7. What is filter in MVC? What are the types of filters in MVC?
  8. What is rout table in MVC?
  9. What is a view engine? Which is faster: Razor or ASPX?
  10. How MVC works to process a new request?
  11. What is the difference between MVC and MVVM?
  12. What are the difference between ASP.NET MVC and aspx web forms? When you will choose MVC architecture and when to choose ASPX web forms? 
  13. What is data annotation? Can you define how can I define custom data annotation?
  14. What is view bag, view data and temp data?
  15. How you will pass parameters to controllers? What are different techniques to pass parameters from view to controllers?

March 5, 2014

ServiceStack - An Introduction

What is a ServiceStack?

ServiceStack is an open source, cross-platform for .Net and Mono REST web service framework and can run on both .Net framework as well in Mono platform too. ServiceStack have the flexibility of auto configuration of all standard output formats – XML, JSON, CSV, JSV, SOAP1.1, SOAP1.2 and endpoints –REST, RPC, SOAP without any configuration. It embraces only the concepts of DTO and not RPC concept. Whereas, WCF has the option of both. Service developed in service stack can run in windows environment using .Net framework or in Linux OS with Mono* support.

*Mono supported OS are:

Linux, Mac OS X, iOS, Sun Solaris, BSD, MS Windows, Nintendo Wii, Sony PlayStation 3 etc.


Why ServiceStack?

ServiceStack is not instead of WCF for its better performance, but main feature is that it can be deployed and works in cross platform like Windows, Mono, Linux, iOS, Mac OS etc.


ServiceStack versus WCF:

- WCF can be deployed only windows platform whereas Service Stack supports cross OS environment deployment.
- WCF works on both DTO and RPC concepts whereas Service Stack works uses DTO concept only.
- In WCF, if we do not define attribute [DataContract] then it will ignore it. But Service Stack will serialize it in plain text.


Hosting a Service Stack: 
Service Stack can be hosted in any of the following:

  1. Stand-alone mode
  2. With an existing ASP.Net  web application
  3. Windows service
  4. Console application
For more detail, please read here.


Creating First Service Stack Web Service:

Download Service Stack libraries from visual studio package manager. To download run command:

Install-package ServiceStack

Steps to create a service stack:

Common name space:

using System.Web.UI;
using ServiceStack;
using ServiceStack.CacheAccess;
using ServiceStack.ServiceInterface;
using ServiceStack.WebHost.Endpoints;
using ServiceStack.CacheAccess;
using ServiceStack.ServiceInterface.ServiceModel;
using ServiceStack.OrmLite;
using ServiceStack.Common;

Step: 1 Create an empty web application and then install packages for service stack.

Step: 2 Add a class file ad define request and response class.

[Route("/HelloRequest")]
[Route("/HelloRequest/{Name}")]
public class HelloRequest
{
   public string Name { get; set; }
}

public class HelloResponce
{
   public string Result { get; set; }
}

public class HelloService : IService
{
   public object Any(EmployeeRequest reqObj)
   {
     return new HelloResponce { Result = "You have entered: " + reqObj.Name };
   }

  public object Get(EmployeeRequest reqObj)
  {
    Return your_definedtype;
  }
}


Step: 3 Add a class for AppHost.

public class HelloAppHost : AppHostBase
{
  public HelloAppHost() : base("Here is your service:", typeof(HelloService).Assembly)
 {

 }

  public override void Configure(Funq.Container container)
  {
    // Defined this route in class attribute
    Routes.Add("/HelloRequest")
   .Add("/HelloRequest/{Name}");
  }
}


Step: 4 Add a Global.asax file and add the following code line to initialize the service request.

protected void Application_Start(object sender, EventArgs e)
{
   new HelloAppHost().Init();
}


Step: 5 Add the following lines in Web.config file.


Step: 6 Build the service and run it. On browse you can see the following result, if everything is correct.






Step: 7 To test, type the URL as:

localhost:51391/hellorequest?name=navin&format=xml

This will display the result as you have passed in query string.

February 8, 2014

Custom Validation in ASP.Net MVC 4



To implement custom validation in C# ASP.NET MVC4, it needs to inherit “ValidationAttribute” class and overwrite “IsValid” method in your class. For this you need to add namespace System.ComponentModel.DataAnnotations.

Here, I am creating a class for my custom password attributes and its minimum length should be of 5 chars and maximum  length should be of 10 chars. I have initialized the values in its constructor and defined the code logic in overridden method “IsValid”.

public class PasswordAttribute : ValidationAttribute
{
            int MinLength;
            int MaxLength;

public PasswordAttribute(int minLength, int maxLength)
        {
            this.MinLength = minLength;
            this.MaxLength = maxLength;
        }

            public override bool IsValid(object value)
       {
            // TODO:
                     if (condition_satisfied)
                return true;
            else
                return false;
            }
}

Use the class to validate password value:

 public class SetUserPassword
 {
   [Required(ErrorMessage = "Please enter a password.", AllowEmptyStrings = false)]
   [Password(5, 10, ErrorMessage = "Please enter 5-10 digits password.")]
   public string Password { get; set; }

  }


ASP.Net MVC 4 provides four types of validations:
1. Required – To check for required field.
2. Range- To check for lower and upper limits.
3. Regular expression- To check for an expression.
4. Custom validation- User defined validation.
MVC4 does not provide Compare validation as in previous ASPX web forms. If you wish to use compare validation, either you may need to use the available DLL or go for custom validation.