All posts in ASP.NET

This session is so awesome, I just had to post it here so that I can play it over and over again…
What great times are we living…


If you ever created a professional website/application you’ll probably know the value (you’ve probably learned it the hard way as I did Smile) of stress testing your web applications.

There are plenty of tools you can use in order to stress test your web site, ranging from Microsoft Visual Studio to CMD Line tools. Yesterday I found another one StresStimulus.

StresStimulus is an extension for Fiddler (an awesome and free web debugging proxy) which enables us to create instant load tests with virtual users.

stressing

You can record a browser activity (like creating a user), replay it under concurrent load and get the results for the performance of web pages and the entire test.

If you prefer a simple but powerful tool this one is for you.


Microsoft recently released a new flavor of IIS 7.x that is optimized for developer scenarios called “IIS Express” as part of WebMatrix. IIS Express combines the ease of use of the ASP.NET Web Server with the full power of IIS.  Specifically:

  • It’s lightweight and easy to install (less than 10Mb download and a super quick install)
  • It does not require an administrator account to run/debug applications from Visual Studio
  • It enables a full web-server feature set – including SSL, URL Rewrite, Media Support, and all other IIS 7.x modules
  • It supports and enables the same extensibility model and web.config file settings that IIS 7.x support
  • It can be installed side-by-side with the full IIS web server as well as the ASP.NET Development Server (they do not conflict at all)
  • It works on Windows XP and higher operating systems – giving you a full IIS 7.x developer feature-set on all OS platforms

iisexpressIIS Express (like the ASP.NET Development Server) can be quickly launched to run a site from a directory on disk.  It does not require any registration/configuration steps. This makes it really easy to launch and run for development scenarios.

Unfortunately you’ll need a patch for VS 2010 and Visual Web Developer 2010 Express in order to enable you to automatically launch and use IIS Express in place of VS’s built-in ASP.NET Developer Server, which will come later this year.

For those of us too impatient to wait for a hotfix for Visual Studio to natively support IIS Express, I’ve done some searching and found a post, by Interpid Studios, to [fairly] easily setup a debugging environment for IIS Express and VS 2010.


I guess most of you will know by now that ItPro|DevConnections is holding a lottery for two msdn subscriptions for all of those that took advantage of the early bird offer and subscribed for the event before the 30th of September.

Well, I was assigned to perform the lottery which is going to take place today. This got me thinking, What would be the easiest (don’t have time) and geekiest (after all it’s a tech event) way to perform this lottery? And then it stuck me “why don’t I try LightSwitch, it’ll probably take me 10 minutes to prepare a full blown application”? And so it did, here’s what I’ve done:

1. Get the Data

OrdersSchemaSo first I needed the data, meaning the details (first name, last name, email etc.) of all of those that registered before the 30th of September. Luckily this year all the registrations went through a computerized system (that Techaholics made Winking smile) so it was very easy to extract all the data I needed, in a new table “Orders” in a new database.

The “Orders” table schema in the new database looked something like this.

2. Create LightSwitch Project

Next I created a new LightSwitch project using Visual Studio 2010 and the new template that you get when you install the LightSwitch framework. You can watch the video that I’ve made to see how I did it.

LightSwitch Draw application screencast

3. Randomly selecting a winner

The random selection logic that was put inside the button click handler was as shown in the video was:

Timer tm = null;
partial void Button_Execute()
{
  var orderList = this.OrderCollection.ToList();
  SetBorderColor(Colors.Black);

  if (tm == null)
  {
    tm = new Timer(new TimerCallback((callbackState) =>
      {
        var list = (List)callbackState;
        Random r = new Random((int)DateTime.Now.Ticks);
        var selectedindex = r.Next(list.Count);
        var winner = list[selectedindex];

        IContentItemProxy proxy = this.FindControl("txtWinner");
        proxy.Invoke(() =>
        {
          var txtWinner = (System.Windows.Controls.TextBox)proxy.Control;
          txtWinner.Text = string.Format("{0} {1} ({2})", 
            winner.Name, winner.LastName, winner.Code);
        });

      }), 
      orderList, 
      TimeSpan.FromMilliseconds(0), 
      TimeSpan.FromMilliseconds(100));
  }
  else
  {
    tm.Change(Timeout.Infinite, Timeout.Infinite);
    tm.Dispose();
    tm = null;
    SetBorderColor(Colors.Red);
  }
}

DISCLAIMERS!!

  • None of the selected winners in the above video are the real ones. Winners will be picked later today and officially announced at www.itprodevconnections.gr
  • I don’t guarantee that the winner selection will be made using this application. I just made this one for fun – to explore LightSwitch.
  • The data shown on the screencast are sample data and were deleted once the sample was completed

Last week two security researchers, Thai Duong and Juliano Rizzo, have discovered a bug in the default encryption mechanism used to protect the cookies normally used to implement Forms Authentication in ASP.NET.

Using their tool (the Padding Oracle Exploit Tool or POET), they can repeatedly modify an ASP.NET Forms Authentication cookie encrypted using AES and, by examining the errors returned, determine the Machine Key used to encrypt the cookie. The process is claimed to be 100 percent reliable and takes between 30 and 50 minutes for any site.

Everyone immediately focused on the bug not mentioning what is commonly known as good practice and applied to every production site by any decent software developer “Never expose your production server errors (exceptions) to the client” failing to do so exposes your server to a number of threats not only the one described in the above security vulnerability.

There are several ways you could achieve that and Scott Gu mentions the easiest one in his blog post. An other way you could hide errors from your clients is by handling the Application_Error event in the web app’s Global.asax like this

void Application_Error(object sender, EventArgs e)
{
  try
  {
    Exception ex = Server.GetLastError();

                //Log any way you feel like

    Server.ClearError();
  }
  catch (Exception ex){	}
  finally
  {
    Response.Redirect("~/error.htm");
  }
}

Some of my colleagues are often reluctant to use ASP.NET 2.0 profile provider to store profile data for their web applications. The main reason for this is the fact that the default SqlProfileProvider that ships with ASP.NET 2.0 “blobicizes” Profile data using string, XML or binary serialization prior to storing information in SQL Server. This obviously puts a rather large overhead when you need to query your profile data.

What most developers aren’t aware though is that you can build your own custom profile provider to store Profile data “in the clear” in the database so that the data is available for querying and use in stored procedures.

As a matter of fact Microsoft provides an SqlTableProfileProvider sample implementation which stores each Profile property in a separate database column without serializing it, which means that the Profile property can be easily queried (of course the profile property type needs to be compatible with the target database column).

There is also a second sample provider, SqlStoredProcedureProfileProvider, which maps each Profile property to a parameter on a custom stored procedure. Like the table based provider, this provider expects that each Profile property is of a type that is compatible with its corresponding stored procedure parameter. The powerful aspect of the stored procedure based provider is that other than the requirement to implement some stored procedures with a specific set of parameters, you can implement whatever business logic you need in the stored procedures to map the Profile data to your own database schema and database logic.

You can learn more about these profile providers here.


I’ve been involved for quite some time now with a new Microsoft project codenamed “WebMatrix” but couldn’t say anything about it since all the info was under NDA. Today though, the public availability of the Microsoft WebMatrix Beta was announced, so I guess I’m no longer bound by the NDA agreement and can let you in on a few things.

So first let me clarify a few things, and to do that I’m going to use an excellent explanation from David Ebbo’s blog.

WebMatrix: a stack and a tool

Let’s start with WebMatrix.  The term is actually used is two ways

  1. The WebMatrix stack contains a number of things that you get when you install it via WebPI:
    • The new ASP.NET Web Pages framework
    • The Razor templating engine
    • The WebMatrix tool (see #2)
    • IIS Express
    • SQL CE 4
  2. The WebMatrix tool, which lets you perform various tasks:
    • Create web apps that use the Web Pages framework and the Razor templating engine
    • Install existing sites from the Web Gallery.  Note that those sites don’t have to use the Web Pages framework, and in fact most don’t (e.g. ScrewTurn wiki, Subtext)
    • Manage IIS express
    • Manage SQL CE 4 databases

Key point: the WebMatrix tool is not by any mean the only way to create Web Pages apps.  In fact, the Web Pages framework was designed to be very notepad friendly.  On the other end of the tooling spectrum, it will later be fully supported by Visual Studio.

You can find more info on WebMatrix in ScottGu’s blog:


I briefly got the chance to talk about MetaCMS, the content management system and e-shop platform I’ve designed and built, a while back. Since then a lot of sites have been built using it. Some of which (the biggest ones) include:

 

And as if building these sites wasn’t enough we’ve decided to completely re-write the platform and built MetaCMS V2. The fact that it had been “tied” to LinqToSql was bothering me all along but due to lack of time didn’t have the time to do something about it. But eventually and although I had put it on “steroids”, the Context has been disposed caching bugs I’ve talked about previously, drove us to completely re-write that part.

login

So what’s new in this new version, well basically we’ve done two things

  • First we’ve build View Models of serializable POCO (Plain Old CLR Objects) objects, taking advantage of the T4 Visual Studio templating engine and the Linq models we already had. In addition these View Model objects were designed to have lambda expressions that will lazy load related entities once those are requested.
  • Secondly I’ve designed a simple IoC system that instantiates Repositories that are responsible to return data and “Hydrate” the view model objects.

Repository

Making these changes we were able to solve the caching problems and the dreadful Context has been disposed exception we were getting when caching Linq objects and at the same time build a more robust, scalable, solution one that can target multiple client technologies (Sliverlight, WPF, etc) and use different Data access methods.

But that’s not all, except from the bug fixes a lot of new features and modules have been added as well. Some of which are:

  • Extensibility support
    Hook into various MetaCMS actions and build your own custom business logic.
  • Messaging platform
    Capable of sending templatized newsletters and Emails.
  • Import / Export
    Import and Export engine that allows communication with arbitrary data sources.
  • Stock Market platform
    Utilizes a provider model to allow communication with any Stock Market data provider (Rueters, XAA etc.)
  • Competition Module
    Supports multiple and recurring competitions with custom winner picking rule engine.
  • Elections
    Build to support Elections with maximum detail and data coming from any provider.

And last but not least the e-commerce part of MetaCMS that has been upgraded to an Enterprise Level solution with all the features even the most demanding shop would need. Speaking of which there is a large e-shop project coming up soon that unfortunately though I still can’t disclose.

Time to stop mumbling… if you have more questions or need a demo get in touch and I’ll arrange it.


I’m starting a new line of blog posts in which I’m going to give out a few tips and tricks I’ve picked up during the past years. I’m going to start with one of the most common mistakes I often face when reading code.

CaptureTo demonstrate that, I’m going to use LinqToSQL as my data access method (although the problem can be found in any kind of Data access technology) and use the the same model I used in my earlier Caching series.

As you can see the model is very simple and contains just three entities, a Peson, its Phones and its Email addresses.

Next I’m going to create a web form in which I want to display a list of Persons along with their email address. To do that I’m going to add a Repeater control which I’m going to Bind to the Person retrieved from the store.

<asp:Repeater ID="personGrid" runat="server" OnItemDataBound="personGrid_ItemDataBound">   <ItemTemplate>     <asp:Label ID="lblName" runat="server" Text='<%# string.Format("{0} {1}", Eval("FirstName"), Eval("LastName")) %>'></asp:Label>  |      <asp:Label ID="lblEmail" runat="server" Text='Email' Font-Bold="True" Font-Italic="True"></asp:Label>   </ItemTemplate>   <SeparatorTemplate><br /></SeparatorTemplate>
</asp:Repeater>

Since the Email Address is not in the same entity as the Person I’m going to take advantage of the repeater’s OnItemDataBound event to fetch the Email address of these persons. So typically would find something like that in the code behind.

protected void Page_Load(object sender, EventArgs e)
{
	if (!Page.IsPostBack)
	{
		DataBind();
	}
}

public override void DataBind()
{
	base.DataBind();

	using (AdventureworksDataContext context = new AdventureworksDataContext())
	{
		var query = from p in context.Persons
		select p;

		personGrid.DataSource = query.Take(10);
		personGrid.DataBind();
	}
}

protected void personGrid_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
	Label lblEmail = e.Item.FindControl("lblEmail") as Label;
	Person currentPerson = e.Item.DataItem as Person;

	if (lblEmail != null && currentPerson != null)
	{
		using (AdventureworksDataContext context = new AdventureworksDataContext())
		{
			var personEmail = context.EmailAddresses.Where(ea => ea.BusinessEntityID == currentPerson.BusinessEntityID).FirstOrDefault();
			lblEmail.Text = (personEmail != null) ? personEmail.EmailAddress1 : "";
		}
	}
}

This will work just fine but what some developers don’t realize is that that this will make as many queries to the database as the records on the Persons Table, cause it’s time a Person record is Data bound I’m querying for its Email Address on the ItemDataBound Event Handler.

What we could do instead, is take advantage of all the cool new features in .Net 3.5 and Linq, like data projection, data shaping and anonymous types to prepare a read-only view to bind to the repeater. So a more optimized and much cleaner version of this code would look something like that:

protected void Page_Load(object sender, EventArgs e)
{
	if (!Page.IsPostBack)
	{
		DataBind();
	}
}

public override void DataBind()
{
	base.DataBind();

	using (AdventureworksDataContext context = new AdventureworksDataContext())
	{
		var query = from p in context.Persons
			    select new { 
				FirstName = p.FirstName, 
				LastName = p.LastName, 
				Email = p.EmailAddresses.Select(e => e.EmailAddress1).FirstOrDefault() };

		personGrid.DataSource = query.Take(10);
		personGrid.DataBind();
	}
}

//protected void personGrid_ItemDataBound(object sender, RepeaterItemEventArgs e)
//{
//  Label lblEmail = e.Item.FindControl("lblEmail") as Label;
//  Person currentPerson = e.Item.DataItem as Person;

//  if (lblEmail != null && currentPerson != null)
//  {
//    using (AdventureworksDataContext context = new AdventureworksDataContext())
//    {
//      var personEmail = context.EmailAddresses.Where(ea => ea.BusinessEntityID == currentPerson.BusinessEntityID).FirstOrDefault();
//      lblEmail.Text = (personEmail != null) ? personEmail.EmailAddress1 : "";
//    }
//  }
//}

This way I can also remove the OnItemDataBound event handler completely (or use it just for visual stuff that’s my preference) from the repeater and bind the Email Label to the new Field of the anonymous type that I’ve just created. So the page code is going to look something like that:

<asp:Repeater ID="personGrid" runat="server" OnItemDataBound="personGrid_ItemDataBound">   <ItemTemplate>     <asp:Label ID="lblName" runat="server" Text='<%# string.Format("{0} {1}", Eval("FirstName"), Eval("LastName")) %>'></asp:Label>  |      <asp:Label ID="lblEmail" runat="server" Text='<%# Eval("Email") %>' Font-Bold="True" Font-Italic="True"></asp:Label>   </ItemTemplate>   <SeparatorTemplate><br /></SeparatorTemplate>
</asp:Repeater>

Although this kind of behavior is pretty obvious and I’m pretty sure that most of you are already aware of it, there are times when this behavior is disguised and rather difficult to spot. For example the following code has exactly the same problem since the GetEmailAddress method is going to be called as many times as the person records (although there is no ItemDataBOund handler).

<asp:Repeater ID="personGrid" runat="server" OnItemDataBound="personGrid_ItemDataBound">   <ItemTemplate>     <asp:Label ID="lblName" runat="server" Text='<%# string.Format("{0} {1}", Eval("FirstName"), Eval("LastName")) %>'></asp:Label>  |      <asp:Label ID="lblEmail" runat="server" Text='<%# GetEmailAddress((int)Eval("ID")) %>' Font-Bold="True" Font-Italic="True"></asp:Label>   </ItemTemplate>   <SeparatorTemplate><br /></SeparatorTemplate>
</asp:Repeater>

And of course this behavior doesn’t only apply to repeaters but in every list control (drop down list, GridView, Checkbox list etc) that is going to be bound to fields belonging to more than a single entity.


Before picking up where I left off yesterday, I have to first make a small disclaimer. I received a couple of comments stating that the caching solution I presented wasn’t that sophisticated or complete or that the cache keys that I’ve used were not the right and the answer is of course “yes”. The solution I presented was far from perfect but it served well as a simplified demonstration of the problems one might face when caching Linq to SQL entities.

Ok now that we’re done with the typicalities let’s see what was wrong with the solution shown earlier. To demonstrate the problem I’m going to add a single button to my web form and attach an event handler to it. In the event handler I’m going to ask the Person from the Cache and Lazy load his phones.

public partial class _Default : System.Web.UI.Page
{
	protected void Page_Load(object sender, EventArgs e)
	{
		if (!IsPostBack)
		{
			DataBind();
		}
	}

	public override void DataBind()
	{
		base.DataBind();

		employeesRepeater.DataSource = new List<Person>() { GetPerson("M") };
		employeesRepeater.DataBind();

	}

	protected void btnGetPhone_Click(object sender, EventArgs e)
	{
		Person person = GetPerson("M"); //This person comes from the cache
		var phones = person.PersonPhones.ToList(); //Attempt to lazy load throws exception as Context has been disposed
	}

	protected Person GetPerson(string lastNameStartsWith)
	{
		using (AdventureworksDataContext context = new AdventureworksDataContext())
		{
			return CacheGet<Person>(
					() => context.Persons.Where(p => p.LastName.StartsWith(lastNameStartsWith)).FirstOrDefault(),
					string.Format("Person_LastName_StartsWith:{0}", lastNameStartsWith));
		}
	}

	protected T CacheGet<&lt;T>(Func<T> loader, string cacheKey) where T : class
	{
		var cachedObject = this.Cache[cacheKey] as T;
		if (cachedObject == null)
		{
			cachedObject = loader.Invoke();
		}
		return cachedObject;
	}
}

CaptureIf you ran this code and click the button you’ll end up with the exception
Cannot access a disposed object.
Object name: ‘DataContext accessed after Dispose.’.

That’s the real problem when caching Linq to SQL entities, the fact that they have a dependency (reference) on the data context that created them and as such they can not be cached. There are ways you can work-around this problem by detaching and re-attaching the entities to the currently loaded data context. But since there is no way you can actually detach an entity from the context you can only rely on hacks to do that. A way to detach an entity is serialize it (of course entities must be declared serializable) cache it and then before retrieving it from the cache deserialize it and attach it to the context. Another is to manually detach an entity (set certain properties to null) and another to manually clone it. Each of these methods has advantages and disadvantages, like the fact that you’ll loose all object’s graph if you serialize it or the complexity if you follow the manual detaching path. One thing is for sure though, there is no easy way around it.

What’s my preffered way you ask? I guess the most painful way (;-)) but at the same time the most scalable and robust. Build my own custom POCO entities model, populate it using whatever data access technology and cache those entities.