Minification and Bundling in MVC 4 RC

Asp .NET MVC 4 Release Candidate is out. One of the features that is included is called the minification and bundling feature. This was already there in the beta but in the release candidate version it has changed.

Why should we use it

The reason why we should use the bundling and minification feature is performance. The features increases your loading performance of your website. Every time you reference a JavaScript (like jQuery or your own), or CSS file in your page, the browser makes a call to the server. This is done for each separate reference. Each referenced file has included all the comments and spacing in your file. This makes the file larger then when we should delete those spaced. The bundling and minification feature does this for us.

How does it work

In your Global.asax the CSS and JavaScript files are Bundled with BundleConfig.RegisterBundles(BundleTable.Bundles); line.

image

image

Reference the files in your page.

image

When you run the application and use Fiddler to view the calls to your server, you still see all the files called separately.

image

image

This is because the Bundling and Minification feature by default only work when your not in debug mode. This handy because then you could debug with all the whitespaces in your files and have the performance in the production environment.

See the difference in your production environment:

image

image

Force Bundling and Minification

You can use the BundleTable.EnableOptmizations override but the best way for a little test is to remove the debug=”true” attribute in your web.config.

image

Browser caching

When the feature is active, the browser will cache the files. When you add or change some JavaScript or CSS code, the files are generated again and the version number in the references are updated. In that way, the browser knows that there is a new version and your website wont brake.

image

MissingManifestResourceException solution

Every time I edited a C# file in my solution, I had an error called “Could not find any resources appropriate for the specified culture or the neutral culture.  Make sure "UI.Web.Mvc.Properties.Resources.resources" was correctly embedded or linked into assembly "UI.Web.Mvc" at compile time, or that all the satellite assemblies required are loadable and fully signed.. The error said that the Resource file wasn’t setup correctly. The strange thing about it that my colleagues didn’t got the error and when I cleaned up the web application mvc project and builded the project again, the site worked correctly. Cleaning and building after each edit is a huge consuming of you time so I needed a fix for this. 

After searching for some time I found the difference between my laptop and the laptops of my colleagues. They had the Dutch version of Windows 7 Enterprise and I had the English version. The project is by default Dutch and we are still developing so in the solution we only had the Dutch version of the resource file. When I ran my project, the culture is set to the host and after that, it looks to the culture of the browser. My host is English so I couldn’t find any English resource. Why It worked correctly after a clean, I don’t know. Can you tell me?

I fixed the error by adding the English version of the resource file. Just copied the Dutch version and added “en” to the name. Simple fix, big irritations and a hope useless time… It’s now time to hurry up and finish the baby :-)

Add Area and Iterations permissions in TFS 2010

IMG_16639mkIf you want to give your user permissions to add Areas and Iterations, you could that be following these steps:

Area

  1. Go to: Team –> Team Project Settings –> Areas and Iterations…
  2. Select on the “Area” tab the “Security…” button on the bottom
  3. Select or add the group/person that you want to give the permissions
  4. Set “Create and order child nodes” to allow

Optional: Set “Delete this node” and/or “Edit this node” to allow for edit and delete permissions.

Iteration

  1. Go to: Team –> Team Project Settings –> Areas and Iterations…
  2. Select on the “Iteration” tab the “Security…” button on the bottom (this is a different button than on the “Area” tab.
  3. Select or add the group/person that you want to give the permissions
  4. Set “Create and order child nodes” to allow

Optional: Set “Delete this node” and/or “Edit this node” to allow for edit and delete permissions.

Use .Where().Select().Single() rather than .Single()

When you use the .Single() lambda statement, you will only get one result. When you only use 1 property of the whole object it is totally waste of the performance. Only get want you want. So you could better use the .Select() statement to get only the property you want.

See the difference below where we have an example for getting the profile picture of an unique user.

.Where().Select().Single()

byte[] imageData = Context.Profiles.Where(p => p.Id == profileId).Select(p => p.Picture).Single();

SELECT
[Limit1].[Picture] AS [Picture]
FROM ( SELECT TOP (2)
[Extent1].[Picture] AS [Picture]
FROM [dbo].[Profiles] AS [Extent1]
WHERE [Extent1].[Id] = @p__linq__0
)  AS [Limit1]

.Single()

byte[] imageData = Context.Profiles.Single(p => p.Id == profileId).Picture;

SELECT TOP (2)
[Extent1].[Id] AS [Id],
[Extent1].[FirstName] AS [FirstName],
[Extent1].[LastName] AS [LastName],
[Extent1].[Birthday] AS [Birthday],
[Extent1].[HideBirthdayYear] AS [HideBirthdayYear],
[Extent1].[Picture] AS [Picture],
[Extent1].[ModifiedOn] AS [ModifiedOn],
[Extent1].[UserId] AS [UserId]
FROM [dbo].[Profiles] AS [Extent1]
WHERE [Extent1].[Id] = @p__linq__0

 

Imagine what the difference would be with nested queries, joins, or even bigger objects (tables) than this example.

Default cascading delete in EF Code First

Ralph Jansen Blog

In the new Entity Framework 4.1 Code First you can easily create a database on your POCO objects. But the down side (sometimes) is that cascading delete is turned on by default.

Say you have two objects called Department and Manager.

image

image

A manager needs a department and a department can have multiple managers. This is done because we want to have a one-many relationship in this demo. To do this we can make navigation properties. A navigation property is created by the virtual keyword. If you want to create a many relationship, you should use the ICollection<> type.

image

image

If you generate the database now, the tables are generated and a foreign key relationship is made. To do this, EF has generated another column in your Manager table. The column name should be Department_Id. If you open the foreign key relationship you see that the cascading delete relationship is disabled.

But our POCO objects are not really complete. Because how would we know what the key of the Deparment is when I only want to query the Manager object? You can’t because you need the other object. To solve this, you can add a column that is similar as your generated Foreign key column. So, we change our object to this code:

image

If you generate your database again, you see that some things are changed. The automatically generated column Department_Id is no longer there and the DepartmentId column is now used for your foreign key relationship. Only, this is not the only difference in your project. Because if you look at your foreign key relationship, you see that the cascading delete is now enabled.

But why do we want a cascading delete in this example? Because say in example, that if a department is merged with another department and the department record would be deleted from the database, your managers would be deleted as well. Why will they be deleted? Are the fired?!?!?! Can’t they go to another department?

Luckily you can change this default behavior. You can do this with the next line of code in your OnModelCreating override:

image

If you generate your database again with the latest classes (class with DepartmentId) your Foreign Key relationship would not have a cascading delete enabled.

Entity Framework: Different loading capabilities

Ralph Jansen BlogThe Entity Framework is in the new stage of evolving. We are now in stage 4.1 where the Code First functionality is released. Entity Framework enables just like LINQ to SQL different kind of loading types. But what are the loading types and what are the different capabilities? In this blog I will explain in a simple way what they are and what they can do.

There are 3 different kind of loading types for related data called lazy, Eager and explicit loading. In the next example you see two entities which are related.

image

Department can have many Courses and a Course can only have one Department.

Lazy Loading:
image 

 

Eager Loading:
image

 

Explicit Loading:
image

Because they don’t immediately retrieve the property values, lazy loading and explicit loading are also both known as deferred loading.

In general, if you know you need related data for every entity retrieved, eager loading offers the best performance, because a single query sent to the database is typically more efficient than separate queries for each entity retrieved. For example, in the above examples, suppose that each department has ten related courses. The eager loading example would result in just a single (join) query. The lazy loading and explicit loading examples would both result in eleven queries.

On the other hand, if you need to access an entity’s navigation properties only infrequently or only for a small portion of a set of entities you’re processing, lazy loading may be more efficient, because eager loading would retrieve more data than you need. Typically you’d use explicit loading only when you’ve turned lazy loading off. One scenario when you might turn lazy loading off is during serialization, when you know you don’t need all navigation properties loaded. If lazy loading were on, all navigation properties would all be loaded automatically, because serialization accesses all properties.

HTML klaar voor het grote werk?

Als ik kijk naar de volwassenheid van het huidige web is HTML zelf nog niet helemaal klaar voor het grote werk. Als ik kijk naar HTML 5 in combinatie met frameworks als JQuery, Modernizr etc. zeg ik dat het de goede kant op gaat. De laatste versies van alle browsers werken goed maar er zijn nog steeds een hoop verschillen in functionaliteit die worden ondersteund. Microsoft zegt dat IE9 helemaal het einde is maar ze weten dat ze snel achter zullen lopen. Microsoft zegt zelf dat er geen release cyclus van +/- 6 weken komt voor IE maar ondertussen is de eerste versie van IE10 al in zicht. Ze zullen wel moeten want de concurrenten gaan veel sneller. Ik denk dat we op een gegeven moment ook alleen maar horen over IE en niet meer IE x. Weet iemand uit zijn hoofd wat de laatste versie van Chrome ondertussen is? Pssst antwoord is 11 sinds deze week.

Alle features van HTML 5 zijn nog lang niet bekend. Dit kan nog wel een tijd gaan duren. Tot die tijd zullen we moeten checken op features door middel van frameworks. Als ik verder kijk dan alleen de computer zal HTML bij mij toch echt de voorkeur krijgen. De tablet oorlog is volgens de analisten pas dit jaar van start gegaan. Het aantal tablets bij de consumenten en bedrijven (ik hoor het steeds meer om me heen bij bedrijven) groeit met een rap tempo. Het aanhouden van een standaard is dan wel zo makkelijk.

Ontwikkelmethodieken als MVC stellen je in staat logica en presentatie makkelijker te scheiden. Het compatible maken/ondersteunen van je applicatie voor verschillende platformen is dus ook een stuk eenvoudiger. Je bereikt hierdoor een groter publiek en zal dus meer omzet genereren. De techniek staat niet stil waardoor we onze strategieën zelf moeten beslissen maar wat je wel ziet is dat de doelgroep of manier van werken langzaam wijzigt. De IPad 2 is uit en meteen heel het internet staat vol met tweede hands IPad 1 omdat die oud is. Er is veel meer vraag naar nieuwe techniek en alle informatie dient voor alle gadgets en platformen aanwezig te zijn. Mensen verwachten tegenwoordig dat dit ook zo wordt gemaakt.

De smartphoneverkoop neemt in een jaar tijd met 83% toe. Het aantal verschillende telefoons op de markt met verschillende specificaties neemt ook rap toe. Het gebruiken van standaarden begint nu dus echt belangrijk te worden. Grote organisaties als Microsoft, Google en Apple omarmen dit ook. Het is niet voor niets dat grote organisaties steeds meer open source projecten financieel ondersteunt zodat hier de community weer gebruik van kan maken. Soms worden projecten door dit wel is stop gezet. Denk maar aan de AJAX techniek van Microsoft. Microsoft ontwikkelt zelf nu voor JQeury. Heel het templating in JQuery komt namelijk van Microsoft.

.NET Framework 4.0 on Windows Server 2003 with IIS 6

Ralph Jansen BlogToday I was converting a website to the new .NET Framework 4.0 version. This was an existing website and was already running on a Windows Server 2003 with IIS 6.0 system. After I upgraded the files of the website, changed the config file to the right settings and changed the .NET Framework version on the ASP .NET tab in the properties window of the website to version 4 instead of 2, I was getting a “Page could not be found” error. After restarting the server, registering the .NET Framework again to IIS, I still had the same error on my screen.

When I searched the internet for a solution, I found the blog of Johan Driessen. One blog post explained the error that I was getting with the right solution. Just check if your ASPNET_ISAPI is set to the right .NET Framework (version 4). If not, enable it with the provided command. The only difference on the command in his blog and the one that I used is that I used Framework64 and not Framework.

Change Target Framework version for all the projects in the solution

Ralph Jansen BlogToday I migrated an old project from Visual Studio 2008 to Visual Studio 2010 and with that, I changed the Framework to version 4.0. This is currently the newest .NET Framework. The solution contains a lot of different projects so the challenge was to convert all the target frameworks to the 4.0 version.

 

There are a couple ways to this:

  1. Change every project by hand. (Open the properties of every project and select the target framework that you want);
  2. Edit the project files by hand in notepad;
  3. Use the macro of Scott Dorman.

The macro of Scott can be found here. Just place the macro on the right place on your pc and execute it. After you executed the macro a popup is shown with the question to which target framework you want to migrate. Choose your framework and press OK.

That’s it!!! Safes a lot of time!!

Update:
You can execute a Macro in the Tools->Macros->Macros Explorer window.

clip_image002_thumb

Undo pending changes on a file in Team Foundation Server

Ralph Jansen BlogIn this small tutorial I will explain how to undo pending changes on a file on your Team Foundation Server. I tested this code on a Team Foundation Server 2010 edition.

First you need the name of the workspace that is locking your file on the server. To accomplish this you can run the following code in the Visual Studio Command Prompt:

tf workspaces /owner:<developers_logonname> /computer:* /server:<your TFS server>

After you have found your workspace name, you can undo the changes for the file with the following code:

tf undo "$/<Path to file to undo>" /workspace:<Workspace name>;<Domain and username> /s:<your TFS server>

 

Note:

  1. Your TFS servername must be with http and the portnumber to succeed.
  2. You can find the path to file simply by clicking the properties on the file in the “Source Control Explorer” window

If you followed the above steps, you will see the following message in the command prompt.
image