Ah, there was a time early on during the days of classic ASP when I absolutely despised JavaScript.  I’m not sure if it was because my untrained eyes invariably missed the periods, or my clumsy fingers were not used to the case-sensitivity, or…I just didn’t quite "get it".  Actually, it was all of those things.

More time passed, I became slightly less naive when it came to programming.  More importantly, all the AJAX hype came to the forefront.  I found myself using JavaScript for more than just elementary client-side validation functions.  I suddenly realized I had to actually learn the language that I fostered such hatred for.  LEARN?!

Fast forward a few years…I can’t really believe I hated JavaScript as much as I did.  JavaScript is a language that is sort of like single-malt scotch.  Totally disgusting if you aren’t sure what you want.  Exquisite in every way if you do.  I do a good amount of work in JavaScript these days…both using pure JS and jQuery-magic when appropriate.  More often than not I’m writing some AJAX functionality to manipulate the DOM based on some response I get from a service/DB/dolphin/etc.

I’ve come to realize that it’s easy to write a function, especially in JS, that is cumbersome and not-at-all conducive to being re-used.  A while back, I wrote a function that looked like this:

function SubscribeToUpdates(emailId, errorId, successId) {
	var email = $('#' + emailClientId).val();
	if (!ValidateEmail(email)) {
		$('#' + successId).css('display', 'none');
		$('#' + errorId).css('display', 'block');
		return;
	}
//some other nonsense
}

So, what is wrong with this picture?  It could be worse, right?  I’m passing in the ID of the DOM element that contains, in theory, the e-mail that should get subscribed to updates.  I run that through my ValidateEmail() function.  If the e-mail isn’t valid, I go ahead and hide the success DIV, and show the error DIV..and vice versa.  What? It’s clever, isn’t it?

Sure. It’s great…until a month later you need to use my function and come to the startling realization that the way I wrote my function forces you to have specific elements in your DOMA damn shame, really.  Let’s count how many things I see wrong with this method:

1. It forces the caller to pass in an the IDs of DOM elements.  What happens if I want to pass by class?  The hard-coded "#" screws everything up.  This applies to all the parameters.  If I was going to do this at all, I should have passed selectors.

2. The function leaves me no choice but to have a DOM element for a valid e-mail address, as well as a DOM element for an invalid e-mail address. It’s also not at all obvious what those DOM elements accomplish.  I happen to know the DOM elements contain validation success/error messages, but someone else wouldn’t immediately know that.

3. Even if I have DOM elements for "success" and "error", I’m modifying the display attribute of my CSS.  What if I’d like to toggle a class instead using addClass()?

In summary, then, I am stupid.  But more specifically, I was entirely too short-sighted when I created this function.  Sure, it’s just one lousy JS function.  It serves its purpose.  The issue is, it really only serves its purpose given very specific constraints.  This is far less than ideal.

Let’s take another crack at this function and see what’d it look like if we incorporate the corrections I allude to above.

function SubscribeToUpdates(emailSelector, errorSelector, successSelector, errorCssObj, successCssObj) {
	var email = $(emailSelector).val();
	if (!ValidateEmail(email)) {
		$(successSelector).css(successCssObj);
		$(errorSelector).css(errorCssObj);
		return;
	}
//some other nonsense
}

Okay.  That’s a little better. 

Now I can pass selectors instead of be bound to passing only DOM IDs.  I have also used the jQuery CSS(cssObj) method.  This let’s you pass a JSON object that is essentially a list of your CSS Attributes and their values.  For example, the value of the successCssObj might be this:

SuccessCssObj =
{
	'display': 'none'
};

At this point, you’re probably wondering why I ignored problem number 2, above.  The caller is still bound to having a "success" and an "error" DOM element.  I could get around this downright silly requirement in a few ways.  I could easily check if I’ve passed a selector in for the "successSelector" and the "errorSelector", and proceed to modify their CSS if they exist.  But why bother?  That’s ugly, it’s more code, and it’s just going to confuse the crap out of me when I come back to this in another month.

There is an easier way

And that way is by using callbacks.  If you’ve used jQuery, or any of the other popular JS frameworks floating around, you’ve been using them already without even thinking about it.  When you call $ajax in jQuery, you’re providing both success and error callbacks.  Basically, you’re optionally passing in a function you’d like to execute if an error occurs, and a function you’d like to execute if no error occurs.  The key here is you’re passing in the function to execute, and the function contains the logic you to run given a certain condition (An invalid e-mail, in this case).  This means that my function is only responsible for doing what it is named….Subscribing an email address for updates.  It doesn’t care about the caller’s DOM, and it sure as hell doesn’t care about CSS.  My function doesn’t even like CSS.  Let’s take a look at this glorious function after a makeover.

function SubscribeToUpdates(emailSelector, successCallback, errorCallback) {
    var email = $(emailSelector).val();
    if (!ValidateEmail(email)) {
        if(errorCallback)
            errorCallback();
        return false;
        }
    else{
        if(successCallback)
            successCallback();
        }
        return true;
//some other nonsense
}

There we go, and we’ve even made the successCallback and errorCallback parameters optional if we’d prefer not to pass either or both of them.  As promised, we’ve totally separated the caller’s context from the objective of the function.  Let’s take a look at an example of calling this function.  Again, this will look very familiar to you if you’re used jQuery.  That’s a good thing.

SubscribeToUpdates(’.email’,
	function(){
		$(’#SuccessEmail’).removeClass(’hidden’);
		//Do some other client-specific stuff
	},
	function(){
		$(’#SuckyEmail’).addClass(’error’);
		$(’#SuccessEmail’).removeClass(’hidden’);
		return;
	});

There’s a reason jQuery and other libraries are created in this manner.  It makes it much easier to reuse your code.  The combination of using callbacks and optional parameters really inspires a shift in the way I analyze requirements and code methods in general…especially in JavaScript.  Furthermore, it doesn’t increase complexity.  If anything, it is easier to read methods when they truly have one purpose.  You don’t want to force any method caller/client to have additional requirements, be it DOM elements or anything else.

In the first post in this series, I provided a little info on the HandleError attribute in MVC 1.  In case you don’t want to flip back, the HandleError attribute can decorate a method or a class and will push your users to a generic errors view provided customErrors is “On” or “RemoteOnly”.  There’s a little more to it, but that’s all the background we need for this post.

The out-of-the-box HandleError attribute works well, until you’re in a scenario where you need to do more than hide your errors.  Typically, you may want to do some logging or fire-off some alerts.  Now, as luck should have it, I did some searching before writing this up and Danny Tuppeny already has a great post on this very subject…I encourage you to take a peak at his post, as I’ve provided a very high-level, yet functional summary below.

The facts are these…

- System.Web.Mvc.Controller contains an OnException method that gets fired when an exception occurs [provided custom errors are On/RemoteOnly in the web.config]

- The OnException method can easily be overridden, allowing you to either completely change behavior or add behavior (by calling base.OnException)

- This method will fire regardless of whether your class or method is decorated with HandleError

This means that your could will look like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcErrorHandling.Controllers
{
	public class ControllerBase : System.Web.Mvc.Controller
	{
		protected override void OnException(ExceptionContext filterContext)
		{
		//Do whatever stuff you'd like
		DoSomeOtherStuff();
		//Displays a friendly error, doesn't require HandleError
		filterContext.ExceptionHandled = true;
		this.View("Error").ExecuteResult(this.ControllerContext);
		//Displays a friendly error, *requires* HandlError
		//base.OnException(filterContext);
	}
	protected void DoSomeOtherStuff() { /* brevity */ }
	}
}

To get the above code to work you’d simply make your controller inherit from ControllerBase.  Of course, you’d likely have additional utility-methods in this class that you’d need in multiple controllers.

Lines 17 and 18 can be used to push the user to your error view after you execute the DoSomeOtherStuff() method – this would not require the HandleError attribute.  Alternatively, you can execute System.Web.Mvc.Controller’s OnException by calling it explicitly as it’s done on line 21.  In this case, the HandleError would be required to push your use down the custom-error path you’ve got configured.

And that’s pretty much all there is to centralizing & customizing your error-handling in MVC 1. 

If you came from somewhere else, you may want to take a look at part 1

I’ve been using ASP.NET MVC Release 1 for a bit now, and while it’s definitely not for every application, I happen to like it quite a bit.  There has been a lot of activity on MS-centric blogs regarding MVC, but there are still some really mundane tasks that there could be more information on.  So, this series of posts isn’t going to be anything crazy; it will, however, illustrate what options you have to do centralized error-handling using MVC

We’ll start at the beginning…

The System.Web.Mvc.dll comes with the HandleErrorAttribute class, which contains..wait for it…the HandleError attribute.   This information won’t be important until later in this series, but the HandleErrorAttribute class inherits from the FilterAttribute class, and implements the IExceptionFilter interface – the interface requires a method with the following signature.

public virtual void OnException(ExceptionContext filterContext);

This method is really where the brunt of the work is done when you use the provided [HandleError] attribute.  In case you’ve never taken a look using Reflector, this HandleErrorAttribute’s implementation of OnException looks like this

public virtual void OnException(ExceptionContext filterContext)
  {
      if (filterContext == null)
      {
          throw new ArgumentNullException("filterContext");
      }

      if (!filterContext.ExceptionHandled && filterContext.HttpContext.IsCustomErrorEnabled)
      {
          Exception innerException = filterContext.Exception;

          if ((new HttpException(null, innerException).GetHttpCode() == 500) && this.ExceptionType.IsInstanceOfType(innerException))

          {

              string controllerName = (string) filterContext.RouteData.Values["controller"];
              string actionName = (string) filterContext.RouteData.Values["action"];

	      HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

	      ViewResult result = new ViewResult();
              result.ViewName = this.View;
              result.MasterName = this.Master;
              result.ViewData = new ViewDataDictionary(model);
              result.TempData = filterContext.Controller.TempData;

	      filterContext.Result = result;
              filterContext.ExceptionHandled = true;
              filterContext.HttpContext.Response.Clear();
              filterContext.HttpContext.Response.StatusCode = 500;
              filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
          }
      }
  }

Essentially, you’re grabbing some information from the ExceptionContext, and you’re using the HandleErrorInfo class to pass this information back to your view.

Using [HandleError] is really as easy as using any other attribute.  You simply decorate your method or class with the attribute and your errors will be pushed to the default view for errors (Views/Shared/Error.aspx)

Sample usage of [HandleError]:

namespace MvcErrorHandling.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            if (true)
            {
                throw new ApplicationException("Some error...");
            }
            return View();
        }
        //removed...

Alternatively, you can provide the HandleError attribute with some arguments to specify a view other than the default error-view, or specify a specific view based on the exception type.  Here’s an example of the usage for that…

[HandleError(ExceptionType = typeof(ApplicationException), View = "AppErrorPage")]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        if (true)
        {
            throw new ApplicationException("Some error...");
        }
        return View();
    }
    //removed...

The only other thing you’ll want to make sure you do is ensure your web.config <customErrors> section is configured appropriately.  That is, you’ll want to make sure customErrors mode=”On” to test this out.

Hope this helps somebody; the next part in this series will demonstrate how to add functionality to the existing OnException method that the HandleErrorAttribute class implements, such as logging.

Don’t forget to take a look at part 2!

It took a bit for me to get comfortable enough with LINQ-to-objects to write ‘queries’ off the top of my head…but once you’re used to it you realize it’s much more concise, easier to interpret/read, and well..it’s less code.  Here are some real quick examples…

This first example selects the string array value as well as its position from the someItems array.  Note, the user of new{} creates a new generic type that has the properties ItemName and Position.  I could have called these two properties whatever I pleased, because I’m creating them at query-time.

string[] someItems = { "cat", "dog", "purple elephant", "unicorn" };
string[] someItems = { "cat", "dog", "purple elephant", "unicorn" }; 

var selectedItems = someItems.Select((item, index) => new
{
    ItemName = item,
    Position = index
});

After you run this, selectedItems will look like this….

image

int firstItem = someItems.Select((item, index) => new
{
    ItemName = item,
    Position = index
}).Where(i => i.ItemName == "purple elephant")
  .FirstOrDefault()
  .Position;

In which case, firstItem would equal 2.  Naturally, this is only the beginning of what LINQ to objects can do for you – but it definitely illustrates how LINQ can ease your daily coding.

11
Aug

I’ll keep it short and sweet.  Was browsing this new twitter thing that all the kids are playin’ with and I saw an link to this story: You Deleted Your Cookies?  Think Again.  Short version: You can create cookie-like objects with flash, that:

  1. Don’t get deleted from your machine when you clear cookies
  2. Can be used to re-spawn browser-based cookies if you delete them
  3. Can do a whole bunch of annoying stuff that you probably don’t want done to your machine

To disable this on your browser, go to the following URL: http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager03.html and uncheck “Allow third-party Flash content to store data on your computer”

Keep in mind, you’ll need to do this on each of your browsers

With the release of .NET 3.5 SP1, MS has released a sub-set of the Dundas charting component. They also put together a neat little solution that’ll let you run a number of examples/samples locally so you can get your hands dirty. If you’re looking to do any work with the charting components, or just play around getting these samples should definitely be your first step as the basics will be self-explanatory. The link for that is here.

Now that we got the boring introductory stuff out of the way; the .NET charting component gives you a few different choices when it comes to rendering your chart/image.

Temp directory/ImageTag/ImageUrl Method

This is what I’d consider the simple/out-of-the-box method. Basically, when you create your chart either in the designer or in a code-behind you can specify where the chart should live. This means that ASP.NET will create a chart based on some data that you provide, dump it in a temporary directory, and then you’ll refer to it just as you would any other image.

In other words, your designer markup may look like this:

And, at runtime, the server will spit out something like the following:

Look familiar? That’s roughly what an ASP:Image control would render to had you dropped one of those onto the page. The only difference is that your SRC tag points to a HttpHandler that you specified in your web.config.

In any case, using this method is very straight forward and your client’s browsers will cache your charts just as they would any other image. Of course, the image file that gets cached will look like this:

ChartImg.axd?i=chart_00090164d2f6498095a78f42f0b28216_0.png&g=ec1fd46ebf42485894656b42606e5b27

…The MSDN documentation states that for static data, this caching improves performance. However, in my experimenting even with static data a refresh of the page causes the querystring parameters to change…which means you will need to pull it back down from the server, which also means the browser cached it for nothing. (Although this is what my experimenting indicated, I’m wondering if I missed something. Information to the contrary is welcome…anyone…?…crickets?)

Binary Streaming Method

Now, if you looked at the MS Chart Samples solution, you’ll notice that I’m skipping a couple of “rendering methods” here. That’s largely because I’m thinking if you’re still reading this, you already know you can render a chart in an iFrame, and because their guidance on rendering charts within legacy websites is essentially “use Binary Streaming”.

Binary Streaming is implemented by doing either one of the following

Keep in mind an asp:Image control is getting translated to an IMG tag anyway. In both cases, SomeChart.aspx contains the designer construct for a chart. Something like the following [which is snipped]:

Or…

Keep in mind an asp:Image control is getting translated to an IMG tag anyway. In both cases, SomeChart.aspx contains the designer construct for a chart. Something like the following [which is snipped]:

<%@ Page Language="c#" Inherits="Samples.SomeChart" CodeFile="SomeChart.aspx.cs" %>


	
		

			
			

With this method, you’re basically telling the chart that you’d like it to return a Binary Stream (surprise). In essence, the content of the server’s response will be the string representation of the binary object which your browser will render as an image. In a sense, it’s similar to making a request directly to ChartImg.axd directly. The difference here is you’re creating the binary representation of the chart from memory rather than a physical location on disk.

Both of these methods are very easy to set-up and require little to no-thought. I have to admit using a temporary directory feels a little icky but that may just be my OCD kicking in.

There’s another way, though.

If for some reason these two methods don’t jive with you, though, there is another way. It’s sort of hacky – but it works. Basically, you can convert a binary stream to Base64 and return the string directly to the image tag

	

That means that you can generate your chart entirely in a codebehind and then just return the string via an AJAX request.

//Generate your chart
System.Web.UI.DataVisualization.Charting.Chart Chart1 = new System.Web.UI.DataVisualization.Charting.Chart();
…
//Save it to a stream and return it
System.IO.MemoryStream imageStream = new System.IO.MemoryStream();
Chart1.SaveImage(imageStream, ChartImageFormat.Png);
return Convert.ToBase64String(imageStream.ToArray());

All in all the, binary streaming or the Temp Directory method for chart rendering will probably satisfy your requirements 80% of the time.  It would be interesting to see how each of these scale/perform in a heavily loaded environment.  Hopefully, this provided you with a sufficient high-level overview of your chart rendering options. 

I have been playing with both the iHttpHandler and iHttpAsyncHandler lately, and I came across some interesting information.  There are a couple of blog posts out there explaining when to use one over the other (see Mads Kristensen’s post here, or Vlad Hrybok’s post here)

So when does it make sense to use Async?

Consensus seems to be that it makes sense to use the iHttpAsyncHandler for long running operations, so while it probably doesn’t make sense to use an iHttpAsyncHandler for say, loading images, it probably does for having a web-service perform some [relatively] processor intensive work. In my case, I considering using the Async handler for generating XML that is fed to a flash movie.  Still, there was a potential can of worms here.  Per this MSDN article from Fritz Onion…

"There is one remaining problem with this asynchronous handler implementation—it has the potential to create an unbounded number of threads. If a large number of requests are made to the asynchronous handler, all of which take a significant amount of time to service, then you could easily end up creating more threads than the underlying operating system can handle…"

"Building asynchronous handlers to service CPU-intensive requests only adds threads to compete with the ASP.NET thread pool threads and may actually slow down the overall processing time for the request."

The moral of the story, don’t use AsyncHandlers because they *sound* like they’ll give you a performance boost.  Application of the Async handler should be thoughtful and empirically driven.  That said, Fritz does provide a link to a ThreadPool library that Mike Woodring developed, DeveloperMentor, (link here), should you want to take full advantage of Asynchronous capabilities in a thread-safe manner.

You’d think after all that warning I wouldn’t provide the code to create/implement an iHttpAsyncHandler, but since I couldn’t find VB.NET code too easily, I figured I’d provide it here.

Public Class MyAsyncExample
     Implements IHttpAsyncHandler

' You'll need this to read from session
' Implements IReadOnlySessionState
' You'll need this to read/write from session
' Implements IRequiresSessionState

    Private AsyncTask As AsyncTaskDelegate
    Protected Delegate Sub AsyncTaskDelegate(ByVal context As HttpContext)    

    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpAsyncHandler.ProcessRequest
         'Do what you need
    End Sub

    Public Function BeginProcessRequest(ByVal context As HttpContext,ByVal callback As AsyncCallback, ByVal extraData As Object) _
        as IAsyncResult Implements IHttpAsyncHandler.BeginProcessRequest
        Me.AsyncTask = new AsyncTaskDelegate(Addressof ProcessRequest)
        Return AsyncTask.BeginInvoke(context,callback,extraData)
    End Function

    Public Sub EndProcessRequest(ByVal ar As IAsyncResult) Implements IHttpAsyncHandler.EndProcessRequest
        Me.AsyncTask.EndInvoke(ar)
    End Sub

    Public ReadOnly Property IsReusable() As Boolean Implements IHttpAsyncHandler.IsReusable
        Get
            Return False
        End Get
    End Property
End Class

If you’re looking for more information the MSDN link to Fritz’s article, though far from new, is a great place to start.

Enjoy

In the post below I am going to run down a short-list of some of the less-popular performance tips and the reasoning behind them.  There are loads of blog postings and articles on asp.net performance enhancements, and I urge you to check those out as well.  Onto the good stuff…

Session.ReadWrite versus Session.ReadOnly

It goes without saying that using the Session object will incur some performance overhead so if possible it should be turned off in the web.config.
That said, If you’re using the Session object to maintain session in your application…
Ensure Session.ReadOnly is true rather than using Session.ReadWrite across the application.  There is more information in the link below, however the short story is there is no ReadWriterLock done if Session.ReadOnly = true.  From this MSDN link, “ReaderWriterLock allows multiple threads to read a resource concurrently, but requires a thread to wait for an exclusive lock in order to write to the resource.”  This will make a fairly significant difference if sessions are being managed in a state database, in which case only one-trip to the database is made when using ReadOnly, rather than two while using ReadWrite…which leads me to…

Optimizing your Session when using Out-Of-Process (E.g., State Server or State Database) Session Management

When using out-of-process session management methods objects must be serialized on their way into the state server or state database.  Naturally, this means the data within the session object must be deserialized on the way back out [to the application].  In order for this to work you’ll need to add the [Serializable] attribute to the beginning of the class that needs to go into the session object.  For example…

[Serializable]
public class User{
    public string firstName; //Small text field
    public string lastName; //Another small text field
    public string usersLifeStory; //Is a large text field
}

As you may infer from my not-so-clever comments, there may be a problem with this.  Let’s say the user object needs to be stored in my session object [and therefore needs to be serializable], but there are some large, or otherwise inefficient fields in this object (such as non-primitive types).  For the purposes of this example, let’s also say that I don’t need to store my user’s life story in my session object because it’s only displayed on one page where I can pull it from the application’s database.  The .NET framework makes it very easy to exclude properties within my object from being serialized.  In fact, it’s as easy as adding a few more attributes.

[Serializable]
public class User{
    public string firstName; //Small text field
    public string lastName; //Another small text field
    [NonSerialized]  //Prevents usersLifeStory from being serialized
    public string usersLifeStory; //Is a large text field
}

Easy peasy.  Note that this means the "usersLifeStory" variable will not be accessible via the session object, of course.

Cache and…

think about your caching strategy before you go developing pages or user controls willy nilly.  This will make using the .NET frameworks caching features much easier and will hopefully prevent you from having to make some logic work differently just so you can cache…this will make life especially easy when using features like output cache substitution and creating methods/strategies for querying your DB.  Again, caching is something you should be thinking about before you launch your IDE.

There are tons of resources for learning about output caching, data caching, and the other features the .NET framework provides, so I’m going to skip that.  I am, however, going to mention a really easy way to automagically cache return values from WebMethods/Web-services because I don’t see it mentioned very much. 

public class ExampleService{
    //The cache duration attribute handles ALL caching for you
   [System.Web.Services.WebMethod(CacheDuration=60)]
    public string GetSomethingFromSomewhere(){
        //Logic to get some data from a data-source
    }
}

That’s it…Just add the CacheDuration attribute and you’re good to go.

Update [1/5/2009]: Scott Mitchell has just posted a great, and concise article on per-request-caching.  This is easy-to-use and powerful functionality.  Read the article here.

Use HTTP Compression!!!

Maybe it’s the luck of the draw here, but in my experiences most developers/sys admins/etc for some reason or another don’t enable HTTP Compression, either deflate or GZIP.  I’m sure there are some legitimate reasons for not enabling this functionality for some applications, but everyone else should absolutely have it turned on.  Yes, it’s going to cost some CPU but you can play with the settings.  Bottom line is you will see a dramatic difference in page response times.  Keep in mind you can configure HTTP Compression to compress a number of file-types, including CSS/JS/HTML/ASPX/ASMX/ASHX etc. 

Also, I came across this post doing some research the other night – looks like Mads did some testing on GZIP versus Deflate.  The results are interesting…I have yet to do some testing on my end.

For some reason or another the IIS6 team didn’t give us an GUI to turn on/off HTTP Compression, so you need to go into the metabase.  It’s really only confusing the first time you do it.  There are a number of good tutorials on the web.  I think this is the one I used.  You’ll probably want to ensure HTTP Compression is on by using a tool like HTTPWatch, or its FireFox equal…the name of which currently slips my mind.  Google is your friend :)

Be careful with the App_Themes folder!

I don’t have any screen shots handy, and I’m not at my office so you’re going to have to trust me on this but…Be careful what you put into app_themes.  No matter what you reference in your pages using the <style> tag, ASP.NET/VS is going to load all the style-sheets you have in app_themes.  This means if you’re using a very specific style-sheet on one page (say, for a prototype, jQuery, or script.alicio.us library) that the JavaScript is going to get loaded every.single.time.   So, just to be clear here, no matter what you do, VS is going include all the CSS (or other) files you have in your app_themes folder.  Best idea IMHO is to use this strictly, well, for your themes and create another folder for your CSS, and another for your scripts.  Just don’t use app_themes as your miscellaneous include folder.

Be careful how you populate objects!

Okay, I’m sliding this one in as a general tip just because it’s a bug I discovered in some code I was going through.  Okay, it *may* have been my code, but no one can prove anything.  In any case, I was populating an object and calling a second method within the context of a USING block.

public Employee GetEmployee(int EmpId){
    using (Connection)
    {
	SqlDataReader dr = SqlHelper.ExecuteReader(Connection, CommandType.StoredProcedure, "GetUser", New SqlParameter("@ID",EmpId);

        _firstName = dr[0];
        _lastName = dr[1];
        _photo = GetEmpPhoto(EmpId);
    }
}

public byte[] GetEmpPhoto(int EmpId){
   using (Connection)
   {
	return SqlHelper.ExecuteReader(Connection, CommandType.StoredProcedure, "GetPhoto", New SqlParameter("@ID",EmpId);
   }
}

What happens in the above scenario?  I’ll give you a hint, it’s not good.  The call to GetEmpPhoto() in the GetEmployee() method spawns a new connection to the database within the GetEmpPhoto() method.  The problem is the connection spawned within GetEmpPhoto() never gets closed (or returned to the pool).  This is probably a pretty subjective case, but in any case doing stuff like this is basically asking for trouble.

There are probably an infinite number of applications tweaks to increase performance, including some of the more popular ones listed below that you can easily Google and find information on.  In this entry I’ve tried to explain some of the lesser-known/lesser-implemented tips I found useful.  Be sure to get the following items out of the way when you’re looking for performance gains.

- Disable viewstate (In web.config or on a control-by-control basis.  Don’t forget about control-state).   Also, be sure not to store any non-primitive types in viewState as you’ll big a large price in terms of performance.  I have seen some suggestions on forums informing people to use the session object, instead.  I’d be wary of this as well.

  1. Set debug="false"  This shouldn’t need much explanation.
  2. Check for isPostBack, and isCallBack in page.Load() to avoid re-loading unnecessarily
  3. Minify CSS/JS
  4. Compress images
  5. Use AJAX not only when convenient, but when it will enhance performance

Omar Al Zabir does a pretty good job of explaining some of these items.  I would check out this article on codeProject and his blog for info on the above or just do some googling.

Hope this helped!

Sanjay

For my current project I needed to create some logic for users to upload an image…only problem was the image had to be of a fixed size, and therefore aspect ratio.  Enter the need for an image cropper.  You’ve seen them before on a number of sites, like linkedIn, facebook, and everywhere else.  I began my journey of trying to find one.  There are a fair amount of tutorials/code snippets on the web that illustrate how to do this from the client-side using JavaScript.  I also came across some articles on codeProject and such as that explained how to crop images on the server-side.  What I couldn’t find was an article that tied the client-side JavaScript and the server-side cropping together.  And that’s exactly what this article is.
Before I get into the fun stuff…the process is really as follows

  1. User crops image on the client-side
  2. Track the X & Y coordinates, as well as the height and width of the box the user drags over the image
  3. Use the server-side code to actually crop the image [providing the coordinates and dimensions from step 2]

That’s really about it.  I should also say that all the JavaScript I used was obtained from http://www.defusion.org.uk/code/javascript-image-cropper-ui-using-prototype-scriptaculous/

It’s a slick piece of code – please check out the site for updates (I believe version 2 is a work in progress) and to donate.
As for the .NET code (C#) – you can obtain it from here:

You’ll need to make sure that you provide write permissions to the directory where you want to save the new, cropped image.  Check out line 19, where I set the value for the CROPPED_SAMPLE_PHOTO_URL constant string.

Note: The demo and the download work slightly differently.  This is mainly because I’m saving the image to a session variable for the demo, but using the file system in the download.

As for the code, the heart of it is really the CropImageFile method, where you re-draw the image taking into account our coordinates and dimensions. 


protected byte[] CropImageFile(byte[] imageFile, int targetW, int targetH, int targetX, int targetY)
{
        MemoryStream imgMemoryStream = new MemoryStream();
        System.Drawing.Image imgPhoto = System.Drawing.Image.FromStream(new MemoryStream(imageFile));

        Bitmap bmPhoto = new Bitmap(targetW, targetH, PixelFormat.Format24bppRgb);
        bmPhoto.SetResolution(72, 72);

        Graphics grPhoto = Graphics.FromImage(bmPhoto);
        //Adjust settings to make this as high-quality as possible
        grPhoto.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        grPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        grPhoto.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

        try
        {
            grPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, targetW, targetH),
                                targetX, targetY, targetW, targetH, GraphicsUnit.Pixel);
            //Only JPG format for this demo
            bmPhoto.Save(imgMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch (Exception e)
        //removed code to stay concise

	return imgMemoryStream.GetBuffer();
}

Enjoy!

UPDATE 6.18.2008: You can download the file from here

Alright, so I wanted to build a dynamically/DB driven role-based menu system utilizing framework 2. I started with this article… http://msdn.microsoft.com/msdnmag/issues/06/02/WickedCode/

And then converted to VB.NET…Not to come across some items that I needed to change…

I came across the following errors:

“’System.Web.Caching.CacheItemRemovedCallback’ is a delegate type and requires a single ‘addressof’ expression as the only argument to the constructor”

Which required this line “New CacheItemRemovedCallback(AOnSiteMapChanged))” in the BuildSiteMap() function to be changed to “New CacheItemRemovedCallback(AddressOf OnSiteMapChanged))” No biggy.

Then there was some funky stuff going on with NULL values (mainly in the “description” and “parentID” columns” Turns out there was a bunch of this going on..

Dim title As String = IIf(reader.IsDBNull(_indexTitle), Nothing, reader.GetString(_indexTitle).Trim())

Which was freaking out because of the NULL values (see http://weblogs.asp.net/psteele/archive/2003/10/09/31250.aspx)

So I added a simple function “CheckNullRefs” to account for that.

Lastly, it looks like the “Roles” property from SqlSiteMapProvider was actually giving me the _number_ of roles assigned to a siteMapNode rather than a collection of the actual roles themselves. So for example roles=”2” instead of

roles{0}=”Users”

roles(1)=”Admin”

I added a public array list, and then added the line below to the “CreateSiteMapNodeFromDataReader” function.

roles = ArrayList.Adapter(rolelist)

I’m sure there is a more elegant way to do all of this…but figured this would be helpful since I found little to no info on it by googling.

Update! I had a, uhm, "feature" in my code..the signature of the ReplaceNullRefs was wrong (was accepting ByVal rdrVal As String instead of Integer.  Thanks to Benjamin Howarth for pointing this out!

Update 9/20:  I’ve updated the ReplaceNullRefs function below, thanks Rob!

This allows me to dynamically build my menu by doing the following in the MenuItemDataBound function…

 Protected Sub PublicMenu_MenuItemDataBound(ByVal sender As Object, ByVal e As  MenuEventArgs)

        'Users can be in multiple groups so...if the roles attribute of a siteMapNode contains one of the roles that a user belongs to

        'do not remove it.  Remove all others.

        If (UserRoleName.Length) < 1 Then
            UserRoleName = Roles.GetRolesForUser()
        End If

        Dim blmRemoveRole As Boolean = True

	For i As Integer = 0 To UserRoleName.Length - 1
            If CType(e.Item.DataItem, System.Web.SiteMapNode).Roles.Contains(UserRoleName(i)) Then
                blmRemoveRole = False
                Exit For
            End If
        Next

        If blmRemoveRole Then
            If e.Item.Parent Is Nothing Then
                Me.MainMenu.Items.Remove(e.Item)
            Else
                e.Item.Parent.ChildItems.Remove(e.Item)
            End If
        End If
End Sub