Peter works on the web!

A Design Pattern A Day: The Singleton Pattern

with one comment

The Singleton pattern, probably the most hated pattern on the internet. But for the sake of being complete I feel obligated in implementing it once. <sarcasm>And never use it again</sarcasm>. Although this pattern has its use cases in some scenario’s. Caching could be one of them. Mind the usage of ‘could’ in the previous sentence. It could be a use case but as always: it depends.

As usual, tests are written using MSpec, code can be found on the public Github repository and we’ll immediately get started with the definition of the pattern from the Gang of Four book:

Ensure a class only has one instance, and provide a global point of access to it.

I think this is a pretty well known pattern, a full explanation can be found on its Wikipedia page. For ASP.Net programmers that really don’t know what I’m talking about. You know the System.Web.HttpContext.Current property? Unfortunately, that’s a Singleton.

250px-Singleton_UML_class_diagram

Let’s get our hands dirty. We’re going to implement our girlfriend as a singleton, because we are all good guys there is only one true girlfriend in our lives. So that will be our singleton. Let’s start with the implementation of our singleton Girlfriend class:

   1:      public class Girlfriend
   2:      {
   3:          private static readonly Girlfriend _instance = new Girlfriend();
   4:   
   5:          private Girlfriend()
   6:          {
   7:              
   8:          }
   9:   
  10:          public static Girlfriend Instance
  11:          {
  12:              get
  13:              {
  14:                  return _instance;
  15:              }
  16:          }
  17:      }

So this class is pretty straightforward. Our class has a readonly static class member that is instantiated when declared. And there is a property which returns the instantiated member. The constructor is private, so we can only create a new instance of the class within the class itself. This way we ensure that no instance of the Girlfriend class is created outside our class.

Our implementation does not lazy instantiate our singleton. There are other implementations which do lazy instantiation but then you have to take multithreading into account. If you’re interested in that implementation, this page gives a nice explanation about the different implementations of the Singleton pattern in C#.

The first test we write is to check if we always get the same instance from our Instance property. We check it by using the GetHashCode function, like this:

   1:      [Subject("Getting the girlfriend")]
   2:      public class When_getting_the_girlfriend
   3:      {
   4:          Because of = () =>
   5:              _hashCode = Girlfriend.Instance.GetHashCode();
   6:   
   7:          It should_always_return_the_same_girlfriend = () =>
   8:          {
   9:              var hashCode = Girlfriend.Instance.GetHashCode();
  10:              _hashCode.ShouldEqual(hashCode);
  11:          };
  12:   
  13:          private static int _hashCode;
  14:      }

Not that difficult, we call the Instance method 2 times and compare the hash codes of both instances. In fact, this confirms that our singleton works. But to be complete, let’s implement another scenario.

The next scenario, a common problem for everyone. Our house is dirty, we haven’t been cleaning for weeks and now it needs cleaning. Because our girlfriend is the best in the world she always volunteers to clean the house. Forgive me the sexism. So we have the following test case:

   1:      [Subject("Getting the person that cleans the dirty house")]
   2:      public class When_getting_the_person_that_cleans_the_dirty_house
   3:      {
   4:          Establish context = () =>
   5:              _dirtyHouse = new DirtyHouse();
   6:   
   7:          Because of = () =>
   8:              {
   9:                  _girlFriend = Girlfriend.Instance;
  10:                  _personThatCleans = _dirtyHouse.CleaningPerson;
  11:              };
  12:   
  13:          It should_return_the_same_person_as_our_girlfriend = () =>
  14:              _girlFriend.GetHashCode().ShouldEqual(_personThatCleans.GetHashCode());
  15:              
  16:          private static DirtyHouse _dirtyHouse;
  17:          private static Girlfriend _girlFriend;
  18:          private static Girlfriend _personThatCleans;
  19:      }


There is the DirtyHouse class which exposes the person that is cleaning it via the CleaningPerson property. A separate variable is instantiated with the Girlfriend instance so we can compare the hash codes of the cleaning person and the girlfriend instance to ensure that both are the same instance. This test is actually obsolete because we are actually testing the Girlfriend class again instead of the DirtyHouse. But that’s outside the scope of this blog post.

This is the implementation of the DirtyHouse class:

   1:      public class DirtyHouse
   2:      {
   3:          public Girlfriend CleaningPerson
   4:          {
   5:              get
   6:              {
   7:                  return Girlfriend.Instance;
   8:              }
   9:          }
  10:      }


No rocket science there. So this concludes the implementation of the Singleton pattern. As mentioned there are different ways to implement the pattern. A definite improvement would be to create an interface for our Girlfriend class so we can mock or stub it when testing other classes that use the Singleton. For example the test for the DirtyHouse class should actually mock the Girlfriend class via its interface so we can only test the logic in the DirtyHouse class and not if the Girlfriend is a singleton. But again that is outside the scope of this blog post.

Want to read more about the Singleton pattern? Check out these links:

Written by Peter

September 15th, 2012 at 8:36 pm

A Design Pattern A Day: The Decorator Pattern

with 4 comments

Last week I started reading the Gang Of Four book for about the fifth time. Unfortunately I’m really bad at reading reference-like books. I always get bored after reading a few design patterns and put the book on my shelf to collect dust again. This time I’ve decided to do something different, because everybody knows:

If you keep doing what you’re doing, you’ll keep getting what you’re getting

So I decided that each design pattern that I read somewhere, be it on Twitter, on a blog
post or somewhere else I’m going to look up in the book of the Gang of Four, implement it and blog my implementation. Although the title of the series is ‘A Design Pattern A Day’, don’t take it literally. I will try to implement a design pattern as often as possible, but it won’t be daily. I just liked the name.

Because C# is what I’m still most fluent at, everything will be implemented in C# using the .Net framework 4.0. All implementations can be found on a public Github repository and we’re are all responsible programmers so all code is covered with unit tests written in MSpec. To get started with MSpec, read this excellent post by my ex-colleague Jan on Elegant Code.

The first design pattern I came across was the Decorator pattern. Let’s start with the definition of the pattern, what can it be used for? From the Gang Of Four book:

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

I’m not going to type out the whole explanation what the Decorator pattern consists of. You can read all about it on its Wikipedia page. If you’re that kind of guy, here is an UML schema for you which should explain it. Or mess things up even further if you’re that other kind of guy. Don’t worry, it will all click together if you see the implementation.

We’re going to use the Decorator pattern to measure and adapt the speed of a running dog. So we’re starting out with our base component, the Animal class which has a Run method. The Run method returns the speed in miles per hour the animal is running at. We can reuse this component class in the future to measure the speed of other animals.

   1:      public abstract class Animal
   2:      {
   3:          public abstract int Run();
   4:      }


We create our Dog class which inherits from Animal, a Dog is an Animal after all, and implement the Run method. After googling for 2 seconds I found out that a dog runs 25 miles per hour.

   1:      public class Dog : Animal
   2:      {
   3:          public override int Run()
   4:          {
   5:              return 25;
   6:          }
   7:      }


But alas, our dog doesn’t have a lot of luck in his life. He is hit by a car and becomes handicapped. Because of his handicap he can only run a third as fast as he could when he still had all his legs. We could subclass Dog an create a HandicappedDog but what if the next animal we get is a Pony and he gets hit by a car? Then we have to create a HandicappedPony which will have the same logic as the HandicappedDog class. And for the smart-asses: yes, when a pony loses a leg or a dog loses a leg they both lose a third of their original speed. I’m sorry but that’s just how things work in the real world.

Although the duplication is minimum, we still want to avoid it and instead of subclassing our Dog class we create a Decorator. We have a generic Decorator which allows us the quickly create a new Decorator.

   1:      public abstract class AnimalDecorator : Animal
   2:      {
   3:          protected Animal Animal;
   4:   
   5:          protected AnimalDecorator(Animal animal)
   6:          {
   7:              Animal = animal;
   8:          }
   9:   
  10:          public override int Run()
  11:          {
  12:              return Animal.Run(); 
  13:          }
  14:      }


We create a HandicappedDecorator which returns a third of the speed of the original Animal it is ‘decorating’. If we create a handicapped dog, you will notice that the speed of the handicapped dog is only 8 miles per hour.

   1:      public class HandicappedDecorator : AnimalDecorator
   2:      {
   3:          public HandicappedDecorator(Animal animal)
   4:              : base(animal)
   5:          {
   6:          }
   7:   
   8:          public override int Run()
   9:          {
  10:              return base.Run() / 3;
  11:          }
  12:      }
 

In the test of the HandicappedDecorator you can see how to use this Decorator:

   1:      [Subject("Measuring the speed of a running handicapped dog")]
   2:      public class When_measuring_the_speed_of_a_running_handicapped_dog
   3:      {
   4:          Establish context = () =>
   5:          {
   6:              _classUnderTest = new HandicappedDecorator(new Dog());
   7:          };
   8:   
   9:          Because of = () =>
  10:              _measuredSpeed = _classUnderTest.Run();
  11:   
  12:          It should_have_a_third_of_the_speed_of_a_normal_running_dog = () =>
  13:          {
  14:              var normalSpeed = new Dog().Run();
  15:              _measuredSpeed.ShouldEqual(normalSpeed/3);
  16:          };
  17:   
  18:          private static HandicappedDecorator _classUnderTest;
  19:          private static int _measuredSpeed;
  20:      }


But we miss the times that our dog ran 25 miles per hour and we buy him a pair of bionic legs to augment its speed. The bionic legs double the speed of the dog, so a normal dog will be running at 50 miles per hour.

   1:      public class BionicLegsDecorator : AnimalDecorator
   2:      {
   3:          public BionicLegsDecorator(Animal animal) : base(animal)
   4:          {
   5:          }
   6:   
   7:          public override int Run()
   8:          {
   9:              return base.Run() * 2;
  10:          }
  11:      }


The cool thing about this implementation is that we can ‘chain’ the decorators, so we can make a dog handicapped an give him a pair of bionic legs. So the handicapped dog runs at 16 miles per hour.

   1:      [Subject("Measuring the speed of a running handicapped dog with bionic legs")]
   2:      public class When_measuring_the_speed_of_a_running_handicapped_dog_with_bionic_legs
   3:      {
   4:          Establish context = () =>
   5:          {
   6:              _classUnderTest = new BionicLegsDecorator(new HandicappedDecorator(new Dog()));
   7:          };
   8:   
   9:          Because of = () =>
  10:              _measuredSpeed = _classUnderTest.Run();
  11:   
  12:          It should_have_a_speed_of_16_miles_per_hour = () =>
  13:              _measuredSpeed.ShouldEqual(16);
  14:   
  15:          private static BionicLegsDecorator _classUnderTest;
  16:          private static int _measuredSpeed;
  17:      }

So that was the Decorator pattern I hope you learned something, if you want to check out all code with tests, head over to the public Github repository. I found another implementation of the Decorator pattern in C# if you still want to know more.

And remember, a design pattern a day keeps the all-nighters away … Or something like that. As always, feedback, remarks? All welcome in the comments.

Written by Peter

June 16th, 2012 at 8:00 am

Starting a project with Express, node.js and Stylus

with 3 comments

Node.js gets a lot of attention lately, out of curiosity I decided to try it out. After reading the excellent hands-on node e-book I wanted to port one of my pet projects, a price comparer between different IKEA branches (site is offline) written in ASP.Net MVC to node.js. As a web framework I went for Express. In this blog post I’ll show you how you can get Express to generate a very basic app for you and how you can use Stylus in combination with Express.

First of all make sure that node and the node package manager are installed on your system, it can be downloaded from the node.js website. Once that is done, you can let Express generate a basic application structure for you. You don’t have to use that folder structure but it gives you a nice head start. It’s ridiculously easy, open terminal and browse to the folder where you want to put your new project and type the following command:

   1:  $ express

Express has generated a few files and folders for you. But before you can run your newly generated web application you have to install the dependencies that express uses. You can use the node package manager (NPM) for that. Just use the following command:

   1: $ npm install

If all went well, you can now access your application by pointing your browser to http://localhost:3000. Don’t forget to start the app before surfing with the command:

   1: $ node app.js

Now that we have a very basic application up and running it’s time to make our web pages pretty. Because plain CSS is so 2004, I was looking for something like LESS or SASS. I stumbled on Stylus, it’s an expressive CSS language that is specifically built for node. Its syntax is similar to the Jade templating engine’s syntax. Installing it is easy with NPM:

   1: $ npm install stylus

Stylus provides you with Connect middleware that you can use in Express to configure stylus. In the following code snippet you can see the middleware in action, you should add lines 8 to 12 to your app.js:

   1:  app.configure(function(){
   2:    app.set('views', __dirname + '/views');
   3:    app.set('view engine', 'jade');
   4:    app.use(express.bodyParser());
   5:    app.use(express.methodOverride());
   6:    app.use(app.router);
   7:  
   8:    app.use(stylus.middleware(
   9:            {
  10:              src: __dirname + '/views',
  11:                dest: __dirname + '/public'
  12:            }));
  13:  
  14:    app.use(express.static(__dirname + '/public'));
  15:  });

If you take a closer look to the added lines, you see we give the stylus middleware a source and destination directory where to find the necessary files. Don’t forget to require stylus in your app.js like this:

   1: var stylus = require('stylus');

The middleware will search for *.styl files in the source (src) directory and compile them to *.css in the destination (dest) directory. Look out! At first I wanted to be fancy and place my stylus files in neatly organized folders, you can do that as long as the folder is a subfolder of the src property that you set in your configuration. For example if you put your *.styl files in a stylesheets subfolder under views, your source directory is still __dirname + ‘/views’, __dirname + ‘/views/stylesheets’ will not work!

Now we add a *.styl file in the source folder (or a subfolder of the source folder) and add a link element to the compiled *.css file in our main layout.jade file. The template file looks like this:

   1:  !!!
   2:  html
   3:    head
   4:      title= title
   5:      link(rel='stylesheet', href='/stylesheets/style.css')
   6:    body!= body

If all went well, rerun the application via the node command and point your browser at http://localhost:3000. The css file will be compiled automatically by stylus and applied to the web page by the browser. You can now start building your app!

All code of this example can be found in a repository in my Github account.

‘Till next time.

Written by Peter

February 29th, 2012 at 7:14 am

Posted in Express,Node.js,Stylus

Using an anonymous object as the model for your Spark view

with one comment

Well another post about Spark, I’ve been spending a couple of hours with the library and I really like it. On one of my previous posts Byron Sommardahl asked if it was possible to use an anonymous object as the model of your Spark view. I proposed a solution but I didn’t really have an idea if it actually worked. Because I was curious if it would work I fired up Visual Studio.

A little warning before we dive in, my gut feeling says that the code could be prettier but it does work. Some reflection is used to get the job done.

As a base of my solution I started out with the code I’ve written in my previous post on how to generate html with Spark. I recommending rereading it before continuing. This is my new, more generic Spark view which will be used to generate HTML:

Where in the previous post we had a data transfer object with a specific type which had all the necessary data, now the Data property is of the object type. There is a second property which will hold a reference to our Anonymous type.

The Data object with which we will be working is this:

A simple Anonymous object with 4 properties will be our DataTransferObject (DTO). We will initialize our AnonymousSparkView with the following data:

Our DTO is filled out into the Data object. The type of the anonymous DTO is filled out in the AnonymousType property. Now is the time to fill out the necessary data in our template. This is the template:

This little snippet uses a bit of Reflection magic to read the properties from our anonymous object. Between the ${ } token in Spark you can put a property from your view or you can put in a c# expression. We get the AnonymousType property of our view and get a specific property of our DTO, which is an anonymous object, via the GetProperty function. Then we can get the value of a specific property by calling GetValue on the found property.

It’s not pretty but it does work. I tried out a couple of methods that didn’t use Reflection but none of them worked. I am planning of putting all future code on my GitHub account. You can find the repository here and fork it if you want. Any comments or alternative solutions are welcome, as always.

Written by Peter

May 20th, 2011 at 9:34 pm

Posted in Spark

Spark HTML generation fails: View source file not found

without comments

I use Spark as engine to generate all sorts of HTML but on Monday last week that specific code snippet failed without being changed. Spark indicated that it could not find the view file, so I checked and double checked that the view was in the correct place. This was as it should be, but still Spark threw the exception that it could not find the view source file. I decided to try the same code on my laptop and there Spark still worked as it should, so the issue was related to my development machine configuration.

When I further investigated the odd exception that was thrown, I saw that the inner exception was an AspNetHostingPermission exception.

So I checked all the rights on the folders where the view files resided and found nothing out of the ordinary. I really couldn’t find anything that could’ve broken the HTML generating. So it was back to the drawing board, in my case Google, to search for possible causes and solutions. After a lot of searching and not finding very much answers I stumbled onto the following post. The error in that post was the same error that I got, but I was obviously not working with Windows 7 RC.

As solution the author states that you have to enable the ‘Load User Profile’ property of the application pool under which your web application runs. You can find the property in the advanced settings dialog of the application pool. Because being a bit really desperate I tried out the given solution and although I was rather sceptic to my surprise it worked.

I have no idea how that property got switched off in IIS, but if you ever have the same problem you’ll hopefully won’t look for a solution as long as I did. You’ve got the solution right here! ‘Till next time.

Written by Peter

May 8th, 2011 at 7:03 pm

Posted in Exception,Spark

Using spark as a html/text rendering engine

with 5 comments

I can’t remember a project which I worked on that didn’t have a requirement which included sending out emails. Most of the time the templates that are needed for these emails are so small that a simple text file with some wildcards does the trick. It does the trick but nothing more. It’s hardly an elegant solution and there is no support to loop through elements or do any other complicated stuff. I wanted a better, broader solution so I started to look around for usable libraries. I have been hearing a lot of good things of the Spark View Engine and wondered if it was possible to use it to generate html from a given template.

Most articles I found were about using Spark with ASP.Net MVC, only one talked about using Spark as a general purpose template engine by Louis DeJardin. Although dating from 2008 it is still very relevant. The article uses an in-memory template so I changed it that it reads its templates from a folder on the file system. This is certainly no rocket science and most of the code is based on the code of Louis but here goes:

First thing to do is create a Spark template, we’ll be using this very simple example:

<div>
    <strong>${name}</strong>
    <span class="address">${address}</span>
</div>

Now we need to create a corresponding abstract view with the properties that will be mapped to the template:

 public abstract class ASimpleView : AbstractSparkView
 {
        public string name { get; set; }
        public string address { get; set; }
 }

There are 2 things you need to remember when creating a view code file. The view must inherit from the AbstractSparkView class and the names of the properties in the view have to be the same as the names in the template file. So, obviously, the property ‘name’ in the view maps to ${name} in the template file.

And at last we glue it all together:

var settings = new SparkSettings().SetPageBaseType(typeof(ASimpleView));

var templates = new Spark.FileSystem.FileSystemViewFolder(HttpContext.Current.Server.MapPath("~/Templates"));
var engine = new SparkViewEngine(settings)
             {
                ViewFolder = templates
             };

var descriptor = new SparkViewDescriptor();
descriptor.AddTemplate("simple_template.sprk.htm");

var view = (ASimpleView)engine.CreateInstance(descriptor);
view.name = "Name";
view.address = "Address";

var stringWriter = new StringWriter();
view.RenderView(stringWriter);

var html = stringWriter.ToString();

Let’s go briefly through this snippet. We first create a SparkSettings object on which the basetype is set to our view. We load the templates via the filesystem, in this example the templates are located in the /Templates folder. Then we instantiate the spark view engine and a descriptor for our specific template. As you can see, after creating an instance of our specific template, the properties defined in the template are strongly typed and we can fill them out with the correct data. Finally we render the view into a StringWriter, getting the html from the StringWriter is as easy as calling the ToString method.

With this solution we can leverage Spark in our templates. I think this is a pretty elegant solution. Any opinions on this matter? What do you use to generate html in your projects?

Written by Peter

October 30th, 2010 at 5:41 pm

Posted in Uncategorized

A Kindle DX or an iPad?

with 4 comments

I love reading technical books, more than blog posts. They give you a better and deep insight in the matter you’re reading about. The big problem is that, at best, these books are relevant for a few years and then can be thrown out. In January of this year Amazon released the Kindle DX with global wireless. Since then I’ve been looking out for the eReader that would best fit my needs. Based on the review by Scott Hanselman and some other internet resources I had set myself to let Amazon fly over my very own Kindle DX to Belgium.

568215

It was about the same time that there was a lot of buzz around the iPad that Apple has released in April of this year. I had already set my mind to buying the Kindle DX and I didn’t have enough patience to wait until the release of the new Apple wunderkind. I had a 3 week holiday planned to Bali in May and that was the perfect opportunity to stress test the device.

The first thing that I absolutely love about the Kindle is the battery life. I used the device a lot during travel, on the plane, on the beach, … and not once did it run out of juice. For me this is a deal breaker, you don’t want to be stuck on a flight of 14 hours and have your eReader run out of batteries after 2 hours. Then you’ll have to watch a movie with Chinese subtitles on those crappy entertainment systems they provide. The second thing that was absolutely great was the screen. Not once did my eyes feel tired or sore from staring at it for a long time. And I read 1000+ pages on the device in a few days. In my opinion there is no LCD screen that can match an eInk screen. Although it’s only black and white and the response is a bit rough, I am a real fan of the screen.

Once in Bali I was afraid that it would be fragile to take the device to the beach, with sand crawling in places you don’t want it. But again I was reassured, it is robust enough to take it to delicate places. You do have to buy a case for it, otherwise it’ll get dirty pretty fast. I’m not the most neat guy and I spilled sunscreen, an exotic cocktail and who knows what else on my Kindle case. The case earned its cost back by protecting my precious Kindle perfectly. Although it’s a bit stained right now but that’s what a case is for right?

And now to my disappointments. My girlfriend had bought a book in KL Airport that she said was very good. I wanted to buy it on my Kindle, because that is a strong selling point of the global wireless, but it didn’t work in Malaysia. It also didn’t work in Indonesia. I could connect to the Kindle store, but every time I wanted to buy a book I got “This book is not available in this country”. Once I was back in Europe, I could surf the Amazon Kindle Store and buy books. If they sell it as global wireless, I want global wireless. Indonesia and certainly Malaysia are not the end of the world. Their internet usage is almost up to par with the European and American so I would have expected the global wireless to work there.

While using it I couldn’t stop thinking how cool it would be being able to read my RSS feeds. I have to admit, I see the Reeder application on iPad and I’m jealous. This is for me the biggest drawback of the device. You can’t install any additional applications on it. I don’t want to play airhockey on the thing but if I have a dedicated mobile reading device it would be nice to download my feeds to it and read them while being offline. In the experimental option there are some new features like playing MP3s and surfing the web. But I haven’t been in a country where I can actually surf the web. Although exciting features in theory, they’re disappointing in reality.

Conclusion? I get a lot of people asking me, what should I buy? iPad? Kindle? Kindle DX? Well, if I had to choose again I’d probably get an iPad. I love the eInk screen on the Kindle and think it’s a must if you read a lot on your device. But installing applications is a real deal breaker for me. The possibilities are endless with an iPad, not so with a Kindle. I haven’t tried myself reading hours and hours on an iPad. But I’ve heard from different persons that it’s a really good screen and isn’t tiring on the eyes. But still I’m pretty happy with my Kindle.

How about you, do love your iPad? Or your Kindle? Show it in the comments.

Written by Peter

June 27th, 2010 at 8:30 am

Posted in Reading,Review

Book review: Getting Real by 37 Signals

without comments

320_383343 If you’re sick of reading book reviews, I’ll give you the short version. If you are a project manager, designer, developer, entrepreneur or business analyst who is involved in creating a (web) application read this book. It’s awesome.

Now for the longer review: although the guys from 37 Signals just published Rework, I still had to read their previous one called Getting Real. They describe their process of creating popular applications like Basecamp, Campfire and many others. I got great value out of it even though I’m currently not developing my own products. It has great advice on subjects like how to deal with clients and users.

For example, scope creep is something everyone involved in a project should really look out for. A web application is never finished and clients will hold the release until the perfect product has been created. Instead they state that you should get your application out into the world as fast as possible. You will instantly see what works and what doesn’t. And no unnecessary features will be introduced just because the client thinks it will be a big hit. This is based on the “Release early, Release often” idea and that’s also what I try to do at Two to Tango when developing software projects. On top of that the book advices not to fix every bug, especially layout bugs. Don’t worry about that button that is 2 pixels out of place in Internet Explorer 6. Just release your application and let the magic happen.

About users they say the following: don’t listen to your users. Don’t implement every little feature that they request. Instead have a clear vision about where you want to go with the product and stick to it. If you listen too much to your users, you’ll get an application that serves it all. I see it as an application without a spine. They advice to build an application for yourself not for your users.

I just described two points that I took away from he book but it is filled with beauties like this. So just go read it now, you won’t regret it! You can even read it for free online. And read Rework also while you’re at it, I’m pretty sure it’ll be worth it.

Written by Peter

April 5th, 2010 at 12:50 pm

Permission to access webcam not asked by Silverlight 4 beta on load of page

without comments

I was playing around with the Silverlight 4 beta and was trying to get my webcam working by following this article. Although the code to achieve this is very simple, the webcam did not work in my *.aspx page which contains my Silverlight component. I googled and stackoverflowed around but didn’t find anyone with the same problem as I had. When the page loaded, I just saw an empty rectangle and Silverlight did not ask for permission to access my webcam like it should.

Picture 4

This is how the component looked in Firefox and this was the code, it’s the same as in the article:

Picture 5

Then I realized that all examples I saw on the web used a button before enabling the webcam. So I changed my component a little: added a ‘Turn on camera’ button and copied the code to start the camera to the click event of the button. If I now clicked the button, Silverlight asked for permission to use the webcam.

Picture 8

So the resulting code looked like:

Picture 7

And I was a happy coder, because I could now see myself in the webcam.

Picture 10

I documented this for everyone who might have the same problem. I don’t know if this is a known bug or not I didn’t find any documentation or ticket about it.

Written by Peter

February 8th, 2010 at 5:38 pm

Posted in Uncategorized

An alternative to editing JavaScript in Visual Studio: RubyMine

with one comment

Unfortunately the images to this post were lost during the migration from Blogengine.Net to WordPress

A while ago Chris Missal asked the following question on Twitter.

One of the projects I am currently working on is a JavaScript intense web application. That’s why the question instantly caught my attention, JavaScript editing in Visual Studio has been bugging me for a long time. In one of my previous posts about Visual Studio somebody said in the comments that VS isn’t build with web developers in mind. Well, that’s the least you can say. But still, since my business is mainly focusing on .Net web development I’m obligated to use Visual Studio for all my ASP.Net Webforms and MVC projects. And for all the JavaScript, (LESS)CSS, ASPX, HTML editing that comes with those projects. If you don’t know it yet, Visual Studio is really bad at all those things. In those cases the editor is comparable to a colored version of Notepad.

Some of the replies to Chris’ question suggested Notepad++ others suggested RubyMine. RubyMine from JetBrains, the same company that created Resharper, is a tool I always wanted to try out and I thought this was the perfect opportunity. So I downloaded the whole thing, there is a trial available, installed it and pulled my Scripts folder into the editor. I didn’t have very high hopes, because I use JavaScriptMVC and jQuery on this project and I thought it would be very hard for the IDE to figure out all the different references and relations between the files and classes. To my surprise the IDE succeeded in parsing the different JavaScript files. So we were all set, time to try some stuff out:

I created this simple class, using the functionality JavaScriptMVC provides for creating classes:

First thing to try out that comes to mind, let’s declare a variable that is not used and see what RubyMine says about it:

Very nice, this thing is already doing more than Visual Studio does. It detects unused variables.

Time to try some more complicated like things renaming a variable which is not possible in Visual Studio. So I tried right clicking on the variable and there is a nice Refactor item in the context menu. A very Resharper-like experience, I haven’t tried out all of them but the basic things like Extract Method, Rename and Introduce Variable worked very well.

All this is really impressive, and there is more! I have multiple classes in this project and RubyMine detects them and provides Intellisense. Even though I use a framework to declare my classes, it still detects which are classes and what functions are defined on my class. Pretty nice huh? On top of that, all R# shortcuts that you are used to also work in RubyMine. Ctrl+N to find a given file, even Ctrl+12 to list and find a method of the open class:

Although I only scratched the surface of RubyMine, navigating, editing and refactoring JavaScript has been a great experience. Certainly when you’re used to using Visual Studio for that. I can already conclude that it beats Visual Studio in every aspect when it comes to writing JavaScript. It’s a shame that we have a feature-rich tool like Visual Studio and still need to open a second IDE to edit JavaScript files. I can only hope that Visual Studio 2010 brings some more options to the table. Maybe JetBrains should think about adding an ASPX editor and a C# compiler to RubyMine, call it SharpMine and sell it. That would definitely be something I would consider buying.

Written by Peter

January 28th, 2010 at 10:59 am

Posted in Uncategorized