Andy's observations as he continues to attempt to know all that is .NET...

Saturday, October 21, 2006

SynchronizationContext assists layering

Having just got back from two weeks travelling I was confronted with the need that my oldest daughter needs to learn her times tables for a tester after half term. Being away a lot and the children having loads of after school clubs etc means we often find it hard to find the right moment to practice. So I decided to write an app to help test them on it…Ok so I’m sure there are tons of them out there…but you can’t beat a home grown solution ;-)

Seriously there is a couple of areas I am focusing on at the moment,

  • Ramping up for DM’s .NET architecture course.
  • WPF.

This seemed like a good exercise where I could put both these skills to good use. Now even DM instructors have time pressures this app needed to be written like yesterday if the kids are to start using it to get ready for their test. My WPF skills aren’t there yet that I could confidently build the UI that quick, but in a few weeks I do want to add a WPF gui. So this creates a great architectural opportunity for me to structure the solution into clear layers…Model, View and Controller. The View and Controller layer is specific to WinForms and I obviously want to write as little code here as possible, putting most of my focus on the Model, in this case a Times Table Test engine.

First I built the model defining a type to represent the test, and exposing properties for three possible answers and a running score. The type also had methods for requesting the next question and submitting an answer. In order to make the view be updated by changes in the model I had to implement the INotifyPropertyChanged interface on each model type in order for them to notify the UI of any changes to the model.

Then I moved onto building a form to display the current question. Labels were used to pose the question, and to display the score etc. The possible answers were represented by buttons. Having laid out the form it was then just a question of wiring up, the various labels and buttons to display the correct values, this was achieved through the use databinding via bindingSources, all the wiring up done inside the designer. I then had to wire up the actions for the various buttons to communicate the users response to the question and to move the question forward. But So far so good…virtually no UI code written.

However whilst this was ok to make the app really useful the user needs to enter the response in a finite period of time. So this created two options implement a timer in the UI layer or in the model…For me I obviously wanted to place it into the model since that piece of code would be reused when I implement the WPF UI.

So off I went and added a Timer thread to my model, the activity on this timer thread would cause various bound properties in the model to be updated, which then had the effect of firing PropertyChanged events to all objects bound to these properties. Since some of these bindings where to UI components this would result in the UI component being updated on a thread other than the thread used to create the UI component. Attempting to update a UI component on a foreign thread is technically not allowed, and in .NET 2.0 if you have a debugger attached and you attempt to do so you get a cross thread exception…to my surprise I didn’t get one…just the update’s failed to be propagated to the UI. This I thought was a bit odd…but since the update didn’t happen I guess it’s by design Im not 100% sure of the exact reasoning behind this..Anyway for me I need to fix this situation since I did want my UI to be updated.

In order to solve this problem I would need to cause the event to actually be delivered on the UI thread. The conventional way to do this in WinForms is to use a pair of methods on every control called InvokeRequired and BeginInvoke. But this would mean that my model code would need knowledge of winforms to ensure that all events fired on the UI thread Yuk and breaks my architectural model.

There is however a more general way of doing this using something called SynchronizationContext, this is an abstract class that provides a way of marshalling a delegate onto a specific thread. You can ask WinForms for the current SynchronizationContext and it will return an object that can be used to post work back onto the UI thread. You write your code against the abstract class, and assuming other UI implementations that require thread affinity also support this then my mode can be written just the once. In fact WPF does have support for this so cool…the model can be written to deliver PropertyChanged events on the correct thread. To ensure my property events are marshalled onto the appropriate thread I have a method which looks as follows.

private
void SafePropertyChangeNotification(string property)

{


if (syncCtx != null)

{

syncCtx.Post(delegate

{

OnPropertyChanged(new
PropertyChangedEventArgs(property));

} , null);

}


else

{

OnPropertyChanged(new
PropertyChangedEventArgs(property));

}

}

What I’m struggling to understand is why they MS never added support in the BindingSource type to perform the marshalling operation, they are after all detecting the attempt to perform a cross thread operation and silently ignoring it, giving you the option to configure the binding source to marshal the update would have been dead cool.

Anyway the SynchronizationContext does allow me to decouple my model from my UI implementation, and does allow me to write a single piece of marshalling code that will work with WPF or WinForms..

The first version of the times table tester is now complete, the UI layer is extremely thin…and I even managed to deploy it in our home network using ClickOnce…I know scary I actually taught the kids how to just say ok to the not trusted publisher prompt….

Over the next few weeks I’m going to build a WPF version of the UI and assuming no hidden gotcha’s Im just simply going to replace the UI layer with a new one


 

You can download the full code from my download page


 


 


 


 


 

Tuesday, October 10, 2006

Korean’s get excited over VSTS

Whilst teaching the other week Jason pointed me to this cool VSTS video where Korean developers had to make their own jingle to spread the news….

Check out the Video ignore all the requests to install the language packs unless you want Korean characters on your machine..


 

BioGuard fingerprinting booted out

If you have read my earlier posts you may have read my rants on how my kids primary school was attempting to implement fingerprinting for school registration. Finally after a whole year and some money they eventually got it that the idea was just plain dumb….how they ever expected to integrate such a system such that they had a reliable and fault tolerant registration system at a reasonable price was beyond me and any else who had any reasonable amount of IT experience.

So whilst I’m pleased I’m just hoping that no other school gets approached by Bio Guard or its resellers in the UK. It also made me chuckle today as their web site hinted that finger prints are globally unique something we now know to be false.


 

More than just coffee

The whole identity theft took a new twist today whilst at Starbucks I noticed that the electronic credit card machine had a sticker on it and in big letters were the Network Address of the device and other network details…..Wow some hacker would just luv to lap those numbers up along with their espresso….The nice girl behind the counter did remove it…


 

Tuesday, September 05, 2006

Slicker Labels

Whilst thinking up some more interesting WinForms demo's I just thought Id have a go and at making a the bog standard label control a bit more interesting...so I knocked up a new version that fades text in and out when the label's text property is modified.

The Source code can be downloaded from my downloads page

Monday, July 24, 2006

WHAK a Mole WPF

Just started to play with WPF, and just had to port Jason’s W infamous WHAK a mole game to WPF. Hasn’t exactly pushed the boundaries of my GPU, but more about starting getting to grips with XAML, WPF event model and inner content.

Download Source


 

Wednesday, July 12, 2006

Every OS Sucks


 

Currently teaching a DM Guerrilla, and we have been playing some short funny geeky type movies, a student offered this one to be considered….

Every OS Sucks…


 


 

Friday, July 07, 2006

Visual Studio and ASP.NET Master Pages


I finally got tierd of the bug in the Visual studio designer for ASP.NET master pages. The issue is this, if you don’t hardcode the master page for the page in the page itself the designer will not see that you are using master pages, even if you define one in the pages section of web.config. This greatly defeats one of the objectives of master pages in that I would like to tweak the master page at deployment time, and the default behavior is page value overrides config file.

Possible solutions are have a default.master page, and make all pages point to that. Then have the actual master pages as separate files and simply copy over the default.master with the one you want at deployment time.

That seems clunky to me, so another option would be to make it use the value in web.config as opposed to the one defined on the page. You can do this by creating a new class that sits between your form and the System.Web.UI.Page class. This class will simply inspect the value held in web.config and if its set override the page setting.


using System;

using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.Web.Configuration;

class SiteMaster : Page
{
protected override void OnPreInit(EventArgs e)
{
PagesSection pagesSection = (PagesSection) ConfigurationSettings.GetConfig("system.web/pages");

if (pagesSection.MasterPageFile != String.Empty)
{
this.MasterPageFile = pagesSection.MasterPageFile;
}



base.OnPreInit(e);

}
}

}


Simply modify your code behind file to look like

public partial class DefaultForm : SiteMaster


And you will now get the master page as defined in the web.config. For pages you want to set by override the site default continue to derive directly from System.Web.UI.Page.




Finger printing in schools just gets hotter…

A while back I mentioned that the primary school my children are attending was planning to introduce fingerprinting for school registration. I believe I’ve managed to get that stopped now, however this is not the case for many parents who are currently discovering that without their knowledge or consent their child’s biometrics have been taken by the school and stored for such trivial uses as borrowing a library book.


The companies involved in this technology keep stating there is no problem and parents have never objected…So thankfully a new web site has been launched which is now clearly stating for the record that this is clearly not the case.


Please check the web site out, and make your voice heard….Leave Them Kids Alone

Thursday, July 06, 2006

Custom Controls and Cross Threading

In .NET 2.0 a feature was introduced so as to raise an exception if an application attempted to access a Windows Control on a thread other than the thread in which the control was initially rendered. This is because Windows Controls are deemed not thread safe, and only expect to interact with a single thread, and thus have no state lock protection. In 1.1 you could blissfully ignore this and most of the time your code would work..

The feature in 2.0 is disabled by default, but when you run under the debugger it is enabled. The debugging environment sets the static member on the Control class CheckForIllegalCrossThreadCalls to true.

Whenever you attempt to get hold of the underlying Windows handle for the control this static member is first inspected and if it evaluates to true the InvokeRequired method is invoked to see if you are indeed on the correct thread. If you are not on the correct thread the exception is thrown

The code below was generated by Reflector, taken from the base Control class

public IntPtr get_Handle()

{

if ((Control.checkForIllegalCrossThreadCalls && !Control.inCrossThreadSafeCall) && this.InvokeRequired)

{

throw new InvalidOperationException(SR.GetString("IllegalCrossThreadCall",

new object[] { this.Name }));

}

if (!this.IsHandleCreated)

{

this.CreateHandle();

}

return this.HandleInternal;

}


There is a slight extra piece of complication in that it is possible to have some control operations that are thread safe, these calls use a class called Control.MultithreadSafeCalllScope which implements IDisposable as a way to wrapup blocks of code that are in fact thread safe and still need to have access to the underlying windows handle.

So using Reflectors Analyze feature I decided to see where this class was used in the framework so that you can see what Windows control methods are Thread safe…

The results were as follows

System.Windows.Forms.Control.BeginInvoke(Delegate, Object[]) : IAsyncResult

System.Windows.Forms.Control.CreateGraphics() : Graphics

System.Windows.Forms.Control.EndInvoke(IAsyncResult) : Object

System.Windows.Forms.Control.get_InvokeRequired() : Boolean

System.Windows.Forms.Control.get_WindowText() : String

System.Windows.Forms.Control.Invalidate(Boolean) : Void

System.Windows.Forms.Control.Invalidate(Rectangle, Boolean) : Void

System.Windows.Forms.Control.Invalidate(Region, Boolean) : Void

System.Windows.Forms.Control.Invoke(Delegate, Object[]) : Object

A few posts back I saw that Invalidate was possible, but now I can see that I can also get the text associated with a windows control.

Anyway back to the plot….the reason for all this was to make my own custom controls behave the same as the underlying windows controls. I basically wanted to ensure that my control was only ever interacted with on a single thread. Since with UI apps you generally expect everything to happen on the main UI thread you don’t want to put the overhead of locking etc in as the majority of cases everything is happening on the UI thread.

So I’ve added a new method to my control called CheckForIllegalCrossCall I make a call to this method inside each of my properties..

private void CheckForIllegalCrossCall()

{

if ((Control.CheckForIllegalCrossThreadCalls) && (InvokeRequired))

{

throw new InvalidOperationException("Illegal cross Thread operation");

}

}

Now I don’t need to worry about state corruption as state can now only be manipulated on a single thread. When debugging we will make the call to InvokeRequired and when not we will simply assume that the programmer knows what he’s doing…

Tuesday, July 04, 2006

Last two weeks

Last two weeks been very manic….went up to Edinburgh to deliver a course at the Edinburgh training centre. Didn’t get to see much of the city but will certainly go back for a weekend visit, what I did see was pretty spectacular. What was great was the fact that although you were in the city you could still get to see some pretty amazing “Vista’s”… ( wow that word is now so much in my vocabulary now ).


 

Second week doing a gig for MS Academic Insight were I spoke to nearly 50 academics on the wonders and joys of .NET. Had a lot of fun and the hotel was fantastic. More often and not Im in London hotels and going to a rural hotel was a breath of fresh air, the staff spoke English ok in this case with a Brummie dialect but that’s ok Im a Brummie too. There were extremely helpful, and just little touches like Breakfast cooked to order goes a long way…A fellow speaker felt the need to praise the hotel on his blog too ( http://www.robmiles.com/ ), mainly for the in room tea tray. The hotel was the Stourport Manor Hotel

Rob was there to deliver a talk on Windows Mobile, and I must say things have come on along way since my original IPaq and NSBasic. I can now develop using full loaded Visual Studio and .NET code…Rob was very passionate about Mobile, mainly due to richness in applications that you can now develop. Since in the case of a smart phone you have access to camera, blue tooth, phone GPS, and GPRS/3G ( Internet ). Such a vast array of devices compact and mobile…


 

He demo’d a neat space invaders game were you can take a picture of your co-worker and then use that picture as the evil alien and blaster them to smithereens… The funniest app was the SMS Roulette were game would select a random name from your contacts and then a random greeting be it nice or bad and send it….A great pub game as Rob put it…


 

So this was indeed neat you had full access to all the resources on the phone…After the initial laughter of this app, it got me and at least one other delegate thinking.. At no point did we get a warning from the app saying it was about to use the SMS service it just did…So the application spent my money without actually asking me…What else could it do…could it farm my contact list and email it to evilspammers.com..Who knows…

When I asked the question about security, there is a step you need to go through to get your app onto a phone whereby you need to get it signed by someone like Orange. However they don’t see what the app does, they simply confirm that you are supplier. It would seem to me that MS has missed the boat here again on security, I will feel very nervous about running smart phone apps unless I can sandbox them.


 

For example it would seem to me that the first time an app is installed its permissions should be restricted to CAS level “internet zone” . If it wishes to elevate permissions to do such things as SMS I should get a list of services I will be happy to grant to it. For example SMS, and potentially to which number. Thankfully they did see the security issue with the camera and managed code cannot access the camera, it can only load a picture from the store..So at least some one was awake at Redmond for the 5 minute mobile security meeting. Come on MS you have made manage code have the ability to be so much more secure please use it…..

Rant over…..After seeing it though I want one…so I’m going to order a smart phone ASAP….I have a feeling that one of the next killer apps will live on a smart phone…


 

Monday, July 03, 2006

Another Security Rant


 

A while back I started playing with the managed support for secure stream protocols available for windows. The managed wrappers of NegotiateStream wrap up access to SSPI. In a previous post on my previous blog (Previous Rant) I mentioned that even though you asked for a secure stream to be mutually authenticated, windows could decide not to bother and use NTLM and only send your credentials. Personally I felt that the API should have thrown an exception since it did not do what was said on the tin…Having discussed it with others it was pointed out that there is a property you can check on the stream called IsMutuallyAuthenticated prior to actually using the stream, so not too bad..Assuming you remember to check..A little internal wrapper method and you could keep yourself safe.

NegotiateStream is used as a foundation building block for higher level communication abstractions such as remoting. When I use .NET remoting I have no access to the underlying stream I simply make a method call in the same way as I make a local call, the communication context is hidden from me. So if in my remoting configuration I actually specify I want to use mutual authentication and it fails to achieve it because the other end refuses to play ball it falls back to NTLM and I’m none the wiser.

One reason for opting for mutual authentication was the fact that the information Im sending to the server is for its eyes only, it may be sensitive and I don’t want it consumed by any other party. Personally I find this totally unacceptable….

So from a pure security point of view that may rule out .NET remoting which would be a real shame, since I really don’t want to go back to the days of creating my own wire format for RPC between my client and server.

So this got me thinking if there was some kind of workaround. The strategy that I think you can adopt is the following

On the server, declare your remoting service in the normal way, and in addition provide a simple tcp listener on a well known port. This tcp listener is the real trusted entity, clients should negotiate a stream to the listener using mutual authentication and after establishing it check that it was successful.. The server sends back along the stream the URL for the remoting service. The client then uses the contained URL to connect back to host..

This way the client can be sure of using mutual authentication to validate the service, after the service has been validated the client continues to use RPC based protocols.


 


 


 


 

At least one more Thread Safe Method on Windows Controls

Its been long understood that it is unsafe to call methods and properties on Windows controls unless you are on the same thread that created the control. Windows controls have always been designed with single threaded environment in mind. In .NET 1.1 you could actually perform the operations and on the whole things did seem to work, until perhaps the application is deployed and then it breaks….Thankfully in 2.0 MS have added programmatic protection when the your application is connected to a debugger, and will fire an InvalidOperationException.

To work around this issue you can deploy the standard InvokeRequired pattern, were by you call InvokeRequired method on the control you wish to access and if that returns true call BeginInvoke on the control passing it a delegate instance that represents the work you wish to have carried out on the controls owning thread. Hold on you said you can’t access a control unless you are on its owning thread, that’s true in the whole accept for some select methods

  • InvokeRequired
  • BeginInvoke
  • Invoke
  • CreateGraphics

The above list was my understanding before today, but what I realised today was that another method can be added to the list. This holy method is Invalidate… I stumbled upon this whilst creating a more funky progress bar control. The control had a progress property that was being set by my background task, and once set called invalidate In order for the progress bar to be updated, this produced no exception when the invalidate was called from the non owning thread, leading me to conclude that it is perfectly safe to do so….

Which makes sense when you think about it since all it is doing is telling the OS that it needs to generate a Paint event for a given control, which ultimately will be delivered on the message queue for that controls owning thread. Since there is no underlying control interaction on the non UI thread no exception is raised.


 


 

Delegate binding in .NET 2

In .NET 1.1 a delegate defined like

delegate void Proc(string foo);

Could only be instantiated with a method which had that exact signature. In .NET 2.0 they relaxed it so that a method defined as

void MyProc( object bar );

Could be wrapped by the above delegate, since MyProc parameter is more restrictive, which makes sense.However what you can't do is

delegate void Proc(int foo);

And make it wrap up

void MyProc(object bar );

The compiler will not let you...Hold on, int ultimately derives from System.Object so why not. My guess is that it comes down to boxing, since in order to make code work the method MyProc must see a reference type. The code invoking the delegate, or the CLR generated code would have to be smart enough to see that the actual implementation was expecting a reference type and perform a boxing operation on the parameters being passed. So perhaps the seamless type system is starting to show a few cracks....

NegotiateStream or is that bend over and take what’s given

Been playing around with NegotiateStream, this class allows you to wrap up any other type of stream typically a socket stream with a tunnel. As part of the tunnel setup you specify the source credentials and the destination identity. The source credentials are used by the server to validate who you are and the destination identity is used in order to confirm that the server is who it says it is. The first phase of setting up the tunnel is authentication, and Windows supports two types NTLM and Kerberos. NTLM is not capable of performing mutual authentication so only cares about the client credentials. Where as Kerberos does support both and will validate that the remote end is infact who you think it should be.</p><p>So great in environments where it is important to know what’s on the other end of the wire, you need to use Kerberos, but here\'s the rub you would think that if you made a call as below, that it would enforce the use of Kerberos


 

NegotiateStream s = new NegotiateStream

s.AuthenticateClient( CredentialCache.DefaultCredentials , “RemoteServiceUser” );


 

However if the RemoteServiceUser was unknown by Windows AD you would think that it would reject the call, but oh no it simply fails back to NTLM. The only way you know it’s not done mutual authentication is when you check the s.IsMutuallyAuthenticated flag. In my mind I think there needs to be an additional methods, one that specifies the remote identity and one that doesn't. That way it’s clear that I want or don\'t want mutual authentication...If I want it and it doesn't happen then an exception needs to be thrown, I shouldn't have to check a property on the stream after the fact, and worse still if I don't want it I shouldn't have to specify anything not even String.Empty.

Fingerprinting in schools

I’ve been campaigning in my kids school to stop the introduction of finger printing for school registration. I was interviewed by the Guardian on Tuesday, the article can be found here

.NET Generics and C++ STL

A fellow instructor was commenting, well moaning to be exact about the fact that .NET generics were not as flexible as C++ templates. In this particular case he wanted to produce a generic Complex number type, such that he could write a single version and instantiate it for ints, doubles etc. This is trivial in C++ templates, but not so in .NET. I did manage to get something close C++ templates in terms of functionality, the details are too long for my primitive blogging editor so Ive written up my findings here .


 

Whilst undertaking this task there is a feature I would really like from the C# compiler and that is a pragma to turn auto boxing off. Why well when writing code that you wish to tune to death, such as a generic algorithm it would be nice to be told at compile time that boxing will be occurring. I guess I could write a generic unit test that inspects a method and fails if it finds a boxing op code

.NET Generics and static methods

Been playing around with generics a bit more and have discovered something a little strange. When you run it you will see that you get the same result even though you instantiate the generic method with two different types that have the opposite functionality. If you know how generics work under the covers then I guess you will think I wouldn\'t be that stupid to write the code below, but If you are not completely up to speed with how it is implemented in the CLR then you may think the behaviour below is a little strange.


 

using System.Collections.Generic;

using System.Text;

namespace Constraints

{

public class A

{

public static bool operator ==(A lhs, A rhs)

{ return true; }


 

public static bool operator !=(A lhs, A rhs)

{ return false; }

}

public class B : A

{

public static bool operator ==(B lhs, B rhs)

{ return false;}


 

public static bool operator !=(B lhs, B rhs)

{ return true; }


 

}

class Program

{

public static void PerformOperation<T>(T lhs , T rhs ) where T:A

{

if (lhs == rhs)

{

Console.WriteLine(“Equal...”);

}

else

{

Console.WriteLine(“Not Equal...”)

}

}

static void Main(string[] args)

{

    A v1 = new A();

A v2 = new A();

PerformOperation<A>(v1, v2);

B v3 = new B();

B v4 = new B();

PerformOperation<B>(v3, v4);

}

}

In fact the C# compiler tries to stop you falling into this trap with a generic method with no constraints. The code below will not compile, the reason being the way in which genercis have been implemented. In .NET a generic method or type are constructed using common piece of IL using special generic IL instructions. All it needs to be know at compile time is which method to call to perform a piece of functionality, the binding to the final implementation either happens at JIT time for valuetypes or using runtime polymorphism in the case of ref types. For static methods and non virtual methods the binding happens when the generic method or type is compiled only the correct specific behaviour is used if the methods are polymorphic, or you supply the same type as defined by the constraint and not a more specialised version. It is for this reason that the C# compiler will not compile the code below as it will always perform an object comparison ( E.g. Reference equality ) even if the method is called PerformOperation<string>( string1 , string2)

public static void PerformOperation<T>(T lhs , T rhs )

{

if (lhs == rhs)

{

Console.WriteLine(“Equal...”);

}

else

{

Console.WriteLine(“Not Equal...”;)

}

}

What I’m failing to understand is why in my case it allows the compilation since it basically suffers the same issue. Perhaps generic methods should not be allowed to use non polymorphic methods.

ASP.NET Themes

The new theme support in ASP.NET is pretty cool. Although personally I don\'t think they took it far enough. When you design your page you can add an attribute to the @Page tag that states which theme to use when rendering this page, this gives the web site designer some flexibility in that they can change the look and feel of the site with a simple change. The simplest way to do this is with a single global change in the web.config


 


 

<configuration xmlns=http://schemas.microsoft.com/.NetConfiguration/v2.0>

<system>

<pages theme=”MyTheme&quot”/>

</system>

</configuration>


 

For me though the cool thing about themes is to allow the user of the web site to select the theme they would like to use. As far as I can tell there is no direct support in ASP.NET to do this for you. So I set about writing a component that could do this. So what we need to do is. For each page as it is about to be rendered change the theme used for that page select the theme based on the user preferred theme


 

In order to intercept the rendering of each page at the appropriate point you can provide a handler for the Page PreInit event, inside this handler you can add the appropriate code to change the theme to use for just that page. In order to hook up to this event I decided on a design where if you wanted a page to have the user selected theme then instead of creating a WebForm that derives from System.Web.UI.Page you actually derive from my new UserThemedPage type which ultimately derives from System.Web.UI.Page. This can be simply done inside the forms Code view, Inside the constructor for UserThemedPage I add the necessary event registration code. Thus when the WebForm is created the code  is in place to handle the PreInit event and apply some policy to determine what theme to actually use. For the second part we need to provide a way for the user to select a theme and also for the theme to be retained across multiple pages and hopefully multiple visits to the site. I didn’t really want to introduce the need for non anonymous access and store the users preferences in a database, so I opted for the use of cookies to store the user\'s prefered theme. Since not every user wishes to enable cookies, I also opted to store the theme in the session store allowing users to retain their preferred theme for the duration of the session, but would need to reselect it on re-entering the site.</p><p>As for selecting the theme to use, I did not want to provide the actual UI for this but simply a method that would allow simple iteration of possible themes to use and then a simple set/get property interface for setting the chosen theme. The iterator simply returns the set of themes that are defined for the current application, its then up to the chosen web app to decide how to ask the user for their chosen theme. So now in order to have a user select their own theme and have it persist across multiple pages and visits, you simply need to derive from my UserThemedPage as opposed to System.Web.UI.Page and provide a form to select the chosen theme. Trivial...You can download the component source and example from the Download Page

Safety Button

This component grew out of a demo I do whilst teaching ENET for DevelopMentor http://www.develop.com

It demonstrates how to extend WinForms controls to add additional functionality. In this case we are extending the standard button, to provide a means to intercept the Click event and prompt the user are they sure they wish to perform the said action, if they decline the registered event handlers of the button event are non the wiser. Whilst I initially thought this was a trivial demo, it actually turns out that alot of code is written inside Click handlers to throw up a “Are you sure” message. So I’ve done a few enhancements to it over and above what we do in class and provided it as a component to download from my Download page. Whilst building the component I stumbled on a bug in VS Designer, in that I wanted to expose a property of type MessageBoxIcon to allow users of the button to determine what Icon to use in the warning message box.

So I exposed the property as normal but when I came to modify the property in the designer I kept seeing multiple copies of a single enumeration..The issue arises because the MessageBoxIcon enumeration has many Names bound to a single value, this seems to confuse VS. So in order to work around this I created my own enumeration that has no duplicates

My First post on blogger.com

First test post on blogger.com

Saturday, June 03, 2006

My First Word 2007 Post


Ok so I seem to move blogs a lot…well recently installed Word 2007 and just had to start using it to blog from as opposed to using the native blog editor.


The version of pLog I was using didn’t seem to work probably with the MetaWebApi so I upgraded to the new version of pLog called LifeType. Has a lot more plugins already written to combat spammers and the such like.


I have found a couple of problems with word postings

  • Word seems to post the wrong date on the posts,
  • Strange characters appear instead of single quotes



Anyway hopefully with nice spell and grammar checking my posts might actually become legible…

Wednesday, February 22, 2006

Const and Immutable types

Recently on the DevelopMentor CLR list there has been a discussion about the string type. Initially it was about why was it immutable and what does immutable mean, the discussion then spiraled into how can I create my own immutable type.

Well after someone kindly posted an example someone countered it saying well with reflection they can get around this...and thus the type is not strictly immutable.

It is at this point where I started to scratch my head in amazement to why this discussion was happening, why ? Well sure they are correct, but you have to ask yourself as a programmer how far do you go to show intent. I mean the const keyword in C++ was great from my opinion I could actually return a const reference if I so wished hinting to the consumer of that reference that they can only safely use this object in a read only context, allowing my implementation to perhaps share this object with multiple clients.

Now if that C++ programmer wishes to cast it to a mutable ie non const reference let them do it, me as the developer of that component washes my hands, Ive done everything reasonably possible to enforce correct usage of my type and the user has decided they know best. In other words the contract that I defined has been broken.

In my opinion when defining a type that should be immutable a far greater failing would be to say, well I can\'t guarantee immutableness via the interface so I won\'t bother. Having the flexibility that I defined above for C++ can make implementations far simpler. For example a type that is read only means that there are no thread safe issues to worry about, as well as having the opportunity to share the object with multiple consumers.

As far as I know there is virtually few useful languages were the contract can\'t be broken in some way at runtime, infact Jon Skeet posted a very nice example of how the most immutable of types the string can in fact be compromised in a very interesting fashion.


using System

using System.Text;

class Test

{

static void Main()

{

string x = “hello”;


unsafe

{

fixed (char *c = x)

{

for (int i=0; i &lt; 5; i++)

{

c[i] = \'!\';

}

}

}

}

}

//Hello doesn\'t get printed...

Console.WriteLine (“hello”);

}

}



To understand why the following example produces the less than obvious results...the following code may through some light onto it


By all means not everything but two obvious tests,


char[] chars = new char[] { 'a’, 'b', 'c', 'd' };

string lhs = new String(chars);

string rhs = new String(chars);

Console.WriteLine(“{0} and {1} are shared : {2}” , lhs , rhs , Object.ReferenceEquals(lhs, rhs) );

lhs = “foo”;

rhs = “foo”;

Console.WriteLine(“{0} and {1} are shared : {2}”; , lhs , rhs , Object.ReferenceEquals(lhs, rhs));


The above snippet, gives false for the first result and true for the second. Static/literal strings are burned into the assembly and the same object is used each time ( for the same assembly).

Even placing the same string in a different source file for the same assembly results in sharing the reference. The process of building an assembly is smart enough to recognise the same literal string is being used and ensures that only one entry is placed into the String object is created.

You can see this via ILDASM, fire up ILDASM, and hit CTRL-M, scroll to the bottom and you will find the User String table

User Strings

-------------------------------------------------------

70000001 : (29) L”{0} and {1} are shared : {2}”

7000003d : ( 3) L”foo”

I wonder if Jon's trick could be used to hide the true values of some sensitive strings you are burning into your assembly...Since the IL for the last print statement looks like

IL_0037: nop

IL_0038: ldstr “hello”

IL_003d: call void [mscorlib]System.Console::WriteLine(string)

IL_0042: nop

Blog Archive

About Me

My photo
Im a freelance consultant for .NET based technology. My last real job, was at Cisco System were I was a lead architect for Cisco's identity solutions. I arrived at Cisco via aquisition and prior to that worked in small startups. The startup culture is what appeals to me, and thats why I finally left Cisco after seven years.....I now filll my time through a combination of consultancy and teaching for Developmentor...and working on insane startups that nobody with an ounce of sense would look twice at...