Thursday, 11 April 2013

Hierarchical LDAP Queries

Want to know if a person or user is part of a group in Active Directory? Rather than retrieving a list of groups that the user is a member of and then find which groups those groups are members of until the desired group is found LDAP supports a chaining operator. Here's a handy article on MSDN that tells you how to use it: After some mucking about I found that you need to leave off the brackets surrounding the distinguished name in order to get this to work. For example
var query = string.Format(
    "(&(objectClass=group)(samaccountname={0})(memberof:1.2.840.113556.1.4.1941:={1}))",
    childGroupName, parentGroupDistinguishedName);

Wednesday, 23 January 2013

Simple Visual Studio TypeScript HTML App with jQuery

I heard about TypeScript a few months ago and have had a bit of a play-around compiling some TypeScript into JavaScript using the Node.js package, but I've not had chance to try it out in Visual Studio. Here is a simple demo that shows how the code generated by the TypeScript project template can be adapted to include jQuery support.

Thanks to this stackoverflow answer for getting me started.

Step 1: Install TypeScript Plugin

Install the Visual Studio 2012 TypeScript plugin from here

Step 2: Create a Project

Create a new project in Visual Studio 2012 using the HTML Application with TypeScript project template

Step 3: Include the jQuery Type Definitions

Create a new file in the project and call it jquery.d.ts

Paste in the type definitions from from here

Step 4: Update the app.ts File

Change the code in the app.ts file to...

/// <reference path="jquery.d.ts" />

class Greeter {
    element: JQuery;
    span: JQuery;
    timerToken: number;
    
    constructor(element: JQuery) {

        this.element = element;
        this.element.text("The time is: ");
        this.span = $('<span>');
        this.element.append(this.span);
        this.span.text(new Date().toUTCString());
    }

    start() {
        this.timerToken = setInterval(() => {
            this.span.text(new Date().toUTCString());
        }, 500);
    }

    stop() {
        clearTimeout(this.timerToken);
    }

}

$(() => {
    var el = $("#content");
    var greeter = new Greeter(el);
    greeter.start();
});

Step 5: Include Reference to jQuery Library

Add the following markup to the head section of the default.htm file...

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

Step 6: Run or Debug

Run or Debug the application to see the TypeScript in action.

You can even put breakpoints in the app.ts file.

Thursday, 4 October 2012

Highcharts JS

I thought that I'd have a go trying to use the JavaScript charting library Highcharts JS. Here's a very quick example of some of the 'Wealth of Nations' data displayed as a simple line chart.

Friday, 31 August 2012

Rogue-Like Game


Below is a rogue-like game implemented in JavaScript and inspired by Eric Lippert's blog articles. In deference to my old spectrum days the control keys are W, A, S, D. Find the treasure, and get out again!

Friday, 6 July 2012

Online PostScript Viewer

Here's a link to a useful PostScript viewer I found online. Just paste the URL in the box!

http://view.samurajdata.se/

Friday, 8 June 2012

Useful JQuery UI Tools

In my job I use JQuery and JQueryUI a lot but JQueryUI suffers from a lack of controls and does not seem to have added any new functionality for a while.

Lucky the guys that are resonsible for JQueryUI have made available a couple of controls on their site that may make it into the main UI library in the future. Here are links to the page containing demos of the controls.

Tuesday, 21 February 2012

Microsoft Excel Application missing from DCOMCNFG

Trying to work with Excel Interop on a 64-bit version of Windows with a 32-bit version of Microsoft Office installed? If so you may find that you cannot set permissions on the Microsoft Excel Application node in DCOMCNFG because it is missing!

Thanks to tibb I now know that this node can be accessed using the following method...

  1. Start
  2. Run
  3. mmc -32
  4. File
  5. Add Remove Snap-in
  6. Component Services
  7. Add
  8. OK
  9. Console Root
  10. Component Services
  11. Computers
  12. My Computer
  13. DCOM Config
  14. Microsoft Excel Application

Tuesday, 14 February 2012

Dead Horse Morris

Sicknote from Dead Horse Morris
If you don't already know I have joined a Morris Dancing side called Dead Horse Morris. They are based in Whitstable in Kent, UK and perform in Kent and the rest of the South East throughout the summer.

If you want to know what they are up to please visit their website. I've also added a twitter feed to the blog and I'm experimenting with a Google Calendar that will display their upcoming events with dates, times and hopefully a link to a map that will show you where to go.

The only event I've added to the calendar so far is Dawn Rising on 1st May 2012, so you may have to click the 'Look for more' link a few times to see it.

Thursday, 27 January 2011

Argument Validation in C#

I've recently created a argument validator for C# that used the following two posts as inspiration

Elegant, appealing parameter validation syntax in C# 3.0

and

A fluent approach to C# parameter validation

Hopefully I'll post what I have (basically combining the two approaches) in the next few days.

Friday, 26 November 2010

Create DDL from Visio 2010

The ability to generate DDL from a Visio ER diagram was removed sometime ago. However it must be a task that is required in many projects.

After a quick search on the Internet I can across the following Office 2010 plug-in: Visio Forward Engineer by Alberto Ferrari. It may not do everything but it will might do all you need.

Friday, 5 November 2010

Console Applications and SharePoint 2010

Recently I tried to create a Console Application that accessed a SharePoint 2010 site. I could not get the application to run. I'd added a reference to Microsoft.SharePoint.dll and included Microsoft.SharePoint as a using clause. After some head-scratching I realised that the following project settings were required.

Application | Target framework = .Net Framework 3.5
Build | Platform target = x64

BTW, The SharePoint dlls can usually be found in the following folder:
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI

Wednesday, 27 October 2010

Very Simple F# Compiler (Part 2 Revisited)

Just a quick note today to say that I have done about 30 seconds reading of some F# documentation and found out that reference cells can indeed be used in closures while local mutable values cannot. As it is a trivial exercise to re-write my character source to use local reference cells rather that global mutable values I have done so. Below is the updated code - I've also been able to remove those globals from my program.
  1 let getNextCharFromString (source : string) =
2
let sourceList = ref (List.ofSeq source)
3
let endOfString = ref (false)
4
fun () ->
5
match (!sourceList, !endOfString) with
6
| _, true -> failwith "Past End of String"
7
| [], _ ->
8
endOfString := true
9
char 0
10
| h :: t, _ ->
11
sourceList := t
12
h

Tuesday, 26 October 2010

Very Simple F# Compiler (Part 2 - The Character Generator)

Last time I defined the data structures for my simple compiler. This time I'll define the code that generates the stream of characters that will be consumed by the token generator. The specifics of this code are not really addressed in the book, and I want to keep things simple by just specifying a string that will be a source of the characters. I'd also like to make the code fairly flexible so I can easily swap out this code and replace it with code that will read characters from a file.

The following code is a bit messy and its the part of the application that I'm least happy with, but it does the job. Perhaps if I have enough time I'll be able to rewrite the code with something more appropriate such as a Sequence or something safer like using a couple of Reference Cells.
  1 let mutable sourceList : char list = []
2
let mutable endOfString = false
3
4
let getNextCharFromString (source : string) =
5
sourceList <- List.ofSeq source
6
endOfString <- false
7
fun () ->
8
match (sourceList, endOfString) with
9
| _, true -> failwith "Past End of String"
10
| [], _ ->
11
endOfString <- true
12
char 0
13
| h :: t, _ ->
14
sourceList <- t
15
h

The function has the following type:

string -> (unit -> char)

First of all I have declared two mutable values that hold the string to be served and a flag to indicate if the end of the string has been reached. The string is stored as a char list so that the cons (::) operator can later be used to decompose it. Next a function is defined that will take a string and return a function that returns a char. Each time the function is called it will check so see if the end of the string has been reached, serves up a 0 if there are no more characters, or serves the head of the list and updates the list with its tail.

A function that will provide the next character from a string each time it is called can be constructed in the following way:
 16 let getNextChar = getNextCharFromString "(2*((3*4)+9))"

This new function charSource has the type

unit -> char

See you next time!

Very Simple F# Compiler

I have decided to try and implement a version of the Demo Compiler in Chapter 1 of Modern Compiler Design by Grune, Bal, Jacobs & Langendoen. To make it harder for myself I'd like to use as much functional code as possible and as little object oriented code. I want to try and change as little of the design as possible so I'll be taking their "narrow" compiler approach.

Let's start by defining the data structured used in the design.

The design in the book has two data structures, token and expression, which are both implemented as structs. To make the code more F#y these structures will be implemented as Discriminated Unions rather than the struct's direct equivalent the Record. This is because both of the structures had redundancy built into them as they both represent data that is could be in more than one mutually exclusive form. This is the kind of structure that Discriminated Unions are made for. This decision will also make our pattern matching code much simpler to write later on. I've also decided to add a further structure the operator which will allow me to keep character checking to a minimum outside of the lexing and parsing code.

Here are my data structures:
  1 type token =
2
| Digit of char
3
| Char of char
4
| Eof
5
6
type operator =
7
| Add
8
| Multiply
9
10
type expression =
11
| DigitExpression of int
12
| ParenthesizedExpression of expression * operator * expression

Formatting F# code on Blogger

There doesn't appear to be too many tools on the internet for nicely formatting F# code on Blogger. I recently stumbed across CodeHTMLer which produces output like this:
  1 let rec interpret =
2
function
3
| DigitExpression a -> a
4
| ParenthesizedExpression (l, o, r) ->
5
let left = interpret l
6
let right = interpret r
7
match o with
8
| Add -> left + right
9
| Multiply -> left * right

See my last post for an example in C#

Tuesday, 29 September 2009

Custom .Net Two Way Bindable Properties

Often when creating .Net applications that interface with a database a developer will want to create custom controls that bind in a similar way to database fields as the existing controls like TextBoxes and CheckBoxes.

Getting the control to update to reflect the database value is trivial. You can just add a DataBinding as you would with another control. But this will not propogate updates back to the data object. In order to do this you need to implement two way data binding on your custom control. Start by adding the attribute [Bindable(true)] to the property in question and then implement the INotifyPropertyChanged interface. An example of how to do this can be found on MSDN here: http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx.

The catch comes if you ignore the advice to not implement INotifyPropertyChanged and provide an additional event for the property you want to bind to. If you call the additional event Property Name + "Changed" then the .Net framework binding code seems to get confused and the two way binding will not work. Eg if you property is called ClickCount and the additional event is called ClickCountChanged the two way binding will fail.

I was surprised by this as I have seen tutorials on two way data binding that encourage the provision of events for individual properties as well as the generic PropertyChanged event. Just remember that if you must do this be careful with the name of the events.

Here is a quick code sample that demonstrates how to create a control with two way binding:
  1 public class ButtonCounter : Button, INotifyPropertyChanged
2
{
3
private int clickCount;
4
5
public event PropertyChangedEventHandler PropertyChanged;
6
7
[Bindable(true)]
8
public int ClickCount
9
{
10
get
11
{
12
return clickCount;
13
}
14
set
15
{
16
if (value != clickCount)
17
{
18
clickCount = value;
19
Text = clickCount.ToString();
20
DoPropertyChanged("ClickCount");
21
}
22
}
23
}
24
25
public ButtonCounter()
26
{
27
Click += (o, e) =>
28
{
29
ClickCount += 1;
30
};
31
ClickCount = 0;
32
}
33
34
public void DoPropertyChanged(string propertyName)
35
{
36
if (PropertyChanged != null)
37
{
38
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
39
}
40
}
41
}

Monday, 21 September 2009

Channel Swim Progress

I'm currently 4.5 km across the channel, just over an eighth of the way, now 30.9 km to go.

Monday, 14 September 2009

Channel Swim under way!

I'm currently 1 km accross the channel, only 34.4 km to go!

Now all I need is to get some sponsorship...

Monday, 3 August 2009

Creating Synchronous Web Requests in Silverlight

A word of warning out there to all you budding Silverlight developers. Don't try and do something like this...
private class RequestState
{
public HttpWebRequest Resquest { get; set; }
public HttpWebResponse Response { get; set; }
public ManualResetEvent ResetEvent { get; set; }
}

public static IEnumerable<string> GetFolders(string uri)
{
var requestState = new RequestState();
requestState.Resquest = (HttpWebRequest)WebRequestCreator.ClientHttp.Create(new Uri(uri, UriKind.Absolute));
requestState.ResetEvent = new ManualResetEvent(false);
requestState.Resquest.BeginGetResponse(GetFoldersCallback, requestState);
requestState.ResetEvent.WaitOne();
return ProcessFolderResponse(requestState.Response);
}

private static void GetFoldersCallback(IAsyncResult result)
{
var requestState = (RequestState)result.AsyncState;
requestState.Response = (HttpWebResponse)requestState.Resquest.EndGetResponse(result);
requestState.ResetEvent.Set();
}
It won't work and will just hang. Even though the exact same code will work a treat in a non-Silverlight environment. I tried all sorts to get this to work and pulled my hair out for hours. The reason for this is that the Silverlight runtime gets upset if the main thread gets blocked. So you'll just have to stick with the asynchronous methods and callbacks.

The best I could do was to ask for my own callback and wrap that in a call to Dispatcher.BeginInvoke.
public static void GetFolders(Dispatcher dispatcher, string uri, Action<IEnumerable<string>> folderAction)
{
var request = (HttpWebRequest)WebRequestCreator.ClientHttp.Create(new Uri(uri, UriKind.Absolute));
request.BeginGetResponse(ar =>
{
var response = request.EndGetResponse(ar);
var folders = ProcessFolderResponse(response);
dispatcher.BeginInvoke(() => folderAction(folders));
}, null);
}

Sunday, 2 August 2009

Swim it With Dave

I've just signed up to swim the channel!!!

It's not as mad as it seems. I have to swim 22 miles over 12 weeks at my local swimming pool. For more information go to http://www.aspire.org.uk/channelswim.