mostlylucid

March 2004 Entries

New blog alert...

One of my colleagues Jonny Anderson just started a new blog..."the joy of c#"

Simple Guid validator...

Another of my fairly simple functions (actually written by a colleague of mine, Jonny Anderson) - this time just a simple way to validate a Guid - in this implementation  you pass in a Guid as an 'out' parameter along with the string you want to test - it then fills in the Guid and returns true / false depending on whether the Guid was valid...

 

private static Regex isGuid = new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled);

                                    internal static bool IsGuid(string candidate, out Guid output)

                                    {

                                                bool isValid = false;

                                                output=Guid.Empty;

                                                if(candidate!=null)

                                                {

                                               

                                                            if (isGuid.IsMatch(candidate))

                                                            {

                                                                        output=new Guid(candidate);

                                                                        isValid = true;

                                                            }

                                                }

                                                return isValid;

                                    }

?>

Lovely new Windows Forms DataGrid replacement

Paschal points out a really nice Windows Forms DataGrid replacement on CodeProject. This control looks really well done, the author has already posted some valuable updates on his own site, which also provides a nice RSS feed for updates on this and his other controls.

Another Nested Repeaters article

Marcie just let me know that there's another Nested Repeaters article been published, this time by Thomas 'Aylar' Johansen. Looks pretty good...I'll be working on a revision and followup to my article on this subject over the next few days, covering alternative, and I think, better ways of doing this as well as looking at some more advanced uses of nested repeaters.

Bug from hell..my 3 days of pain!

Just sorted one of the nastiest bugs I have ever had...I built a .NET class which was used from Classic ASP, so it too in recordsets then loaded then into a DataTable and fired them across a Web Service to another .NET app. Problem was I got all sorts of strange errors like   "MSDataShape error '80004005'" after the .NET component ran - this also affected every other use of ADO in my ASP application - not good!
What was the error? Well, after 3 days of wrestling with deployment issues, all versioning stuff - hint, if you're going to do this, set all your versions to 1.0 - not 'Best Practice' but saves a hell of a lot of hassle - I discovered it was pretty simple - any guesses?
Well, it so happens that my Recordsets were disconnected - fine, I thought, should be easy to send them out of process...umm...wrong, you see the problem was I applied a Filter to the Recordsets - this was the whole problem! It seems applying a filter somehow makes them unable to be marshalled properly (at a guess) which led to all these strange problems...

Ah well, problem solved now..I thought for a while there this was going to turn out like The Bug in Ellen Ullmans' book

Data Access Application Block V2

New release of the Data Access Application Block (funny, I thought version 2 had already been released...). Got this from Michael Swanson's blog.

Woohoo! ASPToday is back...

Just noticed (well read it on Jason Salas' blog if truth be told) that ASPToday has finally made a comeback and it has new clothes! Oh, and it now includes the C# Today content - which is just so fantastic I think I may pop...anyway, go, subscribe and keep this thing going, it is just the single best ASP / ASP.NET resource around. Oh, and they even have an rss feed!

Running ASP.NET on Linux

Excellent article on ASPAlliance on how to run and test ASP.NET applications on Linux and using Mono...is it just me or are the 'pages' on ASPAlliance getting REALLY short?

Nested Repeaters article...part 1

I've published part 1 of the very first article I've ever written here, it includes a link to the source used in the article. Now I want some comments - but please remember, I am by no means a professional (or even barely competent) writer and I have never written anything like this before. So I will resind my usual policy for comments where I leave anything short of a porno ad in comments - please be constructive in any comments or I'll just delete them...sorry, but only way to protect my fragile ego.

 

Ok, so this article....slight change of plans...

I've realised that it's taking far longer to write this thing that I'd hoped (the fact that I've started again 4 times may have something to do with it...). Plan is, I'll post the first part tonight  - this covers Nesting Repeaters using the ItemDatabound event the post the remaining part - which covers Member methods, declarative and a few other tips later...

The hell of article writing...

Well, I've had a few emails asking where the hell the article I promised has gotten to - I am writing it, it's just really tricky to do that stuff; for me, people like Dino Espsito seem to crank fantastic articles out at a rate of knots. Well, currently I'm working on a few pieces of demo code - I figure that if I write the demos first it'll give me a bit of structure for the article. So, I've complted the first one - which I kind of like. Idea is to show what you're use events for in repeaters when you're not wanting to nest repeaters (it made sense at the time!). Basically the example makes a little image for each company name, binding it on to an ASP:Image control in the ItemDataBound event - if it's over 30 characters, it changes the text to 'Too Long!" and flips the color. Opinions, is this a good example of what you could use events for? (oh, click on the image below to see a bit more of what I'm on about...)

Click to see the big version

Very nice little deployment tool from Matt 'eWorld' Hawley

Not content with producing some of the best free ASP.NET tools around, Matt's only gone and made a fantastic little utility to make deploying web sites much easier.
This little tool lets you deploy sites to either FTP or file shares with version checking etc...this just makes life so much simpler when you have to deploy sites (and are incredibly disorganised as I am...)

Rory goes nuts...playing with the mad folks...

I love this sort of stuff...(oh, and do check out the comments Chris A. has some really 'interesting' views :-)). It does remind me a lot of some summer jobs I had - I used to work with people with dementia / schzophrenia, the arguments I've read recently about open source versus MS are strangely reminiscent;

  • Use of 'statistics' to justify a position - this happens a LOT, latching on to some meaningless stat as a basis for an entire position.
  • 'religious' arguments - 'Linux is better than windows' - then self-select 'evidence' to defend a single side of the argument. Reminds me of a person who I knew that claimed that custard was toxic - evidence, they knew three prople who ate custard and died within a week...in a hospital where 2-300 people died that week.
  • 'Case Studies' - this is an especially wierd one, again self-selection of the type - such and such selected x over y == this proves x is better than y in all cases umm...no, no it doesn't.

Anyway, let me state for the record - I have no issue whatsoever with open source (well, I hate the GPL but that's a whole different issue). I was formerly a J2EE (oddly, not open source  although many people conveniently forget that :-)) architect, using open source servers with great gusto. I've used Linux numerous times (though I admit I was forced to). 

Right...gonna get back to this...and a request for assistance!

As I've been posting a bit recently,I've been having some problems with my DNS (entirely of my own making I should point out). Anyway, so these DNS problems have led me to do a bit of thinking about this here site - conclusion, I've been very lazy about posting stuff / looking after you my loyal reader (there is one of you right...hellooooo) - so I'm going to try and be a bit more proactive rather than reactive.
Right, so plan is that I start writing mini-articles, at least one every two days on items as varied as repeaters to compression to using interfaces, all sorts of stuff - here's where you come in. Problem is I am no writer, so anything I'm going to write is likely to be a bit on the pants side ;facts and coding wise it should be fine - I do that for a living - but I am no writer and English is not my first language (I'm Scottish :-)). So, I'm going to expose my inadequacies to the world and I want you, my reader to help me out by pointing out where the problems are.
My solemn vow is: I will post an article, as complete as I can make it on methods of Nesting Data List controls along with some tips and tricks thereon no later than 9pm GMT on 18/03/2004...

UPDATE: OK, for what it's worth the first part of the article is now up here - constructive comments appreciated...stupid comments ignored - and may lead to violent reprisals (kidding!)

The saga continues...

Well there's still a problem with my mail server...so the contact section of this site doesn't work right now...trying to figure out why...

Another new version of BlogJet

New beta
some features fixed
looks good

Email Borked again...

I'm having 'issues' with my email at the moment...normal service will (hopefully) be resumed shortly...

UPDATE:Umm...anyone who just got a really old email from me umm...sorry! I switched back to an old email server which seems to have had a bunch of mails stuck in it's queue...

Interesting site - with a focus on Patterns in .NET

Found this site really interesting from Maxim V. Karpov, basically it's a blog with a focus on the use of design patterns in .NET - which I personally think are currently not widely underused but could provide a huge boost to a whole lot of developers. Maxim recently wrote an article looking at the ASP.NET Out Of Process Session State - which is in itself an implementation of the Intercepting Filter pattern. If you're interested in patterns in .NET you could do a lot worse than look at the Microsoft Patterns site - whilst it isn't perfect (I'd personally like to see a WHOLE lot more example code) it is a great introduction.

New Version of Ghengis

I forget where I shamelessly ripped this off from...but I did - if it was you, please leave a comment berating me in some way...Anyway, a new version of Ghengis , the excellent .NET Windows Forms control toolkit has been released...if you haven't checked this out before - go there now!

UPDATE: Just found where I ruthlessly stole this from...it  was Scott 'Great god of .Text' Watermasysk

Very handy thing on troubleshooting VS.NET Debugging

This is one of the major pains with using Visual Studio .NET to work with ASP.NET - debugging almost never works on a new install and it can be a major pain to get it working. Noticed this link on Min's blog (he's also on the Debugger Team which helps :-)) - from G. Andrew Duthie - who I always wonder about, what is so bad about the G. bit that it needs eliminating? Oh, and Eric Gunnerson - who I just noticed posted it a bit earlier (and who writes some cracking stuff in his regular MSDN column)

Improving .NET Application Performance and Scalability - free book (kind of)

Just come across this free book (well a bunch of word documents but get a printing press and a book binder  - y've got yourself a book!) there's also a 'feedback' thingy on TheServerSide.NET.
Anyway, I've been skimming through it and it's all good stuff, covering pretty mich every aspect of improving performance in .NET applications in a way I haven't seen done before...

Huge bargain alert!

I love those crazy ergonomic keyboards...I use an old Natural Keyboard Pro at home, it's just the best keyboard I've ever found, it prevents RSI entirely and it has a little USB hub -  but they're stopped making that model and the latest ones aren't up to much...well, I just discovered this - it's the Logitech version of the same kind of keyboard,comes with a mouse - and it's wireless! Best thing though it that it only costs £19.99 (my original one cost me £80 about 3 years ago) - that's cheap even for a normal wireless keyboard, this place also has them (US), but their cheapest price is $54.99 (usual price $129.99)...so anyway,a bargain, it has great reviews on the Amazon UK site. If you haven't tried one of the ergonomic keyboards, I really recommend it!

Nice article...declaratively bind Form / Querystring parameters onto member parameters

I just like this implementation of doing this pretty useful task...one of those things you end up doing over and over (I'm going to extend it to work with ViewState :-)). Also, a nice example of using Attributes and Reflection for something useful...

Really nice cross-browser method of doing the 'DefaultButtons' thing - so that when you hit enter, the correct button 'clicks'

This is one of the major UI problems which is essentially caused by ASP.NET's 'one form' rule, as Darrell points out  there's a number of solutions out there but none of them really solve the whole problem (i.e., for all browsers), well now there's  a great solution - from Darrell Norton's Blog (link): (reproduced here because I'll never find it again otherwise...)

Submitting default buttons when the user presses the Enter key - finally!

One of the hardest things in web development is getting a certain button to submit if you have more than one button on the page.  Andy Smith, of Metabuilders fame, has one that works for late-model browsers.

 

Due to rather strict client requirements for a public e-commerce site, I needed something that went further back in browser history.  I found a code sample from Janus Kamp Hansen that only worked for IE.

 

I extended it to work with Mozilla and Netscape 6+, then added some more code to get it to work with most Netscape 4+ browsers.  Then I tweaked the performance a bit, and that’s it!  A fast, easy-to-use code snippet to force specific submit buttons to fire from developer-determined textboxes.

 

First, copy this method into an easily accessible place:

public void SetDefaultButton(Page page, TextBox textControl, Button defaultButton)

{

      // Sets default buttons.

      // Originally created by Janus Kamp Hansen - http://www.kamp-hansen.dk

      // Extended by Darrell Norton - http://dotnetjunkies.com/weblog/darrell.norton/

      //   -- added Mozilla support, fixed a few issues, improved performance

      string theScript = @"

<SCRIPT language=""javascript"">

function fnTrapKD(btn, event){

 if (document.all){

  if (event.keyCode == 13){

   event.returnValue=false;

   event.cancel = true;

   btn.click();

  }

 }

 else if (document.getElementById){

  if (event.which == 13){

   event.returnValue=false;

   event.cancel = true;

   btn.click();

  }

 }

 else if(document.layers){

  if(event.which == 13){

   event.returnValue=false;

   event.cancel = true;

   btn.click();

  }

 }

}

</SCRIPT>";

 

      Page.RegisterStartupScript("ForceDefaultToScript", theScript);

      textControl.Attributes.Add("onkeydown", "fnTrapKD(" + defaultButton.ClientID + ",event)");

}

 

This code registers the given script with the Page.  Then it adds an attribute to the textbox, which in this case is an onKeyDown event that calls the fnTrapKD function with the button’s clientID (it’s HTML ID in the rendered HTML) and the event.  I had to pass the event in because Netscape/Mozilla browsers can’t catch this kind of event unless you pass it in to the function.  IE can access the event from the document object, but we want something nice and cross-browser compatible.

 

The document.all if statement covers IE.  The document.getElementById covers Netscape 6+ and Mozilla browsers.  The document.layers if statement works with Netscape 4+.

 

Now add a line of code linking each textbox that you want with a certain submit button.  For example:

 

      SetDefaultButton(this, TextBox1, Button1);

      SetDefaultButton(this, TextBox2, Button2);

      SetDefaultButton(this, TextBox3, Button3);

 

I usually put that in the Page_Load, since the Page.RegisterStartupScript method will ignore duplicate scripts.  Now it is simply a matter of making a call to SetDefaultButton for each textbox-submit button association.

 

I haven’t tested this extensively yet, and some of the JavaScript may be unnecessary.  And considering the number of Netscape 4 versions (and their bugginess), it probably doesn’t work on all of them.  But it works (for now).  And at least making an attempt at Netscape 4+ and IE 5+ will cover 99% of my site’s web browsers.

Very cool stuff which I can't write about...

I've recently been working on a project for Microsoft UK doing some community stuff for the UK bCentral site which is pretty interesting - especially as it's given me some insight as to how Microsoft builds their sites.
Recently I've been working on some branding stuff which involves using the core Microsoft branding elements - now, how this is done is amazingly cool and to be honest it pretty much sets the pattern for how I think sites should be built...however, it's covered by an NDA - I have no idea why, but it is so I can't discuss it. Well, I guess I can discuss a bit as it mentions the MNP system here  (Microsoft.com Network Project - if you've ever seen a .mspx file extension, now you know what it is) - essentially it provides a way to provide common functionality, branding etc...across huge disparate sites with extreme ease whilst maintaining performance. Anyone from Microsoft want to put up a proper article about this system? Here's a bit from the above page which should go some way to explaining what it's all about...

MNP solves this problem, integrating XML-based content from multiple sources using ASP.NET to encapsulate parts of a Web page into reusable components.

"Essentially we create plug-ins that tell MNP how to read different formats," Mulvey said. "Content providers who own the content stores can write a little bit of code so anyone using MNP to build their site can consume that content in their pages."

Dumb little thing...class which outputs an Excel compatible table from a DataSet

Very simple and based on the one I blogged about previously (well not based on the code but based on the same idea). Anyway, hook this up to a link button, pass in a dataset and it'll provide a downloadable Excel compatible file...

public class GetExcel

{

public static void Convert(DataSet ds, int dataTableId, HttpResponse response, string fileName)

{

DataGrid dg = new DataGrid();

dg.DataSource = ds.Tables[dataTableId];

dg.DataBind();

response.Buffer = true;

response.ContentType="application/vnd.ms-excel";

response.AddHeader("Content-Disposition", "attachment;filename=" + fileName) ;

using(StringWriter sw = new StringWriter())

{

using(HtmlTextWriter writer = new HtmlTextWriter(sw))

{

dg.RenderControl(writer);

response.Write(sw.ToString());

}

}

response.End();

}

public static void Convert(DataSet ds, int dataTableId, HttpResponse response)

{

Convert(ds,dataTableId,response,"report.xls");

}

public static void Convert(DataSet ds, HttpResponse response)

{

Convert(ds,0,response);

}

}

Smart spam...

I had an interesting comment spam today...as usual the URL of the sender was an 'Online Pharmacy' - interesting thing was that the actual comment was a reordering of a previous comment - so for all intents and purposes it looked like a real comment. Anyone know if these are human entered or if there's some system out there picking out keywords and posting realistic looking comments? Or am I just being paranoid?

Security through Diversity - why I don't like ValidateRequest

I'm aware this is a fairly controversial viewpoint, I should explain some of my own background as a precursor to my dislike of this. In the bad old days, I was a penetration tester; I ran my own little company which provided this service to a number of customers, my job was to essentially crack / in other ways break web sites and 'other' networks. In my time as a pen tester, one of the most annoying things was flaws which could effect a huge number of sites / installations at the same time, classics were Cisco password flaws, Perl and PHP security flaws and, worst of all, backdoors in Web Applications. So, as time has progressed and I moved more into actually writing applications rather than breaking them I've always been aware that application security systems should not be inherently trusted, while less likely to be flawed than some ad-hoc implementation, that flaw can be potentially more serious since is is almost certain to become widely know and exploited within a very short space of time.
That's part of the problem I have with ValidateRequest, it provides a crutch, a shortcut for the lazy developer. OK, it is useful, it blocks any incoming 'html' like request information - and will therefore block many XSS (Cross Site Scripting) attacks which can be pretty serious. Problem is, flaws have already been found in this and the patch is not obvious / easy to find (had you heard of it before?) - so not there's an issue which will effect ALL ASP.NET 1.1 sites which rely on this feature to protect them from XSS attacks. Even worse, how many sites do you think will take additional precautions over and above this to protect their input - do you know if it protects you from SQL Injection attacks, Buffer Overflow attacks and various others (including such gems as simple backdoors, Cookie Hijacking and the like).

My point is, in my view, responsibility for application security should lie with the developer - they should understand and plan for the consequences of choices they make in application design. Read a book like Michael Howard's Writing Secure Code [US] - get to know where the vulnerabilities in your application may lie and compensate for them.
In short, don't rely on things like ValidateRequest as your only line of defence - use it by all means, it will stop many things getting through which you may not want - but learn what it actually does and what it doesn't.

For instance, what will you do when you only want certain tags to get through and not others? You may need to look at something like this (I wrote this a while ago - I'm not claiming it's entirely or even partially foolproof - just proof of a concept).

Anyway, views always welcome - how much application security should you delegate to the framework - has anyone else come up with their own little 'security' toys which they use to validate user input?

UPDATE: Forgot to mention, if you're still on IIS 5.0 be sure to check out IISLockdown - you MUST have this installed, it will help you avoid a huge number of security holes, known / future...if you have IIS 6.0 , it's already there but be sure to check out this to avoid any development problems...

FreeTextBox 2.0 - now cross browser compatible!

This is so fantastic, I just read this on Colt Kwong's blog - FreeTextBox - which is just the best WYSIWYG editor for use in ASP.NET has just begun to support other browsers than IE. This is a really big step, for many web projects (which specify support of Mozilla browsers) this makes it possible to provide this type of functionality to all users - just remember to validate their input!

UPDATE: Just noticed one thing, the source code is no longer included, you can buy it for $50 which is reasonable...but worth noting!

Here's what Colt wrote...

FreeTextBox 2.0 Released

FreeTextBox 2.0 has been released. The most obvious new feature is support for non-IE browsers, which means, I should soon be able to edit this blog using FireFox :)

  • English, Spanish and Chinese are supported
  • Projects Using FreeTextBox: ASP.NET Forums, .Text, DNN, Rainbow...
  • Cross-browser support (Mozilla 1.3+, PC/IE 5+)
  • Button/DropDown feedback
  • Localization (create your own language files)
  • Inline toolbar customization
  • Back button support in IE
  • Office 2003 Style
  • External JavaScript
  • Completely recoded as a development platform

Personally, I use FTB in various Web apps lately, which is definitely a GREAT work! Thanks John.

Fixing Internet Explorer's CSS Deficiencies...and a link to the best menu implementation I've seen...

I really wish there were more blog posts like this one, it covers a whole host of problems IE has with CSS, from the lack of :hover support, to the well known issues with PNG files - oh and check out the comments, an awful lot of clever people have replied with other issues / fixes for issues with IE - oh and some stuff on CSS3 Media Queries - which seem just incredibly useful - anyone know when / if IE will support CSS 3?
I also discovered this as a link from that article, essentially it's a nice, simple, standards compliant (for which read, accessible, lightweight and cross-browser compliant) drop-down menu system - it's also the only menu system I've seen which is just phenomenally easy to do in an ASP.NET repeater - which is VERY handy - look out for a new menu soon on this site :-)!