Oct 15, 2012

Entity Framework and Cascade Delete of dependent Entities

I have a edmx containing of an entity “School”.
“School” contains a List of “Standards”, which contain a List of “Sections”, which in-turn contains a list of “Students”
image
I was finding it difficult to delete any entity which contained a reference to another entity
The error was one related to referential integrity.
I tried to manually delete each of the contained inner objects, viz, all Sections under a Standard, but even after the deletion and a call to SaveChanges(), still the same error persisted.
Finally added Cascade Delete option to the master tables through scripts. This did the trick and I was allowed to delete master elements after this..

Sample Cascade delete script:
ALTER TABLE [dbo].[Standard]
WITH NOCHECK ADD CONSTRAINT [FK_Standard_Sections] FOREIGN KEY([StandardId) REFERENCES [dbo].[Sections] ([ID])
ON DELETE CASCADE
GO

Oct 5, 2012

View Switching in Asp.net MVC4: device based switching of views

The following article is excerpted  from the following links:
http://www.asp.net/mvc/tutorials/mvc-4/aspnet-mvc-4-mobile-features




What is View Switcher?

 
View Switcher is a component available as part of jQuery.Mobile.MVC NuGet package for ASP.NET MVC 4. It contains prototype helpers for jQuery Mobile in ASP.NET MVC 4. Generally when we are browsing mobile site in mobile/tablet sometimes we may want to switch to desktop view, but usually as per the browser detection technique, application always redirects to mobile page.
 
 
 
View Switcher gives the provision to user to switch from mobile view to desktop view and vice-versa.
 
 
 
We can get jQuery.Mobile.MVC package as part of our solution in 2 ways.
 
 
 
Using The Package Manger Console
 
Go to View Menu –> Open Package Manger Console
 
Run the following command : Install-Package jQuery.Mobile.MVC
 
 
 
 
 
 
 
In Solution Explorer
 
Right click on the solution explorer –> From popup menu choose “Manage Nuget Packages…”
 
It will pop up the “Manage Nuget Packages…” dialog –> choose online from left side options –> then in right side top of the window in “Search Online” textbox type “jquery mobile”.
 
From the options choose “jQuery.Mobile.MVC” –> click on install, It will popup a window to choose the projects in your solution, choose the required projects, if you have more than one project in solution .
 
It will install all the components as part of that package.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Once you install this NuGet package, it will install following components into solution.
 
 
 
ViewSwitcherController (~/Controllers/ViewSwitcherController.cs)
 
_ViewSwitcher.cshtml (~/Views/Shared/_ViewSwitcher.cshtml)
 
_Layout.Mobile.cshtml (~/Views/Shared/_Layout.Mobile.cshtml – jQuery Mobile based Layout)
 
 
 
 
 
 
 
 
 
ViewSwitcher partial view is added in _Layout.Mobile.cshtml, so that when u are in mobile page while browsing in mobile, you can switch to desktop page.
 
 
 
 
 
 
 
The highlighted UI is generated by _ViewSwitcher.cshtml partial view, this is the mobile page , if you click on “Desktop View” hyperlink, you will be redirected to desktop page.
 
 
 
Lets try to understand view switcher code and how it works, lets us understand _ViewSwitcher.cshtml,if we look at the code:
 
 
 
It will find out whether the request is from mobile browser & it should be a http get request,then if both conditions satisfies, it will start rendering the code inside it.
 
Now it will check whether the request is actually from mobile device are not, using “ViewContext.HttpContext.GetOverriddenBrowser().IsMobileDevice” property.
 
If the request is from mobile device, it will render the hyperlink to switch to desktop view.
 
@: Displaying mobile view @Html.ActionLink(“Desktop view”, “SwitchView”, “ViewSwitcher”, new { mobile = false, returnUrl = Request.Url.PathAndQuery }, new { rel = “external” })
 
 
 
This hyperlink will actually redirect the request SwitchView() action method with ViewSwitcher Controller with parameters “mobile = false” (because this link should redirect to desktop page, so mobile is false) and “returnUrl =Request.Url.PathAndQuery” (Request.Url.PathAndQuery – Gets the AbsolutePath and Query properties separated by a question mark (?))
 
When the request reaches SwitchView() action method with in ViewSwitcher Controller.
 
It will compare Request.Browser.IsMobileDevice (Gets a value indicating whether the browser is a recognized mobile device) with mobile parameter value, we are passing mobile parameter as false.
 
Request.Browser.IsMobileDevice is actually true because we are sending a request from mobile browser, mobile mobile parameter as false, so condition fails.
 
Now it set the overrides as actual mobile browser with desktop browser using SetOverriddenBrowser() method & returns to the passed URL desktop view.
 
When comparing the Request.Browser.IsMobileDevice against the mobile parameter value , if condition is true, then it will removes any overridden user agent for the current request using ClearOverriddenBrowser() method and returns to the passed URL actual view (if the request is from mobile browser it redirects to mobile view, else the request is from desktop browser it redirects to desktop view).
 
When checking “ViewContext.HttpContext.GetOverriddenBrowser().IsMobileDevice” property is false then, it will render the hyperlink to switch to mobile view:
 
 
 
@: Displaying desktop view @Html.ActionLink(“Mobile view”, “SwitchView”, “ViewSwitcher”, new { mobile = true, returnUrl = Request.Url.PathAndQuery }, new { rel = “external” })
 
 
 
This hyperlink also works in same way as explained above, but it will render link to switch to mobile view from a desktop view.
 
 
 
Note : ViewSwitcher component is actually using new Brower Overriding API, introduced with ASP,NET MVC 4. If you want to understand more about Brower Overriding API, read my article on Brower Overriding API here : http://theshravan.net/blog/browser-overriding-features-in-asp-net-mvc-4/
 
 
 
================================================================     ASP.NET MVC4 : Create a Mobile Application
 
In this post, I will show you three new functionalities brought by MVC4 for mobile websites.
 
  • The mobile Application Template 
  • The View Switcher 
  • The Display mode by Browser type 
Smartphone and tablet are able to read websites not optimized for tiny screen but if a user can jump automatically on an optimized version of the website, it’s better for everyone!
 
 
 
One interesting feature of this new version of the ASP.NET MVC framework 4 is the new Mobile Application template. With this template you’ll be able to develop quickly a website especially for mobile and tablet.
 
 
 
1 – Create a full-mobile Website
 
 
 
In Visual Studio, Create a new MVC4 project and select the “Mobile Application” template.
 
 
 
 
 
Mobile Application Template - MVC4
 
I consider that you’ve already develop a classic MVC application. If true, you will not be surprised by the generated project. It’s almost the same as a classic MVC desktop website.
 
 
 
So what the difference?
 
 
 
 
 
In the “content” folder you will find another JavaScript library: jQuery Mobile. ASP.NET MVC4 Mobile Template is based on the famous JavaScript framework for mobile application. You can learn a lot if you visit the jQuery mobile website.
 
 
 
Models and Controller are similar to a classic MVC Application.
 
 
 
In the view, you just have to add some tag to tell how jQuery mobile needs to display the page.
 
 
 
If we take a look at this code (Menu of the website generated by MVC4), you will probably recognize the Razor syntax. Nothing change when you want to develop Mobile Application with MVC4. You just have to use special attribute in your HTML.
 
 
 
Here, we declare a classic HTML list….and jQuery Mobile will transform it into an accessible list for mobile devices user.
 
 
 

   
  • Navigation

  •    
  • @Html.ActionLink("About", "About", "Home")

  •    
  • @Html.ActionLink("Contact", "Contact", "Home")

  • .
     
     
     
     
    The mobile version of ... Coding-in.net !
     
    This new template is perfect to start learning ASP.NET MVC4 mobile functionnalities and JQuery Mobile. If you already worked with MVC 3, you will see a big different between generated websites ! The MVC 4 website is simple, clean and uses jQuery. It’s a very good point to start learning !
     
     
     
    2 – Classic and mobile Website
     
     
     
    I will not describe all the new mobile features in MVC 4 in this post but there’s two another interesting features that I want to talk about and wich can interest some of you. It’s the “Display mode by Browser type” and the “View Switcher”.
     
     
     
    “View Switcher”
     
     
     
    A lot of mobile website have a special link to switch between mobile and classic view. ASP.NET MVC4 allows you to do this in … 1 click !
     
     
     
    This browser overriding ability allows user with mobile device to switch onto the classic version and vice versa.
     
     
     
    To add this functionnality to your ASP.NET MVC4 website, just open the Package Manager Console (Visual Studio > Tools > Library Package Manager) and paste this line :
     
     
                   Install-Package jQuery.Mobile.MVC
     
     
     
     
     
     
     
    NuGet is awesome isn’t it ? Your solution is updated and you now have a beautiful view switcher in your website !
     
     
     
     
     
     
     
    If we take a look at the added code, you should have a new partial View (in the Shared folder) called _ViewSwitcher.cshtml.
     
     
     
    @if (Request.Browser.IsMobileDevice && Request.HttpMethod == "GET")
     {
         

          @if (ViewContext.HttpContext.GetOverriddenBrowser().IsMobileDevice)
          {
              @: Displaying mobile view
               @Html.ActionLink("Desktop view", "SwitchView", "ViewSwitcher", new { mobile = false, returnUrl = Request.Url.PathAndQuery }, new { rel = "external" })
           }
         else
          {
                @: Displaying desktop view
                @Html.ActionLink("Mobile view", "SwitchView", "ViewSwitcher", new  { mobile = true, returnUrl = Request.Url.PathAndQuery }, new { rel = "external" })
          }

    }
     
    In this code we can see the new GetOverridenBrowser method which returns the request’s user agent override value, or the actual user agent string if no override has been specified.
     
     
     
    The view call the SwitchView action in the ViewSwitcher controller.
     
     
     
    public RedirectResult SwitchView(bool mobile, string returnUrl)
    {
      if (Request.Browser.IsMobileDevice == mobile)
           HttpContext.ClearOverriddenBrowser();
      else HttpContext.SetOverriddenBrowser(mobile ? BrowserOverride.Mobile : BrowserOverride.Desktop);

      return Redirect(returnUrl);
    }
     
    Here again we could take a look at some new method wich allows overriding brower agent value.
     
     
     
    “Display mode by Browser type”
     
     
     
    Okay, that is cool. You are now able to develop a full mobile website … But how to switch automatically between classic and mobile website depending on the browser type ? Thanks to MVC 4 , everything can be done easily !
     
     
     
    For example, if you already developped a classic website, you can easily develop the Mobile version with a new view called by the same name and with the extension .mobile.cshtml.
     
     
     
    If you have a Home.cshtml, create a Home.mobile.cshtml. If a user tries to acces to your website, the mobile version will be displayed.
     
    Better, you can override this feature and develop particular pages for a specific device. Thanks to the User Agent name available in the page request, you can, for example, target an iPhone, Android or WP7 user.
     
     
     
    In the Global.asax file, in the Application_Start method, just copy the code below.
     
     
     
    DisplayModes.Modes.Insert(0, new DefaultDisplayMode("Android")
    {
    ContextCondition = (context => context.Request.UserAgent.IndexOf ("Android", StringComparison.OrdinalIgnoreCase) >= 0)
    });

    DisplayModes.Modes.Insert(0, new DefaultDisplayMode("WindowsPhone")
    {
    ContextCondition = (context => context.Request.UserAgent.IndexOf ("Windows Phone OS", StringComparison.OrdinalIgnoreCase) >= 0)
    });.
     
    Here, we are saying to MVC 4 that we will add particular views (With .Android.cshtml and .WindowsPhone.cshtml) to the solution. If the user Agent is declared as an Android or Windows Phone browser, MVC4 will try to find the good view for this device. Simple and efficient !
     
     
     If you want to change the user agent without buy every mobile on the market, you could use amazing extension like User Agent Switcher (For Firefox). 
      
    Okay that’s all for today ! I hope you will enjoy as me these new functionnalities.
     
    Stay tuned of Coding-in.net, I will publish some post about MVC4 !
     
     
     
                                                       

    Oct 4, 2012

    string interning.. C# fundamentals

    We all know that string objects are immutable in C# i.e we can only create a new instance of the object we cannot alter or modify them.Let us take a quick look into the following lines of code:

    static void Main(string[] args)
    {

      string s1 = "sankarsan";

      string s2 = "sankarsan";

      if (object.ReferenceEquals(s1, s2))

       {

         Console.WriteLine("Both s1 and s2 refer to same object");

       }

      else

       {

         Console.WriteLine("s1 and s2 refer to different object");

       }

      Console.Read();

    }

    As strings are immutable s1 and s2 should be two different objects and output of the program should be "s1 and s2 refer to different object".But somehow that is not the case the output of the above code is "Both s1 and s2 refer to same object".But how can this happen? Let us also take a look into the IL code

    IL_0001: ldstr "sankarsan"

    IL_0006: stloc.0

    IL_0007: ldstr "sankarsan"

    IL_000c: stloc.1

    ldstr basically allocates memory for a string and stloc stores the reference into a variable in stack.   Now let us carefully study the documentation of the ldstr opcode in MSDN : http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.ldstr.aspx.

    The following lines in MSDN needs to be carefully noted:

    The Common Language Infrastructure (CLI) guarantees that the result of two ldstr instructions referring to two metadata tokens that have the same sequence of characters return precisely the same string object (a process known as "string interning").

    CLR internally maintains a hashtable like structure called intern pool which contains an entry for each unique literal string as key and the memory location of the string object as value.When a string literal is assigned to the variable CLR checks if the entry present in the intern pool,if exists it returns reference to that object otherwise creates the string object, adds to the pool and returns the reference.This is String Interning.The basic objective of this is reduce memory usage by avoiding duplication of same strings which are immutable objects.

    But this can have negative performance impact as well.This is because the additional hashtable lookups are costly and moreover all the interned strings are not unloaded from the memory till the app domain is unloaded.So they will occupy memory even if they are not used.

    We can try to off string interning by adding the following attribute to the assembly

    [assembly:CompilationRelaxations(CompilationRelaxations.NoStringInterning)]


    But it is upto the CLR as it may or may not consider this attribute.But if the native image is compiled using Ngen.exe then it considers this attribute.

    This feature of string interning is not something specific to CLR but also present languages like Java,Python etc.   ============================================================== The process of invoking string interning explicitly:     string a = new string(new char[] {'a', 'b', 'c'});   object o = String.Copy(a);

      Console.WriteLine(object.ReferenceEquals(o, a));

      String.Intern(o.ToString());

      Console.WriteLine(object.ReferenceEquals(o, String.Intern(a)));   Use String.IsInterned() to check if a string is in the intern pool string s = new string(new char[] {'x', 'y', 'z'});

      Console.WriteLine(String.IsInterned(s) ?? "not interned");

      String.Intern(s);

      Console.WriteLine(String.IsInterned(s) ?? "not interned");

      Console.WriteLine(object.ReferenceEquals(

      String.IsInterned(new string(new char[] { 'x', 'y', 'z' })), s));   ======================================================================= The above content was excerpted from the following links... http://broadcast.oreilly.com/2010/08/understanding-c-stringintern-m.html http://stackoverflow.com/questions/2506588/c-sharp-string-interning
    http://aspadvice.com/blogs/from_net_geeks_desk/archive/2008/12/25/String-Interning-in-C_2300_.aspx

    Oct 3, 2012

    Asp.Net MVC Web Api and Entity Framework issues (and the resolution)

    Recently, I was working on a test project for Asp.Net Web Api. The models were auto-generated EF models (DB first).
    The dummy database is that of a School. So the Tables/Classes are   Standard, Section, Students, Teachers
    Relationship:
    Standard: Section = 1:1
    Standard: Student = 1 : many
    So in my StandardController, I have 2 methods:
    Get – returns back all the Standards
    and
    Get(int id) – returns back the individual Standard based on the passed id

    They return back json objects which is parsed by a jquery function in a view and a html table is created based on the content.

    The calls were all reaching the Controller and then the classes were also properly fetched from the Db and returned.. but the jsnon was always erroring out..

    Even after repeated attempts there was failure in retrieving the data.

    I inspected the response object through Mozilla's firebug plugin and saw that it contained a JSON serialization exception.


    I was using a “using” block to fetch the entities thru LINQ / lambda and then populating a local variable which was returned back to the view..

    The Controller code before the change..

    public Enumerable<Standard> Get()
    {  IEnumerable Standards= null;  string connstr = SessionFactory.DBConnectionString;
     SchoolEntities context = new SchoolEntities (connection); /// the data context
      using (EntityConnection connection = new EntityConnection(connstr)) {

      using (SchoolEntities context = new SchoolEntities(connection))
      {
        context.ContextOptions.LazyLoadingEnabled = true;
        Standards = context.Standards;
      });
    }
    }

    return Standards;
    }

    I searched the net and found that the problem was in fetching and then retaining the inner collection of Students contained within each of the Standard object.

    After trying multiple ways to mitigate it, I tried one thing which worked

    I just had to remove the using section and was manually opening and closing the  data context and entity connection
    And it worked!!!

    The changed code:

    public Enumerable<Standard> Get()
    {

    IEnumerable Standards = null;

    string connstr = SessionFactory.DBConnectionString;

    EntityConnection connection = new EntityConnection(connstr);
    connection.Open(); // Open the connection
     

    SchoolEntities context = new SchoolEntities (connection); /// the data context

    Standards= context.Standards;

    connection.Close();
    return standards;

    }