Scripting ease with Script Packs

Script Packs are a really cool extensibility point we added into scriptcs. A pack delivers a bundle of functionality that makes frameworks more palatable to consume from script. They are available as nuget packages making them very easy to consume.

For example, if you look at our Web API sample, you’ll see there’s a bunch of fiction if you just try to get web api working from scratch.

  • You need to add using statements for each namespace you want to use. This is a lot more painful than one might thing when you don’t have intellisense.
  • You need to configure web API, this involves creating a host, defining default routes etc. Adding lots of object creation and such starts to make the script pretty hairy. Not impossible, but painful when there’s no template.
  • You need to teach Web Api how to resolve controllers in script by implementing a custom controller resolver.

Now pull in the Web Api script pack (scriptcs –install scriptcs.webapi) using the Require<WebApi>() and your boiler plate code evaporates to this:

The script pack does all of the following to make the experience better:

  • Removes the need for using statements for common namespaces. The script pack provides those which is why you don’t have to add the web api namespaces in your example above.
  • Adds dll and nuget package references that bring the dependencies the framework needs.
  • Removes general boilerplate code. In the previous sample you need to create a host, define routes etc as I mentioned. In this case the script pack creates the host for you and configure with the default routes. You can customize if you need to.
  • Provide APIs to fill gaps that prevent the framework from working well in script / supporting dynamically emitted assemblies. The Web Api script pack brings in and configures a custom controller resolver for you.

We’re just getting started with the work we’ve done with script packs, but they are a really nice extensibility point and really take advantage of nuget as a delivery mechanism. The community has been rising to the occasion and building out quite the gallery as well.

There’s some great posts about script packs covering topics like how to build them or even use them from the REPL that you should really check out.

Have fun exploring the new world of scripting in C# with scriptcs!

Posted in c#, scriptcs | Leave a comment

@model and beyond

In my previous post I had been fiddling with the html helper used in Razor views. Since then our custom html-extensions have been doing great things for our project. To mention some:

  1. Standardizing the look and feel. It is far more consistent and maintainable to set attributes (including a css class) and event handlers in one centralized place.
  2. Simplify the script. Often a part of the logic the script will follow is already known server side. Instead of writing everything out in javascript rendering the intended statements leads to a leaner client. There is an example in my previous post on building post-data.
  3. Decoupling the libraries used. At the moment we are using the Telerik MVC suite. In my previous post I described how our html helpers build standardized Telerik components for our views. In the not to far future we want to switch to the Telerik Kendo suite. Having wrapped up the library dependency in our Html helper will make this switch a lot easier to implement.

What has evolved is the way we work with the model. In MVC the implementation of the controller and the view is clear. When it comes to the implementation of the model there are almost as many different styles of implementation as there are programmers. In general the model can bring any data to the view you can imagine. Not only the source of the data varies, from plain sql to a C# property, also the use of the model’s data varies. It can be a customers name from the database. Or it can be the string representation of some html attribute needed for a fancy picker. Here data and presentation start to get mixed up. Our extensions needed information for the Html-Id. The original Html helper had a custom constructor to get that specific data from the model into the helper. Which required to create our own htmlhelper when starting the view and use that one instead of the standard @html. As seen in the eposHtml in the previous story. It would be cleaner if our extension methods could be satisfied with the default html helper. It would also be cleaner to keep a better separation between ‘real’ data and presentation.

The model is available in every HtmlHelper extension method.

public static PostDataBuilder<TModel> PostData<TModel>(this HtmlHelper<TModel> htmlHelper)

{

    return new PostDataBuilder<TModel>(Id(htmlHelper.ViewData.Model));

}

 

It’s a property of the ViewData.

In our case we needed something to give the control an unique Id. The Id method builds that Id. Previously we passed the Id-base in the constructor, which lead to the custom helper. A far more elegant solution is using a very basic IOC-DI pattern. As implemented By the Id method

private static string Id(object model)

{

    var complex = model as IProvideCompositeId;

    if (complex != null)

        return complex.CompositeId;

    var simple = model as IProvideId;

    return simple == null ? “” :  simple.Id < 0  ? String.Format(“N{0}”, Math.Abs(simple.Id)) : simple.Id.ToString();

}

 

The method queries the model first for the IProvideCompositeId interface, in case the model does not implement that it is queried for the IprovideId interface. Resulting in a string which can be safely used in an HtmlId. (A negative number would lead to a ‘–’ in the string, which is not accepted in an Html Id).

These interfaces are very straightforward

public interface IProvideCompositeId

{

    string CompositeId { get; }

}

 

public interface IProvideId

{

    int Id { get; }

}

 

In case the model is going to be used in a view requiring unique Id’s the model has to implement one of these interfaces.

public class FactuurDefinitie : IProvideCompositeId

{

    public readonly int IdTraject;

    public readonly int UZOVI;

    public readonly bool Verzekerd;

 

    public FactuurDefinitie(int idTraject, int uzovi, bool verzekerd)

    {

        // The usual stuff

    }

 

    public string CompositeId

    {

        get { return String.Format(“{0}{1}{2}”, IdTraject, UZOVI, Verzekerd); }

    }

}

 

Working this way:

  • We can use our custom html extensions in the default html helper
  • Specific data from the model is available inside our extensions
  • The model and the view do not get entangled

The code is no big deal. I know. But the model is something whose horizons are still not in sight.

Posted in Uncategorized | Leave a comment

Don’t assign a field from many methods

For the next NDepend version, amongst plenty of cool stuff, a new default code rule will be added. It has been named Don’t assign a field from many methods. It falls into the category of Purity – Immutability – Side-Effects rules, one of my preferred set of rules since often hard-to-find and to-fix bugs come from wrong state managements.

Screenshot2

As its name suggests this rule matches fields assigned from multiple methods. Bugs due to corrupted state are often the consequence of fields anarchically assigned.

On many code bases tested, I found the threshold of 4 methods writer to be the best balanced number between too many false positives, and a decent amount of suspicious matches to look after at code-reviewing time. Of course this threshold is easily customizable.

Several parameters can be taken account.

  • Is the field static? in which case it can be pretty serious if many methods assign it.
  • Does the field type is a value or a reference type? In the case of a reference type, such situation might reveal a potential NullReferenceException scenario luring.
  • Is the field assigned outside from its class. Since another rule prevents fields to be visible from outside its class, this case has been eliminated.
  • How many assigner methods of the parent class are visible outside the class? How many  methods calling directly or indirectly an assigner method are visible outside the class?
  • Can a particular class instance be accessed from multiple threads? in which case the situation sounds pretty alarming.

Not all cases are taken account since static analysis have limits and for code review warning purposes the rule algorithm must be kept easily understandable. Here is the rule code and comments that contain insight about how to generally fix such issue.

I’d be curious to read your suggestions and comments on that.

And here is what it looks like when we run the rules on the NUnit code base:

NDepend CQLinq Rules

Posted in C#, high cohesion, Immutability, Maintainability, measurement | Leave a comment

scriptcs gets a REPL!

Hello c# scripters!

Before you go further, if you are wondering what all the scriptcs hype is about please check out Scott Hanselman’s great post and his new Tekpub video.

Last few days I’ve been working on a new REPL experience for scriptcs and now it’s in! REPLs are nothing new to dynamic languages but they have not really been available in C# with one exception, Mono has a great REPL. Roslyn introduces the Roslyn interactive window in VS which is also a REPL which runs in the editor.

This REPL is different than both in that it is specific for scriptcs, and like the rest of the scriptcs experience, there’ s no IDE required. Basically it combines the goodness of scriptcs (nuget) with an interactive experience. You can just install some nuget packages and type code which instantly executes. For example imagine just pulling in HttpClient and then just doing some http requests!

Below you can see I am installing the mongo nuget package. Then running scriptcs by itself and typing in some simple code to work with the package.

clip_image001

And then we have pretty error handling.

clip_image002

Thanks to the Roslyn team’s efforts layering a REPL on top was AMAZINGLY easy. The REPL part itself was like 15 lines of code! And thanks to the nuget team for even making this a remote possibility through having an awesome package ecosystem. I look forward to ALSO seeing the mono version soon :-)

If you wanna try it, you can grab the latest from github at http://github.com/scriptcs/scriptcs in the dev branch.

It will also be on our chocolately nightly builds tomorrow: http://www.myget.org/F/scriptcsnightly. It should be on our public feed very soon there after.

Posted in scriptcs | 3 Comments

Relaunching SerialSeb – Practical ReST and then some

Well. After 5 months of soul-searching, ups and downs, I’m back, more focused than ever (think laser beam focus). This week has seen the launch of several important projects for me, and I’m very excited to share them with you, a year after my last blog post! The hiatus is over and Seb is back.

Practical ReST – the book

I’ve been talking for years about writing a brain dump of what I know of ReST. The project has started, you can pledge to buy your copy today (in various editions) and get content as early as next month!

The response has been amazing, with three quarters of the minimum funding pledged in 48 hours. Of course, the more contributors the more time I can allocate to the book, the quicker the book will be in your hands, so don’t hesitate!

Writing a book in itself is a big challenge, and the scope is very ambitious. But it’s also a foray into self-publishing, and I expect it to be an amazing opportunity for learning.

Practical ReST – the class

I’ve been giving a ReST class for a while, but I’m rewriting it so it follows the same structure as the book, and make it open to people with many technological backgrounds.

First date should be in May in London, and I expect Warsaw, Vilnius and other locations to pop up this year.

If you want to see a workshop organised in your city (or your company), pop me an email.

I’m also launching a referral program *and* group rebates, so if you’re a training company and you want to add the course to your books, you can too.

Hanselminutes podcast

Scott was nice enough to have me on his show this week, talking about Practical ReST. It’s published and ready to be listened to, and while I was half-way through an asthma attack and having microphone problems, Scott saves the day by being a great host.

Cancer Research UK

You may remember that I asked for your contributions to help me raise money for cancer research UK. I can now announced that we raised more than 700£, and that both my objectives of non-drinking were achieved. I cannot thank you all enough for your generosity.

serialseb.com

It had to happen. I now have my own web site. You cannot imagine how difficult it is for me to put work and effort in talking about what I did rather than what I want to do. But you will find on there a link to all my previous talks, with videos and slides (where applicable), as well as where you’ll find me next, my future talks and where classes will be delivered next.

What next?

ReST will be my focus for the next few months. I have a couple of other projects up my sleeve, but this is enough announcements for now, don’t you think?

Posted in Uncategorized | 7 Comments