 Sunday, January 20, 2008
Interpolation is just a fancy word for variable substitutioin in a string. According to the free dictionary interpolate means: 1. To insert or introduce between other elements or parts. 2. a. To insert (material) into a text. Perl does this very well, other language less so. Less is a hybrid of the C# method for string formatting. I find it pretty convenient when creating a lot of dynamic html to insert using that oh so hander innerHTML property. Remember, innerHTML is usually the fastest way to add dynamic html. function format(format) { var params = arguments; var toReturn = format;
for (var i = 0; i < params.length - 1; i++) { var rString = '\\$\\{' + (i) + '\\}'; var regex = new RegExp(rString, "g"); toReturn = toReturn.replace(regex, params[i + 1]); }
return toReturn; } Here's the original interpolation function that extended the string object. I don't really think that extending builtin objects is a great idea unless there is no other way.
 Tuesday, January 08, 2008
Have you ever need to browse to several pages and print them? It seems like it should be easy and it is with this little Python script.
I had an Intranet based system that displayed items in a browser. The manager of the group I built this for asked for a hard copy of every item that fit a certain criteria. So instead of them going to over 400 pages by hand I just created this simple script.
It worked like a charm.
#start script
from win32com import client import time
ie = client.Dispatch("InternetExplorer.Application")
def printPage(url):
print "printing " + url ie.Navigate(url)
while ie.Busy: time.sleep(1) print 'navigating...'
print 'starting print job...' ie.ExecWB(6, 2) print 'executed print job.' while ie.Busy: time.sleep(1) print 'printing...'
printPage("http://google.com") ie.Quit()
#end script
Sources:
http://www.darkcoding.net/software/printing-word-and-pdf-files-from-python/
http://www.grimsworld.org.uk/printie.html
 Wednesday, December 05, 2007
http://www.aspfaqs.com/webtech/042606-1.shtmlOne of the best (not to mention easiest) paging methods I've seen. In fact it requires no temp tables or table variables. Paging is something that is so common yet seems to hard to get right and keep performant that it pays to have a nice easy template to start from. I've posted this mainly for my own benefit so I have a permanant bookmark to this code. The example uses a stored procedure, but its important to understand that a stored procedure is not required to make this work. Here's the code: CREATE PROCEDURE [dbo].[usp_PageResults_NAI]
( @startRowIndex int, @maximumRows int ) AS
DECLARE @first_id int, @startRow int -- A check can be added to make sure @startRowIndex isn't > count(1) -- from employees before doing any actual work unless it is guaranteed -- the caller won't do that
-- Get the first employeeID for our page of records SET ROWCOUNT @startRowIndex SELECT @first_id = employeeID FROM employees ORDER BY employeeid
-- Now, set the row count to MaximumRows and get -- all records >= @first_id SET ROWCOUNT @maximumRows
SELECT e.*, d.name as DepartmentName FROM employees e INNER JOIN Departments D ON e.DepartmentID = d.DepartmentID WHERE employeeid >= @first_id ORDER BY e.EmployeeID
SET ROWCOUNT 0
GO
 Friday, October 12, 2007
ProMesh is too immature at this point to complete the project I am working on. I think given a few weeks or months this framework will be top notch.
Right now however I am constantly getting the latest version to get around some bug only to discover another bug. I don't want to come across as negative about ProMesh.Net, again I think it will be one of the best frameworks out there once its matured a bit. -- Update -- Again, to make it clear I think ProMesh is a good framework. I have released a small project with it and it workds great. My problems are with the validation scheme that changed and a looming deadline. I am still using it for other projects. My rants below are about me screwing around too much and finding myself short on time and having to use WebForms. -- End Update --
Back to the present, I need to get work done. I have spent a little too much time playing with ProMesh and some various other languages and frameworks. I neeed to get some work done. So I'm back to ASP.NET WebForms.
It's telling how poor WebForms are as I can barely get a simple form working correctly. Control postbacks and the whole business is absolutely frustrating. I want to make a form that changes which controls are displayed based on the value in a drop down box. Simple right? Wrong. I'm once again battling the stupid page lifecycle. Is this really the best we have?
I'm looking forward to seeing Microsoft's MVC for ASP.NET. I hope that takes .NET web development in the right direction.
Many people compare WebForms to WinForms. Something about WEbForms being VB6 on the web. Well I can tell you VB6 was never this unecessarily complicated. Good grief.
I think it's a bad sign when you spend 80 percent of your development time working around your framework instead of with it.
 Thursday, July 19, 2007
Joel on Software's admin dude wrote a post about how they are doing db backups.
http://www.michaelgorsuch.org/wordpress/2007/07/11/some-times-you-have-to-roll-your-own/
Funny thing is that this is how all databases fundamentally perform
backups. Just makes me think that once you get X years under your belt
you come to the conclusion that you've seen it / know it all.
Fundamentally, this stuff is simple, the problem comes into play when
MS (or vendor of choice) tries to layer multiple extra layers of shite
on top of a simple concept.
Html, javascript, css are easy (compared to multi-threaded servers and
C++). ASP.NET makes them much more complicated then the have to be.
I'm currently in the process of removing all of the ASP.NET AJAX CRAZY
framework out of the whatsyour20.com as it's just too damned
complicated for what you get. Also I think the ASP.NET page life cycle
is ridiculous. We stopped teaching ASP.NET for web development at the
college I used to teach at because it was just too hard for students to
figure out. Ironically, MS made ASP.NET follow the desktop paradigm to
get the Windows Forms dudes (like myself) to buy in, which caused
ASP.NET to become almost incomprehensible for those that wanted to
learn web development without having any desktop experience.
There is a reason PHP and MySQL are so popular. Simplicity has a place
and that place is HUUUUUGE. It's a big house on the hill overlooking
the lake with a great view.
The point of this rant is that sometimes we make things so complex by
trying to make them simple. Instead are we perhaps better off if we
let the complexity stay were it needs too.
ASP.NET missed being one of the best pieces of software ever designed.
Why? Page lifecycle (why must i figure out if i need init, load, pre
init, pre load after load, after init, and the if (postback == false) {
madness). The dirty little secret about ASP.NET is that nobody needs a
freakin' data grid! They are completely useless. Html tables are easy
to make. Grids are ridiculous and bloated and don't support Ajax worth
a damn.
Why I'm at it I should rant about how SQL Server 2005 leaves out
features already in 2000. But this post is getting too long as it is.
ASP.NET needs a sane alternative implementation that works with the web instead of against it.
 Wednesday, May 23, 2007
There is a discussion over at Scott Hanselman's site about URL Rewriting in ASP.NET. I found a similar article about URL Rewriting in ASP.NET on Coding Horror. Synopsis:Here is a brief synopsis of the problem. In order to have an http module or handler take care of your url rewriting you must have all requests sent to aspnet_isapi.dll via application extension mapping in IIS 6. Here is an example: I want http://whatyour20.com/modules/view-location.aspx?locid=1234 to instead look like: http://whatyour20.com/locations/yellowstone-national-park/ I do this for several reasons. The number one reason is SEO. We want google to give google a good idea of what this page is about. Obviously the latter url does the much better. It also gives the users an idea of what the link is about. Number two, it makes our links hackable. Number 3, it makes our links more aesthetically pleasing. I think that is very important. If I see a url that is meant for people instead of machines, I know the web site creator took some time to dot every i and cross every t. Number four is the less likely option that I will switch technologies and I don't want to lose all my links and there associated page rank if I switch to a new technology or if Microsoft changes thier extension in the future when the next great thing comes out (Silverlight Foundation Server Pages Advanced with SteelRuby, LOL). At whatsyour20.com we use UrlRewritingNet.UrlRewrite to handle all url rewriting duties. UrlRewrite is an asp.net http module that can rewrite any incoming url and it can handle redirects (301, 302). This works great but it doesn't get rid of the aspx extension by itself. In fact no http module or handler can do that because iis uses the file extension to determine which program should handle the request. So we need to have IIS route all requests for the domain (http://whatsyour20.com) to the aspnet_isapi.dll as stated above. The problem with this is that now ALL request will go through asp.net. We may not need this for all requests. In fact this can be a problem as it can hurt performance. I've seen the a claim of 30% performance decrease someplace but I don't remember where right now. However, it's safe to assume that routing static content through asp.net is just not the best solution. Solution:The solution? After the background information we are finally at the payoff. This is how we get the goodness of using asp.net url rewriting via http modules and the associated debugging and high level of control this brings us WITHOUT the downside of routing static content through asp.net. We access all the static content via a sub-domain. We use static.whatsyour20.com to server all the static content on the site (Right now this is mostly images). This is very easy to accomplish. You simply create another web site in IIS, with the path to the same location as your main domain but using the sub domain. On this domain you DO NOT route the requests to asp.net. So on this sub domain all content is handled by IIS because it is static. You could even take that a step farther and put it on a separate server or use another web server that is optimized for static content. Our solution works in a share hosting environment because usually you can set up sub domains on shared hosting. Also you can usually get all requests routed to asp.net if you put in a ticket and simply ask for it. A nice side effect of using sub domains is improved performance on the client side. By increasing the number of hostnames (within reason) we can increase the speed at which the page loads. Here are a few reference articles on multiple domains names to speed up downloads: http://yuiblog.com/blog/2007/04/11/performance-research-part-4/http://www.ajaxperformance.com/?p=33http://www.die.net/musings/page_load_time/Conclusion:Using the presented solution we get a urlrewriting solution that is easy to use and configure (all configuration in web.config), transfers easily between hosting providers (again its all provided by asp.net and web.config) and it improves performance. I'm still looking for any possible downsides. Please let me know if you know of any.
 Wednesday, December 27, 2006
If you have been struggling like me to make your sites XHMTL compliant you realize that it’s not an easy task. Most of the changes are straight forward if you have a validation tool. I code a lot of sites in Visual Studio 2005 and it will complain like crazy if you have invalid XHTML. Hence I try not to write invalid XHMTL because I hate errors and warnings and will compulsively try to make my pages as valid as humanly possible.
One of the areas where I’ve had the most trouble with this is create bookmarks with anchor tags. Most of the examples I’ve seen use the name tag on an anchor so that you can link to it using something like http://example.com/test/#somebookmark. I think this is an underused feature of html as it makes navigation much better and faster, plus it is much easier to link into a page at just the right point with something like this.
When using XHTML you should not use the name attribute as it has been deprecated. Instead you should use the handy id attribute. The id attribute will work exactly the same way and has the benefit of being compliant. Plus you get additional validation of making sure each element has a distinct id. This was a problem with some sites I’ve seen that use name. I see the same name used all over the place. This makes linking to the element somewhat difficult and error prone.
On a related note, did you know that most modern browsers can link directly to any element that has a valid id attribute? This is very handy as you want have to include anchor tags all over you html just to get convenient linking.
Bad: <a name="bookmarkid">Test</a>
Better: <a id="bookmarkid">Test</a>
Best: <p id="bookmarkid">the element i actually want bookmarked can be linked to directly</p>
 Wednesday, November 15, 2006
As you may have noticed, I'm on a performance kick as of late. Here's one more tip for you. Compressing / Minimizing / Shrinking your JavaScript files can decrease download times. Putting your scripts together in one file will also help performance. Here's a good article on reducing page load times from a Google engineer. This article is the source for most of this wisdom. So armed with this new knowledge I went in search of some pre-shrunk versions of the Prototype and Scriptaculous JavaScript Libraries. This is what I found. I still need to test the library but it seems promising. I will keep you posted.
Ok URL Rewriting is good. I won't go into the reasons why but if your searching for it then you already know you want it. If you followed the standard progression you probably started with this MSDN article on URL Rewriting. This implementation works fairly well in ASP.NET 1.x. However, I've run into problems using this implementation in ASP.NET 2.0 with output caching. For some reason it breaks output caching. So what is the solution? Well I'm glad you asked. I've found a solution that works quite well with ASP.NET 2.0 and output caching. The UrlRewritingNet.UrlRewrite assembly provides all the features of the original URL Rewriter mentioned above but also fixes the problems with output caching plus adds some interesting features like redirecting and programmatic access to the rewrite rules at runtime (say that ten times fast!). I'm currently using this on http://www.whatsyour20.com and I must say it works quite well. I also like the fact that it is an active project and it even has a bug tracker system. There is also a forum for this project. That's always a good sign. Enjoy!
What do you do when you want HTTP Compression to speed up your site but you are using ASP.NET (1.x or 2.0) in a hosted environment? You get HttpCompress from www.blowery.org/code/httpcompressionmodule.html. This is a module that sits inline and handles compression of your .aspx pages and any other mime type that may be handled by ASP.NET. This is a pretty good work around if you don't have permission to IIS to enable HTTP Compression there. Of course that would be a better solution but many hosters won't enable it because of the possible CPU consumption issues. Oh well, get around them by implementing your own solution! I know dasBlog uses it in the 1.9.x version. WhatsYour20.com is also using it at this time. It's been around for awhile, it's configurable and it's easy to use. Give it a try and speed up your site today! One caveat is testing it using ASP.NET Development Server. Check out the link for more info.
 Tuesday, November 14, 2006
So if you're having odd issues with a JavaScript function like WebForm_InitCallback(); which is a built in ASP.NET JavaScript function and you are using the HTTP Compression Handler from blowery and you are testing a site on the ASP.NET development server, I may have a fix for you. In your web.config you should add an exclude statement to exclude the WebResource.axd path: <httpCompress preferredAlgorithm="gzip" compressionLevel="high"> <excludedMimeTypes> <add type="image/jpeg" /> <add type="image/gif" /> <add type="image/png" /> </excludedMimeTypes> <excludedPaths> <add path="WebResource.axd"/> </excludedPaths> </httpCompress>
 Thursday, October 19, 2006
Here's a quick tip to get png's with alpha transparency to show up correctly in Internet Explorer. Instead of hacking you website, hack the picture! Using a utility like TweakPNG, you edit the meta information of the PNG format to display a white background (or whatever color you want). Open the .png in TweakPNG and insert a chunk named bKGD using the Insert menu. Then simply double click your newly created chunk in the main window to bring up a color chooser. Select the background color and away you go.
 Tuesday, October 10, 2006
 Monday, October 09, 2006
I've found yet another blog and post(sheesh) regarding Query Notifications. It's a survey asking some general questions. If you have some complaints or comments head over there and let MS know what you want to see. I'm still formulating my customer solution.
Observation: Microsoft has a habit of assuming their solution should be satisfactory and doesn't really give an example of what to do if it isn't. The user is left to try to piece together a solution that actually works in the real world. So many of MS's examples assume that you are a drag-and-dropping cheeseball that uses SELECT * for queries and the SQLDataAdapterConnectorInterpreterManagerGateway for all things data.
What about us folks who actually want to write code. If I see one more MSDN artcile trumpeting the fact that you don't need to write one line of code, I'm going to puke. Yeah instead of using a first class IDE supported language to write code I want to put some mish mash of bastardized markup into my ASP.NET page. That's a great solution. Try debugging that pile of angle brackets when something doesn't work. Code is good. I like writing code. The IDE supports writing code.
MS for god's sake let me write code!
 Friday, October 06, 2006
 Friday, September 15, 2006
You may have noticed that I have added Google Ads to the site. This is more of an experiment than anything else as I wanted to see how AdSense works and the best way to learn about something is to try it. Obviously this is not a high traffic site but it has been up for a while and there is some very (if I so say so myself) high quality content so I might get some search traffic now and then. My goal is to make enough to pay the hosting bill of the site and hone my SEO abilities so that I can make my other sites better.
If you have a blog I would encourage you to try AdSense or the sponsored search and see if it can take the sting out of your hosting bills. You never know, you may find a new source of revenew that you can introduce your clients to and thus enhance thier profits and yours.
 Wednesday, August 23, 2006
I was testing a new caching implementation for the 20 when I noticed that items I placed in the cache were not staying in the cache.
I ran into this yesterday and luckily I realized what was happening before I did something drastic. The ASP.NET caching facility automagically dumps items out of the cache when roughly 90% of your physical memory is in use. So a laptop with 1 Gig of memory has a pretty good chance of seeing this happen. Load up Visual Studio 2005, Firefox, IE6, the ASP.NET development server and have SQL server running and you are going to get pretty close especially after you've been running all day without restarting any programs or the computer. The two biggest offenders are typically Visual Studio and Firefox in that order. In the defense of Firefox I usually have about 15 to 20 tabs open and I have about 15 extensions installed. Visual Studio can chew up about 400K on its own with all of its child processes running around checking code, looking up help topics etc.
The moral of the story is to shut everything down and then bring it back up so that you have some room cleared out in memory for the obects you want to cache in memory. Seems like a no brainer when you think about it. This is also a good reason to have at least 2GB of memory in your development machine. That's right TWO Gigabytes of memory. Someone at work thought I was crazy when I bought my new home machine with 2GB already installed but after using Visual Studio for a while I knew it would come in handy.
 Friday, August 18, 2006
Here's a piece of JavaScript code that allows you to format strings in a style similar to C#.
String.prototype.format = function() { var params = String.prototype.format.arguments; var toReturn = this;
for (var i = 0; i < params.length; i++) { var regex = new RegExp("\{" + i + "\}", "g"); toReturn = toReturn.replace(regex, params[i]); }
return toReturn; }
Original Source: http://chapnickman.com/2006/02/10/string-formatting-in-javascript/
I love this because I can program in a style in which I am familiar. However does this reduce portability or can it lead to a collision? If we all add our own little extensions to the built in objects will we end up with a uncooperative mess? This comes to mind because of the way the very popular prototype javascript library extends the build in JavaScript objects. Some people people criticize prototype.js pointing out that is monolithic or bloated and lacks documentation. While it is rather large it is also very powerful and everthing works together. I don't have to include 5 different libraries from 5 different authors and hope that they work and play together nicely. The documentation criticism is certainly legitimate as the author provides very little documenation. However many sites have posted articles and even whole user guides that have come in very handy.
I haven't even discussed Scriptaculous yet. Scriptaculous is a visual JavaScript framework that uses Prototype for a foundation. I have used this library for several sites and it works well and that is the whole point. Both of these frameworks Just Plain Work! I don't have to cobble something together each time I need a visual effect or an AJAX updater I can just use something in this toolkit.
There is something to be said for re-using the same set of tools. You become very proficient with those tools over time and you can use them more effectively as your experience grows. I find this especially true of using the .NET framework also.
You can't get anywhere by reinventing the wheel each time you need to build a cart. Use other people's experience and work as a foundation for your own and become more productive.
 Tuesday, June 27, 2006
I'm developing a set of server controls in ASP.NET 2.0 that use several JavaScript, image and stylesheet (CSS) files. One of the problems with distributing controls is that you usually have to send along these files and tell the end user to install them in the appropriate directory.
Along comes ASP.NET 2.0 and the ability to embed resources right into assemblies and then access these resources via URLs. My first impression is that this seems like a good idea but I'm wary because I've been burned by MS's good ideas in the past. My main concerns are debugging and the effect this embedding has on caching.
Caching
One of the problems with frameworks like ASP.NET is that they sometimes take you too far away from the underlying system. HTTP and HTML is rather straight forward. Embedded resources in ASP.NET call the the resources via URL's and use cache headers to insure the browser caches the content correctly. Also the output cache in the form of disk output cache is automatically used to cache these resources. So these embedded resources should still allow a fairly performant solution. My question is still whether this is as good as a plain static file and the caching IIS can perform on these files. I still need to research this.
Debugging
One of the problems I've run into involves debugging. When a JavaScript file is embedded and it contains an error, Visual Studio.NET 2005 will open a file dialog asking for the location of the file. This is a pain as you lose the precious JavaScript debugging ability that we gained with VS 2005. Is this behavior by design or is there something I'm missing in regards to debugging JavaScript as an embedded resource? My tempo ray solution is to keep the JavaScript files in a static folder while I'm debugging and then switch them to Embedded Resources when I'm deploying the control.
However on the plus side of debugging when you change the JavaScript file it is automatically picked up the next time you do a build. The URL of the embedded resource is changed and thus the browser grabs the newer file. However this has a downside in that you must stop the running project to make changes to the JavaScript file and then rebuild the project to have the changes show up.
I've found that the static file path is much easier for debugging.
An excellent article that I've referenced for this post:
http://www.nikhilk.net/WebResourceAttribute.aspx
 Thursday, June 22, 2006
This JavaScript Code will cycle through all elements on a page and find the next one that should recieve the focus. This worked well in IE6 but the results in FireFox where mixed. I don't have time right now to clean it up but I wanted to post it as this is one of those gems that you know you will want in the future.
Original Source: http://www.codecomments.com/message290822.html
Original Author: Daniel Kirsch
// returns the next focusable object for a given one function getNextFocusElement(elm,restart,dir,_looped) { var allElm = document.getElementsByTagName('*'); var found = false; //(start == true); var allowedElements = 'input,textarea,a,button'; if (!dir) dir = 1; var start = dir > 0 ? 0 : allElm.length-1; var end = dir > 0 ? allElm.length : -1; jslog.info('start: ' + start + ' end: ' + end);
for (var i=start; i!=end; i+=dir) { if (!found) { if (allElm[i] == elm) { if (_looped) return null; found = true; jslog.info('i: ' + i ); continue; } } if (found || (restart && _looped)) { if (allElm[i].focus && allElm[i] != elm) { if (isInList(allElm[i].nodeName.toLowerCase(),allowedElements) && isVisible(allElm[i])) jslog.info('i: ' + i); return allElm[i]; } } } jslog.info('starting next loop...'); return (_looped) ? null : getNextFocusElement(elm,true,dir,true);
}
function isVisible(elm) { if (elm.style.visibility == 'hidden' || elm.style.display == 'none') return false else return elm.parentNode && elm.parentNode.style ? isVisible(elm.parentNode) : true;
}
function isInList(aItem,aList,aSep,aCaseSensitive) { if (typeof aItem == 'undefined' || typeof aList == 'undefined') return false;
// make sure, the element is a string. aItem = String(aItem); if (aCaseSensitive !== true && typeof aItem == 'string') { if (typeof aList == 'string') aList = aList.toLowerCase(); aItem = aItem.toLowerCase(); } if (!aSep) aSep = ','; var lString = aSep+aList+aSep; return (lString.indexOf(aSep+aItem+aSep) > -1);
}
 Monday, June 19, 2006
Do you want to limit the imput of a text input (textbox) to valid date characters? Here you go:
// START SCRIPT
function runKeyFilter(e) { if (e.srcElement.readOnly) return;
var key_code = e.keyCode; var oElement = e.srcElement; //alert (key_code);
try { if (!window.event.shiftKey && !window.event.ctrlKey && !window.event.altKey) { if ( (key_code > 47 && key_code < 58) || // numbers on top of keyboard (key_code > 95 && key_code < 106) || // number on numpad at right of keyboard (key_code > 36 && key_code < 41) || // arrow keys (key_code == 35) || // end (key_code == 36) || // home (key_code == 45) || // dashes (key_code == 111) || // forward slash / (key_code == 191) || // forward slash / (key_code == 8) || // backspace (key_code == 46) || // delete (key_code == 9) || // tab (key_code == 16) //SHIFT TAB ) { e.returnValue = true; return; } } } catch (ex) { alert('Error Message: ' + ex.message ); } // if we get here then we didn't have a number e.returnValue = false;
} // end runKeyFilter()
//using the helper functions from prototype.js Event.observe('|CONTROL|', 'keydown', runKeyFilter, false);
// END SCRIPT
 Friday, June 09, 2006
I do a lot of web development. Unfortunetely at work all the folks out on the floor have Internet Exploder oops I mean Explorer. So I do most of my testing in IE6. The problem comes in as we start to do more DHMTL (AJAX) on our sites. Ofter you need to view source to see what is rendered. Well of course IE just gives you little old notepad and calls it good. Firefox does a better job by at least highlighting syntax. Well, I've found a good solution for IE. Notepad++. Two big bonuses here. Excellant syntax highlighting and code folding. Code folding is the ability to expand and contract sections of code so it's out of your way when you don't want to look at it. The syntax hightlighting is great plus Notepad++ is one great editor in general. I use it for heavy duty JavaScript development because of the code folding and the lings that line up the beginning and ending tags and code blocks. Give it a try. http://notepad-plus.sourceforge.net/uk/site.htmI believe it promts you on the install to act as the view source client for IE.
If Jerry Seinfeld were a programmer he might ask "What's the deal with configuration files having to be in XML format?". I just find them to be incredibly hard to read and decipher. The problem with XML is that it's just so verbose. Java has property files which may or may not be berrer. Ruby on Rails using YAML files. These seem fairly reasonable. One thing an XML file does however is let you show relationships and nesting of data. So does the complexity of .NET require that the configuration files are also complex? The configuration file seems to be a collection of serialized objects spat out at random into a file. Is it a result of the everything must be XML crusades at the turn of the century? Could the files be simplified? Could we have seperate config files for seperate concerns. Example, I go into the config file to change a setting and I typo. My whole site (or server) goes down. Is this expected behavior? So does the nature of .NET itself demand XML configuration or is this laziness on the programmers part to simply allow them to deserialize the configuration settings in the most convenient way (for them) possible?
 Thursday, June 08, 2006
IF you have a server to monitor that has many different applications, for instance an intranet server, and you want one error logging/reporting solution to rule them all then you've come to the right place. It took me forever to find this information so I'm going to explain it.
ASP.NET 2.0 comes with a feature called health monitoring (healthMonitoring). This feature allows us to configure the monitoring and reporting of information related to ASP.NET. Almost anything useful can be monitored but I was most concerned about handling server wide exceptions in a consistent manner. Of course you should handle all errors/exceptions in each application if possible but sometimes this gets overlooked. In Classic ASP we would route the errors (500's) to a certain page and capture them with the Server.GetLastError which worked just fine in Classic ASP. However, in ASP.NET this doesn't work so well. You lose the exception when you transfer to another application. So you either have to store the exception somewhere by using the application_error or use a solution involving health monitoring. I chose the latter as a blanket solution just in case anything got through the cracks in an individual application. I've included a file that will help you set this up. If you want server wide coverage then these settings need to go into the web.config located at C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG\. Once you apply these settings you should be able to receive emails and log events to the event log. You can also set up a SQL provider that will log events to an SQL database instead.
The important things to look at in the file is the mailSettings tag under the system.net group. This sets up your SMTP server.
Next you want to check out the settings in the healthMonitoring section. This should give you a good idea how to set your server up. I've noticed that the MSDN examples and documentation is riddled with errors and inconsistencies. I don't know why they aren't shouting this stuff from the rooftops as it makes application and server administration so much easier.
I've attached the web.config file (web.config.txt (31.22 KB)) to this post. Here are the relevant sections:
Setting up your SMTP server:
<system.net>
<defaultProxy>
<proxy usesystemdefault="true" />
</defaultProxy>
<mailSettings |