Shadow Casting

I did this a few weeks ago actually but didn’t have time to write a post about it.

Well I was planing to write a longer post about it but considering it’s not that fast ( not as fast as it should be ) and buggy ( got some corner cases ), I decided to skip the post thingy and just put it here as is ( mainly because I have no intention to fix&improve it further )

Oh and again, it is inspired by Amit and his Shadow Casting post.

 

 

And here it is;

http://barankahyaoglu.com/shadowcasting/

( You might need to refresh the page right away )

 

TypeScript

Soooo guess it’s time to learn some Javascript eh? Now that even Anders Hejlsberg doing it.

Just in case you don’t know, TypeScript, created by Ander Hejlsberg, is a typed superset of Javascript with a much more C#-like flow and ECMA standards. Pretty much like CoffeeScript one might say. Or somewhat comparable to Dart I guess. Yea it’s like the 1000th attempt to fix Javascript and probably no one would have taken it seriously if it wasn’t for Microsoft and Hejlsberg.

Feels kinda weird really. Hejlsberg? Doing Javascript? I mean after Turbo Pascal, Delphi and C#, Javascript feels kinda odd.

But if all mighty & all knowing Anders think this might work, I sure won’t dare to question his wisdom.

One interesting thing though, from Miguel de Icaza’s blogpost on TypeScript;

Dart on the other hand is more ambitious as it uses the type information to optimize the quality of the generated code. This means that a function that adds two numbers (function add (a,b) { return a+b;}) can generate native code to add two numbers, basically, it can generate the following C code:

double add (double a, double b)
{
return a+b;
}

While weakly typed Javascript must generated something like:

JSObject add (JSObject a, JSObject b)
{
if (type (a) == typeof (double) &&
type (b) == typeof (double))
return a.ToDouble () + b.ToDouble ();
else
JIT_Compile_add_with_new_types ();
}

This is kinda interesting. I never knew that but sounds like a great idea. For some reason, TypeScript doesn’t go into that kinda of optimization. Makes me wonder though, why? My first guess is that TypeScript ( unlike Dart ) is a superset of JavaScript and such optimizations might break that. Or maybe they thought it just doesn’t worth it? ( scratch that. surely it’s because of the standard javascript engine compatibility. Silly me. )

Oh well, guess I’ll post some JS stuff soon. It can’t be THAT bad, right?

Creating a custom ActionResult

OK so now that we know a little more about ActionResults , let’s create a new one! I’ll go with a simple one , a personalized ViewResult.

It’ll be pretty much like standard ViewResult. First we’ll derive a base class from ActionResult , this abstract base class will take care of the ViewData , TempData , ExecuteResult method and stuff. Then we’ll derive our ViewResult from that base class , FindView there and maybe add some logic into that.

I’ll call our little action result , “MaryLouResult” from now on. I’ve already admitted I’m bad at naming stuff , so I’ll just stick with the song ( Mary Lou – Sonata Arctica ) I’m listening at the moment.

So let’s start with MaryLouBase!

protected abstract ViewEngineResult FindView(ControllerContext context);

public override void ExecuteResult(ControllerContext context)
{
    if (context == null)
    {
        throw new ArgumentNullException("context");
    }
    if (String.IsNullOrEmpty(ViewName))
    {
        ViewName = context.RouteData.GetRequiredString("action");
    }

    ViewEngineResult result = null;

    if (View == null)
    {
        result = FindView(context);
        View = result.View;
    }

    TextWriter writer = context.HttpContext.Response.Output;
    ViewContext viewContext = new ViewContext(context, View, new ViewDataDictionary(), TempData, writer);
    View.Render(viewContext, writer);

    if (result != null)
    {
        result.ViewEngine.ReleaseView(context, View);
    }
}

Nothing fancy here , actually I’ve just copy&pasted the ExecuteResult method of ViewResultBase class as it’s pretty straight forward. A few null checks , then FindView then ReleaseView.

You can also find ViewData and TempData implementations in ViewResultBase code or in the solution file at the bottom of this article.

Of course we could have simply used ViewResultBase and derive our MaryLouResult from that , but I just wanted to show you there is nothing magical about ViewResultBase class , you can just create another one as you like ( or totally skip it an derive your result from ActionResult ).

Now that we have a base class to handle ExecuteResult for us , all we need now is a MarylouResult with FindView method.

 

public class MaryLouResult : MaryLouResultBase
{
    private string _viewName { get; set; }
    private string _masterName { get; set; }
    private object _model { get; set; }

    public MaryLouResult(string viewName = "", string masterName = "", object model = null)
    {
        _viewName = viewName;
        _masterName = masterName;
        _model = model;
    }

    protected override ViewEngineResult FindView(ControllerContext context)
    {
        //Yeap you can get your Controller from here
        var faschoController = (context.Controller as FaschoController);

        //And check if it's an Ajax Request
        var ajax = context.HttpContext.Request.IsAjaxRequest();
        var FaschoAjax = faschoController.IsAjax;

        //Or if the user is Authenticated
        var auth = context.HttpContext.User.Identity.IsAuthenticated;
        var FaschoAuth = faschoController.IsAuthenticated();

        //Or if the user is actually an Admin
        var admin = context.HttpContext.User.IsInRole("admin");
        var FaschoAdmin = faschoController.IsAdmin();

        ViewData = new ViewDataDictionary(_model);

        //Then you can add some logic here as you like to select the view or the masterpage
        if ((context.Controller as FaschoController).IsAjax)
            _masterName = null;

        var result = ViewEngines.Engines.FindView(
        context,
        string.IsNullOrWhiteSpace(_viewName) ? ViewName : _viewName,
        _masterName
        );

        if (result.View != null)
        {
            return result;
        }

    }
}

OK so let’s see , we have a few fields for view name and master age name , then a a simple constructor and then the real part , FindView method.

FindView method gets a ControllerContext as a parameter which includes stuff like , current controller and HttpContext so we have lots of information in our hands just in case.

I really don’t have a special thing for Master pages but again the first thing came to my mind was playing with that.

As you can see you can use both HttpContext and your custom Controller ( if you have one ) from here. This means we can just check if the request is an Ajax request and change our FindView call according to that. Or maybe return Error Page if user is not authenticated?

I’ll have to say it tho , I don’t really like putting this kind of logic here. It feels out of place and I already usemy little Fascho Controller for these stuff.

This little example here was a little limited as it’s just a personalized ViewResult but actually there is literally no limit to what you can do with ActionResults. I’ll probably add a few more examples on ActionResults in future too.

You may also want to check these out ;

File Download Action Result by Phil Haack – Old but a very nice example

Image Result by Maarten Balliauw

Visual Studio 2010 Solution

Understanding ActionResults in Mvc

Almost all our Action in Mvc returns some kind of an ActionResult ( surprise! ). Or let’s say , they return a class derived from ActionResult , such as ; 

· ViewResult

· RedirectResult

· RedirectToRouteResult

· JsonResult

But how does this ActionResults work? It pretty simple actually ;

namespace System.Web.Mvc
{
    public abstract class ActionResult
    {
        public abstract void ExecuteResult(ControllerContext context);
    }
}

Told you! It’s just an abstract class with ExecuteResult function.

So let’s look into one of the most commonly used ActionResult , ViewResult and ViewResultBase ( Why I can’t link directly to a particular file  , *sigh* ).

Abstract base class , **ViewResultBase** first ;

 

namespace System.Web.Mvc
{
    using System;
    using System.Diagnostics.CodeAnalysis;

    public abstract class ViewResultBase : ActionResult
    {
        private TempDataDictionary _tempData;
        private ViewDataDictionary _viewData;
        private ViewEngineCollection _viewEngineCollection;
        private string _viewName;

        //Lots of properties below , the best part , ExecuteResult , is at the bottom

        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly",
        Justification = "This entire type is meant to be mutable.")]
        public TempDataDictionary TempData
        {
            get
            {
                if (_tempData == null)
                {
                    _tempData = new TempDataDictionary();
                }
                return _tempData;
            }
            set
            {
                _tempData = value;
            }
        }

        public IView View
        {
            get;
            set;
        }

        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly",
        Justification = "This entire type is meant to be mutable.")]
        public ViewDataDictionary ViewData
        {
            get
            {
                if (_viewData == null)
                {
                    _viewData = new ViewDataDictionary();
                }
                return _viewData;
            }
            set
            {
                _viewData = value;
            }
        }

        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly",
        Justification = "This entire type is meant to be mutable.")]
        public ViewEngineCollection ViewEngineCollection
        {
            get
            {
                return _viewEngineCollection ?? ViewEngines.Engines;
            }
            set
            {
                _viewEngineCollection = value;
            }
        }

        public string ViewName
        {
            get
            {
                return _viewName ?? String.Empty;
            }
            set
            {
                _viewName = value;
            }
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (String.IsNullOrEmpty(ViewName))
            {
                ViewName = context.RouteData.GetRequiredString("action");
            }

            ViewEngineResult result = null;

            if (View == null)
            {
                result = FindView(context); //this is the part we care about at the moment
                View = result.View;
            }

            ViewContext viewContext = new ViewContext(context, View, ViewData, TempData);
            View.Render(viewContext, context.HttpContext.Response.Output);

            if (result != null)
            {
                result.ViewEngine.ReleaseView(context, View); //And probably this
            }
        }

        protected abstract ViewEngineResult FindView(ControllerContext context);
    }
}

Wow , that’s a lot of code. But actually it’s just a few properties for stuff like ViewData and TempData. What we really care about here is ExecuteResult method ( at the bottom ). As you can see , ExecuteResult ( the only thing we really need for a custom ActionResult ) does 2 main things ; go find the view ( FindView ) and send it to ViewEngine ( ReleaseView ).

And the last part of our ActionResult , **ViewResult** ;

 

public class ViewResult : ViewResultBase
{
    private string _masterName;

    public string MasterName
    {
        get
        {
            return _masterName ?? String.Empty;
        }
        set
        {
            _masterName = value;
        }
    }

    protected override ViewEngineResult FindView(ControllerContext context)
    {
        ViewEngineResult result = ViewEngineCollection.FindView(context, ViewName, MasterName);
        //Obviously this gives you a good opportunity to interfere View & MasterPage selections
        if (result.View != null)
        {
            return result;
        }

        //I took out the part about error generation for now
    }
}

So all ViewResult does , is to use our ViewEngineCollection to find the page ( view ) we want. Remember , then it goes back to ViewResultBase and releases the view and we’re pretty much done with ActionResult , ViewEngine will take care of the rest.

Let’s have a look at how this all executes ;

Client Requests a Page

Controller is Created

-> Controller – OnActionExecuting runs

Action runs

->ViewResult is Created ( at return View(); )

ActionFinishes

-> Controller – OnActionExecuted runs

-> Controller – OnResultExecuting and OnResultExecuted runs

-> ViewResultBase – ExecuteResult runs

-> ViewResult – FindView runs

-> ViewResultBase send the view to ViewEngine ( ReleaseView )

Some magic happens after that which I know nothing of yet

Client gets the html , and hopefully happy now

You can also check this MSDN article about the execution process.

And Codeplex page of Asp.Net for the source code of Mvc

In next post , we’ll create a new custom ActionResult and play with it a little…

A Different Approach To Master Pages

I’ll just say it out loud , I don’t understand why do we ( or at least the MVC ) use _ViewStart to apply master pages. I just don’t get it. I mean we have a controller layer for decisions right? Why would I want to put decision logic in View layer ( or folder ).

I’m not a MVC purist , not eve close but still I don’t like this _ViewStart thing either.

@{ //Yeap it's Razor
//And we don't want any Master Page if it's an Ajax Request right?
Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml";
}

Another solution I learned a while ago was putting decision logic into ViewEngine. In TekPub Mastering Mvc Series , [Rob Connery](http://twitter.com/robconery) derived a personal View Engine, from WebForms view engine and put master page decision logic into that . Sounds like a nice idea isn’t it?

   

public override ViewEngineResult FindView(ControllerContext controller , string viewName, string masterName, bool useCache)
{

masterName = "DefaultMasterPage";

if(controllerContext.HttpContext.User.IsInRole("Administrator")
{
//Admin gets a special Master Page
masterName = "AdminMasterPage";
}

return base.FindView(controllerContext, viewName, masterName, useCache);
}

I like that a lot more than _ViewStart but still , adding a new View Engine and putting master page decision making process in a View Engine? Not a fan of that. Looks nice , works nice but I really don’t want to go to ViewEngine files whenever I want to change Master Page logic , feels kinda weird and out of place.

Of course , yet another and probably simplest option is to set Master Page in Controller Action while returning a view

   

public ActionResult About()
{
    return View("About","_SpecialLayout");
}

Well it’s in Controller now , right? But do we want to type the master page name in every single action? Of course not! Then we have to find a way to centralize this decision in Controller , do it once and then forget all about it right?

Just like what we did before ( in Fascho Controller post ) , we can just override OnResultExecuting method and put Master Page decision logic there! And since we’ll derive all our Controllers from this new Controller base class , it’ll be centralized , easy and pretty.

   

protected override void OnResultExecuting(ResultExecutingContext filterContext)
{
    if (filterContext.Result is ViewResult) //if we're done and returning a view 
    {
        var temp = (ViewResult)filterContext.Result;

        if (!IsAjax) //We dont want a masterpage around data if it's an Ajax call
        if (string.IsNullOrEmpty(temp.MasterName)) // And we don't want to override if there already is a masterpage 
        {
            //MasterPage selection logic
            temp.MasterName = IsAdmin() ? "_AdminLayout" : "_Layout";
        } 
    }
    base.OnResultExecuting(filterContext);
}

Doesn’t it look good? OnResultExecuting runs right after your Action returns something ( and obviously before OnResultExecuted ) so it’s not much more different than sending MasterPage name as a parameter , yet it’s centralized and all actually inside the Controller layer. 

You can find a sample solution file below. Fascho Controller now includes both this and previous Ajax solution but I did my best to seperate them with comments so it shouldn’t be a problem.

Visual Studio 2010 Solution

Extending Controller for Better Ajax Support

First blog post ever! Let’s see how it’ll turn out.

So I’ve been playing with Html & Js for a while as it’s the “cool” thing these days. It was all working fine , a few Ajax calls here and there etc. But after a while , I noticed this one weird or maybe even buggy behavior.

There is this one controller where I check out the incoming requests and if everything is OK then I redirect it to another action. And then in that second action I want to check if it’s an Ajax request or not , since I just want to send back raw page ( without Master Page ) if it is indeed an Ajax request.

When I did that , I thought my first action would run and just switch to the second action when it comes to RedirectToAction.

But it turns out when you use RedirectToAction method , MVC actually finishes the first Action , even fires up the OnResultExecuting / OnResultExecuted method and then starts a new procedure , creates a new controller and runs that second action etc.

Well OK , what’s the problem? The problem is , the request I’m working on is an Ajax request. But when I redirect to that second action , using RedirectToAction() , the second action runs as if the request is just an ordinary ( non-Ajax ) request. So when you go check Request.IsAjaxRequest() in that second action , you’ll get a huge , sad FALSE. Long story shorter ; RedirectToAction loses the Ajax Flag!

After Googling about it a little , I found a StackOverflow Q&A for this issue. Unfortunately I can’t seem to find it at the moment but I’ll add the link whenever I do. The suggested and accepted solution was extending the default controller to preserve the Ajax flag by using TempData. Obviously TempData is a great fit for the job as it’s created and used to store information that can be consumed in subsequent requests , right?

Unfortunately there were some little bugs with the suggested solution in that Stackoverflow Q&A so I just write my own little custom controller for it.

Enough with the talk eh?

 

 

public class FaschoController : Controller
{
    private const string AjaxTempKey = "__isAjax";
    public bool IsAjax
    {
        get
        {
            return (Request.IsAjaxRequest() || TempData.ContainsKey(AjaxTempKey));
        }
    }

    private void PreserveAjaxFlag()
    {
        if (IsAjax)
        {
            TempData[AjaxTempKey] = true;
        }
        else if (TempData.ContainsKey(AjaxTempKey))
        {
            TempData.Remove(AjaxTempKey);
        }
    }

    protected override void OnResultExecuting(ResultExecutingContext filterContext)
    {

        if (filterContext.Result is RedirectToRouteResult)
        {
            PreserveAjaxFlag();
        }

        base.OnResultExecuting(filterContext);
    }
}

 

 

First of all , I’m really bad at naming stuff so I just go with the first thing came to my mind. And what are we doing here , extending , strengthening the “Controller” right? THE Controller… So yeah , Fascho Controller! It’s silly I know, anyway…

So what’s going on here? We just override the OnResultExecuting method and make sure that it saves the Ajax flag to somewhere safe ( well safer than a controller which will be destroyed in seconds ) in case it’s a RedirectToRouteResult.

protected override void OnResultExecuting(ResultExecutingContext filterContext)
{
    if(filterContext.Result is RedirectToRouteResult)
    {
        PreserveAjaxFlag();
    }
    base.OnResultExecuting(filterContext);
}

Remember we’re still in first action so Request.IsAjaxRequest() will return true. Then we put this answer into TempData with a static key defined in our controller.

private void PreserveAjaxFlag()
{
    if (IsAjax)
    {
        TempData[AjaxTempKey] = true;
    }
    else if (TempData.ContainsKey(AjaxTempKey))
    {
        TempData.Remove(AjaxTempKey);
    }
}

And we’re done with the first action! Now when MVC redirect to second action , you’ll see that standard Request.IsAjaxRequest() will return FALSE but if you check our new IsAjax property , it’ll go check and return the TempData value we saved earlier. And NOW you can handle the request properly in your second action!

One more thing tho , it may or may not be necessary ( depending on your project ) but I also like to remove that Ajax key in TempData myself , just in case.

 

if(filterContext.Result is ViewResult)
{
    TempData.Remove(AjaxTempKey);
}

If you add this to OnResultExecuting part , it’ll remove the key whenever our application returns a view , which generally means we’re kinda done with the request and returned a proper response.

I’ll extend FaschoController even more in future , there are some other stuff I want to throw in Controller , mainly just to clean my Actions and get ride of some repetitive logic.

Visual Studio 2010 Solution