Udemy

Translate C# code to JavaScript in Visual Studio using DuoCode

Sunday, March 29, 2015 1 Comments A+ a-

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.
Udemy

Bind Enum to DropdownList in asp.net mvc

Friday, March 27, 2015 2 Comments A+ a-

Introduction:

 
Sometimes we have scenario while development where we need to populate dropdownlist from Enum. There are a couple of ways to do it. But every way has it's pros and cons. One should always keep in mind the SOLID and DRY principle while writing code. I will show two ways to do it and you will be able to understand which one is better and why it is better.

Approach 1 (Typical Way):

The first approach in my point of view is not very elegant but it will surely do what we want it to.

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)

Problem in Approach 1:

The problem with the above way is that whenever we have Enum to be binded with some Html Helper we have to write the above linq query code to get the enum all values in the action which is a bit pain to rewrite one thing again and again.We will see next how we can make it better and reusable.

Approach 2:

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 we just need to 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.

We can extend the extension method according to our requirents.

Overload with Selected Value parameter:

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;
   }
}





Udemy

How to Convert List to DataTable in C#

Wednesday, March 18, 2015 0 Comments A+ a-

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 Reflection , 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 List of each type do every time when we want data-table against any type of List from them then we have to write every time the above code for each type of List which is code redundancy and its against DRY(Do not Repeat Yourself).


Now consider this solution using Generics and Reflection. It is an  Extension Method on type List<T> . You can read more about Extension Methods in detail from here:


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 object type of List<T> and it will return DataTable against that List<T>.

This is how to use it:


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

DataTable dt = users.ToDataTable();

Enough for today.