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.
Andy's observations as he continues to attempt to know all that is .NET...
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.
Currently teaching a DM Guerrilla, and we have been playing some short funny geeky type movies, a student offered this one to be considered….
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;
}
}
}
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.
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
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…
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…
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.
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
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.
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....
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.
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
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
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.
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"”/>
</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
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