Category Archives: Uncategorized

Simple object dumping extension method for CSharp

Standard

Here’s a useful little extension method I created to dump fields and properties to the console of an object in CSharp.  

It demonstrates simple reflection and extension method syntax.

 

 

public static class ObjectExtensions
{
public static void DumpProperties(this object obj)
{
Console.WriteLine(obj.GetType().Name);
Console.WriteLine("{");
foreach (var fld in obj.GetType().GetFields())
{
Console.WriteLine(String.Format("{0} = \"{1}\"", fld.Name, fld.GetValue(obj)));
}
foreach (var prop in obj.GetType().GetProperties())
{
if(prop.CanRead) Console.WriteLine(String.Format("{0} = \"{1}\"", prop.Name,prop.GetValue(obj, null)));
}
Console.WriteLine("}");
}
}

 

 

 

Creating a an instance in EC2 with .net and passing parameters

Standard

When starting an Amazon EC2 instance, you can pass something called “user metadata”.  This can be a file or values.  These values are not stored in an environmental variable or file on the new instance, but can instead be retrieved by doing a HTTP Get to a “special” IP address to retrieve those values.

For example:

1.  Create the instance

RunInstancesResponse response = Client.RunInstances(new RunInstancesRequest()
  .WithImageId(ami_id)
  .WithInstanceType(instance_type)
  .WithKeyName(YOUR_KEYPAIR_NAME)
  .WithMinCount(1)
  .WithMaxCount(max_number_of_instances)
  .WithUserData(Convert.ToBase64String(Encoding.UTF8.GetBytes(bootScript.Replace("\r", ""))))
);

2.  In a startup script on the instance, make a call like this:

GET http://169.254.169.254/latest/user-data
1234,fred,reboot,true | 4512,jimbo, | 173,,,

See the links below for further info

 

 

 

 

 

Links

http://stackoverflow.com/questions/7420368/how-to-start-an-amazon-ec2-instance-programmatically-in-net

http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html

What every phonegap developer on windows phone 7 needs

Standard

 

Error logging!  An unfortunate side effect of developing apps in Javascript in mobile IE9 is that there doesn’t appear to be any error dialogs.

Try the following Javascript:

 

// provide our own console if it does not exist, huge dev aid!
if (typeof window.console == “undefined”) {
window.console = { log: function (str) { window.external.Notify(str); } };
}

// output any errors to console log, created above.
window.onerror = function (msg,url,linenumber) {
console.log(“Error ::” + msg + ” in ” + url + ” at line ” + linenumber);
};

console.log(“Installed console ! “);

This also gives you a “console.log” for free.

 

Enjoy!

 

 

Aspect Oriented Programming in Javascript

Standard

 

In designing javascript for modularity and “separation of concerns”, I was pleasantly surprised to discover a way of implementing AOP (Aspect Oriented Programming) in Javascript.

 

AOP can be useful for automatically “wrapping” methods to provide tracing, error logging or caching.

In this example, we are “wrapping” a method to show an alert when a method starts and finishes:

$.aop.around({ target: homelinksModel, method: 'get' }
 , function (invocation) {
alert("Method Call");
 
var ret = return invocation.proceed(); // This line calls the original method
alert("After Call");
return ret;
});

I used it for caching using Lawnchair  (an abstraction around local storage on client browsers).  It is designed to cache the result of data calls to the server.

$.aop.around({ target: homelinksModel, method: 'get' }
 , function (invocation) {
var lc = new Lawnchair(function () { });
var keyName = 'homelinksModel' + invocation.method;
var rec;
lc.get(keyName, function (ret) {
if (ret == null) {
    res = invocation.proceed()
    lc.save({ key: keyName, value: res });
    rec = res;
 }
 else {
 rec = ret.value;
 }
});
return rec;
}); // </aop>

I’m still learning Lawnchair, so there’s probably better ways of implementing this, but I thought a “useful” example might be helpful.

Peter Chung has an excellent article about Jquery AOP if you’d like to learn more.

There’s not alot of recent “action” around AOP in the Javascript space (Google Search).   I suspect that either some of it’s functionality is automatically part of jQuery or that the Javascript world isn’t mature enough yet to care much.    Perhaps it’s the former.

Over the past few days I’ve had a marvelous time implementing the MVVM pattern in Javascript.  I’m discovering all my favourite technologies are there, such as object databases (Lawnchair), binding (Knockout) and much more.  I hope to be blogging more about some of these soon.

Links

 

 

Data Uris–A way of embedding images in your html page or UIWebView

Standard

image

Currently I’m investigating ways of using  UIWebView to render a user interface.  

I’d like to re-purpose some server side html form rendering logic so that it can be resused on the iPhone, Android and Windows Phone. 

Modern forms incorporate more than simple form elements however.  They may include data, such as images.

By default, the UIWebview supports images in the “bundle” and images in the documents area. 

What if I want to create images in memory, then display these in the HTML?

An little known feature of many modern web browsers (including Webkit) is datauris.  A datauri allows data to be embedded in a webpage where a url would usually be.

Here’s an example:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
There are disadvantages however, which are the obvious effect this will have on caching and pagesize.
The Stackflow article Display Local UI Image On a UIWebView shows how to this, replicated here for your convenience.
This code demonstrates reading a file from the local bundle, then embedding into the background image, in the html dom of a UIWebView:

#import "NSString+DataURI.h"

#import "NSData+Base64.h"

...

-(void)webViewDidFinishLoad:(UIWebView *)webView

{

    NSString *imgPath = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"png"];

    NSData *imgData = [NSData dataWithContentsOfFile:imgPath];

    NSString *imgB64 = [[imgData base64Encoding] pngDataURIWithContent];

    NSString *javascript = [NSString stringWithFormat:@"document.body.style.backgroundImage='url(%@)';", imgB64];

    [webView stringByEvaluatingJavaScriptFromString:javascript];

}

This code uses the following utility functions that provide the base 64 encoding support:

NSData+Base64.h

@interface NSData (Base64)

+ (NSData *)dataWithBase64EncodedString:(NSString *)string;

- (id)initWithBase64EncodedString:(NSString *)string;

- (NSString *)base64Encoding;

- (NSString *)base64EncodingWithLineLength:(unsigned int) lineLength;

@end

NSData.Base64.m

#import "NSData+Base64.h"

static char encodingTable[64] = {

'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',

'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',

'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',

'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/' };

@implementation NSData (VQBase64)

- (id)initWithString:(NSString *)string {

    if ((self = [super init])) {

        [self initWithBase64EncodedString:string];

    }

    return self;

}

+ (NSData *) dataWithBase64EncodedString:(NSString *) string {

    return [[[NSData allocWithZone:nil] initWithBase64EncodedString:string] autorelease];

}

- (id) initWithBase64EncodedString:(NSString *) string {

    NSMutableData *mutableData = nil;

    if( string ) {

        unsigned long ixtext = 0;

        unsigned long lentext = 0;

        unsigned char ch = 0;

        unsigned char inbuf[4], outbuf[3];

        short i = 0, ixinbuf = 0;

        BOOL flignore = NO;

        BOOL flendtext = NO;

        NSData *base64Data = nil;

        const unsigned char *base64Bytes = nil;

        // Convert the string to ASCII data.

        base64Data = [string dataUsingEncoding:NSASCIIStringEncoding];

        base64Bytes = [base64Data bytes];

        mutableData = [NSMutableData dataWithCapacity:[base64Data length]];

        lentext = [base64Data length];

        while( YES ) {

            if( ixtext >= lentext ) break;

            ch = base64Bytes[ixtext++];

            flignore = NO;

            if( ( ch >= 'A' ) && ( ch <= 'Z' ) ) ch = ch - 'A';

            else if( ( ch >= 'a' ) && ( ch <= 'z' ) ) ch = ch - 'a' + 26;

            else if( ( ch >= '0' ) && ( ch <= '9' ) ) ch = ch - '0' + 52;

            else if( ch == '+' ) ch = 62;

            else if( ch == '=' ) flendtext = YES;

            else if( ch == '/' ) ch = 63;

            else flignore = YES;

            if( ! flignore ) {

                short ctcharsinbuf = 3;

                BOOL flbreak = NO;

                if( flendtext ) {

                    if( ! ixinbuf ) break;

                    if( ( ixinbuf == 1 ) || ( ixinbuf == 2 ) ) ctcharsinbuf = 1;

                    else ctcharsinbuf = 2;

                    ixinbuf = 3;

                    flbreak = YES;

                }

                inbuf [ixinbuf++] = ch;

                if( ixinbuf == 4 ) {

                    ixinbuf = 0;

                    outbuf [0] = ( inbuf[0] << 2 ) | ( ( inbuf[1] & 0x30) >> 4 );

                    outbuf [1] = ( ( inbuf[1] & 0x0F ) << 4 ) | ( ( inbuf[2] & 0x3C ) >> 2 );

                    outbuf [2] = ( ( inbuf[2] & 0x03 ) << 6 ) | ( inbuf[3] & 0x3F );

                    for( i = 0; i < ctcharsinbuf; i++ )

                        [mutableData appendBytes:&outbuf[i] length:1];

                }

                if( flbreak )  break;

            }

        }

    }

    self = [self initWithData:mutableData];

    return self;

}

#pragma mark -

- (NSString *) base64Encoding {

    return [self base64EncodingWithLineLength:0];

}

- (NSString *) base64EncodingWithLineLength:(unsigned int) lineLength {

    const unsigned char     *bytes = [self bytes];

    NSMutableString *result = [NSMutableString stringWithCapacity:[self length]];

    unsigned long ixtext = 0;

    unsigned long lentext = [self length];

    long ctremaining = 0;

    unsigned char inbuf[3], outbuf[4];

    unsigned short i = 0;

    unsigned short charsonline = 0, ctcopy = 0;

    unsigned long ix = 0;

    while( YES ) {

        ctremaining = lentext - ixtext;

        if( ctremaining <= 0 ) break;

        for( i = 0; i < 3; i++ ) {

            ix = ixtext + i;

            if( ix < lentext ) inbuf[i] = bytes[ix];

            else inbuf [i] = 0;

        }

        outbuf [0] = (inbuf [0] & 0xFC) >> 2;

        outbuf [1] = ((inbuf [0] & 0x03) << 4) | ((inbuf [1] & 0xF0) >> 4);

        outbuf [2] = ((inbuf [1] & 0x0F) << 2) | ((inbuf [2] & 0xC0) >> 6);

        outbuf [3] = inbuf [2] & 0x3F;

        ctcopy = 4;

        switch( ctremaining ) {

            case 1:

                ctcopy = 2;

                break;

            case 2:

                ctcopy = 3;

                break;

        }

        for( i = 0; i < ctcopy; i++ )

            [result appendFormat:@"%c", encodingTable[outbuf[i]]];

        for( i = ctcopy; i < 4; i++ )

            [result appendString:@"="];

        ixtext += 3;

        charsonline += 4;

        if( lineLength > 0 ) {

            if( charsonline >= lineLength ) {

                charsonline = 0;

                [result appendString:@"\n"];

            }

        }

    }

    return [NSString stringWithString:result];

}

@end

  

NSString+DataURI.h

#import <Foundation/Foundation.h>

@interface NSString(DataURI)

- (NSString *) pngDataURIWithContent;

- (NSString *) jpgDataURIWithContent;

@end

NSString+DataURI.m

#import "NSString+DataURI.h"

@implementation NSString(DataURI)

- (NSString *) pngDataURIWithContent;

{

    NSString * result = [NSString stringWithFormat: @"data:image/png;base64,%@", self];

    return result;

}

- (NSString *) jpgDataURIWithContent;

{

    NSString * result = [NSString stringWithFormat: @"data:image/jpg;base64,%@", self];

    return result;

}

@end

  

 

Setting the default browser in Visual Studio 2010 in an MVC Application

Standard

image

To set the default browser used for debugging in an ASP.Net web application you need to bring up the “Browse With…” option on an aspx web page.  In a default MVC application you won’t have this option.

To do this temporarily add a “default.aspx” form to the root of your project, then the “Browse With…” context menu option will appear.  Choose your favourite browser, then remove the “default.aspx”.

Hanging WCF Service

Standard

 

image

Suffering from a hanging WCF service? I was.  The hanging wasn’t in my service code but in the depths of service side WPF.

Apparently the serverside was being throttled within WCF instelf (see this article) due to many open connections.  Basically, in the client remember to call Close on the service. 

Dim loService As New ClientService.ClientConnectClient
Dim lsOut As String = loService.SomeServiceMethod("Hello")
loService.Close()

Because methods are so stateless (and I didn’t have to call an Open method) it didn’t occour to me that I’d need to call Close.

Although WCF is supposed to abstract you away from the network I’m finding that an understanding of the underlying technology (eg IIS) is essential to work effectively with it.

Links

http://blogs.msdn.com/b/tess/archive/2009/01/09/net-hang-my-application-hangs-after-i-called-my-wcf-service-a-couple-of-times.aspx

Windows Identity Framework – Externalising Authentication

Standard

image

As an architect that works for an ISV, I’m interested in making our application functionality to as useful as possible to as many people as possible in an organisation.

A “barrier to entry” for applications can be when a customer only needs a small part of the application functionality.    Many applications have their own authentication and login sequence, which make them unsuitable for this kind of functionality.

Typically customers have some kind of corporate application, intranet or portal that is designed to incorporate little bits of applications.  Over the last few years a number of authentication standards have become accepted by many organisations, including Microsoft.

Microsoft have released the RTM version of WIF (Windows Identity Framework) which provides a layer of abstraction over authentication, allowing a pluggable approach to establishing trust between web applications.

Vittorio Bertocci provides an excellent overview of WIF in his PDC09 Talk.

In this demo, Vittorio demonstrates adding an “STS Reference” to his project.  An STS is a “Secure Tokens Service”.    He also shows how “Claims” (properties against a credentials token) can be bound to fields in a webforms user interface.

It’s heartening to see Microsoft attempting to take a traditionally complex area and create tools to make it usable.

Catching Application Level Mouse Events in Winforms

Standard

image

As part of my work on flick scrolling I’ve created an example of a class that can create mouse events for an entire Winforms application.

To use it, just declare it, like so:

Private WithEvents moAppMouseEvents As New ApplicationLevelMouseEvent

 

I’ve only implemented the MouseUp and MouseDown events, but these are consistent with the Form ones:

 

Private Sub moAppMouseEvents_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles moAppMouseEvents.MouseUp

 
End Sub
Private Sub moAppMouseEvents_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles moAppMouseEvents.MouseDown
 
End Sub

 

The code uses an IMessageFilter in the tradtional fashion:

 

Public Class ApplicationLevelMouseEvents
    Implements IDisposable
    Implements IMessageFilter

    Public Event MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
    Public Event MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)

    Private Const WM_LBUTTONUP As Integer = &H202
    Private Const WM_LBUTTONDOWN As Integer = &H201
    'Private Const WM_RBUTTONDOWN As Integer = &H204
    'Private Const WM_MBUTTONDOWN As Integer = &H207
    'Private Const WM_NCLBUTTONDOWN As Integer = &HA1
    'Private Const WM_NCRBUTTONDOWN As Integer = &HA4
    'Private Const WM_NCMBUTTONDOWN As Integer = &HA7
    Public Sub New()
        Application.AddMessageFilter(Me)
    End Sub

    Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements System.Windows.Forms.IMessageFilter.PreFilterMessage
        If (m.Msg = WM_LBUTTONDOWN) Then

            Dim loArgs As New MouseEventArgs(MouseButtons.Left, 1, System.Windows.Forms.Cursor.Position.X, System.Windows.Forms.Cursor.Position.Y, 0)

            RaiseEvent MouseDown(Me, loArgs)

        ElseIf (m.Msg = WM_LBUTTONUP) Then
            Dim loArgs As New MouseEventArgs(MouseButtons.Left, 1, System.Windows.Forms.Cursor.Position.X, System.Windows.Forms.Cursor.Position.Y, 0)
            RaiseEvent MouseUp(Me, loArgs)
        End If
        Debug.WriteLine(m.Msg.ToString)
        Return False

    End Function

    Private disposedValue As Boolean = False        ' To detect redundant calls

    ' IDisposable
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                Application.RemoveMessageFilter(Me)
            End If
        End If
        Me.disposedValue = True
    End Sub

#Region " IDisposable Support "
    ' This code added by Visual Basic to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
#End Region

End Class

 

The sample could be enhanced to support the full range of events such as mouse move, so feel free to take the sample and change it.  If you post your code, please link back to this post.

 

Links

A Simple Scroll Controller for Winforms

3D in Silverlight 2.0

Standard

image

So what’s the difference between WPF and Silverlight again?  Oh yes, well WPF has more advanced features.

You know, 3D graphics!

Isn’t it strange that many Silverlight demos invariably incorporate 3D style effects? 

Take a look at this article for a very rich solution:

Silverlight: Building Advanced 3D Animations with Silverlight 2.0

I wonder how long it will be before Silverlight supports 3D natively?