Chris Cavanagh’s Blog

Steorn Technology Demo, Dublin

December 20, 2009 · Leave a Comment

While visiting the UK over Christmas, I popped over to Dublin to see Steorn’s Orbo technology demo and absorb a pint or two of the black stuff

Here are a few videos:

Slightly longer clip:

Here’s a browse around the exhibit and quick chat to one of the guys about what he was measuring:

Fyi – “Popped” doesn’t exactly do justice to the journey.  It was more like getting a train to Holyhead at 10:56pm, a 4hr ferry to Dublin, a long walk in the cold & dark, all the while my son (who came along with my dad :) ) getting sicker and sicker from a mixture of previous jet lag and a caffeine crash.  If you’re in the area, be sure to visit The Art of Coffee (next door to the Waterways Center) – best cappuccino ever, and a lifesaver when you need to thaw a frozen child :)

(It’s interesting to see reactions to this stuff online; there are some strong opinions out there about violations of those pesky laws of thermodynamics).

→ Leave a CommentCategories: .NET

Interactive Fiction + Linux + Moonlight

November 2, 2009 · 2 Comments

Moonlight 2 beta 7 (at time of writing) is getting really close to working with SilverGlulxe / SilverFyre!  The only issue right now is none of the story text appears… ;) (could just be a simple font issue).

FYI one of the cool things about SilverGlulxe is its handy “Transcript” option (link at bottom of game).  It gives you a transcript of the story so far (including your commands) and lets you send a copy (including XML source) by email.  Apparently it’s very useful for story debugging [if you’re an Interactive Fiction writer].

kick it

→ 2 CommentsCategories: .NET

Silverlight VisualBrush and rounded corners

September 24, 2009 · 7 Comments

As you know Silverlight 3 doesn’t support VisualBrush, which can make things like this pretty tricky.

Here’s my attempt at a workaround :)   It’s a control called VisualImage which can be pointed at any element and exposes it as a WriteableBitmap.  You could bind an Image to this to create a reflection effect like this (don’t forget to look at Jeff Prosise’s sample):

image

You could even bind it to an ImageBrush… if it supported binding.  To work around this, VisualImage can be bound to the ImageBrush instead.  One application of this is for clipped, rounded corners on any element (here’s the WPF way):

image

You can try a live sample here (source on CodePlex).

Although VisualImage is a Control, it doesn’t render anything itself – it just acts as an intermediary between your visual and whatever you want to bind it to.  Here’s everything you need (also available here):

/// <summary>
/// VisualImage
/// </summary>
public class VisualImage : Control
{
    #region Visual DependencyProperty

    public static readonly DependencyProperty VisualProperty = DependencyProperty.Register(
        "Visual",
        typeof( FrameworkElement ),
        typeof( VisualImage ),
        new PropertyMetadata( OnVisualChanged ) );

    public FrameworkElement Visual
    {
        get { return (FrameworkElement)GetValue( VisualProperty ); }
        set { SetValue( VisualProperty, value ); }
    }

    private static void OnVisualChanged( DependencyObject obj, DependencyPropertyChangedEventArgs args )
    {
        var visualImage = obj as VisualImage;
        visualImage.OnVisualChanged( args );
    }

    private void OnVisualChanged( DependencyPropertyChangedEventArgs args )
    {
        if ( args.OldValue != null ) ( (FrameworkElement)args.OldValue ).SizeChanged -= VisualImage_SizeChanged;
        if ( args.NewValue != null )
        {
            var visual = (FrameworkElement)args.NewValue;
            visual.SizeChanged += VisualImage_SizeChanged;
            PrepareBitmap( (int)visual.RenderSize.Width, (int)visual.RenderSize.Height );
        }
    }

    private void VisualImage_SizeChanged( object sender, SizeChangedEventArgs e )
    {
        PrepareBitmap( (int)e.NewSize.Width, (int)e.NewSize.Height );
    }

    #endregion // Visual DependencyProperty

    #region Bitmap DependencyProperty

    public static readonly DependencyProperty BitmapProperty = DependencyProperty.Register(
        "Bitmap",
        typeof( WriteableBitmap ),
        typeof( VisualImage ),
        null );

    public WriteableBitmap Bitmap
    {
        get { return (WriteableBitmap)GetValue( BitmapProperty ); }
        set { SetValue( BitmapProperty, value ); }
    }

    #endregion // Bitmap DependencyProperty

    #region ImageBrush DependencyProperty

    public static readonly DependencyProperty ImageBrushProperty = DependencyProperty.Register(
        "ImageBrush",
        typeof( ImageBrush ),
        typeof( VisualImage ),
        null );

    public ImageBrush ImageBrush
    {
        get { return (ImageBrush)GetValue( ImageBrushProperty ); }
        set { SetValue( ImageBrushProperty, value ); }
    }

    #endregion // VisualBrush DependencyProperty

    /// <summary>
    /// Initializes a new instance of the <see cref="VisualImage"/> class.
    /// </summary>
    public VisualImage()
    {
    }

    /// <summary>
    /// Prepares the bitmap.
    /// </summary>
    /// <param name="width">The width.</param>
    /// <param name="height">The height.</param>
    private void PrepareBitmap( int width, int height )
    {
        Bitmap = new WriteableBitmap( width, height );
        Invalidate();
    }

    /// <summary>
    /// Invalidates the VisualImage and causes WriteableBitmap to be refreshed.
    /// </summary>
    public void Invalidate()
    {
        if ( Bitmap != null && Visual != null )
        {
            Array.Clear( Bitmap.Pixels, 0, Bitmap.Pixels.Length );
            Bitmap.Render( Visual, this.RenderTransform );
            Bitmap.Invalidate();

            if ( ImageBrush != null && ImageBrush.ImageSource != Bitmap )
            {
                ImageBrush.ImageSource = Bitmap;
            }
        }
    }
}

For performance reasons it only refreshes the WriteableBitmap when the target Visual’s size changes.  You can call the Invalidate() method to force a refresh (consider calling it from CompositionTarget.Rendering if you want it to refresh every frame).

Here’s how to get rounded corners on anything (similar to WPF technique, with added VisualImage and named ImageBrush):

                <Grid HorizontalAlignment="Center" VerticalAlignment="Center">
                    <Border x:Name="mask" Background="White" CornerRadius="20" Padding="10"/>
                    <local:VisualImage Name="visualImage" Visual="{Binding ElementName=mask}" ImageBrush="{Binding ElementName=brush}"/>
                    <Image Source="http://farm2.static.flickr.com/1429/1430528819_edb63b79a6.jpg">
                        <Image.OpacityMask>
                            <ImageBrush x:Name="brush"/>
                        </Image.OpacityMask>
                    </Image>
                </Grid>

And here’s a reflection:

                <TextBlock x:Name="myText" FontSize="96">Hello</TextBlock>
                <local:VisualImage Name="reflectImage" Visual="{Binding ElementName=myText}"/>
                <Image Source="{Binding Bitmap, ElementName=reflectImage}" RenderTransformOrigin="0.5,0.2">
                    <Image.RenderTransform>
                        <ScaleTransform ScaleY="-0.8"/>
                    </Image.RenderTransform>
                    <Image.OpacityMask>
                        <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                            <GradientStop Offset="0" Color="#00FFFFFF"/>
                            <GradientStop Offset="1" Color="#80FFFFFF"/>
                        </LinearGradientBrush>
                    </Image.OpacityMask>
                </Image>

kick it

→ 7 CommentsCategories: .NET

YouCube 3.0 (Chromium WebBrowser) – Source Code

September 8, 2009 · 10 Comments

Source code for YouCube 3.0 (WPF 3D Chromium-based WebBrowser) is now on CodePlex.  See the related WPF Chromium WebBrowser project for the Awesomium wrapper source.

kick it

→ 10 CommentsCategories: .NET

WPF 3D Chromium Browser

August 27, 2009 · 24 Comments

UPDATE: Now shows separate browser on each face! (a fast PC will help :) ).  Click a face in “browse” mode to select it and change the URL (or interact with it).  Source code available on CodePlex (see related post).

There’s an updated version of YouCube (WPF 3D Web Browser) available based on my Awesomium / Chromium control.  Try it here!

image

If you prefer you can run the application locally instead (ZIP here).

image

For more examples, and an important note about VS2010, be sure to check out Sacha Barber’s related post :)

kick it

→ 24 CommentsCategories: .NET

WPF Chromium WebBrowser source code!

August 25, 2009 · 114 Comments

The source code for my WPF Chromium WebBrowser control is now available on CodePlex.

The source includes:

Cjc.ThreeDeemium – The sample application, currently without any 3D features.  Go figure.
Cjc.ChromiumBrowser – The WPF Chromium WebBrowser control.  Depends on Cjc.AwesomiumWrapper and the two Awesomium / Chromium C++ DLLs (Awesomium.dll and icudt38.dll).
Cjc.AwesomiumWrapper – A Managed C++ / CLI wrapper around Awesomium.  This is much easier to maintain than the old P/Invoke stuff, and is almost nice to look at :)
Awesomium – C++ headers and libraries for Awesomium / Chromium.

There’s also a bonus project :) :

Cjc.WebSnapshot – A small command-line utility using Cjc.AwesomiumWrapper to snapshot a URL (you need to specify a full URL including the scheme – http://chriscavanagh.wordpress.com etc).

→ 114 CommentsCategories: .NET

A Real WPF WebBrowser

August 25, 2009 · 175 Comments

UPDATE: Source code available!  See post here.  Fixed keyboard / Javascript bug :)   Added some sample pixel shader effects! (including HatchingEffect by Charles Bissonnette).  If you need Awesomium_d.dll (for debug builds) you can get it here.

Being able to render and interact with webpages within WPF opens up some great opportunities.  While WPF already includes a WebBrowser, it’s just a wrapper around IE’s ActiveX control.  Unfortunately this prevents it playing nicely with WPF’s layout system :(

Mixing Google’s Chromium project, a great wrapper called Awesomium and a little WPF pixie dust, we finally have one :) :

WPF Chromium Control

You can try the ClickOnce application here.  Source is available on CodePlex (discussed here).  You should find it works great with Flash and Silverlight (assuming plug-ins already installed) but currently it might choke on XBAPs and Java applets.

If you prefer to run the binaries locally, you can get them here :)

image

image

For more examples, and an important note about VS2010, be sure to check out Sacha Barber’s related post.

For more fun, have a look at YouCube 3!

kick it

→ 175 CommentsCategories: .NET

Silverlight 3 + ClearType

July 9, 2009 · 6 Comments

As we knew, Silverlight 3 includes ClearType support.  Now it’s released we can finally see it in action :) :

image

More importantly, it works great with SilverGlulxe!

→ 6 CommentsCategories: .NET

WPF 2D Physics Plus

June 25, 2009 · 1 Comment

Rohit Gupta is working on some great enhancements to the WPF 2D Physics demo I posted.  Features include:

  • Click to remove a body from the world
  • Click and “push” the body in any given direction

Be sure to take a look!  The project is here on CodePlex and you can run it as a ClickOnce app here.

→ 1 CommentCategories: .NET

MVC IsAuthorized and AuthorizedActionLink

June 11, 2009 · 8 Comments

UPDATE: Fixed broken IsAuthenticated logic (thanks Travis).

Robert Dean published a great post last year about his Security Aware Html.ActionLink.  It allowed you to conditionally render links based on the [AuthorizeAttribute] assigned to a controller’s action methods.

Here’s an alternative implementation based on expressions, so you get type safety, intellisense and slightly simpler code :)   First, a helper to determine if an action is authorized:

public static class AuthorizationExtensions
{
    private static Dictionary<Expression, AuthorizeAttribute[]> expressionAuthorizers = new Dictionary<Expression, AuthorizeAttribute[]>();

    /// <summary>
    /// Determines whether the specified action is authorized.
    /// </summary>
    /// <typeparam name="TController">The type of the controller.</typeparam>
    /// <param name="helper">The helper.</param>
    /// <param name="actionMethod">The action method.</param>
    /// <returns>
    ///     <c>true</c> if the specified helper is authorized; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsAuthorized<TController>( this HtmlHelper helper, Expression<Action<TController>> action )
    {
        var call = action.Body as MethodCallExpression;

        if ( call == null ) return false;

        var authorizers = expressionAuthorizers.ContainsKey( action )
            ? expressionAuthorizers[ action ]
            : expressionAuthorizers[ action ] = GetAttributes<AuthorizeAttribute>( call );

        return ( authorizers.Length > 0 )
            ? authorizers.All( a => a.IsAuthorized( helper.ViewContext.HttpContext.User ) )
            : true;
    }

    /// <summary>
    /// Gets the specified attributes for an action method.
    /// </summary>
    /// <param name="call">The call.</param>
    /// <returns></returns>
    private static TAttribute[] GetAttributes<TAttribute>( MethodCallExpression call ) where TAttribute : Attribute
    {
        return call.Object.Type.GetCustomAttributes( typeof( TAttribute ), true )
            .Union( call.Method.GetCustomAttributes( typeof( TAttribute ), true ) )
            .Cast<TAttribute>()
            .ToArray();
    }

    /// <summary>
    /// Determines whether the specified <see cref="AuthorizeAttribute"/> authorizes the specified user.
    /// </summary>
    /// <param name="authorize">The <see cref="AuthorizeAttribute"/>.</param>
    /// <param name="user">The user.</param>
    /// <returns>
    ///     <c>true</c> if the specified user is authorized; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsAuthorized( this AuthorizeAttribute authorize, IPrincipal user )
    {
        if ( !user.Identity.IsAuthenticated ) return false;

        var users = authorize.Users.SplitString();
        if ( users.Length > 0 && !users.Contains( user.Identity.Name, StringComparer.OrdinalIgnoreCase ) ) return false;

        var roles = authorize.Roles.SplitString();
        if ( roles.Length > 0 && !roles.Any( user.IsInRole ) ) return false;

        return true;
    }

    /// <summary>
    /// Splits and trims the specified string.
    /// </summary>
    /// <param name="original">The original.</param>
    /// <returns></returns>
    public static string[] SplitString( this string original )
    {
        return string.IsNullOrEmpty( original )
            ? new string[ 0 ]
            : original.Split( '.' ).Select( s => s.Trim() ).Where( s => !string.IsNullOrEmpty( s ) ).ToArray();
    }
}

With that, it’s possible to write markup like this:

<% if ( Html.IsAuthorized<ModelingController>( c => c.Index() ) ) {%>
    <div>My conditional content...</div>
<%}%>
 

If you’re using ASP.NET MVC Futures, it’s straightforward to write an authorized ActionLink:

public static class LinkExtensions
{
    /// <summary>
    /// Render an HTML action link if authorized by the target action.
    /// </summary>
    /// <typeparam name="TController">The type of the controller.</typeparam>
    /// <param name="helper">The helper.</param>
    /// <param name="action">The action.</param>
    /// <param name="linkText">The link text.</param>
    /// <returns></returns>
    public static string AuthorizedActionLink<TController>( this HtmlHelper helper, Expression<Action<TController>> action, string linkText )
        where TController : Controller
    {
        return AuthorizedActionLink<TController>( helper, action, linkText, null );
    }

    /// <summary>
    /// Render an HTML action link if authorized by the target action.
    /// </summary>
    /// <typeparam name="TController">The type of the controller.</typeparam>
    /// <param name="helper">The helper.</param>
    /// <param name="action">The action.</param>
    /// <param name="linkText">The link text.</param>
    /// <param name="htmlAttributes">The HTML attributes.</param>
    /// <returns></returns>
    public static string AuthorizedActionLink<TController>( this HtmlHelper helper, Expression<Action<TController>> action, string linkText, object htmlAttributes )
        where TController : Controller
    {
        var routeValuesFromExpression = ExpressionHelper.GetRouteValuesFromExpression<TController>( action );

        return helper.IsAuthorized( action )
            ? helper.RouteLink( linkText, routeValuesFromExpression, new RouteValueDictionary( htmlAttributes ) )
            : null;
    }
}

NOTE – You could do the same thing without MVC Futures, but would need a little more code (you’d need something like ExpressionHelper’s GetRouteValuesFromExpression method).

Here’s a markup example:

<%= Html.AuthorizedActionLink<ModelingController>( c => c.Index(), "Modeling" ) %>
 

→ 8 CommentsCategories: .NET