Tuesday, April 28, 2015

Should i use Abstract Class or Interface ?

Most of the time developers get confused about abstract class and interface. while interview most of the time interviewer asks the difference between abstract class and interface, we give answer that we read on internet and what we have understanding, but it gets messed up always.


Also when developing applications, we are not sure often that it is the scenario to use abstract class or create interface.

I am posting text from CLR via C# book where Jeffery Richter is trying to explain when should we use abstract class and when interface. Here is the text from book:

I often hear the question "Should i design a base type or interface ?" The answer is not always clear cut.

Here are some guidelines that might help you:


  • IS - A VS CAN-DO relationship : A type can inherit only one implementation If the Derived type can't claim  IS-A relationship with the base type, don't use a base type, use an interface. interfaces imply a CAN-DO relationship. If the CAN-DO functionality appears to belong with various object types, use an interface. For example, a type can convert instances of itself to another type (IConvertible), a type can serialize an instance of itself (ISerializable), etc. Note that value types must be derived from System.ValueType, and therefore, they cannot be derived from an arbitrary base class. In this case, you must use a CAN-DO relationship and define an interface.
  • Ease of Use: It’s generally easier for you as a developer to define a new type derived from a base type than to implement all of the methods of an interface. The base type can provide a lot of functionality, so the derived type probably needs only relatively small modifications to its behavior. If you supply an interface, the new type must implement all of the members.
  • Consistent Implementation:No matter how well an interface contract is documented, it’s very unlikely that everyone will implement the contract 100 percent correctly. In fact, COM suffers from this very problem, which is why some COM objects work correctly only with Microsoft Word or with Windows Internet Explorer. By providing a base type with a good default implementation, you start off using a type that works and is well tested, you can then modify parts that need modification.
  • Versioning:If you add a method to the base type, the derived type inherits the new method, you start off using a type that works, and the user’s source code doesn't even have to be recompiled. Adding a new member to an interface forces the inheritor of the interface to change its source code and recompile.

Monday, April 27, 2015

Extension Methods Feature in C# with Simple Example

Introduction:


Extension methods are special type of methods which were introduced in C# 3.0. They are used to extend the functionality of  any existing type in .Net.Using extension method we can add new methods to a class/type without modifying original source code of  Type, recompiling, or creating a new derived type.

Normally when we use linq standard query operators that add query functionality to the existing IEnumerable and System.Collections.Generic.IEnumerable<T> types. For using the standard query operators,first bring them in scope by writing using System.Linq in the code file.

Now you can call for example GroupBy,OrderBy etc like instance methods on any type that implement IEnumerable<T>

According to MSDN :


Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

Syntax of writing Extension Method :


As extension method is a special method, it is defined little differently than normal method.Here is the points to be noted when writing extension method:

  1. It should be a static method.
  2. It should be written in a static class.
  3. its first parameter starts with this keyword followed by type parameter
  4. Extension method should be in the same namespace otherwise you will need to inculde namespace of the class with a using statement. 

Simple Example:


We can write extension method for any existing type in our code.Most of the time we write extension method for types that we cannot modify which are built-in in the .Net Framework.

I will make a simple extension method on string type to convert string to integer.


public static class StringExtensions
{
 public static int ToInt32(this string value)
 {
  int result;
  if (int.TryParse(value, out result))
  {
   return result;
  }

  return 0;
 }
} 

and we can use it to convert string to integer if string contains numeric value in. We can call it this way:


public class Program
{
 public static void Main()
 {
  
  Console.WriteLine("123".ToInt32());
  
 }
}

You can see running example in  this fiddle


Sunday, March 29, 2015

Translate C# code to JavaScript in Visual Studio using DuoCode

I have just seen this interesting thing that is launched with Roslyn Compiler in C# 6 which is that we can now write code in C# and Roslyn Compiler will translate it in to JavaScript for us.It is a tool for compiling JavaScript without actually writing JavaScript.

It allows developers to develop Html5 applications using C# and .Net Framework inside the Visual Studio IDE.

It also supports many C# features including Class Inheritance,strong typed classess,generics, Linq, Lambda Expressions, Reflection

The name of this is DuoCode. It is also called Cross Compiler as it cross compiles C# code in to JavaScript.


DuoCode is a fully-featured C# compiler, powered by Microsoft® Roslyn, and integrated in Visual Studio.

It cross-compiles your C# 6.0 code into high-quality readable JavaScript code, enabling rapid development of web applications utilizing the extensive features of the C# language, the Visual Studio IDE, and the .NET Framework base class libraries.

It automatically generates source mappings which allows developers to see and debug C# code inside the browser in Visual Studio 2015.

This feature allows developers do full debugging of C# code using browser Developer tools which includes breakpoints, step in, step over , watch etc.

You can see live working sample here and here is the official site of DuoCode

It is available as Visual Studio Extension in Visual Studio Gallery with title DuoCode for Visual Studio and is also available as Nuget Package. It is automatically added to the project when creating project from the template.

For adding in existing project run Install-Package DuoCode -pre from Nuget Package Manager Console.

Friday, March 27, 2015

Binding Enum with DropdownList in asp.net mvc

Sometimes we need to populate dropdownlist from Enum. There are a couple of ways to do it. First I will start with an approach that is not  very elegant in my point of view.

Consider following Enum which we want to populate in the drop down:


 public enum eUserRole : int
 {
    SuperAdmin = 0,
    PhoenixAdmin = 1,
    OfficeAdmin = 2,
    ReportUser = 3,
    BillingUser = 4
  }

So normally what we do is create SelectList by adding each Enum value following way in the action:


var enumData = from eUserRole e in Enum.GetValues(typeof(eUserRole))
               select new 
                      { 
                        ID = (int)e, 
                        Name = e.ToString() 
                      };

Now set it in ViewBag so that we can use it in View:


ViewBag.EnumList = new SelectList(enumData,"ID","Name");



and Now in View:


@Html.DropDownList("EnumDropDown",ViewBag.EnumList as SelectList)



Now here is an elegant way to achieve it using Extension Method and Generics, which will return us Enum values as a SelectList for any type of Enum:


public static class ExtensionMethods
{
     public static System.Web.Mvc.SelectList ToSelectList<TEnum>(this TEnum obj)
         where TEnum : struct, IComparable, IFormattable, IConvertible 
     {

     return new SelectList(Enum.GetValues(typeof(TEnum)).OfType<Enum>()
         .Select(x =>
             new SelectListItem
             {
                 Text = Enum.GetName(typeof(TEnum), x),
                 Value = (Convert.ToInt32(x)).ToString()
             }), "Value", "Text");

     }
 }

and now just call it on any Enum in action  this way:


ViewBag.EnumList = eUserRole.SuperAdmin.ToSelectList();

we can also use it directly in the View, just we have to include namespace in case it's in seperate namespace:


 @Html.DropDownList("EnumDropDown",eUserRole.SuperAdmin.ToSelectList())


You will probably need to set selected value of dropdownlist in the case when user is editing record.

Here is the extension method overload to pass selected value in case we want to set selected value, you can write other overloads as well according to the need:


public static class ExtensionMethods
{
    public static System.Web.Mvc.SelectList ToSelectList<TEnum>(this TEnum obj,object selectedValue)
  where TEnum : struct, IComparable, IFormattable, IConvertible 
    {

    return new SelectList(Enum.GetValues(typeof(TEnum)).OfType<Enum>()
        .Select(x =>
            new SelectListItem
            {
                Text = Enum.GetName(typeof(TEnum), x),
                Value = (Convert.ToInt32(x)).ToString()
            }), "Value", "Text",selectedValue);

    }
}

and usage in View this way:


@Html.DropDownList("EnumDropDownWithSelected",eUserRole.SuperAdmin.ToSelectList((int)eUserRole.OfficeAdmin))


Now the drop down will have OfficeAdmin selected by default.


In most of cases we don't want to show Enum value I'm dropdown list instead of that we want to show user friendly term as dropdown text, for that  purpose we can write our Attribute for Enum following way:

Create a custom class which inherits from Attribute type:


 public class EnumDisplayNameAttribute : Attribute
{
  private string _displayName;
  public string DisplayName
  {
      get { return _displayName; }
      set { _displayName = value; }
  }
}

and Now use attribute on Enum :


public enum eUserRole : int
{
    [EnumDisplayName(DisplayName="Super Admin")]
    SuperAdmin = 0,
    [EnumDisplayName(DisplayName = "Phoenix Admin")]
    PhoenixAdmin = 1,
    [EnumDisplayName(DisplayName = "Office Admin")]
    OfficeAdmin = 2,
    [EnumDisplayName(DisplayName = "Report User")]
    ReportUser = 3,
    [EnumDisplayName(DisplayName = "Billing User")]
    BillingUser = 4
}

 Now we will need to modify or write another extension method as now we need to pick value of DisplayName attribute .

We now have to extension methods now, one which return specific Enum value DisplayName Attribute value and second which return SelectList against for Enum:


public static class ExtensionMethods
{
    public static System.Web.Mvc.SelectList ToSelectList<TEnum>(this TEnum obj)
        where TEnum : struct, IComparable, IFormattable, IConvertible // correct one
    {

    return new SelectList(Enum.GetValues(typeof(TEnum)).OfType<Enum>()
        .Select(x =>
            new SelectListItem
            {
                Text = x.DisplayName(),
                Value = (Convert.ToInt32(x)).ToString()
            }), "Value", "Text");

    }


   public static string DisplayName(this Enum value)
   {
       FieldInfo field = value.GetType().GetField(value.ToString());

       EnumDisplayNameAttribute attribute
               = Attribute.GetCustomAttribute(field, typeof(EnumDisplayNameAttribute))
                   as EnumDisplayNameAttribute;

       return attribute == null ? value.ToString() : attribute.DisplayName;
   }
}





Wednesday, March 18, 2015

How to Convert List to DataTable in C#

Sometimes we have scenario where we need to make a DataTable from a List of some type.Normally what comes in mind is that create a DataTable, create columns that are in that type  and iterate on list items and add rows one by one, which is surely needed here.

A normal approach used is like:


List<SomeType> list = new List<SomeType>();

DataTable dt = new DataTable();

PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(SomeType));

foreach (var prop in props)
{
 dt.Columns.Add(prop.Name,prop.PropertyType);
}


and now iterate on List and add row one by one:


foreach (var item in list)
{
 dt.Rows.Add(item.Property1,item.Property2);
}


But there is another way which is much better using generics , and which will work for any type of List.

Though the above code will work, but think if we have 50 classes in project and we have Lists of that type then we have to write every time the above code for each type of List when needed.


Now consider this solution using Generics and Extension Methods:


public static class ListExtensions
{
   public static DataTable ToDataTable<T>(this List<T> iList)
   {
    DataTable dataTable = new DataTable();
    PropertyDescriptorCollection propertyDescriptorCollection =
        TypeDescriptor.GetProperties(typeof(T));
    for (int i = 0; i < propertyDescriptorCollection.Count; i++)
    {
        PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
        Type type = propertyDescriptor.PropertyType;

        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
            type = Nullable.GetUnderlyingType(type);


        dataTable.Columns.Add(propertyDescriptor.Name, type);
    }
    object[] values = new object[propertyDescriptorCollection.Count];
    foreach (T iListItem in iList)
    {
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = propertyDescriptorCollection[i].GetValue(iListItem);
        }
        dataTable.Rows.Add(values);
    }
    return dataTable;
  }
}

Now you just need to call it on any type of List and it will return DataTablev against that List.

This is how to use it:


List<SomeType> list = new List<SomeType>();

DataTable dt = users.ToDataTable();

Enough for today.

Sunday, October 26, 2014

asp.net mvc Adding Custom direcotry for Views (asp.net mvc How to specify which folder the View pages reside in?)

In asp.net mvc by default when we create application, our Views reside in Views directory for our Controller actions. For Example, by default it create Home controller with Index action, and if we see in Solution Explorer in Views directory we can see directory Views -->> Home --> Index.cshtml  and we have its action like this:

 
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

and we have this action's Views in Views folder see the following screen :




Now by default it will first look for Index.cshtml file in Views/Home folder and it is unable to find it there then it will find in View/Shared folder, if it also not finds it there it will throw exception that view file is not found, here is the exception text which is thrown:


The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Home/Index.aspx
~/Views/Home/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Home/Index.cshtml
~/Views/Home/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml

 

See:


The same is the case for partial view when we call return PartialView() it first looks in the respective controller's Views/Home  directory in the case of HomeController and in case of failure it looks in the View/Shared folder.

Now what if i had make a separate directory for partial views in my Views folder and Shared folder like : 



Views/Home/Partials and Views/Shared/Partial then we have to tell the ViewEngine  to look in that directory as well by writing the following code in Gloabl.asax  file in  Application_Start event.

For Example i have this code and i am returning _LoginPartial.cshtml from Index action of HomeController , now what will happen it will look in View/Home directory first and in failure it will look in View/Shared , but this time i have my partial views in seperate directory named Partial for every controller and for shared as well, In this case HomeController partial views are in Views/Home/Partials  and in Views/Shared/Partials:


public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

In this case also i will get the same exception as Engine will not be able to find the View file _LoginPartial.cshtml.

What we have to do is to register this directory pattern in the application so that every time call any View it should look in those direcotries as well in which we have placed the View files. So here is the code for that

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterAuth();

        RazorViewEngine razorEngine = ViewEngines.Engines.OfType<RazorViewEngine>().FirstOrDefault();
        if (razorEngine != null)
        {
            var newPartialViewFormats = new[] 
          { 
            "~/Views/{1}/Partials/{0}.cshtml",
            "~/Views/Shared/Partials/{0}.cshtml"
          };

            razorEngine.PartialViewLocationFormats = razorEngine.PartialViewLocationFormats.Union(newPartialViewFormats).ToArray();
        }
    }
}

Now whenever we will call return PartialView("SomeView") it will look in that Controller Views directory's subdirectiry named Partials as well and in case it not finds there it will look in both Views/Shared and Views/Shared/Partials.




To Be Continued........

Thursday, October 23, 2014

Application UI hangs on long running operation in C# WindowsForm and WPF (BackgroundWorker in C#)

Once i came across a scenario in a Windows Presentation Foundation where on click of a button i needed to call a Restful Service which returns JSON and then i needed to deserialize the JSON and do soemthing with that, but when i wrote the code in the button event, it worked successfully but one thing that i noted that unitl the all operation completes my button remains pressed and UI also not responsive , so after researching a little i came to know this:

When we have some long running code that can take much time than normal time we should execute in a background thread not on UI thread, becasue executing it in UI thread will make our application un responsive and user will get irritated, here is my code which was executing directly on UI thread in button event:



This worked fine but as it is executing all the code on UI thread the application becomes unresponsive and user has to wait for the process to complete which is not a good user experience in any software or web application, after a  little reasearch i came to know about BackgroundWorker class which executes the code in separate thread not in UI thread.

This is the first version in which it was all happening on the UI thread all was fine but my button state was in pressed state and UI blocked until the service call completed and GridView populated.


private void btnLookup_Clicked(object sender, RoutedEventArgs e)
{

    string url = "http://www.lyfechannel.com/channels/allscripts/allscripts_institutions.php?allscripts=XXXX&user=YYYY&password=ZZZZ";

    WebRequest request = WebRequest.Create(url);

    request.Timeout = 500000;

    WebResponse response = request.GetResponse();

    var reader = new StreamReader(response.GetResponseStream());

    string json = reader.ReadToEnd();

    var jsonAsCSharp = JsonConvert.DeserializeObject<JSONWrapper>(json);

    PatientGrid.DataSource = jsonAsCSharp.Patients;
}

Now i am showing the version in which i used BackgroundWorker class, First of all create BackgroudWorker instance assign its events:


private void MyMethodToCallExpansiveOperation()
{
    //Call method to show wait screen
    BackgroundWorker workertranaction = new BackgroundWorker();
    workertranaction.DoWork += new DoWorkEventHandler(workertranaction_DoWork);
    workertranaction.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
        workertranaction_RunWorkerCompleted);
    workertranaction.RunWorkerAsync();
}

Now write the expensive operation code in workertranaction_DoWork method:


private void workertranaction_DoWork(object sender, DoWorkEventArgs e)
{
    string url ="http://www.lyfechannel.com/channels/allscripts/allscripts_institutions.php?allscripts=XXXX&user=YYYY&password=ZZZZ";

    WebRequest request = WebRequest.Create(url);

    request.Timeout = 500000;

    WebResponse response = request.GetResponse();

    var reader = new StreamReader(response.GetResponseStream());

    string json = reader.ReadToEnd();

    var jsonAsCSharp = JsonConvert.DeserializeObject<JSONWrapper>(json);

    patients = jsonAsCSharp.Patients;
}


and in  workertranaction_RunWorkerCompleted  bind List of Patients with Grid, as Do_Work does not executes in UI thread so we cannot access them in this method:


private void workertranaction_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    PatientGrid.DataSource = patients;
}

Now on button click we need to just call MyMethodToCallExpansiveOperation method:


private void btnLookup_Clicked(object sender, RoutedEventArgs e)
{
    MyMethodToCallExpansiveOperation();
}