Azure cost tip: have consistent regions

Quick tip: pay attention at your Country/Region settings when using a database or a hosted service.

We know that  database transactions are free if database and the service are in the same Azure data center.

However, having a database with Country/Region set to West Europe and a Worker Role (which uses this database) with its Country/Region set to Anywhere Europe which polls periodically the database still leads to access costs.

Azure Database with Location West Europe

Azure Role with Location Anywhere Europe

And if you add in the mix a storage account with Country/Region set to Anywhere Europe, don’t be surprised that you’ll have in the bill a lot of consumed units.

azure_storage_anywhere

Conclusion: be consistent and specific when choosing Country/Region. Making all “Anywhere Europe” will be consistent but not specific and you’ll have additional costs. But if you make all “West Europe” or “North Europe” you’re safer.

Happy cloud saving!

Routing testing in ASP.NET MVC 2.0, a quick workaround

Areas in ASP.NET MVC is a long awaited feature (although there were some workarounds available for version 1.0). If you want to read a quick walkthrough in dividing your ASP.NET MVC project into areas, here is one from msdn.

But, after divided a project into areas, my route unit tests was failing with “System.Web.HttpException: The type initializer for ‘System.Web.Compilation.CompilationLock’ threw an exception”, in my test fixture constructor,  where I call my global HttpApplication RegisterRoutes method like this:

RouteCollection routes = new RouteCollection();
Global.RegisterRoutes(routes);

Assuming I have an AreaRegistration object named Routes in “Admin” area and I want its routes tested, that simple workaround did it:

//Global.RegisterRoutes(routes); 

(new Routes()).RegisterArea(
    new AreaRegistrationContext("Admin", routes));

Now the route collection is filled with routes from Admin area, ready for tests.

Of course, there are some MVCContrib fluent tests options for routes, very good if you’re using NUnit (not the case here, with all tests using MS Test).

MVVM Login demo application update, added Silverlight project

This is the same MVVM login demo application, initially made for WPF and we want to add a Silverlight version, but reusing the business logic that we already have. Currently, I’m using Silverlight 2.

  LoginExample-0.0.3.1044.zip (2.2 MiB, 575 hits)

When you start working with Silverlight, you’ll miss a lot of WPF “goodies”. Understandable, since Silverlight is targeting the rich user experience and should stay small. There is no AdornedElementPlaceholder, no Label control, no Style triggers. So, how do we validate since we learned only the trick with binding the IDataErrorInfo to the user interface? Silverlight 3 have support for validation but with throwing exceptions, not with the help of the IDataErrorInfo.

Some Research
There are already some validation libraries for Silverlight, for example:
http://silverlightvalidator.codeplex.com/ (this is an approach similar with ASP.NET Webforms Validators).
That’s mean that if we add a RequiredValidator for the username in the UI, we duplicate the logic of not having username empty from our model. Not good, we want no duplication.

Reuse
To reuse files in Silverlight, just add them as link. For example, we want the class User to be reused in a Silverlight project, too.

Add a new Silverlight class library project, name it LoginExampleDemoBLL.Silverlight. Add the User.cs from LoginExampleDemoBLL project as link.

LoginSilverlightAddAsLink

IDataErrorInfo workaround
IDataErrorInfo is not part of the Silverlight. Luckily, some others had the same problems. I adapt this solution a little to work with my types of view models, which expose the domain object as a property.

Prism (CompositeWPF) help
In order to bind commands to controls, we need the CompositeWPF binaries for Silverlight.
Our XAML for buttons will looks like this:

<Button Content="Login" Margin="5"
               
cal:Click.Command="{Binding Path=LoginCommand}"
               
cal:Click.CommandParameter="{Binding Path=User}"
               
Grid.Column="0" Grid.Row="3" />

So, even if the validation is triggered when control is losing focus, even if we simplify a little our XAML code used in WPF project, is working, is reusable and is very simple as an example.

Real use of Microsoft Oslo?

How would you use Oslo in the real world? Well, this weekend I got a little Oslo “infection”. For the moment, only with Intellipad tool.
Working with MSpec and with BDD style tests, I always thought that a really good thing would be to generate test’s code or to run somehow tests specified in plain English, not only to see them nicely organized (although, that’s a very helpful thing).
How about writing some BDD style plain English statements, obtain a MGraph from it with a help of an MGrammar, get some expression trees (there are some ways to get CLR objects from that MGraph, with help of Xaml or with some serialize/deserialize helpers or with some graph traversing techniques), compile and run? That could be a real use, allowing clients and business analysts to work directly on specifications. I wasn’t surprised to see that there are already some grammars which can parse that syntax (MisBehave, for example).
Let’s think of an other example, starting from a simple scenario… I have an WPF login demo application. Its specifications/business rules are stored in code. How about get them out from code and being able to modify in plain English? Something like that:

If MyLogin Attempts is greater than 3
Then Message should be ‘Sorry, too many tries already’.


If MyLogin Attempts is equal with 2
Then Message should be ‘One more try!’.

Enter my very first MGrammar:

MyLogin Oslo

I successfully got then LoginRule objects with the help of Xaml (see Person example from msdn) after I modified the projection to look like this:

syntax Rule = "If MyLogin Attempts" o:Operator a:Attempts         
"Then Message should be " m:Message "."
=> LoginRule { Operator => o, Attempts => a, Message => m};

And the LoginRule is my custom object which knows if it has to apply itself or not to my LoginViewModel and, if yes, it set the proper error message.

That’s of course a very limited example but shows (perhaps) some real uses of Oslo.

So, Oslo is not only about data. Since we can transform back and forth code into data, behaviors into data then we can store them in Oslo Repository, we (in fact, the clients) can edit them in a kind of English language and run them as code when needed.

For next releases I expect Microsoft to provide a clearer way to get objects from graphs (perhaps Spring.NET or Castle can help here, too but I didn’t wanted to dig further since I can work for the moment with Xaml way to get objects).

Am I just tired and talk nonsense?

Here is the test grammar used to parse these simple behaviors:

 

//Login Demo with Oslo
module MyLogin {
    language LoginLogic {

        syntax Main = Rule*;
        syntax Rule = "If MyLogin Attempts" o:Operator a:Attempts
            "Then Message should be " m:Message "."
                => LoginRule { Operator => o, Attempts => a, Message => m};

        token Attempts = "0" .. "9";

        token Message = "'" ("a".."z" | "A".."Z" | " " | "," | "!")+ "'";
        token Operator = "is greater than" | "is equal with";
        interleave  Whitespace = " " | "\r" | "\n";
    }
}

WPF Login Demo with MVVM pattern – update

After the first example posted, here are some improvements:

1. Moved business layer into separate project for testing
2. Added a quick test project (with some BDD flavors)
3. Tests are targeting only the ViewModel.
4. Refactored the intentional first naive ICommand implementations (towards Prism via DelegateCommand, although RelayCommand or SimpleCommand can be used also).
5. Still DIDN’T added yet the AttachedProperty to the PasswordBox for simulate a more realistic login. Password is still a TextBox just for clarity.

Small exercise: how to not duplicate the validation logic in CanLoginExecute?

In a future update I intend to add also a Silverlight login demo, based on that example.

Grab the code from here:

  LoginExample-0.0.2.1040.zip (84.9 KiB, 1,058 hits)


And that’s how the tests are looking (clearer, right?):
BDD Testing with MSTest

Database Projects error: “An error occurred trying to load the project properties window. Close the window and try again.”

 

I’m using Visual Studio 2008 SP1, Team Foundation Server 2008 and Database Edition GDR.

Suddenly, my desktop builds doesn’t work anymore. The issue was related to my database project (an Sql Server 2008 Database project). Trying to get database project properties window leads to that error:

An error occurred trying to load the project properties window.  Close the window and try again.
Cannot evaluate the item metadata "%(FullPath)". The item meta-data "%(FullPath)" cannot be applied to the path "obj\Debug|Any CPU\MyDatabase.dbschema". Illegal characters in path.  C:\Windows\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets

If you’re trying to adjust your build configurations in Configuration Manager or to revert your solution to some older version, stop now. Your database project template is corrupted.

Reset your Visual Studio by opening a Visual Studio 2008 Command Prompt and running these commands:

devenv /setup
devenv /resetuserdata

Yes, you’ll loose all your preferences and settings. But it will fix it and you can work again on your project.

The credit for this fix should go to that msdn post (same error but occurring when trying to create a database project).

Simple WPF Login demo, with MVVM pattern

There is a newer version here.

I was offering myself to prepare a quick WPF Login demo (having a minimum set of best practices) for a colegue, so here it is. (I’ll update it with more details and, perhaps, new versions):

  Simple WPF Login Example (16.3 KiB, 3,393 hits)

It uses the MVVM pattern, no code behind (except the lines in which the DataContext is set), binded commands, IDataErrorInfo for business entities, INotifyPropertyChanged.

The goal was to provide a testable WPF application, by using the .NET Framework already builtin capabilities (like it or not) and taking advantage of data binding. Some tricks (like showing error at Tooltip) are very common practices.

I used the password as a simple TextBox just to show binding.  Normally, a PasswordBox should be used, with attached property for binding (next version).

Also for next version I’ll separate the business code into a separate project (now is in a simple folder, just for demo) , perhaps add a quick authentication service, a test project and more.

For more advanced scenarios you should consider using of Prism (Composite WPF from Microsoft Patterns and Practices).

Comments are welcome!

Highlight selected row in ASP.NET MVC: it’s about requirements

This is more a view from a different angle than a technically post: suppose you have an ASP.NET MVC application with a simple table with products (let’s name the view Products). Clicking on any product “Details” link, you should see the same table but with the product clicked previously highlighted and the product details.

How would you implement such a simple requirement? Highlight a row.

Well, my answer is “depends”. Depends how it is asked.
    1. Clear requirement: If the highlight stuff is part of an iteration, is a clear requirement (perhaps your Team Foundation Server check in policy will not allow to check in that fix without specify the test which cover it) then I would do it like this:

public partial class Product
{        public bool Selected
         {
              get;
              set;
         }
}

Add the Selected property in the partial class definition (Product is a Linq2Sql or a Entity Framework entity). You can use also a ViewModel if your page is more complex (and same thing applies, add a new property to the ViewModel).

Then your controller can look like this (just a guideline, don’t use it exactly like this!):

public ActionResult MyProductList(int? productID)
{
    List<Product> products = m_service.FindProducts();
    products.Find(p => p.ProductID == productID).FirstOrDefault().Selected = true;
    return View(products);
}

That is easy testable and you can mark your work item as done and associating with a simple test.

    2. UI Layout or other sources (like an angry email from the project manager): You just have the UI layout from a web designer and there the selected row is highlighted. That simple “spaghetti” code is more than enough:

<% RouteValueDictionary  tRVD = new RouteValueDictionary(ViewContext.RouteData.Values); %>
      <table width="100%">
        <% foreach (var product in Model) { %>
            <tr <% if (product.ProductID.ToString() == tRVD["productID"]) { %>
                class="selected" <% } %>>
                     <td width="80%">
                        <%= Html.ActionLink(product.Name,
                         "Edit", new { id = product.ProductID })%>
                </td>
...

How would you handle case 1 in the proper way?

“Object expected” jquery error: last place to look (or why you should look carefully at the META tags)

That’s will help others for sure: ever happen to work on localhost on a legacy application (no matter if on Apache or IIS) and to have some missing images, css files or js files? Even if you are sure that there are in right place, accessible by the web server?

Here is my Error Console from Firefox:

Firefox Error Console

Here are two Firebug print screens:

On first one, first css file looks ok.
Fire Bug 1

On second one, the css file shows a 404 Not found error, same my jquery script reference.Fire Bug 2

The problem here is the base meta tag!

It appends the live domain to the requested references. That’s why first css reference is found (it is found at the live server, actually) but not the jquery and second css, added locally by me.
First warning in Error Console shows that the request is not made locally.

Hope that will save some time to the others, too!

ASP.NET MVC routing for IIS 6, why ending extension is bad?

Deploying an ASP.NET MVC application to production (on IIS 6) makes the nice looking URL to not work as expected.

Without going into too much details, the issue is ASP.NET needs the .aspx to be present into the URL, in order to be triggered.

So, an URL like
http://www.mycompany.com/Romania/English/Services will lead to a 404 error. Recommended solutions are to adapt the route to http://www.mycompany.com/Romania.aspx/English/Services or to http://www.mycompany.com/Romania.mvc/English/Services, which are not so pretty (second one requires also the mapping of .mvc extension in IIS).

Why not having URLs like:
http://www.mycompany.com/Romania/English/Services.aspx ??

I tested and there is no hidden catch (yes, I thought it might be a technical reason why is not recommended!), but is working as expected.
If you rewrite an application with Web Forms to ASP.NET MVC, step by step, that’s a normal way to do it.

   1: routes.MapRoute(

   2:                 "My Company Homepage",               

   3:                 "{country}/{language}/Products.aspx",

   4:                 new

   5:                 {

   6:                     controller = "Product",

   7:                     action = "List",

   8:                     country = "Romania",

   9:                     language = "English"

  10:                 });

Funny, even the permalink of this post has the filename before parameters, just to trigger the PHP (that blog is hosting on an IIS web server). But still, why not putting the .php extension at the end?

UPDATE: I fixed meanwhile the URL Rewriting of this blog with an .htaccess file