ThreadAbortException

June 2011 Entries

Formatting minified jQuery, JavaScript using the Internet Explorer 9 Developer Toolbar

Much has been talked about the F12 developer toolbar in IE and the support it provides for web developers.  Starting IE8, the Developer Toolbar is a menu item that helps you view the page source, scripts, profiling and many other details of the rendered page.  It even allows script debugging from within and that makes it a truly powerful web developer tool bar.

With IE9, the developer toolbar got even better with the Networking Tab that allows you to inspect the traffic/time taken and drill down into the Request/Response headers and other specifics.

The script tab allows you to view the scripts used in the page.

image

One of the challenges of working with JavaScript / jQuery when they are minified, is that, it becomes really hard to read.  Minified JavaScript is a compression technique and also a best practice for delivering faster web pages.  However, when you would like to debug, minified JavaScript files become very hard since they aren't properly formatted.  Take the case of the above sample, which is a basic MVC 3 Web Application.  It uses the minified jQuery and modernizr files.

Once we select the above scripts, the script source looks as follows:-

image

But with the “Format JavaScript” option in the Configuration icon,

image

Once you click on the “Format JavaScript”, you can see the formatted JavaScript as per screen below:-

image

This makes the script readable and also easy for debugging. 

Cheers !!!

Using the ASP.NET Membership API with SQL Server / SQL Azure: The new “System.Web.Providers” namespace

The Membership API came in .NET 2.0 and was a huge enhancement in building web applications with users, managing roles, permissions etc.,  The Membership API by default uses SQL Express and until Visual Studio 2008, it was available only through the ASP.NET Configuration manager screen (Website – ASP.NET Configuration) or (Project – ASP.NET Configuration) and for every application, one has to manually visit this place to start using the Security and other settings.  Upon doing that the default SQL Express database aspnet.mdf is created to store all the user profiles.

Starting Visual Studio 2010 and .NET 4.0, the Default Website template includes the Membership API controls as a part of the page i.e. When you create a “File – New – ASP.NET Web Application” or an “ASP.NET MVC Application”, by default the Login/Register controls are enabled in the MasterPage and they are termed under “ApplicationServices” setting in the web.config file with connection string pointed to the SQL Express database.

In fact, when you run the default website and click on “Logon” –> “Register”, and enter the details for registration and click “Register”, that is the time the aspnet.mdf file is created with the tables for Users, Roles, UsersInRoles, Profile etc.,

Now, this uses the default SQL Express database within the App_Data folder.  If you want to move your Membership information to some other database such as SQL Server, SQL CE or SQL Azure, you need to manually run the aspnet_regsql command and specify the destination database name.

This would create all the Tables, Procedures and Views required to handle the Membership information.  Thereafter you can change the connection string for “ApplicationServices” to point to the database where you had run all the scripts.

Now, enter “System.Web.Providers” Alpha. This is available as a part of the NuGet package library. 

Scott Hanselman has a neat post describing the steps required to get it up and running as well as doing the basic changes  at http://www.hanselman.com/blog/

Pretty much, it covers what the new System.Web.Providers do.

One thing I wanted to clarify is that, the new “System.Web.Providers” add a lot of new settings which are also marked as the defaults, in the web.config.  Even now, they use SQL Express as the default database.  But, if you change the connection string for “DefaultConnection” under connectionStrings to point to your SQL Server or SQL Azure, Membership API would now be able to create all the tables, procedures and views at the destination specified (i.e. SQL Server or SQL Azure).

In my case, I modified the DefaultConneciton to point to my SQL Azure database.  Next, I hit F5 to run the application.  The default view loads.  I clicked on “LogOn” and then “Register” since I knew there are no tables/users as of then.  One thing to note is that, I had put “NewDB” as the database name in the connection string that points to SQL Azure.  NewDB wasn’t existing and I would assume it would be created before the tables/views/procedures for Membership are created.

Once I clicked on the “Register” to register my first username, it took a while and then registered as well as logged in me in.  Also, I went to the SQL Azure Management Portal and verified that there exists “NewDB” which has just been created Smile

I could also connect to the SQL Azure database “NewDB” from Management Studio and found that the tables now don’t have the aspnet_ prefix.  The tables were simply Users, Roles, UsersInRoles, Profiles etc.,

So, with a few clicks and configuration change, I could actually set up the user base for my application on SQL Azure and even make the SessionState, Roles, Profiles being stored in SQL Azure database.

The new System.Web.Proivders also required MARS (MultipleActiveResultSets=true) setting since it uses Entity Framework for the DAL operations. 

Also, the “Project – ASP.NET Configuration” screen can be used to further create/manage users/roles etc., although the data is stored on the remote database.

With that, a long pending request from the community to have the ability to configure and use remote databases for Application users management without having to run the scripts from SQL Express is fulfilled.

Cheers !!!

Migrating SQL Server Compact Edition (SQL CE) database to SQL Server using Web Matrix

One of the things that is keeping us busy is the Web Camps we are delivering across 5 cities.  If you are a reader of this blog, and also attended one of these web camps, there is a good chance that you have seen me Smile since I was there in all the places, so far.  The topics that we cover include Visual Studio 2010 SP1, SQL CE, ASP.NET MVC & HTML5.  Whenever I talk about SQL CE, the immediate response is that, people are wow that Microsoft has shipped a FREE compact edition database, which is an embedded database that can be x-copy deployed.  If you think, well didn’t Microsoft ship SQL Express which is FREE?  The difference is that, SQL Express runs as a service in the machine (if you open SQL Configuration Manager, you can notice that SQL Express is running as a service along with your SQL Server Engine (if you have installed Smile).  This makes it that, even if you are willing to use SQL Express when you deploy your application, it needs to be installed on the production machine (hosting provider) and it needs to run as a service.  Many hosters don’t allow such services to run on their space.

SQL CE comes as a x-Copy deploy-able database with just a few DLLs required to run it on the machine and they don’t even need to be installed in GAC on the production machine.  In fact, if you have Visual Studio 2010 SP1 installed, you can use the “Add Deployable Dependencies” option in Project-Properties and it would detect that SQL CE is something you would probably want to add as a deploy-able dependency for your project.  With that, it bundles the required DLLs as a part of the “_bin_deployableAssemblies” folder.  So your project can be x-Copy deployed and just works fine.

However, SQL CE has the limit of 4GB storage space.  Real world applications often require more than just 4GB of data storage and it often turns out that people would like to use SQL CE for development/ramp up stages but would like to migrate to full fledged SQL Server after a while.  So, its only natural that the question arises “How do I move my SQL CE database to SQL Server”  And honestly, it doesn’t come across as a straight forward support. 

I was talking to Ambrish Mishra (PM in SQL CE Team, Hyderabad) since I got this question in almost all the places where we talked about SQL CE.   He was kind enough to demonstrate how this can be accomplished using Web Matrix. 

Open Web Matrix (Web Matrix can be installed for free from www.microsoft.com/web) and click on “Site from Template”

image

Click on the “Bakery” template (since by default it uses a SQL CE database and has all the required sample data) and click “Ok”.

image

In the project, you can navigate to the Database tab and will be able to find that the Bakery site uses a SQL CE database “bakery.sdf”

image

Select the “bakery.sdf” and you will be able to see the “Migrate” button on the top right

image

Once you click on the “Migrate” button, you will notice that the popup wizard opens up and by default is configured for SQL Express.  You can edit the same to point to your local SQL Server instance, or a remote server.

image

Upon filling in the Server Name, Username and Password, when you click “Ok”, couple of things happen. 

1. The database is migrated to SQL Server (local or remote – subject to permissions on remote server).   You can open up SQL Server Management Studio and connect to the server to verify that the “bakery” database exists under “Databases” node.

2. You can also notice that in Web Matrix, when you navigate to the “Files” tab and open up the web.config file, connection string now points to the SQL Server instance (yes, the Migrate button was smart enough to make this change too Smile)

And there it is, your SQL Server Compact Edition database, now migrated to SQL Server!! In a future post, I would explain the steps involved when using Visual Studio.

Cheers !!!

Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

MVC 3 is becoming hugely popular thanks to Razor and the Helpers that make building web applications much easier. One of the common requirements in web development, both with web forms as well as MVC based development, is the cascading dropdownlist. Now, for Web Forms, we can use a variety of options viz. server side programming, jQuery or using the AJAX Control Toolkit’s cascading dropdownlist control for accomplishing this.

I saw a few samples on the internet that used the erstwhile Microsoft AJAX Library along with MVC and also few more samples which used hard coded values for wiring up the cascading dropdown. I have built this sample using Database with 3 tables i.e. Cars, Makes & Colours. The colours table is actually redundant but for the sake of showing a 3 dropdown hierarchy I have made it a relational table – just for the purpose of the sample. Also, all the cars mentioned are the brands that I could recollect and driven around in India Smile

To begin with, lets examine the Database – CascadeSample. It has 3 tables

i. Cars

ii. Models

iii. Colours

I filled in some sample data. At the end of this post, I would provide link for downloading the database scripts as well as the solution.

First, lets create our MVC 3 Application using “File – New Project – ASP.NET MVC 3 Web Application” give it a name “CascadingDropdownSample” and select the “Internet Application” and click ok. This would create the basic scaffolding structure with Membership API. We won’t need it though.

As always with MVC, lets build the Model by right click Models Folder – Add – New Item and search for ADO.NET Entity in the search box of the Dialog.

Chose the ADO.NET Entity Data Model Template and give it a name CarModel.edmx and click Add.

Choose the “Generate from Database” option and in the Next steps, connect to the CascadeSample database and select all the 3 tables and then finish the steps to generate the Entity Model. Our Entity Model is now ready.

Next step is to start wiring up the Controller Actions. For the purpose of this simple demo, lets just use the default HomeController.

Lets add using CascadingDropdownSample.Models; to the namespaces in the HomeController.

Lets add CascadeSampleEntities cse = new CascadeSampleEntities(); within the class

Lets add the following within the Index Action.

public ActionResult Index()
{

ViewBag.Cars = cse.Cars.ToList();
ViewBag.Models = cse.Models.ToList();
ViewBag.Colours = cse.Colours.ToList();
return View();
}

 

Lets switch to the View (ROOT – Views – Home – Index.cshtml) and edit it to look as follows:-

@model CascadingDropdownSample.Models.CascadeSampleEntities
@{
ViewBag.Title = "Home Page";
}

<h2>Cars</h2>
<p>
@Html.DropDownListFor(Model => Model.CarId, new SelectList(ViewBag.Cars as System.Collections.IEnumerable, "CarId", "CarName"),
"Select a Car", new { id = "ddlCars" })
</p>

When we run the page, we will get to see the List of cars in the dropdown.

For the next set of actions i.e. populating the Model and Colour, we need the following Methods.

private IList<Model> GetModels(int id)
{
return cse.Models.Where(m => m.CarId == id).ToList();
}

private IList<Colour> GetColours(int id)
{
return cse.Colours.Where(c => c.ColourId == id).ToList();
}

The next main thing we need is Action methods which can send a JSon Result for both Models and Colours.

To first get the Models by car, we add the following to the HomeController

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadModelsByCar(string id)
{
var modelList = this.GetModels(Convert.ToInt32(id));

var modelData = modelList.Select(m => new SelectListItem()
{
Text = m.ModelName,
Value = m.ModelId.ToString(),

});

return Json(modelData, JsonRequestBehavior.AllowGet);
}

 

and to get the Colours for the various Models, we add


[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadColoursByModel(string id)
{
var colourList = this.GetColours(Convert.ToInt32(id));

var colourData = colourList.Select(c => new SelectListItem()
{
Text = c.ColourName,
Value = c.ColourId.ToString(),

});

return Json(colourData, JsonRequestBehavior.AllowGet);
}

 

Finally, we need to add the following jQuery handlers for the dropdownlist selection changed

<script type="text/javascript">
$(document).ready(function () {
$("#ddlCars").change(function () {
var idModel = $(this).val();
$.getJSON("/Home/LoadModelsByCar", { id: idModel },
function (carData) {
var select = $("#ddlModels");
select.empty();
select.append($('<option/>', {
value: 0,
text: "Select a Model"
}));
$.each(carData, function (index, itemData) {

select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
});
});
$("#ddlModels").change(function () {
var idColour = $(this).val();
$.getJSON("/Home/LoadColoursByModel", { id: idColour },
function (modelData) {
var select = $("#ddlColours");
select.empty();
select.append($('<option/>', {
value: 0,
text: "Select a Colour"
}));
$.each(modelData, function (index, itemData) {

select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
});
});
});

</script>

And then add the dropdowns for Model and Colour

<p>
@Html.DropDownListFor(Model => Model.Models, new SelectList(Enumerable.Empty<SelectListItem>(), "ModelId", "ModelName"),
"Select a Model", new { id = "ddlModels" })

</p>
<p>
@Html.DropDownListFor(Model => Model.Colours, new SelectList(Enumerable.Empty<SelectListItem>(), "ColourId", "ColourName"),
"Select a Colour", new { id = "ddlColours" })

</p>

And then, when we build and run we can get to choose the Car, Model and Make, a cascading dropdown built using jQuery and MVC 3

I have uploaded the Visual Studio 2010 Solution as well as the Scripts for the CascadeSample Database to https://skydrive.live.com/?cid=069f94a102eff49a&sc=documents&client=wnf&id=69F94A102EFF49A%21760#cid=069F94A102EFF49A&id=69F94A102EFF49A%21761&sc=documents

Feel free to download and use it for your projects Smile

Also, do share if you find better ways to implement the same.

Cheers!!

Entity Framework with SQL Azure, "There is already an open DataReader associated with this Command which must be closed first."}

I hit this error when I deployed an app built with Entity Framework onto Windows Azure.  Obviously, I wasn’t explicitly using DataReader so it kind of puzzled me.  As it happens every time Smile It worked well with local database, application running local and database on SQL Azure.  But once I used the Dev Fabric to test the application locally, it failed and gave the above error.

Entity Framework relies on using Multiple Active Results Sets (MARS), and it would be a part of connection string multipleactiveresultsets=True.  Earlier SQL Azure didn’t  support MARS, so we have to explicitly set it to “false” before deploying to SQL Azure.

But starting April 2010, SQL Azure supports MARS (yeah, that is the level of update I had on SQL Azure i..e 1 year late Smile) and this post nicely covers on this particular topic http://blogs.msdn.com/b/adonet/archive/2010/06/09/remember-to-re-enable-mars-in-your-sql-azure-based-ef-apps.aspx

On the new SQL Azure features, read http://blogs.msdn.com/b/sqlazure/archive/2010/04/16/9997517.aspx 

In my case, I wired up the connection string myself using the Azure user account and password and totally forgot the MARS setting.

All I had to do was to add the multipleactiveresultsets=True to my connection string and it started working fine.

If you surface this error even after adding the above, and find some resolution, do post in the comments Smile

Cheers!!!

Web Role Instances recreated, repaired while deploying MVC 3 Applications on Windows Azure

Recently, I was deploying an MVC 3 Application on Windows Azure.  The deployment took longer than expected and the Roles were just restarting/repairing and it couldn’t just start the role instances.  Only thing that seemed to have worked was uploading the Packages.  Post that, the Roles were simply unable to start and be ready.  I deleted the deployment, re-created the package and deployed.  Still no avail.  It would successfully upload the package but post that the roles would never be able to start.  They will just keep getting recycled.

I then figured out that MVC 3 is not supported in Windows Azure yet and in fact, you need to explicitly add MVC 3 assemblies to the bin folder or have MVC 3 installed as a start up task along with your Windows Azure project.

Steve Marx has an excellent post (and to the point, of all the posts I read) on getting MVC 3 installed as a start up task on Windows Azure, at http://blog.smarx.com/posts/asp-net-mvc-in-windows-azure

Just follow the instructions and you should be fine to have your MVC 3 Application running on Windows Azure.

Cheers!!