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

Wednesday, October 15, 2014

difference between ~= and *= in jquery

Few days back, i saw a SO question, that what is the difference between [attribute~=value] and [attribute*=value]?



*= is attributeContains selector , From jquery docs:
Selects elements that have the specified attribute with a value containing a given substring.
~= is attributeContainsWord selector , From jquery docs:
Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.


The attributeContains selector is for the string to be contained in the attribute value while attributeContainsWord selector is for string seperated with delimeted space. The official jquery examples clearly explain it.



Attribute Contains Selector [name*="value"]

HTML:

<input name="man-news">
<input name="milkman">
<input name="letterman2">
<input name="newmilk">
JQUERY:

$( "input[name*='man']" ).val( "has man in it!" );
OUTPUT:


Here is the fiddle demonstrating the Attribute Contains Selector [name*="value"] behavior

Attribute Contains Word Selector [name~="value"]

HTML:

<input name="man-news">
<input name="milk man">
<input name="letterman2">
<input name="newmilk">
JQUERY:


$( "input[name~='man']" ).val( "mr. man is in it!" );

OUTPUT:

Here is example demonstrating the behavior of  Attribute Contains Word Selector [name~="value"] 

Saturday, September 27, 2014

Deserializing JSON returned by Restful Service in C#

Nowa days Restful services are more used which mostly return xml or json as reponse. The advantage of restful services are platform independence, a service made restful can be accessed from any platform like Java, c#,php, ruby etc.


I have a service  at this url : http://www.lyfechannel.com/channels/allscripts/allscripts_institutions.php?allscripts=XXXX&user=YYYY&password=ZZZZ  which returns following json as response:


{
"connections":"72", 
"incomplete":"319", 
"qualified":"14", 
"loggedin":"Dr. Frederick Banting | One Medical | San Francisco, Embarcadero", 
"red": "40", 
"yellow": "12", 
"green": "20"
}

First of all we need to create a C# class for deserializing json  to that spcific type, the current json object is not very complex so we can easily write class against this json with properties but mostly we will not have json simple like this, so most of the time i use json2csharp.com to generate classes against the json returned by service.


Our class for this json will look like this:


public class JSONWrapper
{
   public string connections { get; set; }
   public string incomplete { get; set; }
   public string qualified { get; set; }
   public string loggedin { get; set; }
   public string red { get; set; }
   public string yellow { get; set; }
   public string green { get; set; }
}

For deserializing json we have a library available Newtonsoft JSON which we will use for deserializing json to specific type.

We can install it in our project by going to Nuget Package Manager Console in Tools of Visual Studio and writing this command on Nuget Package Manager Console:

PM> Install-Package Newtonsoft.Json 

 If you have dll downloaded on your system you can also add reference by going in to References and click Add Reference from context menu:


 After clicking Add Reference browse to the location where the dll is present and check it and click ok.



Now we will write the code to call the specific url and we will deserialize the returned response to the specific class.


Here we go:


using System;
using System.IO;
using System.Net;
using Newtonsoft.Json;

class Program
{
   static void Main(string[] args)
   {
      try
      {
          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);

          Console.WriteLine(jsonAsCSharp);
       }

      catch (Exception e)
      {
         Console.WriteLine("Error Occured:"+e.Message);
      }
   }
}


Here is the  attached sample project console application