Archive for the ‘Programming’ Category.

Why uptime on WP7 cannot be longer than 24.9 days?

This morning I saw in System View on my Samsung Omnia 7 that uptime is “more than 24.9 days”, and boot time is “earlier than 30-Dec-11 13:07:24”. At first I was amazed, how can it be “earlier than”, and how that reference in time is not fixed (it was 29-Dec yesterday). Then I realized that phone does not “remember” its time of boot, but has some sort of incrementing register for counting uptime, and it hits its limit on 24.9 days. It would be interesting for how long this phone can work without reboot, as it seems very stable, but it seems that cannot be known without manual recording of boot time Disappointed smile.

I did some calculations, and it seems that phone is using SIGNED int as register value which counts number of MILISECONDS since boot. As 25 days has about 2’160’000’000 milliseconds, and 2^31 is 2’147’483’648, it starts to seem logical where did number 24.9 days came from Nerd smile. It is logical that boot time itself is not recorded, as there it would be a possibility of reporting “fake” uptimes by setting the clock on the phone. However, in my opinion, method used is also not optimal.

So, what could be better here? Light bulb

- For start, it could be unsigned int, so the OS would be able to keep track for more than 49 days of uptime.
- It could also count seconds instead of milliseconds, that would make possible to count more than 1300 years of uptime Smile, or if for some reason needs to keep milliseconds (i.e. does not want to break all existing functionalities?), unsigned long (int64) could be used (although I don’t remember if it is available in WP7), to give overkilling amount of almost 585 millions of years Hot smile.

All this considered, it seems that 49 days would be enough, change would not break anything, and it requires changing only one variable declaration.

Check which rule is not fullfiled in jQuery validate plugin

Recently, I have encountered a situation where I used jQuery validation plugin and needed to know which of validation rules are failing. After asking this question on http://stackoverflow.com/questions/7648727/jquery-validate-check-which-rule-is-not-fullfiled and receiving no answers for 15 days, I have spent some time to solve it by myself.

It turned out quite easy, after inspecting source code of plugin on https://github.com/jzaefferer/jquery-validation/blob/master/jquery.validate.js, I have found out that this can be done by adding my own function to it:

 

$.validator.prototype.ruleValidationStatus = function( element ) {
    element = $(element)[0];
    var rules = $(element).rules();
    var errors ={};
    for (var method in rules ) {
        var rule = { method: method, parameters: rules[method] };
        try {
            var result = $.validator.methods[method].call( this, element.value.replace(/\r/g, ""), element, rule.parameters );
 
            errors[rule.method] = result ;
 
        } catch(e) {
            console.log(e);
        }
    }
    return errors;
}

This function returns list of validation rules with their results, and usage is simple:

$("#myform").validate().ruleValidationStatus($("#myField"));

Simplify common data access functions by using Entity Framework extension points

 

Whenever there is a new project with database, there is substantial amount of time spent on design of that database, as changes to database later cause much more overhead and problems than in beginning. In today’s conditions, however, it is very rare that database schema is not changed even during implementation (or immediately after deployment Smile). That is one of reasons why we now have CodeFirst workflow in EntityFramework.  It is great to have one common set of properties in one place (base object) inherited into all tables (i.e. UserCreated, DateCreated etc), and not having to think about it in individual objects.

It is even better to have all logic that uses those common properties in one place, but that tends to be hard to implement if repository pattern is used with all “common” logic implemented in common repository containing basic CRUD operations and data context as a dependency object. The problem is that each repository will inherit from common repository, and all will have “same” behavior, but EF allows you to save complex objects at once, and this can make your life bitter when you have common repository. The thing is, your custom behavior is executed for object you are saving, but not for referenced objects which are also saved when you add or update your main object. Workaround is to have instance of repository for each type which is referenced in your main object, save each first through “its” repository, and then save your main object which references all of them. As thing always can be made better (and better is more simple for me), I tried to find an answer for this problem. My answer is on github and if you are interested check it out (it has sample which works out of the box), and read description here.

There is a simple solution for this problem – common repository is code first context! It has couple of extension points (virtual methods left which can be overriden) where you can implement your own logic to handle journaling, validation, business rules… Almost everyone who worked with CF has used (overriden) OnModelCreating method, as it is very common in tutorials, but there are couple more:

bool ShouldValidateEntity(DbEntityEntry entityEntry)

System.Data.Entity.Validation.DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)

int SaveChanges()

ShouldValidateEntity and ValidateEntity are usefull places to call from your business rules and all possible validators, as there is no way that something will go to database by not passing through these (often ignored methods). These extension points are fairly simple to use and domain-specific, and I will not write about them in this post. My target of interest is SaveChanges.

go.DB.JournalingBase is simple project featuring usage of EntityFramework CodeFirst and overriding SaveChanges method of DBContext in order to keep record of changes on entities in database. There is a simple usage sample project and a test project with couple of test cases to confirm that everything is working. Database is SQLCompact, so no SQL Server is necessary and everything works on “F5”.

This is the idea: I have one “base” object – JEntity from my database objects inherit, and have corresponding DBContext, from which my repository(ies) inherit. Common object has Id property and other common properties I want all my journaling objects to have:

public abstract class JEntity
    {
        /// &lt;summary&gt;
        /// Gets or sets the id.
        /// &lt;/summary&gt;
        /// &lt;value&gt;The id.&lt;/value&gt;
        public int Id { get; set; }
 
        /// &lt;summary&gt;
        /// Gets or sets the original id.
        /// &lt;/summary&gt;
        /// &lt;value&gt;The original id.&lt;/value&gt;
        public int OriginalId { get; set; }
 
        /// &lt;summary&gt;
        /// Gets or sets the date created.
        /// &lt;/summary&gt;
        /// &lt;value&gt;The date created.&lt;/value&gt;
        public DateTime DateCreated { get; set; }
 
        /// &lt;summary&gt;
        /// Gets or sets the date deleted.
        /// &lt;/summary&gt;
        /// &lt;value&gt;The date deleted.&lt;/value&gt;
        public DateTime? DateDeleted { get; set; }
 
        /// &lt;summary&gt;
        /// Gets or sets the user created.
        /// &lt;/summary&gt;
        /// &lt;value&gt;The user created.&lt;/value&gt;
        public string UserCreated { get; set; }
 
        /// &lt;summary&gt;
        /// Gets or sets the user deleted.
        /// &lt;/summary&gt;
        /// &lt;value&gt;The user deleted.&lt;/value&gt;
        public string UserDeleted { get; set; }
    }

This object has OriginalId property, as a reference to “original” object – the first one that was added to database. When objects are updated, new version is created each time, “old” object is marked as deleted (DateDeleted is set in this case). All versions of same object share same OriginalId value, which is the same as Id value of oldest version.

Mapping to database is done using IEntityMap class, so this one is clean and simple, and does not have database metadata. The reason is that in real life you often have to refactor your code and change something. If model is created from metadata, then any change will cause your existing database to be “broken” and you will have to recreate it. This is good strategy in the beginning when you initialize your database with test data every time and test through unit tests, but if you have some staging environment where application is deployed and tested by users/testers they may have problems with that (whereee areee all thoose records I entered in friday?? Smile). This is especially important if you are making some serious enterprise application that will have longer lifecycle, and you want to make support easier (we do not want to have a “bomb” which will delete production database).

public IEntityMap()
	{
		//// Primary key
		this.HasKey(t => t.Id);
 
		//// Properties
 
		this.Property(t => t.OriginalId)
			.IsRequired();
 
		this.Property(t => t.DateCreated)
			.IsRequired();
 
		this.Property(t => t.DateDeleted)
			.IsRequired();
 
		this.Property(t => t.UserCreated)
			.IsRequired()
			.HasMaxLength(50);
 
		this.Property(t => t.UserDeleted)
			.IsOptional()
			.HasMaxLength(50);
 
		//// Column mappings
		this.Property(t => t.Id).HasColumnName("Id");
 
		this.Property(t => t.DateCreated).HasColumnName("DateCreated");
 
		this.Property(t => t.OriginalId).HasColumnName("OriginalId");
 
		this.Property(t => t.DateDeleted).HasColumnName("DateDeleted");
 
		this.Property(t => t.UserCreated).HasColumnName("UserCreated");
 
		this.Property(t => t.UserDeleted).HasColumnName("UserDeleted");
	}


So,  separate mapping class allows you to refactor properties without having to change their names in database, or to manually sync your database with your model, as everything is clean and readable.

The context – JContext overrides SaveChanges method, which takes care of actions necessary for journaling:

public override int SaveChanges()
{
	// We need same time for all entities updated in same transaction.
	DateTime now = DateTime.Now;
	// Get reference to user to avoid multiple getter calls.
	string user = System.Threading.Thread.CurrentPrincipal.Identity.Name;
 
	//// Detect changes in case that change tracking is turned off
	if (!this.Configuration.AutoDetectChangesEnabled)
	{
		this.ChangeTracker.DetectChanges();
	}
	List&lt;JEntity&gt; insertedList = new List&lt;JEntity&gt;();
	List&lt;JEntity&gt; invalidList = new List&lt;JEntity&gt;();
	foreach (var entry in this.ChangeTracker.Entries())
	{
		// Make sure that this customized save changes executes only for entities that
		// inherit from our base entity (IEntity)
		var entity = (entry.Entity as JEntity);
		if (entity == null) continue;
 
		switch (entry.State)
		{
			// In case entity is added, we need to set OriginalId AFTER it was saved to
			// database, as Id is generated by database and cannot be known in advance.
			// That is why we save reference to this object into insertedList and update
			// original id after object was saved.
			case System.Data.EntityState.Added:
				entity.UserCreated = user;
				entity.DateCreated = now;
				insertedList.Add(entity);
				break;
 
			// Deleted entity should only be marked as deleted.
			case System.Data.EntityState.Deleted:
				if (!entity.IsActive(now))
				{
					invalidList.Add(entity);
					continue;
				}
				entry.Reload();
				entity.DateDeleted = now;
				entity.UserDeleted = user;
				break;
 
			case System.Data.EntityState.Detached:
				break;
 
			case System.Data.EntityState.Modified:
				if (!entity.IsActive(now))
				{
					invalidList.Add(entity);
					continue;
				}
				entity.UserCreated = user;
				entity.DateCreated = now;
 
				JEntity newVersion = this.Set(entity.GetType()).Create(entity.GetType()) as JEntity;
				newVersion = this.Set(entity.GetType()).Add(newVersion) as JEntity;
				this.Entry(newVersion).CurrentValues.SetValues(entity);
 
				this.Entry(entity).Reload();
 
				entity.DateDeleted = newVersion.DateCreated;
				entity.UserDeleted = user;
				break;
			case System.Data.EntityState.Unchanged:
				break;
			default:
				break;
		}
	}
	if (invalidList.Count == 1)
	{
		throw new InvalidJournalingEntityException(invalidList[0], invalidList[0].GetType().Name);
	}
	else if (invalidList.Count &gt; 1)
	{
		throw new MultipleInvalidJournalingEntityException(invalidList);
	}
	int result = base.SaveChanges();
 
	if (insertedList.Count &gt; 0)
	{
		insertedList.ForEach(t =&gt; t.OriginalId = t.Id);
		base.SaveChanges();
	}
 
	return result;
}


The method handles cases when object is added, modified or deleted. When added, it must save reference to it and set OriginalId after it was assigned Id. As object does not have Id until sql server generates one for it, this has to be done after SaveChanges. Theese few lines should in serious system be inside one transaction, just in case.

When object is changed, change is canceled and  only DateDeleted and UserDeleted is set (same as when object is deleted). Instead, new object is added as new version of changed object.

All this is used from sample project, where new entities and context are created, with no code for usage of theese features except inheritance from JEntity and JContext.

If something is not clear, the best option is to start test project and set breakpoints at places of interest, or ask your question in comments!

kick it on DotNetKicks.com

Log on to windows as a local user without computer name

Yes, you all know that you can use computername\user or 192.168.x.y\user, or even domain\user when logging on to machine.

But, when you want to login as local user and don’t know computer name, and do not want to type IP address, you can use any\user where any can be anything.

Nice little security flaw?

Deserialize form from JSON data using jQuery

Recently, I got task to make feature which will make possible for user to update form data based on some unique “search” field (like VIN or SSN). I wanted to make this short and simple, and above all reusable. So, I made some investigation this weekend and came up with simple solution to use same model object that is used as type of view in asp.net mvc. It is simple javascript function:

 

var formPrefix = 'myFormPrefix';
$('sometextbox').change(function () {
 var myValue = $(this).val()
 $.ajax({ type: 'POST',
  url: 'ajaxcontroller/getcarbysomething',
  data: { something: myValue },
  success: function (data) {
  if (data){
   $("input[name*='" + formPrefix +"'],select[name*='" + formPrefix + "']").each(function () {
    var itemName = $(this).attr("name");
    var prop = itemName.substring(itemName.indexOf(formPrefix) + formPrefix.length);
    var itemValue = data.person[prop];
    if (itemValue && itemValue.substring &&
      itemValue.substring(0, 1) == "/" &&
      itemValue.substring(itemValue.length - 1) == "/") {
         itemValue = "new" + itemValue.substring(1, itemValue.length - 1);
         itemValue = eval(itemValue);
         $(this).datepicker("setDate", eval(itemValue));
    }
    else if (itemValue) {
     $(this).val(itemValue);
    }
   });
 
   }
  }
 });
});

So, to use this you need to make controller action that returns JsonResult and Json(model) instead of View(model). If form is partial view (preffered) or has explicit prefix, formPrefix is place to set it. Each form input element’s name is used to index json object returned from controller and value (if any) is set back into input element.

Autocompleting cascading dropdowns

 

Starting point for this post is source code for last one, available on bitbucket.

I want to replace dropdown list with jQuery autocomplete, like in this example. There are two reasons for this:

  • When there is very large number of records to choose from, then standard dropdown list is not very user friendly
  • When user is entering name of item, besides autocompleting from known items, we can implement addition of new item if item user needs to enter is not present in codebook. This will be done in next post.

For start, I will copy example from jQuery demo, and add textbox in which I will implement this functionality.

image

I have added this code to Index.chtml, which is label for manufacturer, hidden field with id for chosen value from dropdown, and textbox for autocomplete. I have added three attributes for this textbox:
- autocomplete-for is target (hidden field) into which I want to place chosen value
- from-url is address where I will get items for autocomplete
- parent is field for cascading functionality (this will be optional)

Client side code for autocomplete is based on jsonp example from jQuery ui demo:

image

I have added this init function to document ready event. What is happening here is simple: for each input element that has “autocomplete-for” attribute, jQuery autocomplete is added, with custom function as data provider. This function is using ajax to request data for dropdown from from-url specified in view. Parameters are MaxItems (amount of items to show in autocomplete), ParentFilterId (selected value of parent field – for cascading support) and NameStartsWith, which is text entered into dropdown which is autocompleted.

Success function maps “items” collection in response to label, value and id. label and value are automatically used by autocomplete plugin to show label for item in dropdown and to set textbox value when item is selected, and I added id to set hidden field in select event.

To make this work, there is one thing left: controller action which will return items. As you can see in first screenshot, I decided to use Manufacturer controller and action named Autocomplete.

To make parameter passing easier, I have created model for data passed in request:

image

I will receive this object as parameter in my action.

This is how implementation of autocomplete action looks:

image

This is fairly simple – query is filtered by name for NameStartsWith parameter, and I used ToLower method of string, to compare case insensitive, as StartsWith with string comparison options parameter is not supported in linq to entities.

If request contains parent filter id or max items number, then these are taken into account, and response is formed as collection of items with Text, Value and Id properties, which are used in success function of ajax request.

Time to see how it works:

imageimageimage

As this is working nicely, time for little makeup, as I want this more reusable, and not having to remember html attributes that need to be used. So, that smells like html helper:

image

Actually, it is two helpers – one for cascading case, and one for “normal”. It is the same code as in cshtml view, but creating hidden and text field in one method, and when I add comments here (removed to make screenshot smaller), I will have nice intellisense to use this function whenever I need, only having to copy and adjust controller action, which also can be made pretty generic.

 

image

This is how autocomplete is used now. I’m ready to call this a day, and source code from this post is in this changeset on bitbucket.

ASP.NET MVC3 app (part 3) – ajax cascading dropdown–unobtrusive version

 

In part 2, I made cascading dropdowns by calling selectFromAjax javascript function from my view:

image

This function has 3 arguments: address of service which provides data based on second argument – formData (in this case only id of selected item in current dropdown), and target – select list into which items from service are injected, replacing its current contents. These three parameters are almost enough to know that there is dependency between two dropdowns. Why almost? Because there is one implicit parameter – this function is part of “change” event of another dropdown – source of this event. So, source dropdown is fourth parameter. That four things are everything that client needs to know to be able to implement intended behavior of UI.

I will make this functionality unobtrusive by placing necessary information into target dropdown. Why? Because it seems most straightforward and “unobtrusive” to me, that dropdown list says “My contents depend on item selected in dropdown list X, and you need to call service Y to find out what should I show”. It is not ok to have information about MY behavior in some other dropdown X Smile. Besides, with this approach, I’m eliminating one parameter, as I have only two now: dropdown X and service Y. Third was value of dropdown X, and fourth is target dropdown itself, into which I’m adding these attributes. Value of dropdown X I can read if I know which is dropdown X, so this parameter for function anyway must be determined at the moment of changing value in X.

So, if I make my select look like

image 

then my dropdown contains all information needed to remove script from view, and place it in global js file, or make jQuery plugin. To make this information automatically embedded into my dropdown, I need to make html helper for this. If wee look at first overload of DropDownListFor in System.Web.Mvc.Html.SelectExtensions, we can easily see how new method should look:

image

My html helper will have another two arguments – depends on and load from:

image

It is using DropDownListFor helper from Microsoft, and I won’t render my own html code (and so make more space for bugs Smile).

So, view from part 2 should now look like this:

image

and generated html is:

<select cascading-dependson="ProductType" cascading-loadfrom="/Home/Manufacturers" id="Manufacturer" name="Manufacturer"></select>

Now, all that is left, is to automatically attach event handler onto “master” dropdown. It is easy using jQuery:

imageThis is adding initializeCascader to list of functions that are run on document load. This function goes through each select that has cascading attributes and attaches onchange event to element with id in cascading-depenson attribute, with self as a target for selectFromAjax function (from part 2), and value of cascading-loadfrom attribute as a url.

This is very simple concept, but can be used for chaining random number of dropdowns, and can easily be expanded to make dropdown values dependent not only on “master” dropdown, but to depend on whole form. Further improvement of this could be custom data annotation attribute, which could be used for decorating property of model, so html helper does not have to be explicitly called.

Source code for this post can be downloaded here.

UPDATE: I have uploaded source code to bitbucket.

Back to part 2

ASP.NET MVC3 app (part 2) – ajax cascading dropdown

 

To make cascading dropdowns in application from part 1, I created ProductFilter:

image

I will use this class as model for my home controller Index method:

image

Here you can also see Manufacturers JsonResult method, which is used for asynchronous refresh of second dropdown:

imageimage

Manufacturer dropdown is loaded with manufacturers which produce models of chosen product type. This is made possible with simple jquery function:

image

This function accepts url of method which provides json list of items for dropdown, passes formData parameter with id, and places results into target for which selector “target” is provided.

This is how my view from which this method is called looks:

image

Two dropdowns are created using standard MVC helpers, and onchange event function is attached using jquery. More dropdowns can be chained in the same way, there is only necessary to add change function in the same manner. However, this is no good, as event attachment is manual, and script must be written, and included into view as selectors are generated here. My goal is to make these event attachments unobtrusive, and I will write about that in part 3.

For now, you can download project source code here.

Back to part 1

ASP.NET MVC3 app (part 1) – Entity Framework and code first

How often you need to have cascading choices on UI in order to make your application user friendly? In my experience, almost every modern application has some form of hierarchy, and that is where cascading dropdowns are used. But, I want to make this less repetitive and more elegant. So, let’s begin. In first part (this) I will create an simple web app using entity framework code-first and make simple model which will be used for creating this functionality. It is one speedy run-through of new features, without advanced topics, so mind some bad practices, this blog post is not about good programming, first part is for MVC3/.NET 4 beginners with experience with older versions of MVC and .NET.

It will be an mvc3 razor internet application:

image

With latest MVC tools update there are already almost all necessary NuGet packages installed in new project:

image

I will just update all of jQuery packages as they have updates at the moment, and add EntityFramework.SqlServerCompact (NuGet will add dependencies), so SQL server won’t be needed.

As this is demo app, I will put everything into single project. It will be an product catalogue.

This is data model:

image

Central object will be product model (I will use vehicles domain), which has type, version, trim level and manufacturer. Simple enough. Objects on diagram are simple POCO objects with collection properties marked as virtual, so entity framework can override them and inject DynamicProxy objects for lazy loading.

This will be my repository:

image

For this DbContext to work, I need to do one more thing – to put connection string into my web.config:

image

As I don’t want to create test data every time I change my model, I can use database initializer class to create test data (this is useful for unit testing):

image

And this is it. I now have database and data. Actually, I will have it when I start my application, if I add this to global.asax:

image

To test this, I will use controller autoscaffold feature of new MVC tools update:

image

This will autocreate controller and all views Smile. After this action, starting app and visiting http://localhost:57095/Manufacturer will give:

image

Note that only manufacturers for which I created Models are in database. This is because I only added Models, and EF added all related objects, and BMW was not among them.

Using auto scaffold I created controllers for all model objects in couple of minutes.

This is end of part 1, I now have application which will I use to create unobtrusive cascading dropdowns. In the next part I will make cascading dropdown loading using standard methods (jQuery and ajax).

For more info about EF Code First, visit

http://www.hanselman.com/blog/SimpleCodeFirstWithEntityFramework4MagicUnicornFeatureCTP4.aspx

and

http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx

UPDATE: Added part 2

Take my work with me

How often did I need to copy whole virtual machine because I needed to continue work on another location? A way too often. And moments when I wait for 20-30GB to copy, sometimes seem like eternity.

Well, I spent couple minutes last night to prevent that :)

Here is a batch script which copies folder with my work from hdd and takes backup of database. Even more, it restores everything back when I arrive at another location :)

So, save this script as common.bat:

@echo off
set server=HOSTNAME\INSTANCE
set dbName=DATABASE
set projFolder="C:\Users\gorano\Documents\visual studio 2010\Projects"
set backupFolder=%CD%
 
if "%1"=="leaving" GOTO backup
if "%1"=="arriving" GOTO restore
echo Invalid first argument, must be "leaving" or "arriving"
GOTO end
 
:backup
echo backup database %dbName%
@echo on
sqlcmd -E -S %server% -Q "BACKUP DATABASE [%dbName%] TO  DISK = N'%backupFolder%\%dbName%.bak' WITH NOFORMAT, INIT, NAME = N'%dbName%-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10"
xcopy %projfolder% %backupFolder%\Projects  /E /I /Y /Q
GOTO end
 
:restore
if "%2"=="DeleteOld" GOTO deleteold
:restoreNoDelete
echo restore database %dbName%
sqlcmd -E -S %server% -Q "RESTORE DATABASE [%dbName%] FROM DISK = N'%backupFolder%\%dbName%.bak' WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 10"
xcopy %projfolder% %projfolder%.backup  /E /I /Y /Q
xcopy %backupFolder%\Projects %projfolder%  /E /I /Y /Q
GOTO end
 
:deleteold
@echo Press any key to delete database %dbName% on sql server %server%
pause
sqlcmd -E -S %server% -Q "ALTER DATABASE [%dbName%] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE"
sqlcmd -E -S %server% -Q "DROP REMOVETHISWORD DATABASE [%dbName%]"
GOTO restoreNoDelete
 
:end
pause

To run this easily, make “i’mleaving.bat” with

common leaving

and “i arrived.bat” with

common arriving DeleteOld

All you need to change is to set your server\instance, database name, folder with projects, and to delete “REMOVETHISWORD” under :deleteold, as words DROP and DATABASE does not stand well together (I don’t want to hack wordpress script injection protection to post this) :)
In combination with DropBox, this is great thing. You can also add 7z line to compress/decompress these files so dropbox sharing is more meaningfull (if you have large database).

Fix selected tab in SharePoint top links menu

Fastest way to accomplish this is to use jquery! :)

function fixTabs(){
    $.each($(".customNavTabActive"), function() {
        $(this).removeClass("customNavTabActive");
        $(this).parentsUntil("table").each(function() {
            $(this).removeClass("customNavTabActive");
        });
    });
    $.each($("a.customNavTab"), function() {
        if (this.href == document.location.href || this.href + "/default.aspx" == document.location.href) {
            $(this).parent("td").addClass("customNavTabActive");
        }
    });
}

Update: I have improved this code a little bit :)

function fixTabs(){
    var normalNavTavCss = "customNavTab";
    var firstCellActiveCss = "customNavTabActive";
    var firstCellCss = "customNavTab";
    var lastCellActiveCss = "customNavTabActive";
    var lastCellCss = "customNavTab";
    var cellActiveCss = "customNavTabActive";
    $.each($("." + cellActiveCss), function() {
        $(this).removeClass(cellActiveCss);
        $(this).parentsUntil("table").each(function() {
        $(this).removeClass(cellActiveCss);
        });
    });
    var lastCell;
    var lastCellSelected;
    $.each($("." + normalNavTavCss + " a"), function(i) {
        lastCell = $(this).parent("td");
        var location = document.location.href.replace("/default.aspx", "");
        var link = this.href.replace("/default.aspx", "");
        lastCellSelected = (link == location || location.indexOf(link) &gt; -1);
        if (lastCellSelected) {
            if (i == 0) {
                lastCell.addClass(firstCellActiveCss);
            }
            else {
                lastCell.addClass(cellActiveCss);
            }
        }
        else if (i == 0) {
            lastCell.addClass(firstCellCss);
        }
    });
    if (lastCellSelected) {
        lastCell.removeClass(cellActiveCss);
        lastCell.removeClass(firstCellActiveCss);
        lastCell.addClass(lastCellActiveCss);
    }
    else {
        lastCell.addClass(lastCellCss);
    }
}

Most common used xlt transformations on web.config

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<connectionstrings>
        <remove name="MyEntities" xdt:Transform="InsertBefore(/configuration/connectionStrings/add)"/>
        <add name="MyEntities" 
             connectionString="yourconnstring" 
             providerName="System.Data.EntityClient" xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
        <remove name="MyEntities2" xdt:Transform="InsertBefore(/configuration/connectionStrings/add)"/>
        <add name="MyEntities2"
             connectionString="yourconnstring"
             providerName="System.Data.EntityClient" xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
        <add name="ApplicationServices" connectionString="" xdt:Transform="Remove"/>
</connectionstrings>
 
<system .web>
<trust level="Full" xdt:Transform="InsertBefore(/configuration/system.web/compilation)" />
<authorization xdt:Transform="InsertBefore(/configuration/system.web/authentication)">
<allow roles="Administrator"/>
<deny users="*"/>
</authorization>
<authentication xdt:Transform="Remove"></authentication>
<compilation xdt:Transform="RemoveAttributes(debug)" />
<membership xdt:Transform="Remove"></membership>
<rolemanager xdt:Transform="Remove"></rolemanager>
<profile xdt:Transform="Remove"></profile>
<!--
In the example below, the "Replace" transform will replace the entire
<customErrors> section of your web.config file.
Note that because there is only one customErrors section under the
</system><system .web> node, there is no need to use the "xdt:Locator" attribute.
<customerrors defaultRedirect="GenericError.htm"
mode="RemoteOnly" xdt:Transform="Replace">
<error statusCode="500" redirect="InternalError.htm"/>
</customerrors>
-->
</system>

I have some problems with saving and to WordPress post, so dont just copypaste this snippet.

IIS and ASP.NET 4.0 applications

If you cannot start debugging on web server, cannot open application on IIS at all, have any problems with managed integrated handler or similar when accessing application, then you need to install .NET 4.0 on server. Easiest way is using Web Platform Installer, under Frameworks.

If .NET 4.0 is already installed, then you need to open cmd as Administrator, and run “%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i”

That solved problems for me.