A guide to MP’s expenses

May 7th, 2009 by Richard No comments »

So the Telegraph has got hold of MPs expenses before they officially published, stand by for some embarrassing back downs or corrections.

Guido has a great explanation of the phrases we’ll hear over the next few days. I’ve republished here

It has since been corrected” - I knew it was going to come out and it was such a blatant fiddle that I realised I had to repay the fraudulently claimed money before it came out.

The Fees Office approved the payment - the Fees Office always take the word of “honourable” members.  They always make the payment without question.

It was a clerical error” - it was a small fiddle.

Lessons have been learned - we have got away with it, but we won’t do it again.

We have to have two homes to do our job properly” - why stay in a hotel when we can build a property portfolio at the public’s expense.

Claims were made in good faith” - we have always got away with it in the past.

It was within the rules” - MPs make the rules to suit themselves. MPs are  lawmakers, judge and jury.  It is a joke at our expense.  They really are almost all at it. 

How to send a message to an already running .NET application

May 7th, 2009 by Richard No comments »

Here is a problem I came across over a year ago now and never got around to detailing.  Here is the scenario

Scenario

I want to create a URL handler in Windows and send that message to my already running .NET application.  For example I create a url handler called myapp: and I create a link in HTML to myapp://www.richardhyland.com/, I want to send that URL to my application, let’s call it MyApp.exe and do something with it.

Now I can quite easily create a URL handler in the Windows registry and call MyApp.exe, but that will create a new instance of the application, what I want  to do is detect to see if MyApp.exe is already running.  If it is then send the URL to that process and if it isn’t, load MyApp.exe.

My Solution

After many hours with Google, I discovered this cannot be done using managed code, so I had to delve into the scary arena of unmanaged code in .NET.

I first set up MyApp.exe to recieve the message.

protected override void WndProc(ref System.Windows.Forms.Message m)
{
  if (m.Msg == 0x400)
  {
    // We've recieved a message from handler.exe (we must now decode the IntPtr and deal with it)
    try
    {
      BS.BuildString(m.LParam);
    }
    catch
    {
    }
  }
  base.WndProc(ref m);
}

void BS_StringOK(string Result)
{
  if (Result.StartsWith("myapp://"))
  {
    Result = Result.Substring(8);
  }
  string strUrl = "http://" + Result.ToString();

  this.funcDoSomething(strUrl);
}

What we’ve done here is override the WndProc function in the application, examined it for a string and passed it to a function called funcDoSomething()

Next we can create a simple, small .exe for the URL handler to open.

Inside the main class of the handler.exe we need to declare

[DllImport("user32.dll")]
private static extern
bool SetForegroundWindow(IntPtr hWnd);

[DllImport("user32.dll")]
private static extern
bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);

[DllImport("user32.dll")]
private static extern
bool IsIconic(IntPtr hWnd);

private const int SW_HIDE = 0;
private const int SW_SHOWNORMAL = 1;
private const int SW_SHOWMINIMIZED = 2;
private const int SW_SHOWMAXIMIZED = 3;
private const int SW_SHOWNOACTIVATE = 4;
private const int SW_RESTORE = 9;
private const int SW_SHOWDEFAULT = 10;

[StructLayout(LayoutKind.Sequential)]
public struct COPYDATASTRUCT
{
   public int dwData;
   public int cbData;
   public int lpData;
}

Now you can get the string as an arguement in your form loader and process store it to a string

Now let’s detect to see if MyApp is running

Process[] myProcesses = Process.GetProcessesByName("MyApp");

if (myProcesses.Length >= 1) {
 int n = 0;        // assume the other process is at index 0
 // get the window handle
 IntPtr hWnd = myProcesses[n].MainWindowHandle;

 // if iconic, we need to restore the window
 if (IsIconic(hWnd))
 {
   ShowWindowAsync(hWnd, SW_RESTORE);
 }

 // bring it to the foreground
 SetForegroundWindow(hWnd);

 // Process the message through my builder DLL, see later
 RH.SendMessage.BuildString BS = new RH.SendMessage.BuildString();
 BS.PostString(hWnd, 0x400, 0, strUrl);

 // Message sent to exit
 Application.Exit();
}
else
{
 // Application not running so, start it
 string exeDir = System.Reflection.Assembly.GetExecutingAssembly().Location.Replace("\\handler.exe", "");
 System.Diagnostics.Process.Start(exeDir + "\\MyApp.exe", strURL);
 Application.Exit();
}

Finally we need to detail the String Parser DLL that is mentioned in the above code. This I found online, and it is in Visual Basic

Imports System.Text

Public Class BuildString

    Private Declare Function PostMessage Lib "user32.dll" _
Alias "PostMessageA" (ByVal HWnd As IntPtr, ByVal WMsg As _
Integer, ByVal WParam As Integer, ByVal LParam As Integer) _
As Integer
    Public Event StringOK(ByVal Result As String)
    Private HWnd As IntPtr
    Private WMsg As Integer = 0
    Private WParam As Integer = 0
    Private LParam As String = ""
    Private tempA(-1) As Byte
    Private enc As Encoding = Encoding.UTF8

    Public Property Encode() As Encoding
        Get
            Return enc
        End Get
        Set(ByVal value As Encoding)
            enc = value
        End Set
    End Property

    Public Sub BuildString(ByVal b As IntPtr)
        If b <> 0 Then
            'build temp array
            Dim tempB(tempA.Length) As Byte
            tempA.CopyTo(tempB, 0)
            tempB(tempA.Length) = b
            ReDim tempA(tempB.Length - 1)
            tempB.CopyTo(tempA, 0)
        Else
            'decode byte array to string
            Dim s As String
            If enc Is Encoding.UTF8 Then
                s = Encoding.UTF8.GetString(tempA)
            ElseIf enc Is Encoding.Unicode Then
                s = Encoding.Unicode.GetString(tempA)
            ElseIf enc Is Encoding.ASCII Then
                s = Encoding.ASCII.GetString(tempA)
            Else
                s = Encoding.Default.GetString(tempA)
            End If
            'send out result string via event
            RaiseEvent StringOK(s)
            ReDim tempA(-1)
        End If
    End Sub

    Public Sub PostString(ByVal HWnd As IntPtr, ByVal WMsg _
As Integer, ByVal WParam As Integer, ByVal LParam As String)
        Me.HWnd = HWnd
        Me.WMsg = WMsg
        Me.WParam = WParam
        Me.LParam = LParam
        'create a new thread to post window message
        Dim t As Threading.Thread
        t = New Threading.Thread(AddressOf SendString)
        t.Start()
    End Sub

    Private Sub SendString()
        'create byte array
        Dim ba() As Byte
        'encode string to byte array
        If enc Is Encoding.UTF8 Then
            ba = Encoding.UTF8.GetBytes(lParam)
        ElseIf enc Is Encoding.Unicode Then
            ba = Encoding.Unicode.GetBytes(lParam)
        ElseIf enc Is Encoding.ASCII Then
            ba = Encoding.ASCII.GetBytes(lParam)
        Else
            ba = Encoding.Default.GetBytes(lParam)
        End If
        Dim i As Integer
        For i = 0 To ba.Length - 1
            'start post message
            PostMessage(hwnd, wMsg, wParam, ba(i))
        Next
        'post a terminator message to destination window
        PostMessage(hwnd, wMsg, wParam, 0)
    End Sub
End Class

And voila, that is now I sent a message from one running .NET application to another without starting a new process of the recieving .NET application.

8 bit characters in Active Directory

May 6th, 2009 by Richard No comments »

Once again, after discovering very little information from Microsoft about Active Directory over LDAP I was posed with a question on the adLDAP forums https://sourceforge.net/forum/?group_id=104193

And that was how to handle accented characters over LDAP. Running a standard ldap_modify() will cause a ‘Constraint violation’ error from the domain controller.

I finally discovered, after reading the RFC for LDAP that I need to encode the ‘offending’ characters as UTF-8.

I could have simply executed

$adldap->user_modify('AD.UserName', array('firstname'=>utf8_encode('Göran'));

but that would be too easy wouldn’t it. Seeing as my believe with libraries should be, you shouldn’t have to think about this, let us allow the library to do this work for us.

Whenever you modify or create attributes in adLDAP it passes the attributes array through a schema function so let’s process the array detecting 8 bit characters

array_walk($attributes, array($this, 'encode8bit'));

Then let us create the function encode8bit

protected function encode8bit(&$item, $key) {
        $encode = false;
        if (is_string($item) === true) {
            for ($i = 0; $i < strlen($item); $i++)
            {
                // Detect the ordinal value of the character
                if (ord($item[$i]) >> 7) {
                    $encode = true;
                }

            }
        }
        if ($encode === true) {
            $item = utf8_encode($item);
        }
    }   

Update Wordpress was messing with the rendering of this function, I’ve now corrected it.

I’ve committed the code to the repository trunk and it’s now available to download directly from SVN

Send Brown a T-Shirt

May 6th, 2009 by Richard No comments »

Saw this at http://www.the-daily-politics.com/2009/04/send-brown-shirt.html. Bit rude but funny all the same

shirts_2_gordon-large

adLDAP version 3.0

May 1st, 2009 by Richard No comments »

adldapWell since joining the adLDAP project on SourceForge, I’ve just published version 3.0.

Version 3.0 is a big change from 2.0, firstly I’ve removed support for PHP 4, by using proper PHP 5 constructors and making variables / functions public and protected.

I’ve added a number of new functions for Exchange mailbox creation, contact management and user deletion (as well as PHP Doc style commenting the code).

I’ve also gone and re-organised much of the documentation on the Wiki.

Go check it out for yourself http://adldap.sourceforge.net

Political Parties and YouTube

April 29th, 2009 by Richard No comments »

Gordon Brown just got asked at Prime Minister’s Question Time when we can expect another comedy performance from him on You Tube.

Gordon replied that YouTube was a very important communication medium and that he will continue to use it even if the other parties do not?

Maybe he wasn’t aware of:

  • http://www.youtube.com/user/webcameronuk
  • http://www.youtube.com/user/LibDem
  • http://www.youtube.com/user/greenpartyew
  • http://www.youtube.com/user/ukipwebmaster

to list just a few

Active Directory Management over PHP

April 22nd, 2009 by Richard No comments »

Update: I’m now part of the original adLDAP project, so libAD has been withdrawn, look forward to seeing my contributions and Exchange supposed on adLDAP in the near future.

A while ago I started using a library called adLDAP, unfortunately there have been a number of bugs and lack of some features with it.  Couple this with the lack of updates for the past two years, I decided to re-work this library and release it myself.  This library is called libAD.

libAD is a PHP library providing Active Directory authentication and management over LDAP.

It provides intelligent Active Directory integration with PHP. This extends on the original project that has not been updated for some time. It’s aim is to help other developers with getting over the same hurdles that we’ve experienced in getting the whole LDAP SSL Active Directory puzzle working natively on Linux.

This library is not designed to be a complete Active Directory management systems, but give you a set of functions through an API that will allow you to interface successfully with your Active Directory.

Given the varied nature of organisations and sites, adLDAP may not be your complete solution, but it should be a very sound starting point. LDAP isn’t overly friendly on first glance, and it’s a steep learning curve made alot worse when coupled with Microsoft’s seemingly unending army of catches.

The information you can retrieve from Active Directory is as useful as you make it. If you don’t fill out all their account information there’s not really going to be much to query.

libAD is open source software and is released under the GNU General Public License v2. This is a change from the license used under adLDAP which was LGPL.

Update: I’m now part of the original adLDAP project, so libAD has been withdrawn, look forward to seeing my contributions and Exchange supposed on adLDAP in the near future.

So have we solved Global Warming?

April 19th, 2009 by Richard No comments »

… or did it maybe not exist at all.  If the article I’ve just read is true then the Antarctic is bigger and denser than for 30 years.  Hmm but I thought all our taxes were going up to stop us from melting all the ice caps?

Windows Update frustrations

April 19th, 2009 by Richard No comments »

These days I’m a Mac person, but I do still use Windows for work and also occasionally for other bits and pieces, such as games, Windows software or Windows development.

Now today I booted my Mac into Windows Vista under Bootcamp, started a video encoding process that would take between 2 and 3 hours.  Obviously I’m not going to sit in front of my computer watching it encode a movie file, that would just be a monumental waste of time, so I leave it running.

I come back 2 hours later to discover the computer in sleep mode, that’s fine if the encode has finished then it’ll usually go to sleep automatically.  I wake the computer to discover the OS X login screen.

I check the Windows logs to discover that Windows Update has decided not only to download and install new updates but decided that regardless of what the computer is doing at that current time it should reboot itself and loose any work I happened to be working on.

Now I understand for the default settings and need for Windows Update to auto download and install, it helps protect computers from users who don’t, and have no need, to know about what security patches are required.

What I object to is Windows deciding to reboot itself automatically.  I’ve seen the little prompt before saying click me to snooze the reboot, but I wasn’t at my PC to be able to see that prompt.

The Windows Update system should look at the system processes and open applications to determine whether it might be acceptable to display the prompt, if the processor is very busy, there might just be a chance, that something important is going on!  Alternatively, maybe Microsoft can provide a way to applications to send a flag saying ‘Busy here, move along please’ and then remove the flag when they exit.  If they are worried about Viruses setting that flag then maybe restrict it to digitally signed applications only?

I feel Microsoft are intentionally putting features in Windows to piss off IT professionals!  So two hours of wasted processor time thanks to Windows Update.