Sunday, September 27, 2015

Asp.Net MVC Intellisense for ViewBag

Introduction/Problem Statement: If you are a typical MVC developer, you might have used ViewBag or ViewData to pass data from Controller to View at times. Also, it is well understood that ViewBag is a dynamic type and hence you will not get intellisense for this. Again, it is a similar case with ViewData which is a dictionary instead and hence no strongly typed support and needs to deal with magic strings.

Workaround: We can easily create our own workaround for this. Here is a sample -
/// 
/// A class to hold the data which can be used to interact between controller and view.
/// 
public class ViewBagHelper
{
    /// 
    /// Gets the current instance of 
    /// 
    public static ViewBagHelper Items
    {
        get
        {
            if(HttpContext.Current.Items["item"] == null)
            {
                HttpContext.Current.Items["item"] = new ViewBagHelper();
            }

            return HttpContext.Current.Items["item"] as ViewBagHelper;
        }
    }

    // TODO: Add your intended ViewBag/ViewData properties here. Ex: To hold an id, do this
    // public int Id { get; set; }
}

Now anywhere you want to use ViewBag just do this - 

ViewBagHelper.Items.MyItem

Where, MyItem is your item name, which is basically a property of ViewBagHelper class. While using this in the View, make sure that you are using fully qualified name or you added the appropriate namesapce in the MVC's Web.Config file. For example, if my helper resides in the following namespace 'ViewBagIntellisense.Helper', then your razor config section of Web.Config should have this - 
  
    
    
      
        
        
      
    
  
The idea is not new, people often do this to avoid magic strings. For instance, 3 years back I myself asked the stackexchange community to review similar pattern. Well, it is still in unresolved state because the answers were not convincing enough. However, I continued to use this pattern in various projects and it worked well for me. Even you can find it in one of my old article

Downsides: The one potential downside which I can think of is, it shares various state representations across the application. However, still the memory footprint will be considerably low, as reference type properties are get initialized only on need basis and value types are inherently lightweight (Off-course, Unless you create one!). 

Recommendation/Best Practice: It is always good to have a Model/ViewModel to exchange data between controller and view. Use this pattern (Or ViewBag in general) only if you have some cross-cutting scenarios where putting the data in Model/ViewModel doesn't make much sense or you have only one piece of data to transfer.

Tuesday, July 30, 2013

MVC 4 - WCF - Add Service Reference Generates Blank Proxy

After a long time I created a WCF Service with ws2007HttpBinding which has a complex data model (with inheritance involved). I created the service as usual with the well known configuration and hoping it to work. I just run the application and it ran without any error. Bingo! wow great, I created a service in single go!

Now its time to create a client application. The client I was trying to create is MVC 4 web application (which I am most familiar with). The app was already present and I just need to add a service reference to consume my wcf service. As usual I just right clicked the project, clicked on AddServiceReference, entered the service url, given a friendly name to the service and clicked Ok. Wow! I'm ready with a client for my service. Now its time to call the service method by creating an instance of the client proxy. Being a lazy guy waiting for the visual studio intellisense to show up the given friendly proxy name by typing its initial few letters. Unfortunately, intellisense was not showing anything. OMG! need to wake up now.

Started to trace to identify what went wrong:
            First step I did is checking the proxy code (because I can't relay on intellisense for 100% accuracy. There are times, when everything is fine but intellisense itself is having problems). Well, I did that by clicking on the marked places below:

I noticed that the proxy classes are not generated and the Reference.cs file is blank:

Now my mind also became blank! I was following all the holy steps but still not able to wok as expected. Went back to my WCF application and started to verify following things:
  • Whether all my required data structures are decorated with DataContract (classes) & DataMember (properties) or not.
  • Whether the base class is decorated with DataContract or not. 
  • Whether the KnownTypes are set or not.
Everything was looking fine there but still proxy is not getting created. Frustrating!!!

Decided to check the service with wcftestclient (vs command prompt -> wcftestclient -> Right click & click on Add Service -> Enter service url -> ok) tool. 


Wow, great! it works here. Then, what might be the problem with my MVC 4 application. Just got another thought. Created a new console application and added the service reference in the same was as I did in MVC 4 app. Amazing, worked with single go.

Now the thing is pretty clear that there is something wrong in MVC 4 app. Its time find the solution (well just a google search will do it).

Solution:
Go to, configure service reference.


Select the option, Reuse types in specified referenced assemblies -> Check all except Newtonsoft.Json -> ok

Thats it. The proxy will be created now. We can do this while adding the service reference itself, by going to the Advanced window.

Note: Microsoft has fixed this issue in this update: http://support.microsoft.com/kb/2750149

The Cause (by microsoft): 
This issue occurs because the DataContractSerializer class has encountered a type 
(Newtonsoft.Json.Linq.JToken) that it does not support. In this case, it throws an exception, 
and then stops generating the service reference.

Conclusion: Since I am working in WCF after a long time I was continuously thinking that there is something wrong in my service and spent a lot of time to figure it out. Also, I missed one basic step in my tracing with which I could have saved my time (i.e. checking the Error List). Hope this article helps to someone else in future.

Out-of-interest, the error list was showing this error & warning.

Error:Custom tool error: Failed to generate code for the service reference 'ServiceReference1'.
Please check other error and warning messages for details.

Warning:
Custom tool warning: Cannot import wsdl:portType
Detail: An exception was thrown while running a WSDL import extension: System.ServiceModel.Description.DataContractSerializerMessageContractImporter
Error: Type 'Newtonsoft.Json.Linq.JToken' is a recursive collection data contract which is not supported. 
Consider modifying the definition of collection 'Newtonsoft.Json.Linq.JToken' to remove references to itself.

Sunday, June 9, 2013

Assembly Reference - Best Practice

Introduction: 
             
               Its obvious that the applications do have references to one or the other assemblies to accomplish their job. The CLR looks for the referred assemblies in global assembly cache, any private path added to the app domain or one of the special folder called bin (i.e. current directory of the executing assembly).
             
             While working with Visual Studio IDE, we refer lots of related libraries using add reference tool. When we compile the code, the referred assembly files are copied from the source location and placed into the special directory called bin, so that the application can find those assemblies at runtime and load them into memory. If we refer the assemblies wrongly, then there will always be a configuration problem which we encounter, when we move the application from one location to another. This article discuss about those issues and possible solutions by providing some best practices.

Background: 
         
            It was very unfortunate situation that, my system has changed 3 times in last one month. Still there is one more chance to change! Each time the system has changed, I had to setup the currently working project. The project uses Microsoft Enterprice Library and some assemblies in it. The problem with the setup is that, the project fully relies on GAC for these assemblies and the bin folder of our project is readonly by default. Hence, the compiler is failing to copy the files from GAC to bin. Also, I forget to remove readonly attribute from the bin folder each time, causing the application to fail on runtime by giving following error, or sometimes some other error with InnerEdxception as this:

Could not load file or assembly 'xxx' or one of its dependencies.
The system cannot find the file specified.

Fixing the above issue is simple though, it wastes our time which we can save otherwise. This and my previous some other experience made me to come-up with a best practice to avoid this problem.

Wrong Approach: 
  1. Referring assemblies from bin directory.
  2. Not referring anything and making the assembly available via bin folder.
  3. Relying on GAC for almost every assembly.
The first and second approach is completely deprecated(NEVER DO THAT). Third approach is okay though, personally I prefer to have my own copy(because, its good for portability - specially in web-applications). Usually, placing the assemblies in GAC is preferred only for shared assemblies.

What is bin folder?

         The bin stands for binary. By default, in visual studio it is configured as the output folder for your build code.


In Visual Studio, you can change this to any other directory to obtain the build code(PE file). When you right click to your project or solution in visual studio and click on 'Clean', it clears the output directory and as soon as you build your project, new build files will be placed there. Ususlly, the new build files will  override the existing files in output directory when we rebuild our projects but sometimes there will be some glitches & we need to execute the clean command explicitly or we may need to delete the output folder from file-system manually.

Why referring and placing the assemblies on bin is bad idea?

         Since bin is an output folder, each time you build your code the new files will override the existing one in bin. However, this won't cause any problem to us but there are situations like:
  1. Sometimes Visual Studio takes older version assemblies for execution and we may need to delete the bin folder to overcome from this issue.
  2. We may need to remove bin and obj folder to reduce the size while porting the application.
As you can see, there are situations where bin folder needs to be deleted or recreated. Hence, it is not good to depend on this directory for required assemblies. 

Best Practice:
  1. Within the applications root directory, create a folder called Lib, Library or whatever you prefer.
  2. Place the required assemblies there.
  3. Refer them in the application using Add References tool of visual studio.
This way you can always be safe that required assemblies are exists and available all the time. Also, you can delete or recreate the bin folder without any issue. If you follow this simple best practice, no other configurations are required to setup your application on any machine.

NuGet Package: 
           
            Before I conclude my topic, here is an interesting tool to introduce (You might already been using it, if you work with MVC projects - at least to setup your project). NuGet is a tool, which helps you to port your application easily by reducing or completely eliminating the configuration burdens.

          Even this tool uses the same pattern for assembly reference. It creates a folder called packages on the root of your application and modifies your project file to refer the assemblies from that location.

Conclution: It is bad idea to refer assemblies directly from bin folder. Rather, I recommend to create a dedicated folder for this purpose and refer the assemblies from there. This enables you to port and configure the application easily.

Thursday, February 28, 2013

Tips and Tricks of Exception Handling in .Net - Part 3

This is the continuation of my article Tips and Tricks of Exception Handling in .Net - Part 2

Fail Fast Method: There are situations where your application's state is very bad and no code should be executed further - not even finally block code and your application needs to be closed immediately. How you do this?
           The answer is Environment's FailFast method. As the name suggests, this  is a special method which causes your application to fail immediately. It also creates a dump and event viewer entry.
 try 
 {
     Environment.FailFast("Text to be logged");
 }
 finally
 {
     Console.WriteLine("This finally block will not be executed.");
 }
Compile above code and execute the generated .exe you will see the following windows prompt, which you get usually when your application is having unhandled exception.















Process.GetCurrentProcess().Kill() vs Environment.FailFast(""): The finally block will not be executed even if you use Process.GetCurrentProcess().Kill() and this also ends your application immediately, then how it differs from FailFast? well, the difference is - FailFast will create a dump and event viewer entry but killing the current process will not.

Note: The both should be used with extensive care. In real-world these are required very rarely.


Corrupted State Exceptions (CSE): These are the exceptions which cannot be catched. Behind the scene Environment's FailFast method throws one of these exceptions. Hence, it cannot be catched and your application ends with an unhandled exception.

Here is the explaination of CSE by Jffrey Richter's words:
      Usually, CLR considers few exceptions thrown by native code as Corrupted State Exceptions, because they are usually the result of a bug in the CLR itself or in some native code for which the managed developer has no control over. Here is the list of native Win32 exceptions that are considered CSEs:

EXCEPTION_ACCESS_VIOLATION        EXCEPTION_STACK_OVERFLOW
EXCEPTION_ILLEGAL_INSTRUCTION     EXCEPTION_IN_PAGE_ERROR
EXCEPTION_INVALID_DISPOSITION     EXCEPTION_NONCONTINUABLE_EXCEPTION
EXCEPTION_PRIV_INSTRUCTION        STATUS_UNWIND_CONSOLIDATE

By default, the CLR will not let managed code catch these exceptions and finally blocks will not execute. However, Individual managed methods can override the default and catch these exceptions by applying the System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptionsAttribute to the method. In addition, the method must have the System.Security. SecurityCriticalAttribute applied to it. You can also override the default for an entire process by setting the legacyCorruptedStateExceptionPolicy element in the application’s Extensible Markup Language (XML) configuration file to true. The CLR converts most of these to a System.Runtime.InteropServices.SEHException object except for EXCEPTION_ACCESS_VIOLATION, which is converted to a System.AccessViolationException object, and EXCEPTION_STACK_OVERFLOW, which is converted to a System.StackOverflowException object.

Note: Even with the attribute HandleProcessCorruptedStateExceptions, we cannot handle the following exceptions, for a given reason:

  • StackOverflowException - As this is a hardware failure and there is no more stack available for further processing (Thanks Abel Braaksma for pointing this out).
  • ExecutionEngineException - It occurs because of heap memory corruption and hence cannot be handled further (Reference).

Summery:
  • Structured Exception Handling - This is the exception handling mechanism which is offered by Microsoft Windows and .Net Framework Exception Handling is built on the top of it.
  • What can be thrown? - The CLR allows an instance of any type to be thrown. But CLS mandates to throw only the Exception derived objects. The C# compiler allows to throw only exception derived types.
  • Throw different exception than the originally thrown one, when you want to maintain the meaning of a methods contract.
  • Make sure to set original exception as inner exception when you throw a different exception.
  • Constrained Execution Regions - Make sure that your catch or finally block will never throw an exception by making use of CER. You can use it by calling RuntimeHelpers's PrepareConstrainedRegions method and applying ReliabilityContract attribute wherever required.
  • The C# language automatically emits try/finally blocks whenever you use the lock, using, and foreach statements.
  • Call Environment's FailFast method when you want your application to be closed immediately and put a dump with event viewer entry.

Thursday, February 21, 2013

Tips and Tricks of Exception Handling in .Net - Part 2


This is the continuation of my article Tips and Tricks of Exception Handling in .Net - Part 1


Constrained Execution Regions:  Usually, we write code to recover from an exception in catch block. Now what if the catch block itself throws an exception?

Well, you can say that we can use another try/catch block inside our catch. But are you sure you properly recovered from the corrupted state or you are just ignoring it and going forward. This all depends on the actual implementation though, we should always try our level best to keep our application in proper state. In other words, the application should never-ever contain a corrupted state. The CLR provides CER to handle such a situation.

The CER allows you to compile all the code written in your catch and finally block prior to the try block. Hence, if there is any chance of failure in catch block, that happens immediately there by not letting your application with the corrupted state. Here is a sample code describing it from the book CLR via C#.
        public static void Test()
        {
            // Force the code in the finally to be eagerly prepared
            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                Console.WriteLine("In try");
            }
            finally
            {
                // MyType's static constructor is implicitly called in here
                MyType.Foo();
            }
        }

        public class MyType
        {
            static MyType()
            {
                Console.WriteLine("MyType Constructor Called");
            }

            // This attribute is required for PrepareConstrainedRegions to work.
            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
            public static void Foo() { }
        }
If you execute this code you will get the following output:
MyType Constructor Called
In try
As you can see in the output, finally block is compiled prior to the try block there by executing the MyType's static constructor first. All we need to do is call RuntimeHelpers's PrepareConstrainedRegions method prior to try block and apply ReliabilityContract attribute to the methods which needs to be compiled in prior.

Refer this link for more information.

Automatic Generation of try/finally: Ensuring that cleanup code always executes is so important that many programming languages offer constructs that make writing cleanup code easier. For example, the C# language automatically emits try/finally blocks whenever you use the lock, using, and foreach statements. The C# compiler also emits try/finally blocks whenever you override a class’s destructor (the Finalize method). When using these constructs, the compiler puts the code you’ve written inside the try block and automatically puts the cleanup code inside the finally block. Specifically,
  • When you use the lock statement, the lock is released inside a finally block.
  • When you use the using statement, the object has its Dispose method called inside a finally block.
  • When you use the foreach statement, the IEnumerator object has its Dispose method called inside a finally block.
  • When you define a destructor method, the base class’s Finalize method is called inside a finally block.
These are the words of Jeffry Richter(from the book CLR via C#). There is another interesting point which he did not mentioned in the book, but I found it in this stackoverflow question. Here pb noticed that iterator block generates try-fault block instead of  try-finally. 

Now what is this try-fault? can we use it in C#?
       The answer is given in the same SO question by Steve Steiner. In his words, a Finally block always executes on frame exit. A fault block executes only if an exception is unwound past the frame.. That means, the fault block executes only if there is an exception. Now again, another question comes into mind i.e.

If fault block executes only if there any exception in the try block, then whats the difference between fault and catch?
      While researching about this, I got this SO link. Here, the accepted answer says this:
catch - I need to do something with the exception object when an exception occurs.
fault - I don't need the exception object, but I need to do something when an exception occurs.
finally - I don't need the exception object, but I need to do something before the end of the function.

Here is another interesting article regarding this.

Before ending this section, there is another thing which I need to mention. That is about exception filter - Now what is this new concept again? well, here is the answer from previously linked SO post:

It is similar to a catch block but can run arbitrary code to determine whether it wants to handle the error, rather than just matching on type. This block has access to the exception object, and has the same effect on the exception stack trace as a catch block.

Oh! I forgot about the question, can we use fault in c#? You may already got the answer, if not here is it.
        Currently, no languages provide support for fault. However, Bart De Smet shown a way to use it in c# here (You can also produce it using reflection as shown in MSDN, but this is a big pain). The c# also doesn't support filter handler but VB.Net supports it.


Topics will be covered in Part - 3:  FailFast method and CSE(Corrupted State Exceptions).

Read Part - 3

Tuesday, February 19, 2013

Tips and Tricks of Exception Handling in .Net - Part 1

This week I was reading Exceptions and State Management chapter of the book CLR via C# and learnt some interesting stuffs. I did some experiment and summarized few points which I would like to share. OK, lets start them one by one.

Structured Exception Handling: The .Net Framework Exception Handling is built using this mechanism which is offered by Microsoft Windows. It mainly introduces 3 blocks namely try, catch and finally. 
Where,
  • try - is like a guard where we write the code which might cause an exception to be raised.
  • catch - is a block which is intended to handle an exception which is raised in try block.
  • finally - is a block which is intended to write a cleanup code.
Refer this link for more information regarding SEH.

What can be thrown?
       The CLR allows an instance of any type to be thrown. But CLS mandates to throw only the Exception derived objects. The C# compiler allows to throw only exception derived types.

Some points about try, catch, finally and throw in C#:
  • try cannot stand by itself. Means, try block musht be followed by catch or finally block.
  • You can write multiple catch blocks for a single try block but you cannot write multiple finally blocks.
  • You can write catch in 2 ways:
          1. Without specifying any exception type.
          2. By specifying an exception type.
  • finally  block always executes, even if try block is having a return statement. However, you cannot write return statement in this block!
The points which I mentioned above is the basic things and compiler itself teaches you if you are not aware of it. But there are some interesting things which is related to these points which I will address later on this post.

catch vs catch(Exception ex): These both are same and used to handle generalized exceptions.
The first one can be written like this:
try
{
}
catch
{
   throw; // Throws any and all exceptions without altering the stack trace.
}
and the later one can be written like this:
try
{
}
catch(Exception ex)
{
   throw; // Throws any and all exceptions without altering the stack trace.
}
The above two code fragments will be having same behavior(but you will get compiler warning for the second one, since the variable ex is not used in the block).

Note: This is same only if the CLR version is 2.0 and above - Prior to that the later one will catch only CLS-Compliant Exceptions. In version 2.0 of CLR, Microsoft introduced RuntimeWrappedException class which is derived from Exception so it is CLS-compliant exception type. This class contains a private field of type Object. In version 2.0 and above  of the CLR, when a non-CLS compliant exception is thrown the CLR automatically constructs the instance of RuntimeWrappedException and initializes its private field to refer to the object that was actually thrown.

When we need to log the exception information or do some other operations based on the values of exception object, then we can use the later one. Otherwise first one will be fine to delegate the exception to the caller.

Be Careful with throw vs throw ex

Now lets alter the second code like this:
try
{
}
catch(Exception ex)
{
   throw ex; // Throws any and all exceptions by altering the stack trace.
}
Note the throw statement above. This makes a lot of difference to the first code(i.e. throw;). When an exception variable  is specified along with the throw statement, the stack trace of the exception will be altered. Here we are lying the client code by changing the actual location of the exception! Hence, it will be difficult to debug such codes and therefor it is not the preferred or recommended way.

Here is an example code to check this behavior.

Throwing different exception than the catched one: We can also throw a different exception than the one which is catched by catch clause. This is useful when we need to maintain the meaning of a methods contract. Ex:
    
    // Source: CLR via C# by Jeffrey Richter
    internal sealed class PhoneBook
    {
        private string pathname;

        public string GetPhoneNumber(string name)
        {
            string phone;
            FileStream fs = null;
            try
            {
                fs = new FileStream(pathname, FileMode.Open);
                // Code to read from fs until the name is found goes here.
            }
            catch (FileNotFoundException ex)
            {
                // Throw different exception containing the name, and
                // set the originating exception as the inner exception.
                throw new NameNoteFoundException(name, ex);
            }
            catch (IOException ex)
            {
                // Throw different exception containing the name, and
                // set the originating exception as the inner exception.
                throw new NameNoteFoundException(name, ex);
            }
            finally
            {
                if (fs != null)
                    fs.Close();                
            }
        }
    }
As you can see in the above code GetPhoneNumber's contract is to find and return the phone number. Hence, in this case a meaningful exception will be NameNoteFoundException(Off-Course, this should be of type Exception derived).

We can see this approach in many places of FCL like type initialization, smtp connection, dealing with entity framework context etc.

Note: This should be used with extensive care. Improper usage of this will make the code horrible to maintain!

You can also add information to the exception variable before throwing it. Like: ex.Data.Add(anyObject);


Topics will be covered in Part - 2: CER(Constrained Execution Region) and Automatic Generation of try/catch/finally.

Read Part -2

Tuesday, October 30, 2012

Order of Javascript Execution

Situation/Problem: In an ASP.Net MVC application, I had a tab control where the tab click is disabled using following code:
    $(function () {
        $("#tabs").tabs({
            select: function (event, ui) {
                if (enableTabSelection) {
                    enableTabSelection = false;
                    return true;
                }
                return false;
            }
        });
    });
Here enableTabSelection is a flag which is used to enable the tab selection temporarily. On some javascript function, I was selecting a particular tab like this:
function navigate(pageDetails){
          enableTabSelection = true;
          var $tabs = jQuery("#tabs").tabs();
          $tabs.tabs("select", pageDetails.tabId);
}
This was working fine. Later, there was a requirement where I need to select a particular tab on load of the page depending upon a json data. Well, Inside the script tag I used below code to do this.
navigate(@Html.Raw(Json.Encode(Model)));
Unfortunately, the intended tab was not getting selected with this.

 What was wrong with this code?
  • I called the same function to navigate to a specific tab. 
  • Checked pageDetails.tabId in console it was returning the proper value. 
  • There is no error/exception on the page. 
but still the intended tab was not getting selected. Searched web and spent hours but no use.

Workaround/Solution: Finally, while debugging navigation function I noticed a tab which is getting selected and after completion of debug its going back to first tab.

Then, I realized that the intended tab is getting selected but its re-initializing in jquery initializer. So, the solution is quite simple. I need to call navigate function after execution of tab initilizer on jquery initializer. Here is the final working code:
    $(function () {
        $("#tabs").tabs({
            select: function (event, ui) {
                if (enableTabSelection) {
                    enableTabSelection = false;
                    return true;
                }
                return false;
            }
        });

       navigate(@Html.Raw(Json.Encode(Model)));
    });