SmoothFriction.nl

posts - 35, comments - 18, trackbacks - 0

Saturday, January 09, 2010

TekPub's Mastering LINQ Challenge

I’m always up for a challenge. I still have to watch the Mastering LINQ videos up on TekPub (which is amazing by the way, I encourage you to check it out!), but someone (hi Tuna!) tweeted about a small challenge related to the series.

Basically, the challenge is to use a chained LINQ statement to create a prime number filter, without using any custom functions. Without further delay, here’s my solution:

var primes = Enumerable.Range(1, 30)
    .Where(x => x > 1)
    .Where(x => x%2 != 0 && x != 2)
    .Where(x =>
            !Enumerable.Range(2, (int) Math.Sqrt(x)).Any(y => x%y == 0)
          );

This isn’t an optimal solution, but good enough for a first version. Basically, this is what’s happening:

  • All primes are greater than one. So filter on that first.
  • All primes are odd, except the number 2. Filter on that using modulus, and a hardcoded check for 2.
  • Now comes the real work: A prime can be found by trying to divide the subject by all numbers up to the square root of the subject. If any of the divisions has no remainder, the subject is not a prime.

I’m curious to see who’ll come up with a neat solution first, as this is obviously more or less brute force. While waiting, I’ll try to come up with another solution.

posted @ Saturday, January 09, 2010 12:07 AM | Feedback (3) | Filed Under [ c# LINQ ]

Thursday, November 26, 2009

ASP.NET MVC: Tricky modelbinding feature (?)

I just ran into a situation which could lead to very annoying latent bugs in your web application. Observe the following code.

The view:

<form method="post" action="Photo/Save">
  <input type="text" name="Photo" />
  <input type="text" name="Title" />
</form>

The Controller action:

public ActionResult Save(PhotoDTO photo)
{
    // do something with the object
    return RedirectToAction("Index");
}

The class:

public class PhotoDTO
{
    public string Photo { get; set; }
    public string Title { get; set; }
}

 

At first sight, there’s nothing wrong with this code. You’d say when the form is posted, the PhotoDTO object gets automatically created by the default modelbinder in the framework, and you’ll be able to do what you want with the PhotoDTO (like, errr, save it?). However, what REALLY happens is that the parameter photo will be null. Now I’ll give you a moment to realize what’s happening.

Alright, that’s enough. What’s happening is that the field with the name ‘Photo’ is getting precedence over binding the whole thing to the PhotoDTO class. So let’s say I put the value “SomePhoto” in the textbox, it’ll try to bind that value to an object of the type PhotoDTO. That fails, so it returns null.

I’m not sure it’s intended, I’m assuming it’s just a side-effect of what needs to be done to be able to bind to complex models as well as simple parameters. Either way, if you’re not aware of this quirk you’re in for a surprise if you accidentally run into this!

The conclusion

I asked Phil Haack on twitter if this was intended. He said:

@erikvanbrakel yes, by design. BTW, your PHotoDTO needs to make properties public too.

So there you have it, keep this in mind when writing your code, it’s not going anywhere, it’s as intended!

Note: I corrected the PhotoDTO, it was missing the ‘public’ access specifiers.

posted @ Thursday, November 26, 2009 12:24 AM | Feedback (0) | Filed Under [ c# asp.net mvc ]

Monday, November 23, 2009

.Less twitter love

I just checked our analytics after I noticed a bit of retweeting going on after Jon Galloway picked up .Less. Can you spot at which points in our graph twitter was flooded with .Less tweets?

twitterlove

I thought so ;-)

I’d like to use this oppportunity to thank everyone for bringing us extra publicity! Thanks!

posted @ Monday, November 23, 2009 3:33 PM | Feedback (1) | Filed Under [ general .less ]

Sunday, November 22, 2009

About the .Less project

I had a short twitter conversation with Aaron Jensen on the decisions we made developing .Less. As I’ve blogged about before, for me personally it was more of a learning project than something with a set goal, at first. That aside, I had one thing in mind: being able to use less during development, without having to worry about it, add a handler and go!

Less.Net, v0.1

My first solution was to simply install ruby and wrap the whole system call in a HttpHandler. Very clunky, but it worked! I blogged about this a while ago: Using LessCSS in an ASP.NET site.

I got it working, tried to implement it in my web project, and ran into another problem: It’s SLOW. Could be solved with caching, but in development I generally dislike that. It presents another point of failure which can take quite some time to figure out.
Another point was the fact that ruby should be installed. If you’re familiar with the .NET ecosystem you’ll know that a lot of people just want to deploy a single DLL and be done with it. Installing ruby, getting it to install a gem and then using that in your build process is quite a bit of work you want to avoid, if at all possible. That’s two problems I wanted to solve.

Being influenced a bit by the things I saw coming by on twitter (Linq to NHibernate to be exact) I looked into ANTLR for the parsing, which was simply an interesting technique to learn. I got a working prototype for a simple less file, published it, and got in touch with Daniel and Chris, with which we formed the current .Less project. Before joining up, Daniel gave IronRuby a shot for implementing the ruby gem in .NET, but it turned out to be too painful to deploy and too slow.

Perhaps with the next version of the CLR IronRuby will be a good option for Less, but honestly, I don’t expect that to be mainstream for at least another year.

Less.Net and nLess become .Less

After a few talks via skype, we decided to work on Chris’ codebase, called nLess at that moment. The reason why is that the grammar style he used is very similar to the ruby treetop grammar, which makes porting new language features quite painless. Also, I ran into a few problems with my grammar which would require quite a bit of rewriting of the grammar.

We’re not aiming for creating our own dialect, we want to adhere their standard as much as possible. The general idea is to introduce the less syntax in the .NET world, in such a way that it’s recognizable for the average .NET developer. That’s why having a grammar which is easily ported from one to the other is of great value to the project.

The future

While we do want to adhere to the ‘official’ syntax, we’re not bound to the functionality the ruby gem offers. We’ve got a few cool ideas we can do, but not before we’ve got a more edge cases of the current implementation covered. We’re also looking into creating a Visual Studio plugin, to, again, reduce the friction of using less in your ASP.NET solutions.

Another thing that’s on our agendas is to create more viable specs to test. We’re currently using the somewhat outdated ruby specs, which are generally very big umbrella specs. They also don’t exactly do what you’d expect. Hopefully we can create a common set of specs both the ruby gem as our .NET DLL, as the PHP version that’s around there can use. That way it won’t matter which environment you use, your less files will always work.

Well, that’s the story about .Less and how it came to be. If you’re interested in the project, I invite you to go to http://www.dotlesscss.com/ and try it out. We’re usually quite fast on the response to our google group, so if you want to ask anything, feel free to do so.

posted @ Sunday, November 22, 2009 10:30 PM | Feedback (2) | Filed Under [ general c# asp.net .less ]

Saturday, November 21, 2009

The importance of specifying your locales

Lately I’ve run into several bugs which were caused by developers incorrectly assuming that the default locale settings were good enough for parsing a value. I’ll show you what I mean.

Case 1

Consider the following snippet:

.something {
    width: 21.4em;
}

This is a simple CSS rule, making all elements with class ‘something’ have a width of 21.4em. In .Less, we parsed this without an explicit locale. The output would only show 21em, truncating the value from the implied decimal separator onwards. Once we set the locale to Invariant (who needs specific locales in CSS?), the problem was fixed. All in all a fix of only an extra parameter on the parse method.

Similarly, I am setting up a private TeamCity server, just for trying out how it works. I used a git plugin to enable downloading the source from github, which threw an exception when parsing the date. Consider the following two snippets:

  private static final String GIT_DATE_FORMAT = "EEE MMM dd HH:mm:ss yyyy Z";
  private static final String VERSION_DATE_FORMAT = "MM/dd/yyyy HH:mm:ss";
  public static final SimpleDateFormat GIT_DATE = new SimpleDateFormat(Constants.GIT_DATE_FORMAT);
  public static final SimpleDateFormat VERSION_DATE = new SimpleDateFormat(Constants.VERSION_DATE_FORMAT);

  private static final String GIT_DATE_FORMAT = "EEE MMM dd HH:mm:ss yyyy Z";
  private static final String VERSION_DATE_FORMAT = "MM/dd/yyyy HH:mm:ss";
  public static final SimpleDateFormat GIT_DATE = new SimpleDateFormat(Constants.GIT_DATE_FORMAT, , new java.util.Locale("en"));
  public static final SimpleDateFormat VERSION_DATE = new SimpleDateFormat(Constants.VERSION_DATE_FORMAT, new java.util.Locale("en"));

The first one is the bugged one, the second one is the fixed one. All I did was make sure the date is being parsed expecting english localization. This simple fix enables the plugin (it’s from the git-teamcity plugin on github) to work on any system, opposed to the ones who happen to have their locale set to any english variant.

This leads me to one conclusion: developing on a non-english locale is a good thing, you’ll find a lot more bugs that way! Joking aside, these examples led me to be a lot more careful with assumptions, especially on region specific settings.

posted @ Saturday, November 21, 2009 1:24 AM | Feedback (0) | Filed Under [ general localization ]

Thursday, November 19, 2009

Getting started with TeamCity : Installing

For .Less we use TeamCity by JetBrains for continuous integration. Whenever one of us commits to the master branch, the server notices, runs the tests and produces the binaries we need. When one or more tests fail, the committer gets an e-mail to make sure build errors are noticed as soon as possible. Working like this reduces the friction a lot when working with a team: members of the team are getting direct feedback if something goes wrong, AND there’s always a source for the latest binaries for anyone who likes to run on the bleeding edge.

Daniel set up our TeamCity environment, and I must say, he did a very good job at it. However, this meant that I have no experience setting up the thing, while I do think it’s useful to know how it works. So, I decided to give it a shot. I’m simply going to install it on my windows box, as I don’t really need to deploy it anywhere. I just want to figure out how it works, and have easy access to it.

Installing the server

Simply go to the TeamCity website and download the windows package. This is a around 220 megabytes served from a decent server, so it shouldn’t take you more than a few minutes (you’re a dev, you’ve got a good internet connection, right? RIGHT?). When it’s done, start the installer. It’s a default windows installer, so it should pose no problem.

I suggest installing the bunch (build client, server, both as windows service), so the defaults are fine. I changed my paths to point to a different home directory though. I like to have things together, so I created a TeamCity folder on my X: drive. My folder layout looks like this:

  • \
  • \TeamCity
  • \TeamCity\bin
  • \TeamCity\config

I’ve pointed the binaries to the bin folder, and set the default config folder to config. This way my TeamCity files will all be in their own cozy folder. I won’t say you have to do this, but if you like to keep things together like I do, go for it!

TeamCity has a web interface, which defaults to port 80. I don’t like to have anything that’s not a production website on port 80, so I changed it to another random port number > 1024.

Alright, now we’ve got the server installed, let’s move on to the next bit:

Configuring!

First steps

Make sure your services are running and accessible. Your next work will involve a web-browser and the TeamCity web UI. Open your favorite browser, and navigate to http://localhost:<your port>/. TeamCity will present you with the next installation steps. When asked to create an administrator account, keep in mind that it might be handy to use the same username as you use on your VCS for notification purposes.

Once you’re done with these simple steps, login to TeamCity using your shiny new administrator account. You’ll see the following screen:

Create project

If you see that, you’ll know that everything is alright, and you can start configuring a project!

What’s next?

.Less uses Git, so we’ll need to install a plugin to allow TeamCity to download sources from a Git repository. There’s basically two options: git-teamcity on github, by Chris Ortman, or the official JetBrains plugin. Although I usually tend to go for the official releases, we’re going to use the one by Chris. The official plugin has a few restrictions, and we don’t want to have to work around this.

The next post will deal with building and installing the git plugin. If you want to be prepared, make sure you’ve got a recent Java SDK install and Apache Maven on your machine.

posted @ Thursday, November 19, 2009 5:54 PM | Feedback (0) | Filed Under [ Continuous integration TeamCity ]

Thursday, November 12, 2009

Introducing the Smooth Friction testdata generator (v0.1)

Between work, .Less and other things, I’ve been working a bit on a tool I would personally use. How many times did you just need a big set of test data for an application? How many times did you resort to simply dumping randomly generated data into your tables? Well, I’ve did that a few times, and one of the biggest annoyances is that the generated data is usually not really ‘real’, if you know what I mean.

Say I have an application which has keeps customer records. I’d have a name, address, maybe some dates, something numeric and so on. With my new project, I aim to make getting some sample data easy(tm). It’s very, VERY prototype’ish right now, but I want to practice a bit of ‘release early, release often’ this time. So here it is! Take a look at the Smooth Friction test-data generator, and tell me what you think. Is it something you’d use? Should I continue working on this?

Disclaimer:
I am not a designer, so it looks crap. It’s a very early version, so expect bugs. Lots of them. Break it please, and tell me about it and how you did it ;-)

posted @ Thursday, November 12, 2009 12:27 AM | Feedback (4) | Filed Under [ general testing ]

Friday, November 06, 2009

A tricky situation with the IEnumerable<T> interface

Recently I ran into a situation which isn't very obvious at first glance if you don't know how the Linq to objects extension methods work in C#. If you know how the IEnumerable<T> works in combination with the various extension methods in the System.Linq namespace however, you’ll quickly see what'll go wrong. Observe the following snippet:

List<int> source = new List<int> { 1, 2, 3, 4, 5, 6 };
var filter = source.Where(x => x > 4);

foreach(var listitem in filter)
{
	// do something with the value //
	source.Remove(listitem);
}

This will throw an InvalidOperationException, stating that the collection has been changed. If you don’t know exactly how this construction works, you assume that ‘filter’ is not related to ‘source’. However, internally it still uses the source object and simply decorates the source with WhereIterator<T>. In other words, if you do something with ‘source’, any result from methods like Where(), Select() and so on will be affected as well. To circumvent this, you’ll have to convert this enumerable to a new object, like a List. This is done simply as such:

List<int> source = new List<int> { 1, 2, 3, 4, 5, 6 };
var filter = source.Where(x => x > 4).ToList();

foreach(var listitem in filter)
{
	// do something with the value //
	source.Remove(listitem);
}

By calling ToList() on the enumerable, the enumeration is evaluated and the result will be put into a new list. This way, you’ll remove the reference to the source object, solving this bug.

PS: I know this example could be implemented in a better way, but to illustrate the problem this is the easiest example.

posted @ Friday, November 06, 2009 5:29 PM | Feedback (0) | Filed Under [ c# ]

Sunday, October 18, 2009

Introducing .less, goodbye to Less.NET

As some of you might know, I’ve been diligently working on the C# port for the 'funky' ruby gem, {Less}. Well, we merged the nLess and Less.NET groups, creating .Less, and we’re live! We support the main {Less} specs, up to version 1.2.0 if I am correct. Here’s a quick synopsis, taken from our main site:

Variables

Variables allow you to specify widely used values in a single place, and then re-use them throughout the style sheet, making global changes as easy as changing one line of code.

 
@brand_color: #4D926F;
 
#header {
  color: @brand_color;
}
 
h2 {
  color: @brand_color;
}
Operations

Are some elements in your style sheet proportional to other elements? Operations let you add, subtract, divide and multiply property values and colors, giving you the power to do create complex relationships between properties.

 
@the-border: 1px;
@base-color: #111;
 
#header {
  color: @base-color * 3;
  border-left: @the-border;
  border-right: @the-border * 2;
}
 
#footer { 
  color: (@base-color + #111) * 1.5; 
}
Mixins

Mixins allow you to embed all the properties of a class into another class by simply including the class name as one of its properties. It's just like variables, but for whole classes.

 
.rounded_corners {
  -moz-border-radius: 8px;
  -webkit-border-radius: 8px;
  border-radius: 8px;
}
 
#header {
  .rounded_corners;
}
 
#footer {
  .rounded_corners;
}
Nested Rules

Rather than constructing long selector names to specify inheritance, in Less you can simply nest selectors inside other selectors. This makes inheritance clear and style sheets shorter.

 
#header {
  color: red;
  a { 
       font-weight: bold; 
       text-decoration: none; 
    } 
}

We’re currently in the process of tidying up the codebase, and we’re looking into which features we really want to include for the v1.0 release candidate. There’s a few options we consider, but please, if you have suggestions, drop them on our uservoice!

posted @ Sunday, October 18, 2009 12:54 AM | Feedback (0) |

Monday, October 05, 2009

ASP.NET MVC: Access an action only by ajax

In a standard ‘web 2.0’ (god, I hate that buzzword) web application, you’ll often have ajax calls to your code. I prefer using jQuery, but any method will do. A proper ajax request will set a header value in the HTTP GET request, and ASP.NET is a good boy and catches that. By checking if the IsAjaxRequest() method on the request returns true.

This feature can be utilized for something I like to do on my ajax-exclusive controller actions: restrict access in such a way that only ajax requests can call the action. Other actions will get a 404, which effectively means the action will never be indexed by search engine crawlers, for one. To do this, I think a good way is to follow the convention set by the framework itself on restricting the actions to certain verbs (GET, POST): use an attribute on the method!

So how do we do this? It’s very simple actually. ASP.NET MVC provides a bunch of extension points, and this is one of them. There’s an class in the framework called ‘ActionMethodSelectorAttribute’, which contains only one method, which returns true if the call is permitted, false if it isn’t. On each call to an action, the framework checks for any attributes on the method which implement this class, and makes sure all of these return true. Simply put: we’ll implement the class in such a way that it will return true when the action is called via ajax:

public class AjaxRequestAttribute : ActionMethodSelectorAttribute
{
    public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
    {
        return controllerContext.HttpContext.Request.IsAjaxRequest();
    }
}

I told you it was simple. Now you can use this attribute in your controllers, as such:

public class HomeController : Controller
{
    [AjaxRequest]
    public ActionResult Index()
    {
        return View();
    }
}

Yes, this is a silly example. It demonstrates the functionality though. When you go to /Home via your web browser now, you will get a 404, page does not exist. However, when you call /Home via ajax, you’ll get the HTML output from the view returned. That’s it.

posted @ Monday, October 05, 2009 12:00 PM | Feedback (1) | Filed Under [ c# asp.net mvc ]