ASP.NET 4.0 Url Routing and Modules
Was working on an ASP.NET website this past week that got flipped over to ASP.NET 4.0 without the team really being aware of the change. A very apparent bug popped up, where a http module we had running on every request (for security purposes), had the current identity user coming back as NULL only on specific URL’s. With some testing and debugging, we found those URL’s to be directories when the module would fail. After finding that I immediately thought about how the .NET 4.0 URL Routing feature might be affected by this?
It turns out that modules are not loaded on every request. In this instance the Membership module needed to be loaded. Essentially the solution is to manually add the required module in our web.config and removing the entry (with a remove statement) from the inherited entries. Be sure to set the precondition=””.
I know I have explained this all very poorly, but you get the gist. Check out this article on routing in IIS7 for all the details!
http://www.heartysoft.com/aspnet-routing-iis7-remember-modules
DataTable .Select and .RowFilter Escaping with Apostrophe’s
Posted by travis in .NET Framework, C# on July 25, 2011
One of the great things about the DataTable or DataView is its ease of ability to Sort and Filter data. Often I utilize the .Select method of DataTable. This involves writing a short where clause string to provide to the method. The contents of this select filter in my scenario actually contained an apostrophe in the string. Thus I had something like this:
table.Select(“column1 = ‘Apostrophe’s’”);
You will note here, the single apostrophe used inside the value. Unfortunately, this is not automatically handled by the select logic, rather we need to properly escape our values. Interestingly enough, I found this article:
http://aspnetresources.com/blog/apostrophe_in_rowfilter
This article talks about Microsoft’s suggested usage for escaping this instance with a back slash:
table.Select(“column1 = ‘Apostrophe\’s’”);
But, that fails horribly. You actually escape the character in this usage, with a second apostrophe, much like you would in a SQL statement:
table.Select(“column1 = ‘Apostrophe’’s’”);
This means that you simply have to use a global replace on the contents of your value if its dynamic (i.e. stringVal.Replace(“’”, “’’”); ).
MSBuild Can’t Find Secondary References
Posted by travis in .NET Framework, Visual Studio on May 19, 2011
That is right, you read the title correctly. MSBuild in versions 2005, 2008 and 2010 of VS does not find and include secondary references. This means that if you have a project Class Library that contains “Content” items that are supposed to copy to the bin, if you reference that assembly, MSBuild publish will not output those files into your website bin (don’t get confused with a Visual Studio Publish – that works fine still!).
What does this mean?
When grabbing output from Build Server under _PublishedWebsites (from the drop location, Releases), don’t expect to see this content in the bin. This makes auto-deployment scenario’s increasingly harder.
Microsoft’s recommended work around is to include that content item that is a secondary reference, directly in your Web application project…..LAME!
Information all found at these articles:
http://social.msdn.microsoft.com/Forums/en-US/tfsbuild/thread/b42c1097-463c-4f20-a171-f9b06d90617a/
http://sstjean.blogspot.com/2006/11/msbuild-cant-find-secondary-references.html
External Project Resource (RESX) Consumption
Posted by travis in .NET Framework, ASP.NET, C# on May 19, 2011
Using resource files can sometimes be troublesome when you need a particular resource in both a Web application mark-up or code-behind and inside a business tier or data model. When you push the Resx file further back into you’re project, you’ll likely need to create it as an embedded resource for easy entry. From there you can quite simply access that resource in any code (as long as you’re referencing the project containing the resx file), as follows:
Namespace.ResourceFileName.ResourceManager.GetString(”ResxItemName“);
You can of course add a “using” statement and remove the Namespace from it. You can also use this in an .aspx or .ascx markup file:
<%= Namespace.ResourceFileName.ResourceManager.GetString(”ResxItemName“); %>
When using in markup, you can also add a Namespace Import and reference without the Namespace prefix:
<%@ Import Namespace=”Namespace” %>
<%= ResourceFileName.ResourceManager.GetString(”ResxItemName“); %>
In some cases, it may make sense to create yourself an entire Class Library Project purely devoted to storing all your Resource files. Then you can simply use that reference anywhere you need it without worrying about circular dependencies.
Dynamic WCF Client Endpoint
WCF is fantastic for easy communication between applications. WCF is normally implemented using binding configurations embedded in each application. You usually have configuration for your server, and also your endpoint for your client. I found myself in a situation in which I had no readily available configuration file to use, as well, the endpoint address was dynamic itself based on the application that is consuming this library. Thus, I began searching on how to programmatically setup your client endpoint. Turns out, it is not that hard. Check it out:
var binding = new BasicHttpBinding();
var endpoint = new EndpointAddress(“http://SPS02:4762/StatService.svc”);
var channelFactory = new ChannelFactory(binding, endpoint);
// create and make channel call
IStatService service = channelFactory.CreateChannel();
StatResults results = service.PostStats(“hello world”);
In my example, I have created a custom statistics posting service. So, IStatService and StatResults is just the service contract created for must WCF service (these would change with your application). Notice the string passed in indicating the location of the service. This obviously creates a BasicHttpBinding configuration only, but you should be able to alter any of your standard WCF Configuration settings programmatically here too (make sure they match the service though J). With this above implementation I have NO config file (and the endpoint address is passed to this code – not hardcoded as shown above).
Elmah Error Logging without HttpContext
For those that use or have used Elmah for error handling, you may have gotten quite use to its logging modules and handlers. If you are not quite sure what Elmah is or what it can do…. you should probably check it out: http://code.google.com/p/elmah/
However, Elmah is a pure ASP.NET architecture in the sense that you are going to need an HttpContext to log an error. 9 times out of 10, that’s not a problem at all. That is until you find yourself inside something like an ASP.NET Web hosted endpoint for a WCF Service, in which you have no HttpContext what so ever, even though you are in a web application. Though, the environment and everything else is a perfect scenario for Elmah usage. Well…. check out how you can log to Elmah without an HttpContext:
- The GetDefault method takes an HttpContext, however, you can just get around that by passing “null”. It won’t cause an error. You just won’t see HttpContext related information in the error details.
- The “Log” method requires an object of type “Error” (which is an Elmah error). You can easily create an Error object by passing a “System.Exception” object into the constructor.
Now you are good to go!
Custom Dundas Chart Handler
Dundas charts are fantastic in terms of some of the charting ability. In configuration you can specify exactly how you want to store the charts you are creating. This includes memory and file system for the most part. However, there are some issues to be aware of when using some of the default handling capabilities with Dundas Charts. Check it out:
Memory – This is the fastest, easiest, best performance process to store your charts between creation and pickup. However, if your system is load balanced without some type of shared state device (i.e. State Server), you simply cannot use Memory as an option.
File System – Usually an alternative when storing in memory is not an option. Allows you to store to the created images to a location you specify on the file system. This location, unfortunately, has to be accessible via your website in order to load the images. This means for a load balanced system you may want to create a central share that both webservers can write too, that map to a virtual directory on each website of each machine. Also, the files will overwrite each other given the configured timeout period, but the files will never be cleaned up once created.
Obviously, if you can use memory for storing your charts, then you are golden from most perspectives. The problems and limitations arise when you begin using the File System functionality (likely for a load balanced environment). This is where you may need to implement a custom handler for your charts. Dundas provides an easy methodology for a custom handler (given you follow their pattern).
Firstly, you need to create your custom handler as follows:
{
public myimagehandler()
{
}
#region IImageHandler Members
public bool Exists(ChartHttpHandler.StorageSettings settings, string key)
{
throw new NotImplementedException();
}
public void Remove(ChartHttpHandler.StorageSettings settings, string key)
{
throw new NotImplementedException();
}
public void Retrieve(ChartHttpHandler.StorageSettings settings, string key, out byte[] data)
{
throw new NotImplementedException();
}
public void Store(ChartHttpHandler.StorageSettings settings, string key, byte[] data)
{
throw new NotImplementedException();
}
#endregion
}
Some things to know about this:
- Notice the class name is lower case. This is quite weird I know, but your class name has to be lower case for this to correctly implement the ImageHandler. In the dundas code itself, when it uses reflection to open the class, it uses a “ToLower”. Essentially, it won’t work if your class name is uppercase at all. TISK TISK DUNDAS !!!
- Implement Interface: Of course Dundas expected interface is defined by IImageHandler… so be sure to implement this.
- StorageSettings: This object is passed into each interface method (following). It contains all information from the configuration (including custom configurations you will want to use).
http://support2.dundas.com/OnlineDocumentation/webchart2005/topic990.html
- Exists Method: Determines if the dundas chart exists – should return true or false indicator based on the key provided.
- Remove Method: Removes a specific Dundas image from storage with the specified key.
- Retrieve Method: Core method used when the handler requests an image. Return the image data into the output variable “data”.
- Store Method: Occurs when the chart is created (before it has been requested). Store the image in “data” given the key, for “Retrieve” usage later on.
Obviously in this custom handler class, you can easily store information however / wherever you want. Whether you want to store in a database or perhaps to a file system (which is not accessible via web), you have complete control at this point. You could potentially write to the file system and alter the name of the file based on an authentication key (i.e. the user or some other context related to your application). An example is a user specific application that associates an encrypted value to the file name based on the company name / user name / regular dundas key. This ensures uniqueness and security for storing and retrieving the charts.
The last thing you need to do is configure Dundas Charts to use your custom handler now. Alter / add the following app setting key/value:
<add key=”ChartHttpHandler” value=”handler=namespace.myimagehandler, projectname” />
Of course for configuration, you probably have some additional items you’ll want to store. So you can also add any additional items you want (can be complete custom), that you can pull out of the StorageSettings object in any of the interface methods:
Example:
<add key=”ChartHttpHandler” value=”ImageType=.png;MaxImages=5;handler=namespace.myimagehandler, projectname” />
int maxImages = Convert.ToInt32(settings.Params["MaxImages"]);
You can also use other StorageSettings like the StorageType to determine if you should store in database, etc.
CSS Tidy Integrated with Visual Studio
Posted by travis in HTML & CSS, Visual Studio on March 18, 2011
CSS documents can often times be quite scrambled when dozens of developers are adding their styles in. Some people like their styles built with one class/id per line (closed) and some like it with one property/attribute per line (open). Either way, if you receive the document in the particular format you don’t want it or perhaps full of inconsistent formatting it is a real pain to format it / read.
So first thing you can do is use an online compressor and quickly copy and paste it back and forth, like this one (works with JS an CSS):
Open Version:

Closed Version (my preference – easier to read and find a single style):
Recently another developer introduced me to CSS Tidy: http://csstidy.sourceforge.net/
And you can use an online version of CSS Tidy here to try it out: http://cdburnerxp.se/cssparse/css_optimiser.php
I saw you could download it and use it from command line (as an .exe). That got me thinking that this could easily be added as a Third Party tool into Visual Studio Tools menu like this:

I had to add an option for both opening and closing. Simply go to, Tools -> External Tools. In the dialog that comes up, configure to work with CSS Tidy has follows:
Title: Whatever you want to name it…
Command: the location of the CSSTidy.exe (which you can download from http://csstidy.sourceforge.net/download.php ).
Arguments (choose one):
- To open tags: $(ItemPath) –preserve_css=true –template=Standard $(ItemPath)
- To close tags: $(ItemPath) –preserve_css=true –template=high $(ItemPath)
And that is at. No simply open the file in Visual Studio to change, then run one of these commands from the Tools menu and will get a notification that file has changed (click Yes to reload). Note – if using with TFS you will need to have the file checked out before CSSTidy will have access to it.
There is, of course, a ton more switches and templates to use….check ‘em out for yourself to tailor the commands to your style: http://csstidy.sourceforge.net/usage.php
Retrieving an Assembly PublicKeyToken
Posted by travis in .NET Framework, Visual Studio on March 7, 2011
Getting the PublicKeyToken
The PublicKeyToken always tends to slow you down it seems. Your moving right along in development, then you have to jet out of Visual Studio and grab the public key token. Some people I know use reflector to quickly grab the token. That seems like a lot of work though. The fastest way I have found to do is to quickly run your “Visual Studio Command Prompt” with the following:
Sn –T assemblyName.dll
Of course when you run the above you will need to be in the same directory as the assembly. And it spits out the PublicKeyToken right at you:
Now that is great! But what is even cooler, is you can simply plug it into Visual Studio if you want, so you never have to leave the comfort of the dev environment.
PublicKeyToken Visual Studio Integration
1. Head on over too Visual Studio, and open up Tools -> External Tools
2. Enter the information for the tool as follows:
The command path varies per system, but by default is: C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\sn.exe
3. And that’s it. All you have to do is open up a file inside any project, then go Tools -> Get SN Token and the PublicKeyToken will appear in the output window of VS.
HTML 5 DOCTYPE Caution
Posted by travis in HTML & CSS on February 5, 2012
So your using HTML 5 now. You just put in your DOCTYPE as:
<!DOCTYPE html>
You open up your HTML 5 page in IE9 to discover that it forces you automatically into IE9 Compatibility view! WHAT? Why would I want to be in compatibility mode when I’m building a new website?
The key is that in the specifications you cannot have anything render before the DOCTYPE. So simply remove any comments you may have put in above the DOCTYPE and you’ll notice everything is now working as expected! Makes sense….but very disappointing if you lost some time to something so inconspicuous.
comments, doctype, HTML5
No Comments