• Why do I waste time with View Engines? (22 Jan 2014)

    A few people recently asked me why I bother writing View Engines like Parrot when it’s very likely that nobody will ever use them.

    It’s not about usage or even getting a popular library out there. It’s all about the experience and growing as a developer.

    One of my first large projects was a clone of text-based game. The game had the ability to add additional functionality via extensions. I wanted to support that as well but in order to do so (I was 13 at the time) I needed to get a way to put this extension in the game. The only way I knew how was to write my own language.

    I called it “Dark Tempest Scripting Language” or “DTSL” for short. It was a very strange language and very lousy.

    saysomething:
        var gold
        var level
        var str
        var hp
        var weapon
        hp ~ gethp ()
        str ~ getstr ()
        charm ~ getcharm ()
        level ~ getlevel ()
        gold ~ getgold ()
        gem ~ getgem ()
        weapon ~ getweapon ()
        println "print something"
    end
    

    That was a function. There were no parameters allowed. I didn’t even think I could figure that out at the time. The functions you do see are built into the language itself. The parser was very simple. It expected things to look a certain way - if it wasn’t formatted properly it would break. This was unacceptable but I didn’t know any better at the time.

    Fast forward 20 years…wow, has it really been that long? I finally got around to wanting to write another language. But why? What would it do? I’ve been playing with view engines a lot recently and decided I was going to make my own view engine with a custom language to boot.

    This was one heck of a learning experience. I learned about parsers and state machines. Mostly from a friend of mine, Roy.

    It doesn’t matter if nobody uses it. I enjoyed the entire process and it’ll definitely help me in the future when I come across similar issues that I ran into while building this.

    -Ben Dornis

  • Introducing Typescript.io (08 Jan 2014)

    For the past couple weeks I’ve been working on a sort of jsfiddle for Typescript. Most of that time has been working on the intellisense features for typescript. It’s amazing what the designers of Typescript made available.

    The UI is fairly simple. You have your typescript, html, css editors and a results pane. You can hide/show them as necessary. All prototypes are private by default.

    I am currently working on adding user login support so you can save you prototypes.

    Here are a couple sample prototypes you can use.

    http://typescript.io/greeter http://typescript.io/Zk434lLa0Ag

    Please mention any bugs you find. I’ll try and fix them as I can.

    I hope you enjoy this site and share it around.

    -Ben Dornis

  • Javascript View Engine for Asp.Net (16 Dec 2013)

    I was chatting with a friend the other day and was remarking about Parrot when I made an offhand comment that I should build a view engine that can execute Javascript.

    I hate when that happens. I started thinking that there are so many great view engines out there written in Javascript that instead of writing a new one I should just use what’s already out there. A few hours later I found myself writing such a view engine.

    First I had to find a nice vm for javascript that I could execute within .Net. I found some promising ones after a lot of searching, v8sharp and Javascript.Net. I first played around with js.net but ran into some issues and since this was just a test I wasn’t interested in figuring out what’s wrong and went with v8sharp instead. Dev went well and I got the basics of the engine working. Eventually I settled on ClearScript. It had the most feature complete implementation that had excellent host side capabilities and is in active development. I could execute a Mustache template without any issues.

    After I got the core library working I started thinking about ways to enhance it. It needed support for the plethora of templating engines already out there available for javascript. Rather than write a separate .Net class for each engine I just had the view engine itself search for specific types of javascript files in the project that it could then load. This has the advantage of being easily upgraded with new engines by just adding new .js files to the project or updating existing .js files.

    The view engine itself is fairly basic and isn’t much different from any other view engine. The main difference is how the views are rendered. We build up our Javascript file run it through ClearScript and return the results. It’s fairly simple and was a quickly put together project.

    To get started one just needs to add the view engine to the list of available view engines to an MVC project.

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
    
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    
        ViewEngines.Engines.Add(new JavascriptViewEngine());
        //ViewEngines.Engines.Add(new JavascriptViewEngine(AlternateEngineDefinitionLocation, new [] { "~/AlternateViewLocationDirectories" }));
    }
    

    Next you’ll need to tell the JavascriptViewEngine the location of your engines script. The default path is ~/scripts/Javascript.ViewEngines.js.

    Register your templating engine with the engine like the following.

    JsViewEngines.add({
        name: "Mustache",
        extensions: ["mustache"],
        template: new Template(function (template, model) {
            return Mustache.render(template, model);
        }),
        requires: ["mustache.js"]
    });
    

    We have a little bit of meta data here. Most are fairly obvious. Extensions is an array of view filename extensions to look for. includes is an array of javascript files required to execute this engine against templates. template is the actual javascript rendering call. It’s different for each engine. You must wrap the template function with the new Template constructor. This will tell the view engine how to execute the view.

    One “gotcha” is that these are run on the server. As such you don’t have the ability to manipulate the dom or output to the console or any other things you can do on a client/browser templating engine.

    You can view a live sample at http://jsve.buildstarted.com/ It has several engines already added. The templates are really simple for now.

    You can check out the code on my github repo at https://github.com/Buildstarted/Javascript.ViewEngines. I’ll be creating a Nuget package soon as there are some issues between x86 and x64.

    -Ben Dornis

  • Organize By Feature (10 Dec 2013)

    Taking inspiration from João P. Bragança in configuring Nancy to organize per feature I’ve taken the concept and applied it to MVC.

    The idea behind it is to group related classes/files together by feature rather than function.

    By default MVC creates a Controllers, Models, and Views folder. This is fine for tiny projects with a couple controllers. It gets unyielding when your website grows.

    Organize By Function

    All we need to do is update the Razor View Engine and tell it where our files now reside.

    private void InitializeFeatureEngineExtensions()
    {
        var razor = ViewEngines.Engines.OfType<RazorViewEngine>().Single();
        razor.ViewLocationFormats = new[] {"~/Features/{1}/Views/{0}.cshmtl"}.Concat(razor.ViewLocationFormats).ToArray();
        razor.PartialViewLocationFormats = new[] {"~/Features/{1}/Views/{0}.cshtml"}.Concat(razor.PartialViewLocationFormats).ToArray();
    }
    

    That’s all there is to it. You can add more paths if you like. I’ve chosen to keep the default paths intact.

    Now we can modify our project structure like so:

    Organize By Feature

    One thing to note is that the tooling for Visual Studio requires the standard Views location. I’m not sure how (if it’s even possible) to modify this yet. Add View and Goto View currently do not work.

    Thanks to João P. Bragança aka The Fringe Ninja for the inspiration.

    Clarification

    One of the problems with MVC Areas is that you’re still stuck with their folder structure. The point of this post was to highlight a little know ability to change the locations of your views from standard to anything you’d like.

    -Ben Dornis

  • Invoking extension methods via reflection (21 Jun 2013)

    As part of a small project I’m working on I created a dynamic wrapper around a class that was almost exclusively used with extension methods. You can’t just do the following.

    _someClass.GetType().GetMethod("ExtensionMethod").Invoke(_someClass, null);
    

    Extension methods are just some compiler trickery. They don’t exist on the class but separately in a static class elsewhere. To do it properly you’ll need to invoke the method on the static class.

    typeof(ExtensionMethodClass)
        .GetMethod("SomeMethod")
        .Invoke(null, new [] { _someClass });
    

    We’re required to pass an instance of _someClass since that is the first parameter on all extension methods.

    This has the minor downside of knowing the extention method class that contains the method we’re looking for. That’s not always readily apparent with someone else’s library and there could be any number of available classes that extend your object.

    -Ben Dornis

  • Understanding jQuery's Deferred (17 Jun 2013)

    I was talking with a coworker earlier today trying to wrap my head around how part of jQuery’s Deferred worked. I didn’t understand how part of Deferred worked.

    Here’s a sample call

    function something() {
        var deferred = $.Deferred();
    
        if (someCall) {
            deferred.resolve();
        }
    
        return deferred;
    }
    
    something()
        .done(function() {
        })
        .fail(function() {
        })
        .always(function() {
        });
    

    What was confusing me was how .done would be called if resolve was executed before the deferred was returned. There was some sort of weird disconnect going on in my brain. I was thinking someCall is async so it’s possible that .resolve won’t be called before the method returns. But that just causes race conditions that I knew weren’t what I wanted to get into. My coworker then set me straight that when .done is executed it checks the state of the deferred and then calls the callback if necessary. This made perfect sense. I don’t know why that didn’t occur to me.

    To cement this in my brain I decided to port Deferred to c#. It helps me a lot to be able to write something.

    Here’s the result.

    I had decided not to make Deferred itself generic because each of the .Done, .Always, .Fail may take many different parameters. I wanted to give some leeway in those calls.

    - Ben Dornis

  • Parrot for AspNet (30 May 2013)

    Install the nuget package using the following command.

    PM> Install-Package Parrot.AspNet

    New to Parrot? See my introductory article on Parrot here.

    How is Parrot different from Razor?

    Views are meant to be dumb. They shouldn’t contain any (or hardly any) code and just output the view with data from the model. Razor’s focus was to give a cleaner separation of code and html, Parrot strives to remove code from your views.

    Here is a sample razor template converted to parrot.

    Razor sample

    <h3>Welcome, @Model.Name</h3>
    
    <ul id="cart">
      @foreach(var item in Model.ShoppingCart) {
            <li class="item">@item.Name - @item.Price</li>
        }
    </ul>
    

    Parrot sample

    h3 | Welcome, @Name
    
    ul#cart(ShoppingCart) > li.item | @Name - @Price
    

    It’s just a basic sample but you can already see some major differences. First note that the Model keyword isn’t necessary. By default the page is scoped to the Model property of the page. You’re not limited to that though. If your view has other objects you want to access, such as HttpContext.Request or ViewContext you can easily do so by specifying the property name instead, @Request.Url (or something similar). If there’s a conflict the Model wins. (I think I need to change this or provide a way to force)

    There’s no need for a foreach in Parrot as well. Tags are smart enough to know if the property applied to them is an array or IEnumerable to loop over the items and apply them to the children. Notice there’s no variable name declaration for the child tag. By default the tag is scoped to the iterator item.

    Layouts and Partials

    Layouts are slightly different in Parrot. In Razor you can define a layout file by setting a variable in either the page or in _ViewStart.cshtml. In Parrot you just wrap your content. The content tag in your layout page Tells Parrot where to output. ‘filename’ should be a path to the layout file.

    layout('filename') {
        h1 |We're in a layout!
    }
    
    html > body > content
    

    Partials are just as simple

    html > body > partial('filename')
    

    Extensibility

    Parrot was designed for extensibility. You can easily add new tag renderers.

    If a tag is specified in code but no renderers exist for that particular tag then it will default to a standard html renderer and output <tag>...contents...</tag>.

    Suppose we needed an if tag that would output it’s children if the object passed in is true. Something like this.

    if(SomeModelValue) |It's true!
    

    It wouldn’t make sense to output <if>It's true!</if> so the custom renderer not only outputs if the value is true but also only outputs the children.

    A lot of renderers exist for common tags that behave differently than standard html <tag></tag>. The ul/ol tags, for example. I’ve created a renderer specifically for those two as they’re lists. If you pass in an IEnumerable object as a parameter it will loop over the items and render the children each time.

    I’ll be working on the documentation on how to create these as well as documenting the features of some of the custom ones in a future blog post.

    Sample If renderer

    Final Thoughts

    Parrot is a very new project. There are going to be some rough edges to be smoothed out. Help is very welcome. Visit This is parrot for more info on the Nancy, Javascript and Asp.Net libraries.

    - Ben Dornis

  • Parrot 1.0 Release (04 Feb 2013)

    I’m proud to announce that Parrot is going 1.0 this week. It went through a lot of changes to get it here. Several major “rewrites” of portions of the system to handle usages I had not conceived of while writing. The more interesting change was the removal of the dependency resolver. Thanks to GrumpyDev for his help in that area.

    Javascript

    One of the more interesting releases is that of a javascript parrot parser. It can be used in webpages or possibly with nodejs once a wrapper is written. Including the required files and jQuery makes it as simple as

    var html = $("#template").parrot();
    

    You can then insert it in your webpage just like any html string.

    $("body").html($("#homepage").parrot());
    

    Parrot in javascript

    Here’s how it’s used on the home page for Parrot.

    Nancy

    Also with this release a version of the Parrot View Engine for the NancyFx. Porting Parrot over to Nancy was one of the ways I found everything that could be wrong with Parrot. This caused several rewrites as I realized I was really dependent on Asp.net. I think this has streamlined how it works.

    Asp.Net

    And of course, there’s support for Asp.Net MVC.

    Nuget

    Installing parrot is easy with Nuget

    PM> Install-Package Parrot.AspNet

    PM> Install-Package Nancy.ViewEngines.Parrot

    Live demo

    This is parrot

    So checkout the website at http://thisisparrot.com/ and try Parrot out for yourself.

    -Ben Dornis

  • Lambda expressions and closures (26 Nov 2012)

    I’ve been dealing a lot with anonymous methods lately I started getting interested in how they work, especially when dealing with closures. I was curious how these variables worked.

    for(int i = 0; i < 10; i++) 
    {
        Task.Factory.StartNew(() => Console.WriteLine(i));
    }
    

    One might think that this would output 0, 1, 2, 3, 4...9 however as the anonymous methods might not be run at the time they’re defined and the loop may finish faster and set i to 10 before the anonymous methods are even executed (depending on the speed of your system). The output on my system results in 10 lines of 10. The reason for this is how c# generates the code for this. I’ve simplified it for brevity.

    //original code
    class Program
    {
        static void Main()
        {
            for (int i = 0; i < 10; i++)
            {
                Task.Factory.StartNew(() => Console.WriteLine(i));
            }
        }
    }
    
    //after compilation
    //this code has been simplified
    //for readability
    class Program
    {
        static void Main()
        {
            c__DisplayClass2 cDisplayClass2 = new c__DisplayClass2();
            for (cDisplayClass2.i = 0; cDisplayClass2.i < 10; cDisplayClass2.i++)
            {
                Task.Factory.StartNew((Action)(cDisplayClass2.b__0));
            }
        }
    }
    
    [CompilerGenerated]
    private sealed class c__DisplayClass2
    {
        public int i;
    
        public void b__0()
        {
            Console.WriteLine(this.i);
        }
    }
    

    Wow. The lambda expression sure does hide a lot of code. Let’s see what’s going on here. Notice a new class was created and it has a public property i. This replaces the local variable in the for/loop. This is how we can access the closure within the anonymous method. It no longer exists in the context of a local variable of the function but as a global field of the generated class. As the methods don’t necessarily execute when called you must make sure to make a local copy of that variable. If not the member variable might change before execution.

    What if you’re accessing a member field of the calling class?

    //original
    class Program
    {
        private string test = "test";
    
        static void Main()
        {
            var p = new Program();
            p.Run();
        }
    
        private void Run()
        {
            Task.Factory.StartNew(() => Console.WriteLine(test));
        }
    }
    
    
    //after compilation
    //this code has been simplified
    //for readability
    class Program
    {
        private string test = "test";
    
        private static void Main(string[] args)
        {
            new Program().Run();
        }
    
        private void Run()
        {
            Task.Factory.StartNew((Action)(b__0));
        }
    
        [CompilerGenerated]
        private void b__0()
        {
            Console.WriteLine(this.test);
        }
    }
    

    As we can see, this time, the CompilerGenerated method resides in the same class. This is required because it needs to access the same field of the calling class. However, if you need both, access to a local variable and one to a member variable it creates a second class with a references to the caller.

    //after compilation
    //this code has been simplified
    //for readability
    class Program
    {
        private string test = "test1";
    
        private void Run()
        {
            c__DisplayClass1 cDisplayClass1 = new c__DisplayClass1();
            cDisplayClass1.__this = this;
            Task.Factory.StartNew((Action)(b__0));
        }
    
        [CompilerGenerated]
        private sealed class c__DisplayClass1
        {
          public string test1;
          public Program __this;
    
          public void b__0()
          {
              Console.WriteLine(this.__this.test + this.test1);
          }
        }
    }
    

    Knowing how the compiler acts on your code is important. Hopefully this will give you some insight as to how some of the magic with anonymous methods/functions happens.

  • Engaging the community (21 Sep 2012)

    If you never engage others, you never chat about what you’ve learned, never ask questions - you’ll never truly grow. It’s through discussion and debate that I’ve found to be the best way to change your views and expand your horizons. I’ve learned more discussing with friends than I think I would learn on my own reading blog posts and what not. When you’re programming by google you’re stuck in a little bubble. You tend to search for things you already know or were exposed enough to already want to learn more. You might be exposed to new ideas on how to do a particular method or implementation but others who understand what you’re trying to accomplish might promote other methods or implementations you might have never thought of before.

    Recently I started a project in which I was designing my own language for an MVC View Engine I’m calling Parrot. This is pretty new territory for me. I’ve designed basic languages before. All based on something I was intimately familiar with. Very basic parsing based on substrings and indexofs. In other words horrible. I would have gone down this same path if I weren’t discussing this new project with a long time friend of mine.

    He suggested I write or use an existing parser/generator engine. What’s that?! Lots of acronyms and strange words were thrown around including LALR parser, SLR, LR(1) and so forth. I’ve never heard of these before. After some reading I discovered GoldParser. This was an amazing discovery. I was able to get the basics of the new language down fairly quickly and get a prototype of it running within the day. New changes to the language came over the week each with modifications to the grammars used by GoldParser. This allowed a lot of flexibility. If I had written my own simple parser I doubt I would have had the ability to change it so easily and advance so quickly.

    Through discussion and by engaging others I was able to learn something new that will benefit me for years to come.

    Friendships

    However, you still need to have friends you can bounce ideas off of. People that listen to what you say and give you advice when needed or just act like a Rubber Duck. But you have to get out there and mingle with other developers. There are Nerd Dinners, Code Camps, DevCamps, User Groups, JabbR, tons of ways to meet other devs who probably share the same passions you do.

    What do you get out of this? The most obvious answer is you make friends. I have met some interesting people by attending the Socal Code Camp. It’s a free event where developers of all kinds can come together and share knowledge and learn from each other. This event has been one of the turning points in my development career. I’ve made friends that I’ve stayed in touch with since we met. You never know what these new found contacts might bring to the friendship. Some bring knowledge. Some bring opportunities. But they all bring something to the table and likewise so do you, even if it’s just a new friend.

    The most important thing is to meet the people you call peers. Take that first step. It can be a tough one but it will pay off in the long run. Some devs stay in the background and try not to be social. Don’t be one of those. Push forward and engage them. You never know who you’ll meet or where that meeting will take you.

    -Ben Dornis