• Direct casting vs as casting (27 Jun 2014)

    There are two primary ways to cast in C#, Direct casting and ‘as’ casting.

    Explicit/Implicit casting

    Here are some examples of Direct/Implicit casting

    byte source = 1;
    int value = source;
    
    object source = 1; //this assignment defaults to an int
    int value = (int)source;
    /* or */
    byte value = (byte)source;
    

    Implicit casts can be used when converting from one type to another without any loss of information. In this example from a byte to a higher order numeric value. Byte to Int32, Int32 to Double. You cannot, however, cast down from Double to Byte without doing an explicit cast.

    The second example shows an explicit cast from an integer to a byte. The explicit cast here is required because there could be a loss of information going from a larger int (4 bytes) to a byte (1 byte).

    Casting using the as operator

    The types must be nullable or reference objects in this case.

    object animal = new Dog();
    var value = animal as Dog;
    
    /* value, is this instance, will be `null` */
    var value = animal as Plankton;
    

    As casting basically does a check to see if the type is convertible and if so returns the value. If not it returns null.

    Are these the same?

    In essense no. Using ILSpy we can see that the generated IL for explicit casts uses the castclass, where as the as operator uses isinst.

    IL_0007: isinst CastClassVsIsInst.Dog
    
    IL_0007: castclass CastClassVsIsInst.Dog
    

    From a little bit of testing it seems that ‘as’ is also faster. Others could confirm this but in tight loops isinst performs significantly faster than castclass.

    castclass vs. isinst

    Charts courtesy of Jon Galloway

    Here’s my quick-and-dirty test.

    Feel free to fork it and make improvements. There might be instances where castclass is faster.

    It’s not perfect but enough to convince me that isinst is a bit faster in tight loops than castclass

    -Ben Dornis

  • Categorizing blog posts (14 May 2014)

    How important is it to categorize blog posts?

    I ask this question because during the redesign process my blog and there were several features offered by the Wordpress that I have left out in this new version. Namely date grouping and tags. I’ve already stopped categorizing my entries as of late due to lack of remembering to do so. Looking at the logs almost nobody has ever clicked on a tag and very few people search by date. I suspect most people who view by date are just going into the past of my blog and seeing what else I’ve written about. Is discovery that important? Quite a few of the blog posts in my past are horribly out of date.

    Tags

    Almost every tag is so generic that they cover most every blog post. c# for instance is basically every post I’ve made since I’ve started this blog. parrot only applies to a handleful of posts that I’ve made in the recent history. MVC is another tag that covers a lot of posts. Maybe I’m not diligent in tagging my posts to be more descriptive but how descriptive does one need to be? I can get to the point where each post has a tag that covers it and probably no other post but that wouldn’t help. Having tags that cover almost every post is also no help to the user.

    Dates

    With the speed that things are changing in the dev world I’ve noticed some blog posts are out of date within months of posting them or I’ve found better ways and probably wrote a new blog post to cover that method. Does this mean that having an archive is pointless? Why would you go back in time to read articles that are no longer of any use to anyone. For me it’s a bit of nostalgia to look back and go “wow…I was really naive then”. But to the general user older posts seem to be of no use. Maybe it’s me. Maybe my blog posts are too specific. I look at someone like Hanselman’s blog and a lot of his articles are relevant today as they were 3-4 years ago when they were posted. Sure, some are very specific and may not be relevant but I could probably go back in his history and find something that I could post on twitter today and people will still get use out of it.

    My Conclusion

    Both tags and date could be served by search. Since my blog is currently a static site that search would have to come from Google/Bing. Each article most likely already has a good tag keyword embedded in the content already. A proper sitemap and RSS feed with published datetime will help Google/Bing/Yahoo/Other to order your posts by date and relevance. As of this point I plan on adding a search box to Google. This may or may not be the right answer. The size of my blog probably has a lot to do with it. If it was more trafficked it might be a good idea. But analytics aren’t showing me that they’re relevant or useful.

    I hope to solicit the community for advice on which way to go.

    -Ben Dornis

  • 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