mostlylucid

January 2004 Entries

Is cheering on Viruses like cheering on Terrorists? Umm...not even close!

Read this on Cameron Reilly's blog:

This says a lot about the intelligence of some of the folks on Slashdot. Are they having a joke? Perhaps. But cheering on a virus is kind of like cheering on a terrorist.

Now I'm sorry, this is such a dumb statement, for me it's the equivalent of saying 'killing a cockroach is kind of like killing your mother' - the hype and over dramitisation of viruses in the media of late has really annoyed me.
If you have a commercial virus checker (or even a free one like AVG Free), you will NOT have had any problems with this virus - if you count a couple of extra emails...umm...please, can you say 'Spam'.

Anyway, it is not my intention to attack Cameron, I normally like his views / posts, it's just that characterising Virus Writers as Terrorists is just an extreme form of dumbing down - which seems to characterise media in both the US and the UK.

Here's the comment I left on Cameron's blog...which kind of explains my position a little better:

Cheering on a virus is NOTHING like cheering on a terrorist (though I don't agree with either) - I wish people would stop over-dramitising viruses, MyDoom has been caught by ALL commercial virus checkers for months, with all the viruses around you really have to be dumb to not have a decent virus checker installed.
OK, so viruses are inconvenient, they may even destroy data - but so far as I'm aware, no-one has been killed by MyDoom. I live in a country (the UK) where we had violent terrorism for 25 years (most people seem to forget this!), believe me I'd rather have people writing self replicating code than blowing up city centres.

Motivation...

I fully admit I am a moody sod...I don't know how / why it happens but occasionally I have real difficulty getting motivated to actually get working.
So, what do you do to motivate yourself to get coding (especially making syntactic / other 'cosmetic' changes to existing apps)?
How do you get over the 'bump' between statring a project and really getting productive on it?
Oh, and VS.NET is really pissing me off right now, why is it that it occasionally can't go into the 'Designer' mode of an html page - griping about the class being 'abstract' - which is especially annoying as it's the class which VS.NET made itself! Whidbey and it's lovely partial classes can't come soon enough for me!

Very small tip...ViewState enabled properties

This really is a very quick tip...I think I got it from Fritz Onion's excellent Essential ASP.NET with Examples is C# (which I really recommend incidentally!). If you want to store a property which should persist using ViewState, you can save yourself a lot of typing and get (IMHO) cleaner code using this method:

public int Test
{
get
{
if(ViewState["Test"] != null)
return (int)ViewState["Test"];
else
return 0;
}
set
{
ViewState["Test"] = value;
}
}
So, there you go...short but hopefully useful - this is how I tend to work now...it also allows me to switch to session / cache persistence when necessary by just changing the little accessors...

 

 

Me 1.1

Sorry I've been a bit quiet over the past few days...as I mentioned on Tuesday, I had a checkup at the Diabetic clinic on Tuesday...umm...well...let's just say it didn't go well - oddly an all pizza diet and no physical activity is not good for you! So, I've joined a gym (for those who know me, sorry for the shock...no choice). So, I'm currently trying to remember how to swim (haven't swam for about 6 years). Oh, also trying to get used to being in a room full of naked men (I'm not homosexual, so I find no particular thrill in this prospect)...and being the 'token fat man' (although tonight was better in that respect)...

Bugs in .NET !

Just noticed this on Stefano Demiliani's blog, lots and lots of bugs, some of them pretty interesting! I don't know just how 'verified' lots of them actually are:

An interesting idea of Dejan Jelovic. This page represents a registry of known .NET bugs. You can use it to see if the strange thing you are seeing is a known bug, or to report a new bug that you just found.

Known .NET Bugs

IDDescriptionProbability*Severity*Fixed
1

Form refuses to close
If a form A contains control B that contains control C that contains control D, and D is removed while it has the focus, the user won't be able to close the form. Details.

HighHigh1.1
2SoapFormatter and BinaryFormatter don't serialize some object graphs properly
If three or more classes have the same name but are in different namespaces, are part of the same hierarchy, and contain variables that have the same name, they will not be serialized properly. Details.
LowHigh1.1
3Text in the Windows Forms combo box cannot be selected using the mouse
Mouse selection simply does not work in a Windows Forms combo box. Details.
HighLow1.1
4Arrays of structures that implement ISerializable do not deserialize correctly
Details.
HighHigh1.1
5

Windows.Identity doesn't work under Windows 98
On Windows 98, You cannot use the Windows.Identity to retrieve the user login name, it returns a system level token and a null user name is returned when you access the .Name Property. Details.

LowMediumNo
6

C# optimizer produces bad code when a try-finally block is inside if-else
If a try-finally block is the last thing inside the if block of an if-else statement, the code inside the else block is always executed when compiling in Release mode. Details.

HighHigh1.1
7

Structs within structs cannot be deserialized
If you have a struct A inside struct B, and If a struct A is inside struct B which is inside object C, deserializing is going to throw a SerializationException.  Details.

MediumLow1.1
8

Problems removing an ActiveX control from its parent
If an ActiveX control is removed from its parent, any action that makes the parent invisible, such as closing the form on which it is on, throws an exception.  Details.

MediumHigh1.1
9

Font.GdiCharSet hardcoded to 1
The property GdiCharSet of the font class is hard-coded to 1.  Details.

LowLowNo
10

.NET Runtime leaks large chunks of memory
If you allocate a block of memory larger than some treshold, the .NET garbage collector will never reclaim it. Details.

HighHigh1.1
11

Instances of NumericUpDown and DomainUpDown are leaked
It seems that the NumericUpDown and DomainUpDown controls forget to remove a listener to a global event, thus always staying locked in memory. Details.

HighHighNo
12

SoapFormatter chokes on some strings
It seems SoapFormatter cannot handle strings that contain characters in the range 0x01 - 0x1f. Details.

HighHighNo
13

FileStream becomes unusable when writing to a removable drive
When writing to a FileStream on a removable drive, and the FileStream gets out of space, it sometimes gets in a state where no other method can be called on the stream, not even Dispose. Details.

MediumMediumNo
14

Mixed-mode assemblies can deadlock
C++ .NET apps can deadlock on startup. Details.

LowHighNo
15

ComboBox Data Binding Bug
ComboBox doesn't update the data through data binding when its style is set to DropDownList. Details.

MediumMediumNo
16

Each Windows Form leaks two GDI handles
Details.

HighHighNo
17

Alocation fails for certain sizes
If you try to allocate an array with a size range between 0x027fefbd and 0x027fffec, the framework throws exceptions. This range corresponds to memory block of little under 40MB. Details.

MediumHighNo
18

No way to access Environment.HasShutDownStarted
This property is not static even though it should be.

LowLow1.1
19

Thread.Abort cannot abort suspended threads
If a thread is suspended, trying to abort will not work and the CPU will be pegged to 100 percent. Details.

LowHighNo
20

Control.Width and Height are silently truncated to 32,767
If you attempt to set a control's Width or Height property to a number larger than 32,767 it will be truncated. Details.

LowLowNo
21

ListView.Cursor set property has no effect.
Details.

LowLowNo
22

RegistryKey.SetValue does not store large integers as DWORD
Call RegistryKey.SetValue with an integer over 2,147,483,647 will result in the value being stored as string, and not as a DWORD. Details.

LowMediumNo

* Probability represents the probability that you will encounter this bug. Severity measures how much the bug hurts when it happens.

Do you know other bugs?

Good article on Codeproject - those wierd little images used to stop automated form submission

This would be pretty useful integrated into .TEXT - kill the problem of 'Comments Spamming' pretty instantly.

The article also contained a link to The Captcha Project - which makes for pretty interesting reading,

Interesting...could this be the tiniest way to use Visual Studio.NET on the move

Just noticed this, not due for a few months yet - the OQO Personal Computer, not overly powered (a Transmeta 1GHZ processor, 256MB Ram and 20GB hard drive). But this might JUST provide a way to have a full Windows XP experience on the move (Pocket PC just doesn't cut it for me, and right now, lugging a TabletPC around just makes you look like a wanker). Anyway, here's a pic - looks pretty neat! Here's the link to the full specs

Trouble sleeping again...so links to a few 'interesting' articles & sites

I think I'm going through one of my bi-annual mid-life crises again. I really should be sleeping, I have a hospital appointment in the morning (just a diabetic clinic followup thing - 10 minutes and a lecture about my diet...great fun - and eerily similar to an ex-girlfriend). Anyway, whilst awake, I've been having a look at some articles around the web (so technically, keeping me awake has been looking at some articles around the web, but stop complaining - you might find some of them useful!)...

One of the least talked about enhancements to Whidbey is the stuff they're doing with Windows Forms, whilst not dramatic they are pretty important improvements in this article, Michael Weinhardt takes a look at some of the cool new features in Whidbey's new Windows Forms Gridview control. There are some really useful features in there!

Also, during my recent load-testing fiasco, I came across Sql Server Performance.com, as the name suggests, this site is full of a ton of tips, queries, tool reviews etc...all focussed on improving the performance of your DB access - all very nice and all easy to understand. This is one of my bugbears - and a thing which i find many developers just don't have a grip on, it's really important to understand the best way to structure your DB for both read and write operations - Indexes are your friends! So, just go to the site and work through some of the articles - you'll be a better coder because of it.

Keith Brown's Security Sample gallery - just a whole load of interesting .NET (and other) samples, covering some of the more esoteric aspect of windows security - if you have a security problem, if no-one else can help...umm...go to this site.

Visendo SQL-Admin...Really useful tool, lets you do proper admin on MSDE - why I hear you cry would I want to do that? Well, if you're wanting to host a pretty low traffic website (i.e., a pretty average website - you can actually handle a whole lot of users with caching etc...), you can save yourself / your client a bomb by using MSDE and Windows Server 2003 Web Edition - as in $397 versus $999 for Standard Edition - plus the cost of a SQL Server 2000 license, so you could have a fully functional DB driven server for less than $400 (plus cost of hardware)!

I'll just cut and paste the bits from the page:

-> Download

Visendo SQL-Admin is a free replacement for the Enterprise Manager of the MS SQL-Server. If you try to install MS SQL-Server on Windows 2003 Server Web-Edition it doesn't work. Installing databases is denied. But you are allowed to install the MSDE (desktop engine). To administrate this, you need an additional tool because you also can't install the MS SQL-Server administration tools.

The solution is Visendo SQL-Admin. With this freeware tool which is built on the .NET Platform, you can administrate your SQL-Server or MSDE very comfortable.

SQL-Admin Features:

- Create databases
- Delete databases
- Backup databases
- Restore databases
- Detach databases
- Attach databases
- Add SQL users
- Remove SQL users
- Add windows accounts
- Remove windows accounts
- Create tables
- Delete tables
- Open/view tables
- Modify table data
- Create views
- Delete views
- Open/view views
- Edit view data
- Create stored procedures
- Delete stored procedures
- Edit stored procedures
- Sql query tool included

Web Service Compression - really nice implementation of a Web Service Extension (with sample)

I've posted about this topic a few times, it's really nice to see that someone has finally given a practical, free method of doing this. This implementation uses WS-E to do this, meaning that you add an attirbute to both the client and server portions of your web service - and there you have it, a compressed SOAP message!
If you're using Web Services and transmitting any non-trivial amount of Data, I really do recommend that you use compression on the SOAP message (especially if you're sending DataSets, those buggers are huge when serialized - of course you can minimize them in a different way), this is a very simple, intelligent approach to this problem, it can actually make Web Services practical where they weren't before (as transmission latency can actually preclude their use in some circumstances).
Anyway, good job Glav!

UPDATE:  Just found this article on DotNetJunkies - which seems to offer HTTP 1.1 compression for web services - yet to try it out (looking at the date it's possible it would only work for .NET 1.0 - but I'll give it a try and report the results!)

Aggressive Begging...the ASP.NET way

Now, I don't mean to be mean here; but on occasion (not mentioning any names for fear of being butchered), there's people who basically demand that I help them do their job.
Let me explain; I hang out a bit in a few forums and newsgroups, as well as requests sent directly though this blog - now these are generally 'normal' requests for information / assistance on some specific aspect of a project with which someone is having a bit of trouble and needs a hand - fine, I have no problem with this, I spend quite a bit of time on these types of question and often write sample projects to more clearly explain concepts (I can't write for toffee...but I can code - that's generally the simplest way for me to explain such concepts).
What really ticks me off though is the 'how do I do the whole project' type questions - which I will generally try to help out by providing links to articles, explanations of basic concepts etc...pretty often though I get really snooty replies, expectations that I should help people do their paid work gratis...
I am seriously considering cutting off my contact form (again) and stopping visiting forums altogether - please remember if you're asking for help - you're in general asking people who do this stuff during the day for real cash money to provide you with free consultancy, in their own time - please don't get pissed off if you can't understand the advice / people don't provide you with the whole project on a platter.
Unfortunately, the only way to learn to use any language / framework is to go through a bit of pain, there are people around (a surprisingly large number of them in places like the ASP.NET forums) who are providing free consultancy for little or no recognition (MVP awards being the exception...but then I've never understood how those doohickeys are awarded...write a book, get an MVP - go figure!).
So policy from now on...if I give you advice and you don't find it useful - ask someone else / actually use your brain to try to process the information which I will have usually spent hours compiling for you, for free!
Gripe over...now I'm going to write an article on Nester Data List Controls...I really am this time...honest!

.NET Passport on Windows Server 2003

There's an odd issue when you try to use Passport on Windows Server 2003 - basically, the default 'Secure Level' of Passport is 10, unfortunately if you don't use SSL this means Passport won't work correctly for you. In .NET this manifests itself as the Passport scarab showing you as logged in but if you try Context.Identity.User.IsAuthenticated, it'll always return 'false'.
 Now, I know what you're thinking, just change it to '0'...umm...nope, the default Passport Administration tool installed with Windows Server 2003 won't let you change this...and you can't (well not in any way that I've found so far) upgrade to 2.5 (appears to...but the admin utility doesn't change...). So, you have two options (well three, but ignoring it rarely works...), either change the registry key (described here) - or connect to your server from a machine with Passport SDK 2.5 installed (from the admin tool) and change it that way.
I have to say, the support for Passport is pretty rotten - as is the SDK and support on Server 2003 (which really is unacceptable IMHO). I've said before, this is a pretty nice system when it works but no-one is going to adopt it when it's so pernickety and costs so damn much ($10,000 a year last I checked)! Come on, what about a developer / community type license? Also, when is .NET Passport 3.0 actually going to arrive (the fabled Web Services enabled Passport)?

New Application Block - Authorization and Profile Block

This looks to be very useful indeed. Found it on the Devhawk blog. Here's some blurb from the page:

Summary: If you are involved in designing and developing applications, you probably need to control how users interact with your applications on a case-by-case basis. For example, administrators, managers, and employees may need varying levels of access to your applications, and in some cases an individual user may have different roles in different applications. It is a significant challenge to enable this flexibility, particularly in situations where administrators maintain account information in different authorities and user databases.

The Authorization and Profile Application Block is a set of reusable code components that you can use to customize the behavior of an application for individual users. This guide describes the design and features of the Authorization and Profile Application Block and demonstrates how you can use the block in your applications.

Similar functionality is supplied in Whidbey (ASP.NET 2.0), but this does looks just stunningly useful. Support for Profiles in a 'standard' manner (which looks very similar to the Whidbey implementation at first glance) is just incredibly useful - how many times have you supplied this functionality, in how many different ways? 
I really recommend getting to know and love the Application Blocks, I use the Data Access Block and the Exception Management Block pretty much all the time now, they help enforce best practices and save a whole load of typing!

I knew it - finally proof that 'slepping on it' helps solve problems!

Just thought this was pretty interesting - from Slashdot:

An anonymous reader writes "CBC news reports that the effectiveness of 'sleeping on it' when faced with a difficult task may have more than just anecdotal roots. 66 students were trained to perform a calculation on an eight digit number using two simple rules which would take seven steps to complete. A different method existed to perform the same calculation 'almost instantly', but was not shown to the students. After eight hours, where half the students were allowed to sleep and the other half remained awake, 60% of the rested and 22% of the wakeful students discovered the more efficient method."

 

Another article in the offing...hopefully...if I get round to it...Member methods versus OnItemDataBound for nested Data List controls

A very common question in the ASP.NET Forumsis "How do I nest one Repeater (or DataList or DataGrid) inside of another?"; well, my usual stock answer used to be to use the OnItemDataBound event then use a FindControl() to find the Repeater inside the template and set it's datasource to the child view - then just DataBind...Recently though, I've gone against this - based in part on a bit in a book by Farhan Muhammad and Matt Milner (can't find the link to the exact book, but this one is pretty useful too), essentially, it involves using a member method. So, instead of hooking up the event you simply specify the DataSource of the Child Repeater as follows (for example)
<asp:Repeater id=FormatsRepeater DataSource="<%# GetFormats(Container.DataItem)%>" Runat="Server">
, along with the rest of the templates etc for the child repeater. Then, in code (the codebehind normally), you simply do this:

public DataView GetFormats(object DataItem)
{
DataRowView di = DataItem
as DataRowView;
if(di!=null)
return di.CreateChildView("JobCount");
else
return null;
}

Hmm..BlogJet isn't great at letting me modify HTML - I'll sort this later...anyway, as you can see, very simple code (incidentally, should mention, I'm using a DataSet with a DataRelation called JobCount). What's the upshot of all of this...well, the Member Method version, as well as (IMHO) being much easier to write than the ItemDataBound version - is also MUCH faster - in some tests, twice as fast! Anyway, I will hopefully write a bigger piece on this with some stats to prove my point - if I get round to it :-)

Free Snow Patrol track with Winamp 5.0 download!

Just noticed that Winamp is giving away a free copy of Spitting Games by Snow Patrol, so you just download the bunde! I bought the Snow Patrol album, Final Straw when it was first released a few months ago - looks like it's now getting re-released with a couple of extra tracks (no idea if this includes the US version, but you can get it on import from Amazon). I really rate this album - recommended!
I should add that this is a limited play (60 days) wma - good quality though and a pretty good song!

More on my Load Testing fun...

Well, still at it (20 hours after starting - yes, the time on this post is correct!). Really fustrating mostly, but one of those times coding where hours and hours of pain (literally in this case - flu and splitting headaches were involved) were followed by a sudden dawning then a solution.
Well, I've learnt more about Load Testing and SQL Server performance today than I had in the previous 2 years, lessons I've learnt:

  • SQL Profiler is god's own tool (not in any nasty sordid way, in a good way) - use it, love it! If you're running a load test, run Sql profiler at the same time...then look at the results, taking special note of reads and duration of queries...then...
  • Use SQL Query Analyzer's 'show execution plan' option, look at the little graph carefully, looking for places where lots of non-indexed table scans are happening / a  whole lot of work is going on where you don't expect it!#

It turned out that my problem was to do with a trigger firing on inserts, this updated a stats table which locked my main table - resulting in a bad Deadlock...as long as I had free connections it was fine, but the connections following the insert which queried the same data were getting hung because of the trigger's lock - so the number of connections racked up, eventually causing timeouts and other horridness...

Incidentally, I came across the rudest, most unhelpful Sales rep on the planet today (my opinion only!), a certain load testing tool company (the No.1 in the world apparently - god knows why!), I needed an eval license to do a quick run through of the load testing script my client was using - so I applied for an eval license from the website, downloaded and installed the tool - so far so good! Now, if this product was good enough, my company would probably have sprung for a license - problem is that they 'don't offer eval licenses in Europe' - implication was that I'd use it to rip them off. Alternative, spend an afternoon with their sales guy or spend $10000 on a product which I've never used (an afternoon would mean rouchly £5000 lost earnings for my company). My alternative was to use the free eval of another company's tool (won't mention the name yet in case I hate it) - so the first company have just lost a potential sale.

If you offer an eval download - especially one that requires you to install the software before you can even apply for a liocense - make damn sure you mention that there's not actually one available!

The agony of load testing - my head hurts (though the two may not be related)

Deadlocks...I hates the little buggers!
Just spent the day trying to fix an 'issue' with a site I developed for a client. This is slightly annoying as it's a 'theoretical' issue. Essentially, the client has chosen to do something that I never normally do, load test the edit pages of the site.
Unfortunately, this site has an odd editing system - it uses the concept of a 'common' tables to hold all items no matter what type of item they are (so it holds all the common properties, with the distinct properties being held in different tables). This design gives me a whole lot of flexibility - and lets me use a bunch of common controls to represent the objects on display, for security etc...
However, it does have a big drawback - to actually edit some items means making multiple updates to the same table on one Use-Case - it also has a couple of indexed views on that same table. This has led me to where I currently find myself, if we run more than say 10 concurrent users (so, creating 10 new items at exactly the same instant, then trying to pull that same data out of the DB) I get this after about 200 or so repetitions:

Transaction (Process ID 74) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.  

Well, I've been working on this all day, optimising queries, creating new indexes, killing triggers, caching data in page, the lot...as a result I have a rotten headache and have basically lost all objectivity - I have no idea if I've really improved matters or not!

Also doesn't help that I don't actually know the target number of users I'm trying to optimise for!
Incidentally, I have calculated that based on common usage patterns, 10 concurrent edits would roughly equal ~1000 concurrent 'view' users or around 144000 visitors a day...umm..yes, that's probably 100+ times more than this site gets at peak...

Oh, should say, if anyone's been having problems with the site today, this is to blame - I've been load testing like a mad thing and my poor server's feeling the pain...

More in my 'my ADSL sucks' series

So annoying...many nights at around midnight, my connection just seems to freeze. Helpfully, my provider says 'well just restart your router'...hmm...so, I apologise if you're having problems connecting, it's even more fustrating for me!

Testing BlogJet - really cool tool to post to your blog from your desktop!

I have downloaded and installed an interesting application - BlogJet. It's a Windows-client for my blog tool (as well as some for other tools).

Actually, it was not me who wrote this text: when I launched BlogJet for the first time, it's edit window already contained this text and the program asked me to click Post and Publish button to post this text to my blog in order to test the connection (yes, and the text above is not mine too! :-)... So, I did.

Now I'm gonna learn all that cool features of BlogJet (don't ask me, there are too much - go to their website and read).

 

I thought I'd post this - VERY nice tool - thanks to Paschal for pointing this thing out, very nice, simple tool - way better than w.bloggar!

Pure ASP.NET file upload...I have my doubts...

OK, maybe someone 'in the know' can settle this, is it possible to upload large files efficiently purely using ASP.NET? 
I've been following a thread in the ASP.NET forums about providing a method to do this using HttpHandlers / Modules to do this. What confuses me though is, is there any point to this? As I understand it, IIS will cache a Request stream before passing it, in it's entirety, to ASP.NET. If this is true then there's no way to efficiently upload files in ASP.NET - since the whole file would need to be held in memory before upload - uploading a 4GB file would require 4GB+ of memory. Can anyone confirm this, does IIS 6.0 change this behaviour???

Another busy weekend - and using Dynamically loaded user controls the easy way

Well, spent the weekend working again - had a sudden stroke of inspiration about a work project, much refactoring later, I have a more stable and flexible implementation.
I may write about this in more detail at a later date, got some pretty cool stuff going with Page templates etc...
Until then, just a reminder about the most useful thing on the planet when using Dynamically loaded user controls - Denis Bauer's DynamicControlsPlaceholder. I've posted a link to this control a few times now, but I can't overemphasize how much faffing around it can save.
Another reminder, if you want to load controls (using the Page.LoadTemplate() method) and have their events work, load the controls in PreRender (since that happens after the PostbackEvent has fired whereas OnLoad fires before) - and use the DynamicControlsPlaceHolder's ControlRestored event to rebind the event back on to the restored control.
Pretty simple, but it's one of those questions I've answered quite a few times in the ASP.NET forum - and is a real gotcha for beginners.
I'll probably post a little example project using this method and a couple of others when I get a chance.

Code Complete 2

Code Complete by Steve McConnell is, in my opinion (and many others), the best book ever about the art and discipline of coding. Basically, it's just the bible of how to design and build quality software. So, I'm really looking forward to Code Complete 2 (link is to a draft manuscript of the book) - if you've never heard of this book or read it, do yourself a favour, set aside a few hours and read the draft - then buy the book when it comes out in June.
As a measure of just how good the original is - it was published 10 years ago, yet many people still consider it the bible of coding!

Wow, use HTC within Mozilla!

This comment to my moan about this is VERY cool:

I think I've solved your problem! I've successfully developed a Mozilla wrapper for Microsoft's HTC files. It is encapsulated in a single XBL binding, so is exremely portable.
The binding is small (4k) and contains compressed JavaScript code which loads the behavior and applies the interface. The interfaces of some objects have been extended to allow further cross-browser compatibility.
I've only just finished this development. So you are the first to here about it (apart from
a few bored friends). I would be delighted if you would take a look and feed back some comments.
For a full working demo (with no browser sniffing), go here:

http://dean.edwards.name/my/examples/moz-behaviors/

there is some (scant) documentation here:

http://dean.edwards.name/my/

Dean Edwards

Had a quick play with this (I'm off work sick right now so I'm doing this in the few minutes between each extended sleep period), and it looks excellent. I also discovered a cross-browser rich text editor recently...it finally looks like it's becoming possible to support a full rich user experience no matter what browser you're using (there is no excuse so far as I'm concerned to be using Netscape 4.x now...)

UPDATE: Dean continues to update this:

Just a quick note to say that I have since updated this to accomodate Mozilla 1.6b, Also, I will be publishing the full source code for this in a few days time (along with some documentation and coding tips). So check out my site in a few days time.

An article I really have to write - oh the woes of being lazy...just why the hell does everyone use DataGrids?

One thing that really puzzles me in the ASP.NET forums (apart from having to be moderated...which is a whole other story) is that practically everyone seems hell-bent on using the DataGrid. Why? What am I missing; I VERY rarely need to use a DataGrid, a Repeater is perfectly adequate for most of my needs - failing that a DataList is just fine.
So come on perople, what's so hot about the DataGrid?
Incidentally, I've been meaning to complete an article on this subject...I really have to get on with writing more articles - if only to give myself something to do!

Stuff on compressing .TEXT RSS feeds from Jeff Julian

Pretty useful if you don't have the ability to use IIS compression (or choose not to) - Jeff Julian has released a 'plugin' for .TEXT which enables you to compress the RSS feeds produced by .TEXT 0.95 - which is very useful, most of my traffic for instance comes from the RSS feeds (I get around 200 HTML compared with 1800 RSS views per day).
This uses the HttpCompression module by Ben Lowery, which is in itself a brilliant way to enable compression. Ben also links to a MS hotfix rollup package which fixes an issue with HttpModules and Server.Transfer - am I the only one who's rerally annoyed that you have to contact MS to obtain this - what's wrong with just providing a download link (oh, I'm not - and i even mentioned this before)?

How not to spend a weekend

I spent this weekend doing some 'product investigation' for a pitch we're preparing - which basically means that ensuring what we're saying in a pitch actually matches up with the product's capabilities. Not much fun, but has given me some ideas for future posts, oh and a future project...details to follow (don't want to queer the pitch by posting too much about it now). Anyway, my friend this weekend has been the marvellous Strong Roast Guatemala from Whittards (UK high street coffee suppliers) - lovely, smooth, chocolatey coffee ideal for espresso.

Playing with MS CMS...

Well, I spent the weekend 'playing' with Microsoft's Content Management Server 2002 - well, it's better than the 2001 version, principally because it feels more like a 'proper' .NET enabled application. Still feels a bit incomplete though - there's way too much swapping between apps involved when you're working with it  - a Visual Studio Server Manager would be great for this thing - even proper MMC would be a boon.
Still, pretty interesting - anyone have any info on the future version?

Another in the 'things I didn't know but really should've done" - you can disable Client Side validation with client-side script...

OK umm, actually quite embarassed about this one...I just discovered this was possible...so I can emit a bit of Javascript which lets me disable validation on a control when some condition is met here's this bit from MSDN:

 

Client-Side APIs

Some additional scenarios are enabled by functions that can be called from your client-side script.

Table 4. Functions called from client-side script

Name Description
ValidatorValidate(val) Takes a client-validator as input. Makes the validator check its input and update its display.
ValidatorEnable(val, enable) Takes a client-validator and a Boolean value. Enables or disables a client validator. Being disabled will stop it from evaluating and it will always appear valid.
ValidatorHookupControl(control, val) Takes an input HTML element and a client-validator. Modifies or creates the element's change event so that it updates the validator when changed. This can be useful for custom validators that depend on multiple input values.

Of particular use is to be able to enable or disable validators. If you have validation that you want active only in certain scenarios, you may need to change the activation on both server and client, or you will find that the user cannot submit the page.

Here is the previous example with a field that should only be validated when a check box is unchecked:

    public class Conditional : Page {
        public HtmlInputCheckBox chkSameAs;
        public RequiredFieldValidator rfvalShipAddress;
        public override void Validate() {
            bool enableShip = !chkSameAs.Checked;
            rfvalShipAddress.Enabled = enableShip;
            base.Validate();
        }
    }

Here is the client-side equivalent:

<input type=checkbox runat=server id=chkSameAs 
   onclick="OnChangeSameAs();" >Same as Billing<br>
<script language=javascript>
function OnChangeSameAs() {
    var enableShip = !event.srcElement.status;
    ValidatorEnable(rfvalShipAddress, enableShip);
}
</script>

Stupid, stupid ADSL

Sorry, ADSL is playing up again, please keep trying if you're having problems...

Well, can't sleep yet again...the questions which flit through my mind in the long hours of sleeplessness

I've been frequenting the ASP.NET forums of late, great resource but not without it's problems. As a supposed 'communities expert' I thought I'd stick my oar in...as usual!


The poster rating system...hmm..I really don't like this one bit, being assigned a status (e.g., top 25 poster) solely based on the number of posts does nothing to encourage quality, rather it encourages swarf and provides no indication to users as to the probable 'quality' of posters answers


Moderation, I was recently stung with this one in the stuff I posted yesterday - the foreach debacle - essentially the bloke I was replying to was not moderated I - being one of the plebes - am, this leads to really odd conversations where I reply to a post meanwhile the other poster continues a line of thought, only for my posting to appear at some later date, totally disjointed!


Errors - especially tonight, this site is pretty error prone (think they're updating a server in the cluster or some such) - this is VERY bad for ASP.NET's image - one of the places where people evaluate a technology is in it's most visible apps - ASP.NET and it's forums are a biggy, scheduled downtime / some other mechanism would be far more preferable!


RSS feeds - nice, but supporting CommentAPI would rule, would let you follow an entire forum without having to access the site!


'User Scarabs' - hmm, these I  guess are some attempt at a 'quality assurance' mark, but there's loads of them! ASPInsider (which no-one has a scooby about!), MVP (OK, that one is useful), moderator (why do I need to know this, what does this imply - except that they're able to ditch your reply), ASP.NET team member - this is a useful one!. So, what about trimming them down - maybe limiting them them to a star type system, indicating the user indicated quality of responses.


The sheer number of forums on the homepage - would be nice to be able to collapse these (ala web-parts), there's a ton I have no interest in but it's really easy for the eye to skip over ones that you are...

I don't expect any response to these, and I'm well aware that there's a Version 2.0 due any day - but I just had to get this stuff off my chest...

Mars today wallpaper...

Though I'd quickly knock this up - wallpaper from the Mars Probes page. Get it here (1600x1200)

Getting involved in dumb arguments...of when 'for' and 'foreach' can lead to idiocy...

I do have a tendency to get involved in pointless arguments in the ASP.NET Forums...a good example is this one, arguing about the performance of 'foreach' versus 'for'...any opinions from here - the crux of my argument is that for() will in general perform better than foreach() - because the generated IL simply does far less in most cases (I am aware of some optimisations which reduce the benefit for very simple collections).

Isn't it ironic

Just looking back through some old posts, I started this blog on my own URL (so not on ASP.NET weblogs) so I could post whatever I wanted...strange thing is, this blog is more focussed on .NET specific information than most of the ones there now...

Even more on ViewState...well, my pet peeve on ASP.NET really...

I've been giving some more thought to the ViewState stuff I mentioned earlier. It actually brings up something which I find most annoying about ASP.NET - and this is not a political point! Why exactly can't 'ordinary' users see the source for ASP.NET, so far as I'm aware, no equivalent of Rotor exists for ASP.NET. I'm guessing that certain MVPs can access this source though the Shared Source initiative - the rest of us have to rely on things like Reflector to poke around (imagine how useful it would be to be able to attach a debugger to the ASP.NET source!).
The argument which I guess may apply to this would be the old 'if we give access to the source we can't change it' or 'people will change it themselves, causing us more problems' - umm, JSP and J2EE have full source access, and always have had - this just hasn't happened (though I did learn JSP far more quickly because I could root about and understand what was going on).
So, assuming we can never access ASP.NET source, how do we get over problems lke I've been having messing about with ViewState? Simple, factory methods for core framework items. Luckily ASP.NET 2.0 does this for some items (mainly the new ones it has to be said) like Personalisation and Membership - where you can specify your own provider classes for these items.
If only this were also the case for all the other ASP.NET core items - for example, Session state has a similar issue, you can persist to the three state stores which ASP.NET allows, SQL server, extrenal state server of In Process - would it have been really so difficult to allow the specification of a user-defined class for this as well (if ASP.NET 2.0 has this already and I'm just to dumb to find the reference, please let me know!)?
So, ASP.NET 2.0 - big step forward in user customisation of core framework items - but just a bit further would be fantastic!

UPDATE:  Just noticed this entry on Jason Salas's weblog - a ViewState API...hmm...not sure about how practical a declarative strong typing system would be (example 2); a site will generally store hundreds of items in ViewState - strongly typing each one would be a total pain. Example 3 is pretty cool though:

CHEESY EXAMPLE 3:

int homePhoneJenny = 8675309;

ViewState.Insert(“keyPhone”, homePhoneJenny,System.Int32);

 

 

That seems pretty useful!, so I could do ViewState.keyPhone to get an Int32 back...still doesn't  solve the issue that we can't play with how ViewState works though - so I can't specify that I want to use Rijndael as the encryption mechanism (3DES is pretty slow!) or that I want to compress the ViewState / even store it elsewhere / modify how controls can access ViewState without all the playing with overloaded methods or even reflection (shudder)...

Really interesting sample on ViewState preservation for non-visible controls

Nice sample and methodology from Robert Downey (obvious joke omitted), shows some really interesting (to me at least) insights into the workings of ViewState (you may be noticing a pattern here :-))

Great article on Eggheadcafe.com on ultra-compact binary serialization of DataSets

Was having a look at this article by Peter A. Bromberg Ph.D. (don't know if that's his given name ;-)) over at Eggheadcafe.com, I always found it a bit annoying that DataSets serialized to XML only. Using the incredibly cool CompactFormatter, combined with the old favourite SharpZipLib, he's able to squish a DataSet down to just 4.6% of it's original size - now that's a pretty useful reduction!
Why is it useful - well when you're sending a DataSet over a webservice, it's likely that most of your latency will be caused by the physical transmission of data...the less data, the smaller the latency!
I really like Eggheadcafe.com, they tend to have more esoteric articles than most other sites around...and it has the best coverage of uses of compression in ASP.NET anywhere!

Can't sleep...and looking for a new aggregator

Well, I'm suffering from post new year sleeping pattern - I basically become nocturnal over the Christmas and New Year (Hogmanay) holidays, have to start work in 8 hours...not good! Anyway, while I am sitting here awake (there's a show on about Turkish Harems; not as tittilating as it sounds, very political), thought I'd embark on a hunt for an new RSS aggregator.

I've been using Feeddemon during the Beta period, it's very nice, pretty interface etc...however it doesn't support CommentAPI and I'm not sure I want to pay $29.95 when there's comparable free products.
I've now installed RSSBandit, it's pretty nice but nowhere near as polished as Feeddemon - why can't I expand the Treeview??? It's in the lead so far...
SharpReader, hmm...still usies way too much memory, but it does have a nice w.bloggar plugin and support for more bloggy type stuff!

I guess it's still early days for this type of product (I can't consider stuff like NewsGator right now due to some mail config stuff (I want to keep stuff away from my Exchange server)...anyone else using interesting aggregators?

More on my journey into the wonderful world of ASP.NET 1.x ViewState

I wrote in a previous post that I was planning to have a poke around with ViewState, extending the stuff I've done on compression into encryption and signing etc...well there's good and bad news for this plan. It looks like (oddly) that the MAC  and encryption stuff is actually handled in the LosWriter class; an internal class used by LosFormatter to actually do the object serialization...it uses the following code to do this (thanks once more to the indispensible Reflector) :

 

internal void CompleteTransforms(TextWriter output, bool enableMac, byte[] macKey)
{ int num1;
byte[] array1;
string text1;
char[] array2;
string text2;
num1 = 0;
if (this._recyclable)
{
 this._byteBuffer = ((byte[]) LosWriter._byteBufferAllocator.GetBuffer());
if (this._freePos > 0)
{
 num1 = Encoding.UTF8.GetBytes(this._charBuffer, 0, this._freePos, this._byteBuffer, 0);
 
}
if (enableMac)
{
 array1 = MachineKey.GetEncodedData(this._byteBuffer, macKey, 0, &(num1));
text1 = Convert.ToBase64String(array1, 0, num1);
output.Write(text1);
return; 
}
array2 = ((char[]) LosWriter._charBufferAllocatorBase64.GetBuffer());
num1 = Convert.ToBase64CharArray(this._byteBuffer, 0, num1, array2, 0);
output.Write(array2, 0, num1);
LosWriter._charBufferAllocatorBase64.ReuseBuffer(array2);
return; 
}
this._byteBuffer = Encoding.UTF8.GetBytes(this._charBuffer, 0, this._freePos);
num1 = this._byteBuffer.Length;
if (enableMac)
{
 this._byteBuffer = MachineKey.GetEncodedData(this._byteBuffer, macKey, 0, &(num1));
 
}
text2 = Convert.ToBase64String(this._byteBuffer);
output.Write(text2);
 
}

 

As you can probably see, this code handles the application of the MAC key  and encryption to the serialized data. This is the code used by the 'MachineKey' to perform the encryption:

 

internal static byte[] EncryptOrDecryptData(bool fEncrypt, byte[] buf, byte[] modifier, int start, int length)
{ MemoryStream stream1;
ICryptoTransform transform1;
CryptoStream stream2;
byte[] array1;
byte[] array2;
MachineKey.EnsureConfig();
stream1 = new MemoryStream();
transform1 = MachineKey.GetCryptoTransform(fEncrypt);
stream2 = new CryptoStream(stream1, transform1, 1);
stream2.Write(buf, start, length);
if (fEncrypt && (modifier != null))
{
 stream2.Write(modifier, 0, modifier.Length);
 
}
stream2.FlushFinalBlock();
array1 = stream1.ToArray();
stream2.Close();
MachineKey.ReturnCryptoTransform(fEncrypt, transform1);
if (!fEncrypt && (modifier != null))
{
 array2 = new byte[((uint) (array1.Length - modifier.Length))];
Buffer.BlockCopy(array1, 0, array2, 0, array2.Length);
array1 = array2;
 
}
return array1; 
} 

 

Unfortunately, this means I'll either have to play about with reflection / dump the source from Refelector / completely reinvent how this works to go much further with my ViewState tinkering, god it'd have been nice if this stuff were done with a Factory originally...guess they didn't think anyone would be nuts enough to want to play with it...:-)

I'm eventually going to have to relent and actually write an article one of these days...problem for me is structuring the thing so it's readable to non-obsessive humans...

More on BZip2

In a previous post, I mentioned I used BZip2 for my compression - mainly because, it's simple, offers the best XML compression for a generic algorithm - IMHO, i.e., not one designed specifically for XML compression like XMill - which if anyone knows a C# or Java implementation of - please let me know.
Anyway, you can get BZip2 (with a number of others) in the excellent SharpZipLib library. I really lament the lack of specific support for compression within the .NET framework, I mean the J# stuff has it  in the java.util.zip namespace, would it really be so difficult to include this invaluable functionality within the framework proper?
As it stands, you can encrypt but not compress data - there's no simple way to use compression from web services, you can't natively compress serialized objects - you can't really even open a compressed file without a third party plugin! XP now has compressed file support, why not the .NET framework!

ViewState compression using BZip2...latest prototype...

Just a first stab at this, uses some classes I used in another project (I'll attribute the compression code later...I believe I got it from the Sharpziplib stuff - with some modifications - I'll stick the comment headers back in to comply with the Licensing stuff later - right now consider it an example only) the actual code to compress the viewstate is VERY simple:

using System;
using System.Web.UI;
using System.IO;
namespace ViewStateCompression
{
    /// 
    /// Summary description for CompressedVSBasePage.
    /// 
    public class CompressedVSBasePage :System.Web.UI.Page
    {
        private LosFormatter  _formatter = new LosFormatter();
        protected override void SavePageStateToPersistenceMedium(object viewState)
        {
            StringWriter sw = new StringWriter();
            _formatter.Serialize(sw, viewState);
            string outStr = Compression.Compress(sw.ToString());
            Page.RegisterHiddenField("__COMPRESSEDVIEWSTATE",outStr);
        }
        protected override object LoadPageStateFromPersistenceMedium()
        {
            string vsString = Request.Form["__COMPRESSEDVIEWSTATE"];
            string outStr = Compresssion.DeCompress(vsString);
            return _formatter.Deserialize(outStr);
        }
    }
}

To use it, just inherit from this page instead of the normal System.Web.UI.Page. Obviously you lose some of the normal Viewstate functions such as encryption - but these should be easy to slot back in...I am currently seeing pretty large savings in ViewState size from using this - using BZip2 compression - as it's a piece of code I had lying about..., please try it out. Any comments / suggestions are, as always, appreciated.

UPDATE (27/05/2004):  I've updated the demo project, you can now download this from here. Main changes are that it now uses my Compression helper object - this uses the standard SharpZipLib, is a bit more efficient and lets you switch between all the SharpZipLib compression types very easily. My experience has shown that this method is best when you're using objects like DataSets which under.1.1 serialize pretty poorly (as in DataSets really serialize to a form of XML - which tends to compress really well). In addition, do not turn on encryption when doing this - the compression is REALLY poor then. It's really simple to add encryption back in again - just do it to the string you get from the Stringwriter after serialization - I'll add an example later (using Rijndael is also gonna be more secure and much faster than 3DES).  Also, someone called 'Mark' left a comment with some great performance figures, here's the comment:

Played around with this a little. For smaller view states (did a short comparison with a view state of 100200 bytes) it's faster on a normal network not to use GZip or BZip2. Roughly: The original file size was 224 Kb. GZip got the file size down to 197 Kb but it took about 0.5 seconds longer, BZip2 got the file size down to 190 Kb, but it took about 1.3 seconds longer. With a larger view state (used a view state of 1115624 bytes) the original file size was 893 Kb. GZip got the file size down to 501 Kb and was actually almost 0.4 seconds faster. The BZip2 got the file size down to 434 Kb, but it was still about 1 second slower than using no compression.

These figures really don't mean much, since I didn't take many samples. However, for me it confirmed that BZip2 might only really make it go faster when the view state is very very big. BZip2 provides very nice compression, but it's slower. GZip doesn't provide as high as a compression rate as BZip2, but it's faster. Below a certain threshold (which is hard to determine since network speed influences this), compression really just slows it down. I am looking at using a fast compression algorithm like LZO. Hope this helps anyone interested in this.

Well, I'm back...and comments on some books...

Had a nice, relaxing holiday, read a few books, I can recommend Charles Petzold's Code and kind of recommend Homer, Sussman and Howard's Introducing ASP.NET 2.0 - I say 'kind of' because I found it really patchy in the writing style...but then I've never liked one of the authors' styles (not Rob's :-)).

 Code is a pretty unique book, goes right from morse code, through binary arithmetic, electronics and right on to microprocessors and finally code - ties it all together in a way that my CS classes never did, not very easy going but very interesting and informative!

Introducing ASP.NET 2.0 gives coverage to most of the new ASP.NET 2.0 specific features - it's NOT a coding book though, more just a general overview of what the new bits are - anyone know a more codey .NET 2.0 book?