Playing with Shaders: Creating a water effect

Lately I’ve been looking at a really cool project on Codeplex for Pixel Shaders. The set of shaders in this library is awsome and really easy to use in you application….

All you need to do to consume any Shader is add a reference to the WPFShaderEffectLibrary class library and you can start using the shaders in XAML.What is really important is that you install the Shaders Build Task before trying to build the shader library (if you just add a reference to the ready build dlls you don’t even need to do this).



So let’s have a look at how we can use shaders to simulate water on screen.

This is very easy all we need is a ripple shader effect. so something like this

   1: <Window.Resources>


   3:    <Storyboard x:Key="waterAnimMain">

   4:        <DoubleAnimation Storyboard.TargetName="rippleMain" Storyboard.TargetProperty="Phase" To="0" From="10" Duration="0:0:2.0"  FillBehavior="Stop" />

   5:        <DoubleAnimation Storyboard.TargetName="rippleMain" Storyboard.TargetProperty="Amplitude" To="0" From="0.6" Duration="0:0:2.0"  FillBehavior="HoldEnd" />

   6:        <DoubleAnimation Storyboard.TargetName="rippleMain" Storyboard.TargetProperty="Frequency" To="0" From="30" Duration="0:0:2.5" FillBehavior="HoldEnd" />

   7:    </Storyboard>


   9: </Window.Resources>

  10: <Grid Background="Transparent" >


  12:    <Border>

  13:        <Border.Background>

  14:            <LinearGradientBrush EndPoint="0.93,0.925" StartPoint="0.094,0.125">

  15:                <GradientStop Color="#FF272788" Offset="0.112"/>

  16:                <GradientStop Color="#FF090916" Offset="0.721"/>

  17:                <GradientStop Color="#FE222267" Offset="0.28"/>

  18:                <GradientStop Color="#FE131339" Offset="0.453"/>

  19:                <GradientStop Color="#FF04040A" Offset="0.974"/>

  20:            </LinearGradientBrush>

  21:        </Border.Background>


  23:    </Border>


  25: </Grid>


  27: <Window.Effect>

  28:    <shader:RippleEffect Amplitude="0" Frequency="0" Phase="0" x:Name="rippleMain"  />

  29: </Window.Effect>

This is our Shader

   1: <shader:RippleEffect Amplitude="0" Frequency="0" Phase="0" x:Name="rippleMain"  />

And we animate this shader like so to make the effect of water

   1: <Storyboard x:Key="waterAnimMain">

   2:      <DoubleAnimation Storyboard.TargetName="rippleMain" Storyboard.TargetProperty="Phase" To="0" From="10" Duration="0:0:2.0"  FillBehavior="Stop" />

   3:      <DoubleAnimation Storyboard.TargetName="rippleMain" Storyboard.TargetProperty="Amplitude" To="0" From="0.6" Duration="0:0:2.0"  FillBehavior="HoldEnd" />

   4:      <DoubleAnimation Storyboard.TargetName="rippleMain" Storyboard.TargetProperty="Frequency" To="0" From="30" Duration="0:0:2.5" FillBehavior="HoldEnd" />

   5:  </Storyboard>

We invoke this animation by having a DispatcherTimer trigger the animation every now and then and changing the Center property of the Shader to a random point from 0 to 1.

This already gets us very close but it still does not feel like real water. The trick is to animate to ripple effects at the same time. This will make the ripple effects expand together and thus making the control which has the shader applied look like water. Yet the problem is that you can only apply ONE shader per control. BUT you can have another shader on the parent control and that would still apply the shader on all children (I explain this in this article).

   1: <Window.Resources>


   3:     <Storyboard x:Key="waterAnimMain">

   4:         <DoubleAnimation Storyboard.TargetName="rippleMain" Storyboard.TargetProperty="Phase" To="0" From="10" Duration="0:0:2.0"  FillBehavior="Stop" />

   5:         <DoubleAnimation Storyboard.TargetName="rippleMain" Storyboard.TargetProperty="Amplitude" To="0" From="0.6" Duration="0:0:2.0"  FillBehavior="HoldEnd" />

   6:         <DoubleAnimation Storyboard.TargetName="rippleMain" Storyboard.TargetProperty="Frequency" To="0" From="30" Duration="0:0:2.5" FillBehavior="HoldEnd" />

   7:     </Storyboard>


   9:     <Storyboard x:Key="waterAnimSub">

  10:         <DoubleAnimation Storyboard.TargetName="rippleSub" Storyboard.TargetProperty="Phase" To="0" From="10" Duration="0:0:2.0"  FillBehavior="Stop" />

  11:         <DoubleAnimation Storyboard.TargetName="rippleSub" Storyboard.TargetProperty="Amplitude" To="0" From="0.6" Duration="0:0:2.0"  FillBehavior="HoldEnd" />

  12:         <DoubleAnimation Storyboard.TargetName="rippleSub" Storyboard.TargetProperty="Frequency" To="0" From="30" Duration="0:0:2.5" FillBehavior="HoldEnd" />

  13:     </Storyboard>


  15: </Window.Resources>

  16: <Grid Background="Transparent" >


  18:     <Border>

  19:         <Border.Background>

  20:             <LinearGradientBrush EndPoint="0.93,0.925" StartPoint="0.094,0.125">

  21:                 <GradientStop Color="#FF272788" Offset="0.112"/>

  22:                 <GradientStop Color="#FF090916" Offset="0.721"/>

  23:                 <GradientStop Color="#FE222267" Offset="0.28"/>

  24:                 <GradientStop Color="#FE131339" Offset="0.453"/>

  25:                 <GradientStop Color="#FF04040A" Offset="0.974"/>

  26:             </LinearGradientBrush>

  27:         </Border.Background>

  28:         <Border.Effect>

  29:             <shader:RippleEffect Amplitude="0" Frequency="0" Phase="0" x:Name="ripple" Center="{Binding ElementName=main, Path=(local:MouseBehaviour.LastMouseUp)}" />

  30:         </Border.Effect>

  31:     </Border>


  33:     <Grid.Triggers>


  35:         <EventTrigger RoutedEvent="UIElement.MouseUp">

  36:             <BeginStoryboard Storyboard="{StaticResource waterAnim}"/>

  37:             <BeginStoryboard Storyboard="{StaticResource waterAnimMain}"/>

  38:         </EventTrigger>

  39:     </Grid.Triggers>


  41:     <Grid.Effect>

  42:         <shader:RippleEffect Amplitude="0" Frequency="0" Phase="0" x:Name="rippleSub"  />

  43:     </Grid.Effect>


  45: </Grid>


  47: <Window.Effect>

  48:     <shader:RippleEffect Amplitude="0" Frequency="0" Phase="0" x:Name="rippleMain"  />

  49: </Window.Effect>

And that’s it. Now we have a perfect water look thanks to the Codeplex Pixel Shader library :)

I created a sample app that shows all this. The app also has another feature so that you can touch the water by using the mouse and the water would ripple from the point you touch (of course this is with Behaviours so that you can even reuse it :D )

Happy coding :D


Mediator v2 for MVVM WPF and Silverlight applications

This last 2 weeks, us WPF Disciples have been talking a lot about the Mediator pattern for MVVM applications. Me and Josh Smith revised my previous Mediator implementation and found some problems with it.

Problem: There was a memory leak. Once a Mediator subscribes for one or more messages it would be kept in memory since the Mediator was holding a reference to the ViewModel.
Solution: We could have just exposed an unregister method so that when you call this method the Mediator would release the instance of the ViewModel. But sometimes it is hard to know when a ViewModel is going to die… So we went a step further and created the WeakAction. The WeakAction stores the instance of the ViewModel in a WeakRefence thus the ViewModel can be garbage collected without any problem and once it does get garbage collected the Mediator automatically removes that ViewModel registration from the list.

While we were at it we PIMPED the Mediator API :) We added 2 approaches to subscribe to the Mediator and we also added support for (thanks to David Anson suggestion) strongly typed parameters.

So now the Mediator offers 2 methods of registration, a declarative way of registering and an imperative way as well.

The Declarative approach. (Supported in WPF and Silverlight)

This approach uses attributes so that you can decorate the messages that act as subscribers for messages.Here is an example

   1: /// <summary>

   2: /// Subscribe to Message1

   3: /// </summary>

   4: /// <param name="message">The message to be passed</param>

   5: [MediatorMessageSink(MediatorMessages.Message1, ParameterType = typeof(SomeData))]

   6: public void Test(SomeData data)

   7: {

   8:     MessageBox.Show(data.Text + "\nReceived by: ColleagueA");

   9: }

So you just have to decorate your method with MediatorMessageSink attribute and the Method will get invoked every time a message is broadcasted via the Mediator.

As you can see the Mediator also supports strongly typed parameters. In order to do so you have to specify the ParameterType property on the attribute as shown in the sample code above. You can pass 0 or 1 parameters. If you don’t have any parameters just ignore the ParameterType (since this is an named Property and you can just not set it )

When using the declarative approach you must register the instance of the ViewModel to the Mediator. This is just one line of code in the ViewModel constructor. Here is how you do that

   1: public ColleagueA()

   2: {

   3:     //Register all decorated methods to the Mediator

   4:     Mediator.Register(this);

   5: }

This will inspect all methods of the ViewModel and look for the MediatorMessageSink attribute and register the appropriate methods to the Mediator. If you are going to have a base class for the ViewModels in your project and you can put this in the constructor of your base class. As simple an that.


The Imperative approach. (Supported in WPF ONLY)

If you do not want to use the attribute based registration we offer an imperative approach where you specify a method to be registered to a specific message. This implementation is exactly as it was in the old Mediator yet now it supports strongly typed parameters.

Here is how you can use this in your code

   1: public ColleagueC()

   2: {

   3:     //Register a specific delegate to the Mediator

   4:     Mediator.Register(MediatorMessages.Message1,

   5:         (Action<SomeData>)

   6:         delegate(SomeData x) 

   7:         {

   8:             Test = x.Text;

   9:             MessageBox.Show(x.Text + " \nReceived by: ColleagueC"); 

  10:         });

  11: }

This method is supported in WPF only since in Silverlight you cannot call an anonymous method (via reflection). If you try to use this method in Silverlight you will get an InvalidOperationException saying “This method is not supported in Silverlight”.



I packaged the Mediator in a class library so that you can go ahead and add a reference and reuse this library in your day to day projects.As always feedback is much appreciated.

Download MediatorLib + Sample application

[MVVM + Mediator + ACB = cool WPF App] – Intro

Finally I managed to spare some time and build a WPF sample application to showcase the use of MVVM + Mediator and also how AttachedCommandBehaviours can be used to further reduce (or better eliminate) C# code in XAML code behind files. I am also using one of my favorite WPF libraries FluidKit. In the app I create my own 3D transition for the FluidKit TransitionPresenter (I will be posting a whole post on this).

I will be posting at least 4 posts


– MVVM and the Mediator pattern

– FluidKit CoverFlow and FluidKit TransitionPresenter

– Using AttachedCommandBehaviours

Here are some teaser screenshots of the application in action :)

Screen1 Screen2

Screen3 Screen4


Setup of application environment

This application uses a SQL Database so you will need an instance of SqlServer 2005 running (you can use SqlServer Express).

I packaged the database as a backup so all you need to do is restore the database from the SqlServer Management Studio Express (this is your easiest option). If you don’t have this I suggest you download it, it’s free.

To restore the database file (WPFDisciplesDB.bak) follow these steps

– First of all download the database file from here.

– Right click on the Databases folder in the SQL Server Management Studio Express and select Restore database

Step 1

This will open a dialog for you. In the Restore Database dialog enter a name for the database in the “To database” text field > Select “From device” radio button and browse for the WPFDisciples.bak that you downloaded. The file will appear in the list. Tick the checkbox (which is un checked by default) and press ok.

Step 2 

Now that we have our database set up all we need to do is specify in the app.config the connection string of the new database and we are done.

Stayed tuned because this should be real fun :)

aaaa I nearly forgot… The data in the database is not the full version… I will add more projects from the mighty WPF Disciples as time goes by…. Will continue updating the download link here (and put a comment or something to show you that I updated the db version)

Download Full Source Code from HERE

Just in case you missed it, here is a copy of the database

XBAPs Part 2: Consuming WCF services from an XBAP


One of the big improvements to XBAPs in .NET 3.5 is the ability to consume WCF services. Nowadays Service Oriented Architectures (SOAs) are very popular and used almost everywhere. This all makes sense, as SOA is very scalable, and for many cases it is the best approach to take for a project; so why not enable SOA for XBAPs as well. To tell you the truth, you could consume WCF services from XBAP in .NET 3.0, yet the XBAP had to have Full Trust, and not Partial Trust, which usually spells trouble. Anyway we don’t have to worry much about this now because .NET 3.5 enables XBAPs to consume WCF services even in Partial Trust. Read more about this and it’s limitations here.

Setting up our workspace

Ok so let’s start by creating a simple WCF service. Open Visual Studio and create a WCF service by clicking File > New > Project and then select Web > WCF Service application


I am not going to cover the basics of how to create a WCF service, yet by default the WCF Service Visual Studio template creates a simple service for us already (called IService). So yes, if you hit F5 and run the service you will already have a service up and running. Once we have our simple service let’s create a Simple XBAP in the same solution (in order to do this please refer to my previous post).

Now that we have both the WCF service and the XBAP how are we going to make them communicate? Well, thanks to Visual Studio this is super simple. All you have to do is Right click the XBAP project, select the “Add Service Reference” option and a Dialog will pop up:


Please Note: If you do not run the service you will get an error while expanding the Tree nodes of the service in this Dialog. If the service is not running Visual Studio cannot get the Metadata of the service, since this is just another EndPoint of the service. In order to run the service just Right Click on Service1.svc and select View in Browser.

Ok, now that we added the Service Reference, Visual Studio will go to work and generate a Proxy class for us. We will use this proxy class to communicate with the WCF service. By default the Proxy class is called <Name of service>Client so in our case it will be called Service1Client. This proxy class will have a method for every OperationContract we have in our service. You can also choose to create an Async version of the service. In order to do so just right click the Service1 (in the XBAP project that got created when we added the Service Reference) and select Configure Service Reference.


In this dialog check the Generate Async operations checkbox and Visual Studio will add an async version of the OperationContracts for you (Thank you VS… we love you :) )

The first error you’ll see

Ok now that we have everything set up lets do a simple button in our XBAP and in the Click event handler call a method. Something like this….

   1: private void Button_Click(object sender, RoutedEventArgs e)
   2: {
   3:     Service1Client client = new Service1Client();
   4:     MessageBox.Show(client.GetData(1));
   5: }

Let’s hit F5 and run our XBAP and see what happens.

AND BAMMMM a big ugly exception is thown.


The WSHttpBinding with name WSHttpBinding failed validation because it contains a BindingElement with type System.ServiceModel.Channels.SymmetricSecurityBindingElement which is not supported in partial trust

which in VS looks like this


Yet I promised you guys that WCF is supported in Partial trust XBAPs…. And it is, it’s just that the default WCF EndPoint is not :) By default a WCF Service has it’s EndPoint set up as WsHTTPBinding which is not supported in Partial trust XBAPs. In order to fix this Right click the app.config of your service and select “Edit WCF Configuration” (if this option is not available go to Tools > WCF Service Configuration Editor then select open and specify the path of your App.config. Once you have the app.config opened in the editor Expand the Bindings Node and select the node under that. Open the Security tab and choose None as security level.


Once that’s done run the app again.

The Second error you’ll see

And this time it’s a SecurityException saying

Request for the permission of type ‘System.Net.WebPermission, System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089’ failed.


In order to fix this Go to the XBAP project Properties and select Debug tab. Select the Start External Program option and enter the following exe path “C:\WINDOWS\System32\PresentationHost.exe” and in the Command Line arguments text field enter the following

-debug <Path of XBAP> –debugSecurityZoneUrl <URL of service>

in my case it was

-debug “D:\net resources\My Blog\XBAPAndWCF\XBAPClient\bin\Debug\XBAPClient.xbap” -debugSecurityZoneUrl http://localhost:53265/Service1.svc


Thanks to Mark Smith I discovered a new an easier way of doing this. All you have to do is

1) Open XBAP project properties

2) Select Security tab

3) Advanced button

4) Check “Grant application access to site of origin” (should be checked already)

5) Type in the URL into the textbox where the web service is running


We have to do this so that we set up an envirorment for the XBAP just like it is running from the same URL of the service.


And there you have it. Now you should be armed and ready to start doing XBAPs that consume WCF service.

Download sample application

XBAPs Part 1: An introduction to this Gem


XBAP XBAPs (XAML Browser Application) are a really cool feature that was introduced in .NET 3.0 together with WPF. Well you can say that XBAPs are as such part of WPF because at the end of the day XBAPs are just WPF applications that can run inside the browser. One important thing to state here is that XBAPs and Silverlight have nothing to do with each other. XBAPs are full .NET enabled WPF applications, while Silverlight is a “cut down version of WPF” that runs as a browser plugin. In order to run a Silverlight enabled website you need to download the Silverlight installer(that is really really small approx 4.3 MB), if you want a client to run a XBAP the client has to have .NET installed on his machine (the Full .NET or Client Profile).

Before we continue I would like to point out that this post is just an introduction to XBAPs. I will have Part 2, Part 3 and Part x that should be much more interesting to follow…. Yet if you never heard of XBAPs you should continue reading this post (and try not to fall asleep :P).

What does your Client need?

As I said above, in order for a client to run your XBAP he/she needs to have .NET framework installed. It’s as if the client is going to run a Windows application. XBAPs got a set of improvements in .NET 3.5 such as support for Firefox (read more here) and also support for consuming WCF service in partial trust mode (with some limitations of course but still it’s good, read more here). So yea if you are planning on using XBAP’s I would seriously consider .NET 3.5.

To summarize your Client needs to have .NET installed and he can use the XBAP in Internet Explorer or if he prefers (and you are using .NET 3.5) Firefox.

Some things to keep in mind …

XBAPs run in the browser and give an impression of being a normal website (super cool website I must say :P) while instead they are just actual apps that never jump out of the browser, yet there is more to it… XBAP’s run in a “sandbox”, basically they run as Partial Trust by default. What this means is that some of the things that you would assume would work in a WPF app would not work in an XBAP, for example Reflection (and also the new 3.5 SP1 feature Effects :( ). Of course there are workarounds. You can run XBAPs as Full trust mode and we will discuss how to later on in this article.

Building a simple XBAP

So let’s start having a look at how one can build an XBAP. In order to create a new XBAP project you have to do the usual stuff, so go to File > New > Project and select WPF Browser Application


Now that we created the project, let’s have a look at what Visual Studio created for us


So as you can see by default Visual Studio created more or less the same stuff it would have created for a WPF Application yet instead of using a Window it created a Page. This is very important because a Page was designed for Navigation (the back and forward button of the browser). I will discuss Navigation more later on in this article. Besides this Visual Studio also created a pfx file. The pfx file is a way how to sign the exe, by default Visual Studio creates a pfx file that it uses to sign the Click once installer for the XBAP.


The image above shows how Visual Studio generated that pfx file. Please not that there is the Computer name and username inside the pfx files (which obviously is not something you want to give to your client). Charles Perzold discusses this in more detail here.

Ok so now that we know what Visual Studio created for us (thanks VS we love you) we can test our XBAP app (yea we can already run it :) ). In order to see something on screen lets just create a button in the Page1.xaml and press F5 to run.

   1: <Button Content="My First XBAP :) " Height="50" Width="150"/>


Yahhooo we have everything figured out don’t we :) well there are a couple of other things we need to have a look at.


If you are a WPF developer you will be developing XBAP in no time. There are a couple of things you must keep in mind, like Code Access Security and other tricks like how to consume WCF service…. In my next posts I will cover these things and make sure that I pass on my knowledge (knowledge that came from a lot of frustration and hours of head banging on the table)

Using the WPF Web browser control in a ToolTip

While writing a small app that I will be publishing here, I stumbled upon a strange issue. I was trying to put the WPF WebBrowser control inside a Tooltip yet the WebBrowser was not appearing on the screen. After an hour of debugging and trying out different things I found this WPF Forum thread that solved my issue… The problem has something to do with the WebBrowser being a native control and not a pure WPF control (so you are actually using an HwndHost in order to show it in a WPF app).  Also you might want to have a look at this blog post, it’s from the answerer of the forum post. Anyway, I just thought to share this with who ever is encountering this problem…..

Now I’m headed back coding my new project… should be cool, will post it shortly hopefully :)

.NET Client Profile + WPF = Superb Apps

For those of you that have been asking where is Marlon? “Why did he stop blogging for these past 3 weeks?”
Well I’ve been really really busy packaging 2 new hot products. I currently work at Uniblue Systems where we develop system utilities that help you keep you PC healthy and clean. I have been working at Uniblue for 2 years but never in these 2 years I was excited as I am today. We released our first 2 products using WPF, packaged with .NET Framework Client Profile.

.NET Framework Client Profile is really superb, it enables us at Uniblue to distribute our products to the end user in a fast and easy way. Before .NET Client Profile, it was very hard for companies such as Uniblue to ship software with .NET Framework because the download of the framework alone is massive. Our customers hate to wait ( don’t yours? ). With .NET Client Profile the download + installation is really fast and that’s why our customers love it!

Client Profile not only installs the basic .NET Framework components, but it installs .NET 3.5 SP1 (Client Only) which means you get all the WPF goodness + all new super stuff that .NET 3.5 SP1 provides. So yea we can also go crazy with user interfaces!  If you want to check out one of our new products (developed fully with WPF) check it out here …. please submit as many feedback as possible… I can’t wait to see what you think ….