mostlylucid

December 2003 Entries

Going home for Christmas

I'll proabbly be posting a lot less for the next 2 weeks, heading home for Christmas...have a great Christmas!

RSS server control from Jason Salas

I've posted a couple of times about using RSS from ASP.NET, so this interested me a fair bit, Jason Salas  has posted a nice server control  which allows very simple generation of RSS feeds based on a query to a SQL Server database.
There's been a bit of chat about whether such a control should be included in Whidbey - to be honest I think it's a bit late for this and I'd rather time was spent improving what's already there than adding arbitrary new features.

Microsoft in Space!

Just noticed this from the Scaled Composites website:

PAUL G. ALLEN CONFIRMED AS

LONG-RUMORED SPONSOR OF SPACESHIPONE

Allen Sponsors Scaled Composites’ Cutting-Edge X-Prize Entry, Attends Today’s

Successful Test Flight of the First Manned Privately Funded Supersonic Aircraft

MOJAVE, CA and SEATTLE – Dec. 17, 2003 –

Investor Paul G. Allen today confirmed

international speculation that he is the long-rumored sponsor behind the innovative

SpaceShipOne project, which broke the sound barrier today during its first manned test

flight. SpaceShipOne and its White Knight turbojet launch aircraft represent the first private

non-government effort to demonstrate a low-cost manned space effort. SpaceShipOne is a

contender for the coveted X-prize.

"Being able to watch today’s successful test flight in person was really an overwhelming and

awe-inspiring experience. I’m so proud to be able to support the work of Burt Rutan and his

pioneering team at Scaled Composites," said Paul G. Allen, who has funded the effort since

he and Rutan joined forces in March of 2001. "As we celebrate the centennial of flight, it’s

wonderful to be able to capture the spirit of innovation and exploration in aviation.

SpaceShipOne is a tangible example of continuing humankind’s efforts to travel into space,

and effectively demonstrating that private, non-government resources can make a big

difference in this field of discovery and invention."

This is very cool indeed, SpaceShipOne has just become the first private aircraft to break the sound barrier. Paul Allen is a pretty cool guy, one of his companies Vulcan is also in the process of developing the coolest looking tiny little PC around...oh, he also co-founded Microsoft with Bill Gates...

Hard-links...umm...well that's it really...

Noticed a post on Robert McLaws'  weblog about Hard-links...go and read the post it'll all make sense... Now, I've recently been working on a project where a requirement existed for an 'uploads' directory to be synchronised between two Web Servers...to cut a long story short, we had to use a product 'approved' by both the host and company for which the site was designed. Now, it is just incredibly simple to write this sort of tool using .NET, but no, we had to use one of these other tools...the ones recommended were WanSync and MS Application Center...overkill in my opinion! Anyway, hard links are pretty cool (automatic synchronization would be better)

Links I've found pretty interesting...

I don't usually do this, but I thought I'd post some link to miscellaneous things I've been reading over the pas few days - there's no particular focus, just stuff I found interesting...

  • MSMQ with ASP.NET  - if you haven't used Message Queues before, check this out...provides an easy method to manage very asynchronous, reliable messages..
  • FullSource - useful little tool which lets you see the actual source which IE uses (if you do a server.transfer for example, IE will show you the wrong source...), alos lets you see modifications made to the DOM by Javascript
  • Markup text in VB.NET - shows a method to display 'colorized' text...nice and configurable.
  • All you ever wanted to know about ViewState - excellent article about ViewState, discover the hidden mysteries...
  • High-Resolution Timer - nice, High-Res timer, useful for benchmarking etc...
  • Using an LCD Panel from .NET - exactly what is says, nice article in the 'Coding4Fun' series...
  • The IComparable interface - really well written article on using this simnple but useful functionality...

Anyway...that's it for now...

Nice Christmassy code...

Nice article on CodeProject on generating fractal snow...and a nice screensaver (which now works on multiple monitors) by Thomas Petricek who has also written a couple of other pretty nice articles and he's only in High School - makes you feel old doesn't it!

Enabling SMTP authentication with CDOSYS (System.Web.Mail)

One of the most common problems with using CDOSYS  (which is the underlying class used by System.Web.Mail) is the lack of authentication for sending mail via SMTP, Darren Jefford posted a method to do this, I've reproduced it below since it's currently hosted on GotDOtNwet and so may disappear at some point:

System.Web.Mail and Authentication

A question came up recently on how to send email from .NET, System.Web.Mail offers a nice MailMessage and SmtpMail class that does the trick.

The classes are a wrapper over the CDOSYS functionality that's been around for a bit, and are much nicer than the rather clunky CDOSYS interface :)

It's really straight forward to send a mail:

System.Web.Mail.MailMessage msg = new System.Web.Mail.MailMessage();    
msg.Subject = "Testing";
msg.Body = "Hello World";
msg.From = "yourname@domain.com
";
msg.To = "
someone@domain.com";

System.Web.Mail.SmtpMail.SmtpServer = "YOUREXCHANGESERVER";
System.Web.Mail.SmtpMail.Send( msg );

However when I was testing it out against an Exchange Server it refused to send, returning this error:

System.Runtime.InteropServices.COMException (0x8004020E): The server rejected the sender address. The server response was: 454 5.7.3 Client does not have permission to submit mail to this server.

By default (and wisely) Exchange doesn't allow unauthenticated users to send mail via SMTP to prevent against spammers, etc.   To cut a very long story shot the SmtpMail class does not handle authentication to the Exchange server meaning that you can't use the class in most secure scenarios.

After a lot of digging I found that CDOSYS does have authentication code as you'd expect, however the MailMessage or SmtpMail class does not expose any way to turn it on.  After a bit more digging I found that the Everett (.NET Framework 1.1) team realised this and added a new property called Fields, which as you can see is missing some documentation ;-)

So, after some further investigation I've found that you can authenticate against a server, if you have Version 1.1 of the framework, and this is the line you have to add to the above code:

msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate",2);

Where the 2 specifies NTLM, 1 for basic, 0 for none (the default)

You can of course also configure the myriad of other configuration options via this Fields collection

I feel a MSDN HOWTO article coming on, and perhaps polietly asking for some MSDN documentation to be uploaded! :-)

Adding confirmation to buttons...and why I've been doing it wrong all along...

I left a comment on Rob Chartier's blog about adding confirmation prompts to buttons, now I do use Andy Smith's Confirmed Buttons controls where I can, but if I need to add a simple confirmation to a button, I tended to use the following sytax from code-behind:

Button1.Attributes.Add("OnClick","javascript: return confirm('Are you sure you want to delete this forum?');");

Now, this does work, but it has a bug around in-page validation - Andy Smith pointed out the error - and the reason why this wouldn't work in .NET 1.0 - which I hadn't noticed! Here's his reply:

Scott, Yes, ConfirmedButtons was originally created because of a bug in v1.0 of the framework. The validation framework didn't combine your onclick with it's own onclick, as it does in v1.1, but instead created two onclick attributes on the button, which meant one of them didn't fire. I created ConfirmedButtons to combine the two onclicks together at the clientside.

Which also brings up a bug in your implementation. You only want to return false if the user chooses no. otherwise the validation doesn't fire, as it gets combined to be after any user onclick stuff. So you want to change it to Attributes.Add("onclick", "if ( !window.confirm( 'sure?' ) ) { return false; }" )

Just another reason why the imminent beatification  of Mr. Smith should come as no surprise to anyone (note: I may just have imagined this :0))

Carl Franklin posts a pretty interesting little Stream / Object compression library

Find it here, I posted a comment about compressing ViewState - I'm really surprised that no-one seems to have done this yet - seems to be the most obvious thing to compress in a page and should have pretty good compression ratios - I may try this again myself...keep you posted :-)

I hate the talented...

Pretty amazing track from Rory Blyth - man I wish had musical talent of any kind; well, I sing but a monkey can sing...not very well, and it obviously appeals most to other monkies...but well, you get the idea...

Stupid ADSL...

Sorry if you've been having problems accessing this site over thelast couple of days, my ADSL has been acting up badly...is you have problems, please try again later (I have to cycle the connection to get it back...)

 

Looking for a project...

Still waiting for the 0.95 release of .TEXT (which is what this blog runs on), so I don't really want to make any changes to this site until then - as the changes I plan may already be in  that release / the changes in 0.95 will be so radical that it will render what I've done inoperable. So, I'm looking for a new project to play with...options currently include:

  1. Blog poster - similar to w.bloggar, except with an in-built HTML editor, the option to use the office dictionary (is this legal?), better UI, pluggable posting layer etc...
  2. A CMS system with a novel, modifiable workflow system - I have some ideas based around an expert system I created recently...hmm...
  3. Some dumb game - managed DirectX
  4. Snazzy screensaver - managed DirectX with web-service involvement...

Anway, whatever project it is, it has to fulfill the criteria of advancing my knowledge; current areas of interest include Windows Forms and managed DirectX (I write ASP.NET applications for a living - so I'd prefer to avoid them!). The Blog poster is a strong possibility...anyone know a good metaweblog api reference?

Excellent Resource Wrapper Generator on GotDotNet

Now this could be tremendously useful - here's the description from Craig Hunter:
Why wait for Whidbey for this functionality? This macro generates a type-safe Singleton-based C# class wrapper that loads string, images, etc. from an embedded assembly resource on demand i.e. only when first accessed. Allows a CultureInfo instance to be assigned that will specify the culture to apply when loading resources. This is VB.NET exported source intended to be imported into and executed from a Visual Studio 2003 macro project. Developed by Craig Hunter.
Oh, and yes, the dumb comment is from me...look it was early...I have a cold coming on etc...

Cool tools links by Poonran Prasad...

Just noticed this at DOtNetJunkies blogs - most interestring link to me was this one which links to the MSDN Regional Directors code center , just a shed load of useful utils there!

 Look what I have found :)

ASP.NET server side Back control by Juval Lowy

Common techniques for implementing a Back link on a web page involve using the browser-side script. There are a number of disadvantages to this solution: the application has no control over where the user is going to be redirected. Often you want to keep the user inside the application, and you do not want them to wonder off to other pages, and it only works if the browser supports client-side script. The biggest disadvantage is that it is not consistent with the ASP.NET programming model of server-side controls. There is also no easy way to enable or disable the back link based on server-side event processing. The download contains a server-side user control, which provides the Back functionality. Simply add it to your toolbox, and drop it on your forms. I love to use this :) One can find one more control similar to this, here.

Apart from this, find some of the most sought after utilities like Remoting Toolkit, Mail Checker, Detailed SQL Error Messages and loads and loads of them here :)

Another 'thing I didn't know but should've done' - the magic of different Binary Search Tree implementations

Hmm...was fishing through GotDotNet user samples when I came across this...now this is an extermely cool implementation of different types of Binary Search collections - now I have never used the Sorted List collection before - but I should've done! It has a very cool feature which lets you access elements by value or key. The GotDotNet ones do pretty much the same thing except they're more efficient for certain types of data; see here for more info on Splay Trees and here for info on Red-Black trees and here for info on Binary Search trees - pretty useful and could help optimise in-memory searches!

Odd favourite films...

I'm beginning to suspect I'm a bit odd...case in point, one of my favourite films is currently on BBC1, L.A. Story, no idea why, I just love this film! Others include Empire Records, Night On Earth (mainly the Italian section) and The Big Blue. So, what does this say about me??? What are your favourites?

DataBinding performance update...

I posted earlier about the difference between DataBinder.Eval and 'strongly typed' binding - mainly to see what other people do...Well in that I mentioned a benchmark I did a while ago to compare the two which showed a roughly 20% difference. So, in the interests of transparency, I've rewritten the benchmark - not looking to win any coding contests, but it should be fairly accurate!
Anyway, if you want to try it out / pick fault with my methods (there's probably a few problems, I just hacked it together) you can get it here.
It basically binds on to two DataGrids multiple times (20 times each in the version I uploaded so it runs 'fairly' quickly), one DataGrid uses DataBinder.Eval, one uses the 'strongly typed' method, it uses a "Select *" from the Orders table in the SQL Server 2000 Northwind database - 830 rows of fairly realistic data.
I use a dataset which I rebind on to multiple times; to get over the impact of the SQL server query, the data is loaded once only. I also run each type twice in 1:2:1:2 order to try to reduce the impact of order effects. I've also run the test in reverse order and with fewer and greater loops (up to 2000 for each grid). My results are fairly consistent at around 20%  (varies between around 15 - 30%) better performance for the 'strongly typed' method.
I hope someone downloads this / does their own test, I have no particular affiliation to either method,but I do  tend to use the strongly typed one, but performance is a secondary concern to the explicitness of that method.
Anyway, if you do try this out, please let me know your results.
I ran this test on my home dev machine, an Athlon XP 2600+ with 1GB PC3700 DDR RAM running .NET 1.1.4322, SQL Server 2000 Dev SP3, Windows XP (all latest patches applied).

Avoiding 'deep linking'

I had a problem where someone linked to one of the images on this site (actually problem still exists), basically a 2mb+ image was being displayed on some forum (I won't include the link :-))  which used a huge amount of my bandwidth... Well, here's a solution, also a pretty nice display of using HttpModules...he also has some nice, hi-res wallpaper here (wouldn't try to deep-link them though :-P)

Small point...what Databinding syntax does everyone use?

UPDATE: OK, before anyone points out the obvious (actually after many people have!) - I am aware that DataBinder.Eval promotes code reuse to some degree; you still have to know what your fields are called of course! My point in this post was that I rarely saw the alternative syntax used and that in my experience I have found almost no drawbacks in using the 'Strong' syntax. This was also a trawl for comments to get the opinions of other developers...with that in mind, let the comments recommence...

Incidentally, in the post below, if anything looks screwy, sorry, having problems with the stupid Rich Text editor again!

Reason I ask is that most of the examples I see all over the web use the:
format...
now the reason for this seems to be that this is  allegedly 'easier' to use and read.
To be honest, I have never used that format, I tend to use this:
<%# string.format("{0:c}",((dbdatarecord)container.dataitem)["price"]%="">  format
now, I understand that this looks more complex  but as it points out here,
"It is important to note that DataBinder.Eval can carry a noticeable performance penalty over the standard data binding syntax because it uses late-bound reflection. Use DataBinder.Eval judiciously, especially when string formatting is not required. ".
Now, in my tests (I benchmark everything...obsessive? Quite possibly :-)), the Eval syntax is a LOT slower, like up to 20% slower - so, what is the actual advantage of using it?
OK, my opinion on why you wouldn't use the 'explicit casting' syntax (i.e., the one I use):

  1. You have to import the correct namespace depending on whether you use a DataSet or a SqlDataReader (or any IDataReader) (System.Data and System.Data.Common respectively).
  2. You have to cast to the 'correct' object so for DataSet it's DataRowView and for SqlDataReader (or any IDataReader) it's DbDataRecord...for any other objects, it's the correct object obviously :-)
  3. It's more 'wordy'
  4. Very few examples show this syntax...

Now, these are pretty good reasons to use the DataBinder.Eval syntax, but to be honest, I just don't find them compelling...so here's some reasons to use the 'explicit casting' one:

  1. You have to import the correct namespace depending on whether you use a DataSet or a SqlDataReader (or any IDataReader) (System.Data and System.Data.Common respectively) - same argument...but I have to say, I like this! It's more explicit about what namespace you're actually using and forces you to know this stuff!
  2. You have to cast to the 'correct' object so for DataSet it's DataRowView and for SqlDataReader (or any IDataReader) it's DbDataRecord...for any other objects, it's the correct object obviously - again, the same as above...knowing what type of object you're using is, in my opinion, a good thing, it gives a whole lot of control in how you represent the object; for example you get access to all the nice DateTime formatters in the .ToString() method - same as you would in code!
  3. It's faster - now this is not a 'be all and end all' argument, but it is important, especially in high-hit sites or when you have to bind really long lists of data - faster = less time for which a thread is used!
  4. Makes you look like a smart ass - OK, just me then :-)

Anyway, I really am interested in hearing people's opinions on this one...which do you prefer, and why?

%>]]>

A bit quiet...

Sorry, I've been neglecting this thing a little of late (causing trouble on the ASP.NET forums instead...gives me something to write about :-)). Anyway, I'll try and think of something interesting to write about..umm..any ideas, anyone got an ASP.NET question???

Back - and code for impersonating users...

Well, had a lovely break...now for some code, this will let you 'impersonate' a user - really handy when, for instance, trying to upload a file to a network location...as usual, no idea where I found this, if it was youre, let me know!

using System;
using System.Web;
using System.Web.Security;
using System.Security.Principal;
using System.Runtime.InteropServices;

namespace Components.Security
{
    /// 
    /// Summary description for ImpersonateUser.
    /// 
    public class ImpersonateUser
    {
        public const int LOGON32_LOGON_INTERACTIVE = 2;
        public const int LOGON32_PROVIDER_DEFAULT = 0;
        WindowsImpersonationContext impersonationContext;
        [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
            public static extern int LogonUser(    string lpszUserUname,
                                                string lpszDomain,
                                                string lpszPassword,
                                                int dwLogonType,
                                                int dwLogonProvider,
                                                ref IntPtr phToken);
        [DllImport("advapi32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]
            public extern static int DuplicateToken(IntPtr hToken,
                                                    int impersonationLevel,
                                                    ref IntPtr hNewToken);
        public bool impersonateValidUser(string userName, string domain, string password)
        {
            WindowsIdentity tempWindowsIdentity;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;
            if(LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
            {
                if(DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                {
                    tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                    impersonationContext = tempWindowsIdentity.Impersonate();
                    return (impersonationContext != null);                    
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        public void undoImpersonation()
        {
            impersonationContext.Undo();
        }
        
    }
}