Saturday, November 21, 2009

Programming in Scala – Part 2/?

In my previous post, we got started with simple Scala HelloWorld and moved on to write a bubble sort in Scala. This time let us look at some differences between a “var” and a “val” in scala. I hope you all know what “immutable” means – simply put Strings in Java/.NET are immutable. Anytime you modify a string, a new object of string is created – they cannot be changed in place. Well, in scala when you declare a variable with a “val” it would be immutable. Look at the following scala code.

object ValVar
{
def main(args: Array[String])
{
val immutableValue = 200
//immutableValue = 20 -> gives compiler error
var mutableValue = 200
mutableValue = 20
println("Immutable : "+immutableValue+"\n Mutable : "+mutableValue)
}
}


The decompiled program would look like shown in Java



import java.rmi.RemoteException;
import scala.Predef.;
import scala.ScalaObject;
import scala.ScalaObject.class;
import scala.StringBuilder;
import scala.runtime.BoxesRunTime;

public final class ValVar$
implements ScalaObject
{
public static final MODULE$;

static
{
new ();
}

public ValVar$()
{
MODULE$ = this;
}

public void main(String[] args) {
int immutableValue = 200;

int mutableValue = 200;
mutableValue = 20;
Predef..MODULE$.println(new StringBuilder().append("Immutable : ").
append(BoxesRunTime.boxToInteger(immutableValue)).
append("\n Mutable : ").
append(BoxesRunTime.boxToInteger(mutableValue)).toString());
}

public int $tag()
throws RemoteException
{
return ScalaObject.class.$tag(this);
}
}


Clearly, it does not look like "immutable" variables are declared final in the Java code. So it appears to me that Scala compiler does the job of making sure that the val'bles are immutable. For those curios to see what happens if you attempt to change a val'ble, see the screenshot below. Also it would be interesting to note that the scala compiler takes care of optimizing our string concatenation to make use of String builder, just like the javac!



image



So what did we learn?: If you wish to keep changing the values for a variable, then use "var" and if you want immutable variables, use "var".



Now that we know how to create both variables and val’bles, let us look at some fancy stuff that we could do with lists.



Whats your range?



Let us say, we need all odd numbers between 20 and 2000 which are divisible by both 5 and 7. If you were like me, we write the program to look like shown below.



object RangeAction1
{
def main(args: Array[String])
{
for(i <- 20 to 2000)
{
if( i % 5 == 0 && i % 7 == 0)
println(i)
}
}
}


Can we do any better? This looks too long now that I have been imagining things, increasing expectations about scala being so nice.



object RangeAction1
{
def main(args: Array[String])
{
(20 to 2000).filter(i=>i%5==0&&i%7==0).foreach(i=>println(i))
}
}


When we say “20 to 2000”, it returns a Range object. Look in the documentation to see what all magic could we do with range. Similarly if we were to work with lists, we could do something similar. Now to add 1 cent to the 3 cents we covered so far, what if i want the range to start with 20 and end with 2000 but increment by 10 and exclusive of 2000.




(20 until 2000 by 10).filter{i=> i % 5 == 0 & i % 7 == 0}.foreach{i=> println(i)}


Also, I wanted to be more like a regular programmer and put my closure inside {} instead of (). More fun later!

Friday, November 20, 2009

Scala for dummies like me!

Well! what should I be saying? I am that kind of person who keeps shifting from one interest to another. Once I am extremely interested in .NET (and I still am, but .NET is now an ocean – would take me too long to catch up with everything) and now I want to explore Scala – all new programming language on the JVM (new to me!) which has been receiving rave reviews. So, I went ahead and ordered Programming in Scala book on a1books.com (which by the way is a great site) but unfortunately I did not receive my copy yet. So here i am with all intention to do something with Scala but am out of resources (no offense but there are no simple tutorial on Scala which is interesting and which doesn’t make me fall asleep in 2 minutes).

Lets first get started and write a Hello World program.

class HelloWorld
{
def main(args: Array[String]){
println("Krishna Vangapandu - Hello Scala world!");
}
}




When you compile this and execute it, you would get a “java.lang.NoSuchMethodException: HelloWorld.main is not static”. Well, the mistake that I did was to put a “class” – but it should be object. So the hello world would be



object HelloWorld
{
def main(args: Array[String]){
println("Krishna Vangapandu - Hello Scala world!");
}
}


So what's the difference between "class" and an "object". Obviously there is no problem for the compiler, only the runtime blows! So what does the documentation say about this? Well even better lets use a decompiler to decompile the .class file we obtained and see how the scala code would when written in java. By the way, I am using this decompiler - which i should say is freaking awesome.


"class HelloWorld" decompiled.




import java.rmi.RemoteException;
import scala.Predef.;
import scala.ScalaObject;
import scala.ScalaObject.class;

public class HelloWorld
implements ScalaObject
{
public void main(String[] args)
{
Predef..MODULE$.println("Krishna Vangapandu - Hello Scala world!");
}

public int $tag()
throws RemoteException
{
return ScalaObject.class.$tag(this);
}
}


"object HelloWorld" decompiled.



import java.rmi.RemoteException;

public final class HelloWorld
{
public static final void main(String[] paramArrayOfString)
{
HelloWorld..MODULE$.main(paramArrayOfString);
}

public static final int $tag()
throws RemoteException
{
return HelloWorld..MODULE$.$tag();
}
}


But what the hell is a $tag() method? Well, I looked into the source code which had a comment on the $tag method which says



This method is needed for optimizing pattern matching expressions which match on constructors of case classes.  




Well, then what is the HelloWorld actually doing? Well, looks to me it was using the HelloWorld$ which was also generated by “scalac”. I cannot dig into what is  going on here, may be sometime in the future.



So far, what I understood is that “object” creates a final class whereas “class” creates a ScalaObject and methods inside would all be instance methods. So anything declared “object” can act only as a static-only container.



Lets do a simple bubble sort program in Scala. What should we be knowing to write a button sort?




  1. Assuming we pass the numbers to sort from command line, how do we convert strings to numbers ?


  2. How do we loop the array?



object BubbleSort
{
def main(ip_args: Array[String]) //we shall get the input numbers to sort into "args"
{
/*
we have a collection of strings, we should get a collection of numbers.
so we use the map which says for each i in the ip_args,
return the value after converting into expression. we get a 1 to 1 returned array.
*/
val args = ip_args.map { i => Integer.parseInt(i)}

/*
Looping : for index j which starts from 0 and ends at args.length-1 (inclusive)
*/
for(j <- 0 to args.length-1)
{
for(i <- 0 to args.length-2-j)
{
if(args(i) > args (i+1))
{
//we do an ascending order sort.
// Swap routine is shown belo.
val temp = args(i) //this is how we define variables in scala
args(i) = args(i+1)
args(i+1) = temp
}
}
}
//print all the numbers
for(i <- 0 to args.length-1)
println(args(i))
}
}


I do agree that even without the comments the code does not look as concise as it should be. But right now, we are just getting started – we would slowly look at how we can write concise code when we think functional programming (I am saying this with my past experience with Groovy and C# Closures – by functional, 90% of the time I mean closures – which I know is not accurate).I have also observed that when you compile the BubbleSort.scala, you end up getting more than one .class files - which I believe is for the anonymous method (closure) we used.



That's it! for this post. See you soon with functional programming using Scala!

Thursday, November 12, 2009

Working with JQuery and list boxes

Code (read comments):

<html> 
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript">
/*
when the document is ready (after all the HTML page is loaded, this shall be executed)
we attach the event handlers.
*/
$(document).ready(function(){ attachEventHandlers(); });
function attachEventHandlers(){
/*
In this method we attach the function(){} to the change event on all the <select> items.
The code inside the function(){} shall be executed when item selections are changed on the select box.
*/
$("select").change(function(){
//using "this" to access the current listbox. the jQuery wrapper would be $(this)
var selectedItems = $(":selected",this);
$("#itemsCount").text(selectedItems.length); //set the items selected count.
var toAppendHtml = ""; //lets store the html that we shall put inside the itemsSelected element.
//for each selected item we add a new line with selected item's text and value to the toAppendHtml.
selectedItems.each(function(){
toAppendHtml += $(this).text() +" : "+$(this).val()+"<br/>";
});
//finally put everything in there as html content to itemsSelected.
$("#itemsSelected").html(toAppendHtml);
});
/*
Alternatively you can use ExternalFunction. The external function should have one parameter "e" called the event object.
$("select").click(ExternalFunction);
*/
}
/*
function ExternalFunction(e)
{
//now within this function, the element which raised the event can be accessed using "this", or "e.currentTarget".
//So the statement "this == e.currentTarget" will always be true.
alert($(":selected",this).length);
}
*/
</script>
<style type="text/css">
select{
width: 100px;
height: 200px;
}
</style>
</head>
<body>
<select name="items" id="items" multiple="true">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
<option value="4">Item 4</option>
<option value="5">Item 5</option>
<option value="6">Item 6</option>
<option value="7">Item 7</option>
</select>
<p/>
<div>total items selected : <span id="itemsCount">0</span></div>
<span>Selected Items are </span>
<div id="itemsSelected"/>
</body>
</html>

Thursday, November 05, 2009

Problem running Scala

I was just trying to run scala on my machine and failed to do so with an error message “…..\java.exe unexpected at this time.” Look at the screenshot shown below.

image

Well, the problem was that environment variables for JAVA was set up using JAVA_HOME variable. The JAVA_HOME environment variable was pointing to the JDK directory and the Path was modified to include the “%JAVA_HOME%\bin” directory.

I removed the JAVA_HOME and then modified the path to specify the complete path to the JDK bin folder and it works now. :)

I might be talking more about Scala in the future, the concurrency scala supports appears to be interesting.

Monday, August 31, 2009

Visual Studio Test System : “Test Run Deployment Issue : The location of the file or directory … is not trusted”

image

I just came across this issue when trying to run tests from Visual Studio test system. To resolve this, simple go to the source of the DLL (in my case, I placed them under LIB directory inside my solution directory), right click on each of the libraries that were taken from external sources (like Log4Net, Moq, etc.) and view the Properties. In the properties window, you should be seeing “Unblock” option as shown below.

image

Simply click “Unblock” button and release the library’s security constraint. Now perform a clean on the solution and rebuild the solution. Your tests should run without any deployment issues.

good luck!

Monday, July 27, 2009

ConfigStation for WCF – prototype for minimal configuration based WCF services

To start off, I would like to stress that I am not a WCF expert and if you go around my blog, you can notice me writing about lot of different things – WPF, DLR, Web Development and what not. So what I present is just something that I made recently as a part of a bigger project that I plan to release. Apparently, this is pretty good start for what I envision for avoiding Configuration Hell in WCF services.

The StockTrader sample from Microsoft comes with a great library – Configuration Service 2.04. The library is pretty good and provides wonderful functionality but the major problem with that, for me, is its strong dependency on the SQL Server backend. In short, the configuration service maintains a service configuration repository which is used to provide centralized configuration repository, load balancing, fail-over in WCF based SOA applications. And I always wanted such a repository which would minimize my effort in developing distributed applications using WCF.

I believe, WCF should allow very simple way to develop services and should provide an easier means to configure them. One way away from configuration through App.Config is to code the configuration, but there seems to be a big lack of proper documentation and decent-real-world samples explaining code-based WCF configuration. Anyway, I would envision hosting a service to be as simple as :

var serviceHost = new AutoConfiguredServiceHost<ServiceImpl>();

With no or minimal configuration, the service host should be clever enough to determine what the configuration defaults are. Similarly, consuming the service should be as simple as :

var client = new RemoteServiceProxy<IService>();

The proxy should be created by accessing the repository to figure out implementation for IService and then use the configuration obtained to create the proxy.

With these goals in mind, the config station has been developed and here is what I have so far.

Sample : Test Service which hosts the ConfigRepository as well as a sample WCF Service implementation. The host method is shown below.

 class Program
{
static void Main(string[] args)
{
using (var configHost = new ConfigStationHost())
{
var hostFacade = new ServiceHostFacade<TestImpl>();
var host = hostFacade.Host;
host.Open();
Console.WriteLine("Test service launched.Enter to Stop");
Console.ReadLine();
//host.Close();
host.Abort();
}
}
}


If you look at the using block, I am creating an instance of ConfigStationHost – which actually hosts the ConfigStation – a repository WCF service. At the moment, this service requires App.Config based configuration of the service – which can be easily removed and which would be my next enhancement to the project. In this example, I am actually hosting the ConfigStation within the same process as my actual WCF service, which is not required at all. You can host the ConfigStation in a totally separate program – all you have to do is create the instance of ConfigStationHost (see required configuration below) and dispose it when you are done.



The configuration for the Test Service is shown below.



 
<configuration>

<appsettings>
<add value="net.tcp" key="ServiceScheme" /> <!-- you can set this to http as well or even msmq ...-->
<add value="9989" key="ServicePort" />
</appsettings>

<system.servicemodel>
<services>
<service name="ConfigStation.Repository">
<endpoint contract="ConfigStation.ServiceContracts.IRepository" binding="wsHttpBinding" address="http://localhost:8731/ConfigStation/Repository" />
</service>
</services>

<!-- This demo acts as a client to ConfigStation, so it is all good-->
<client>
<endpoint name="ConfigStation" contract="ConfigStation.ServiceContracts.IRepository" binding="wsHttpBinding" address="http://localhost:8731/ConfigStation/Repository">
</endpoint>
</client>

</system.servicemodel>
</configuration>


In the shown configuration, the <service> element configuration is used to host the ConfigStation repository in the current process. The <client> configuration is  the WCF client configuration which is used to access the ConfigStation service hosted. The TestService makes interacts with the ConfigStation using WCF and the ConfigStation is treated as a WCF service hosted somewhere remote. So, if we were to host the configstation separately the only configuration required would be that of the <service> defined. The TestService would then have the AppSettings and the <client> configuration – which is pretty easy to set and even easier for me to remove.



Now, the ServiceScheme dictates what communication protocol (BINDING, in terms of WCF) would be used when exposing the service and what binding would be used by the clients consuming this service. The ServicePort tells what port the service should be hosted on. Note that WCF allows hosting multiple services on the same port as long as their address is different (Except for MSMQ, i think).



The test client to consume the TestService is a different program, whose configuration is shown below. The program contains a WCF client to the TestImpl service whose details are obtained from the ConfigStation. Thus, the client process requires configuration which points to the ConfigStation.



<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<client>
<endpoint address="http://localhost:8731/ConfigStation/Repository" name="ConfigStation"
binding="wsHttpBinding"
contract="ConfigStation.ServiceContracts.IRepository">
</endpoint>
</client>
</system.serviceModel>
</configuration>


As you can see, the above is the only configuration required – which would be eliminated once I enhance the ConfigStation. The actual code to access the client is shown below.



namespace Test.Client
{
class Program
{
static void Main(string[] args)
{
var cf = new ClientProxyFacade<ITest>();
ITest test = cf.Interface;
var td = test.SayHello();
Console.WriteLine("Remote Server returned : " + td.Message);
}
}
}


You just create the ClientProxyFacade Of ITest, the service contract used by TestImpl. Then the interface is obtained via the “Interface” property. Then you can execute any method exposed by the Service Contract.



The library is available on codeplex – making this my first public release of open source software, of any kind. In the process, I would like to stress that the library uses the amazing ServiceModelEx library from Juval Lowy, IDesign. I actually tried to contact Juval whether or not to use his library but guess he is too busy so I took the liberty to publish the project having seen a WCF project on google code doing the same. In case I breach any license, please go easy on me and let me know so that I can fix my mistake.



I appreciate any positive feedback and any expert advice on the library. I am glad to learn and fix any changes requested. :) Hope this helps a few of us devs who like to play with some convention based WCF programming. I would be talking more details on the actual implementation, on how the library performs auto-generation of the service configuration and how bad the current repository implementation is, in my next post.

Wednesday, July 22, 2009

Powershell Script to delete bin/obj folders

Shown below is a simple powershell script that can be used to clean up a solution folder. The script excludes the "Libraries" directory and deletes any folder named bin or obj in the specified location.


Get-childitem c:\Temp\MyProjectSolutionFolder -recurse -include *.exe,*.dll,*.pdb,*.exe.config, bin,obj | where {$_ -notmatch 'Libraries'} | Remove-Item -Recurse


This script saves my time a lot and also does not require me to install any tools that does the same but adds registry entries for explorer context menu.

NOTE: Please verify thoroughly before blindly running the script. Use the -WhatIf flag to simulate the execution of the command instead of actually running it.

Saturday, June 20, 2009

Bing : Not a search engine, but decision engine??

I am an active contributor to the MSDN WPF Forums and most of the times I go to the forums through the search engine. And being an ardent supporter of Microsoft, I made Bing my default search engine on my home desktop. So I searched for “MSDN Social” and look what one of the sponsored result is!

image

seriously we are in the 21st century. And BING “decided” for me that I want to visit BAD GIRLS IN MY AREA! when all I wanted to do was to visit MSDN Social Forums. Bing – get a life.

Friday, June 05, 2009

GridViewColumn CellTemplate does not work?

Well, today I came across this interesting question on WPF regarding setting the DataTemplate of a GridViewColumn not working properly. Everything looks fine in the code (assuming his DataTemplate generating method was fine) which got me interested to figure out what the issue is.

And then I made up this sample application whose XAML is shown below.

<Window x:Class="Window1" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300" Loaded="Window_Loaded">
<StackPanel>
<ListView Name="lv" ItemsSource="{Binding Items}">
<ListView.View>
<GridView></GridView>
</ListView.View>
</ListView>
</StackPanel>
</Window>


The code-behind is simple. It sets the DataContext to itself and then fetches sample data using GetData() call. Then the GridView for the ListView is obtained and a new gridviewcolumn is added programatically. The CellTemplate is set on the GridViewColumn using SampleTemplate() method. The SampleTemplate() method constructs a DataTemplate programatically using the FrameworkElementFactory class and returns the same.





 
Private Sub Window_Loaded(ByVal sender As System.Object, _
ByVal e As System.Windows.RoutedEventArgs)
Me.DataContext = Me 'set the datacontext
Items = GetData()
Dim gv As GridView = CType(lv.View, GridView)
Dim gvc As New GridViewColumn
gvc.Header = "Test"
'Display member binding
gvc.DisplayMemberBinding = New Binding(".")
gvc.CellTemplate = SampleTemplate()
gv.Columns.Add(gvc)
End Sub

Private Function SampleTemplate() As DataTemplate
Dim dt As New DataTemplate
dt.DataType = GetType(String)
Dim fef As New FrameworkElementFactory(GetType(TextBox))
Dim bd As New Binding(".")
fef.SetBinding(TextBox.TextProperty, bd)
dt.VisualTree = fef
Return dt
End Function

Public Property Items() As IEnumerable(Of String)
Get
Return GetValue(ItemsProperty)
End Get

Set(ByVal value As IEnumerable(Of String))
SetValue(ItemsProperty, value)
End Set
End Property

Public Shared ReadOnly ItemsProperty As DependencyProperty = _
DependencyProperty.Register("Items", _
GetType(IEnumerable(Of String)), GetType(Window1), _
New FrameworkPropertyMetadata(Nothing))

Function GetData() As IEnumerable(Of String)
Dim x As New ObservableCollection(Of String)
x.Add("Item 1")
x.Add("Item 2")
x.Add("Item 3")
Return x
End Function




And when I run the application all I see is …



image



Ok the binding works and I see my data but somehow the celltemplate is not being reflected. So, I was able to reproduce the issue the question presented.



So I dig around and looked in the documentation for CellTemplate where I found the following.



image



So it basically means that if DisplayMemberBinding is used, then CellTemplate would be ignored and so on with the CellTemplateSelector. So I comment the line that sets DisplayMemberBinding and run again.



image







Yes! its working as expected.



So whats the moral of the story? Actually there are three morals:



1. First of all, when using CellTemplate, do not set DisplayMemberBinding.

2. Refer to the documentation, especially the remarks and code samples section for a method or property. MSDN folks did an amazing job (ofcourse the WPF guys as well).


3. MSDN WPF Forums is amazing and overall Microsoft.NET folks rocks big time.

Thursday, June 04, 2009

What’s wrong with this code?

image

The breakpoint at line 18 never hits.

This is a really silly bug :D.

Leave comments if you know what is wrong.

.NET Funda : MemoryStream ToArray() vs. GetBuffer()

Look at the following program.

 class Program
{
static void Main(string[] args)
{
MemoryStream ms = new MemoryStream();
//write 10 bytes to the memory stream.
for (byte i = 65; i < 75; i++)
ms.WriteByte(i);

System.Console.WriteLine("MemoryStream.GetBuffer() : {0}",
ms.GetBuffer().Length);
System.Console.WriteLine("MemoryStream.ToArray() : {0}",
ms.ToArray().Length);

System.Console.WriteLine("GetBuffer() BytesToString : {0}",
FromBytesToString(ms.GetBuffer()));
System.Console.WriteLine("ToArray() BytesToString : {0}",
FromBytesToString(ms.ToArray()));

ms.Close();
System.Console.WriteLine("GetBuffer() BytesToString : {0}",
FromBytesToString(ms.GetBuffer()));
System.Console.WriteLine("ToArray() BytesToString {0}",
FromBytesToString(ms.ToArray()));
}

public static string FromBytesToString(byte[] b)
{
return ASCIIEncoding.Default.GetString(b);
}
}


In the above code, we use a MemoryStream and write 10 bytes (from A(65) to J(74)).  Running the program gives the following result.



image



The first two print statements displays the length of the byte[] array returned by both GetBuffer() and ToArray(). Now, both these methods returns the byte[] written to the memory stream but the difference is that GetBuffer() returns the allocated byte buffer used by the memory stream and this also includes the unused bytes where as ToArray() returns only the used bytes from the buffer.



Since a memory stream is initialized with a byte array of size 256, even though only 10 bytes have been written to the stream, the buffer returned is of size 256 (of which only 10 bytes are used). Printing the Bytes to string, thus displays a long series of empty lines where as ToArray() returns only 10 bytes that were used and displays the string exactly of size 10.



Note that both these methods work even when the stream is closed (demonstrated by the last two print lines in the code above).



The usage becomes important especially when you are trying to perform in-memory deserialization of some object from the memory stream for reasons like the binary data would be totally different from what was written actually, when using  GetBuffer().

Tuesday, June 02, 2009

WPF Databinding : Using CompositeCollection

The goal is to have a ComboBox whose ItemsSource should bind to more than one collection. In order to this, we make use of CompositeCollection as shown below.

XAML

<StackPanel>
<ComboBox Name="cb" ItemsSource="{Binding MoreThanOneCollection}">
</ComboBox>
</StackPanel>



Code-behind




Private _moreThanOneCollection As New CompositeCollection

Public Property MoreThanOneCollection() As CompositeCollection
Get
Return _moreThanOneCollection
End Get
Set(ByVal value As CompositeCollection)
_moreThanOneCollection = value
End Set
End Property

Private Sub Window_Loaded(ByVal sender As System.Object, _
ByVal e As System.Windows.RoutedEventArgs)
Me.DataContext = Me 'set the datacontext
BindData()
BindMoreData()
End Sub


Sub BindMoreData()
Dim data2 As New CollectionContainer
data2.Collection = GetData().Reverse()
'another set of data, just for the heck of it
MoreThanOneCollection.Insert(0, data2)
End Sub


Sub BindData()
Dim container = New CollectionContainer
container.Collection = GetData() ' the first data
MoreThanOneCollection.Add(container)
End Sub

Function GetData() As IEnumerable(Of String)
Dim x As New ObservableCollection(Of String)
x.Add("Item 1")
x.Add("Item 2")
x.Add("Item 3")
Return x
End Function


Just for practise purpose, I thought I would create the composite collection in code. This can also be done in XAML.

Loading BitmapImage from disk

While loading image in XAML is pretty easy (use <Image Source="xx.jpg"/>), it is not so straight forward to load an ImageSource from a file. (I always forget how to do this). So here is the code which might help you all. I have also specified some commented code which can be used to get thumbnails out of the image and other options like caching, etc.

ImageSource LoadImage(string filePath)
{
BitmapImage img = new BitmapImage();
try
{

img.BeginInit();
img.UriSource = new Uri(filePath, UriKind.RelativeOrAbsolute);
img.CacheOption = BitmapCacheOption.OnLoad;
//img.CreateOptions = BitmapCreateOptions.DelayCreation;
img.DecodePixelWidth = 50;
//img.DecodePixelHeight = 200;
img.EndInit();
}

catch
{
}
return img;

}

By the way, I have at last set up SyntaxHighlighter for my blog! this is sweet. Thanks to this post for the instructions.

Monday, June 01, 2009

Real world – really simple Composite WPF application for Twitter

Well, the name says it all. In this post, I would like to talk about how to implement a very basic (emphasis on very) twitter application as a Composite WPF application. I would like to demonstrate as many concepts in PRISM (Composite WPF) as possible and the following is the list that I am looking at.

1. Getting hold of CAL libraries.
2. Setting up the WPF shell – working with Bootstrapper.
3. Working with Regions – simple and nested regions.
4. Implementing modules and integrating them on to the defined.
5. Using Commanding framework in the application.
6. Communication between the modules – the PRISM way.
7. Last but not the least, we will be using the excellent Tweet#. Get the library from here.

Side-concepts about WPF includes MVVM (as I understand, I am not a guru), defining templates for ListView, etc.

For those expecting wonders, this app does not do anything but implement what http://search.twitter.com does. Give in a search term and it returns you the results. Screenshot shown below. If you like it, then you can proceed and read this long story, otherwise thanks for visiting.

image

Getting the Composite Application Library for WPF & Silverlight

I would not be stressing much on this, just a walkthrough. The composite application library does not ship binaries and ships source instead.

1. Download the latest CA L from codeplex. The actual download site is on the Microsoft Servers – direct download link. Extract/Install the CAL.

2. I placed the extracted files in Development\prism folder. Inside this folder, you see a CAL folder which contains the VS solution files.

image

3. Open the CompositeApplicationLibrary_Desktop.sln in Visual Studio 2008 and build the solution. (I built mine with Debug configuration).

4. Now go into Desktop folder and you see a whole bunch of Composite.* folders. Now the libraries that we would use are the output of the projects that you see in here. To save time, instead of going into individual folders, you can directly go into Composite.UnityExtensions folder/bin/<Debug or Release>. You should see the following libraries (assuming your build was successful).

image

Copy both the DLL and PDB files into a separate folder of your choice. I typically copy mine into a “libraries” folder inside the project that I am working on. It is from here that I add references. I also copied the Tweet# libraries (Dimebrain.TweetSharp.dll and NewtonSoft.Json.dll) into the same folder.

image

Now lets get on with the development.

STEP 1 : The WPF Shell.

1. Create a new WPF application project and name it as you want, I named mine as tru-twitter.

Add references to the Composite libraries that we saved previously. Some prefer not to build the libraries separately. Instead they add the CAL solution using the project linker shipped along with CAL distribution. But I like to keep my projects simple.

2. Now, all composite applications are hosted inside a shell. This shell would be implemented by using the simple steps described next. The shell is created via a bootstrapper which shows the shell (no magic, a shell is just a window which acts as the container for our application) and does other ground-work some of which include setting up the Inversion Of Control Container (Unity is the default with composite app library and this can be replaced, which is a different topic altogether), configures modules, etc.

3. So we need a bootstrapper. For this, add a new file to your project and name it as Bootstrapper.cs. Make your Bootstrapper class public sealed (which I like to do since sealed classes, i think, are more optimization-friendly and design friendly as well). The bootstrapper class should extend the UnityBootstrapper class. You can right click on the UnityBootstrapper and resolve the usages. Then you have to override “CreateShell()” method to say the least. Look at the code below which is pretty much self-explanatory.

public class Bootstrapper : UnityBootstrapper



    {     



        public readonly string ModulePath = Settings.



                                            Default.



                                            Properties["Modules"].



                                            DefaultValue.ToString();



 



        /// <summary>



        /// The CreateShell method instantiates the shell window.



        /// It is also responsible to show the window.



        /// </summary>



        /// <returns>The shell that was shown.</returns>



        protected override System.Windows.DependencyObject CreateShell()



        {



            //get the shell using IOC.



            var shell = Container.Resolve<Shell>();



            shell.Show();



            //RegisterGlobalServices();



            return shell;



        }



 



        /// <summary>



        /// Configure what kind of Module Catalog you would be using.



        /// This application uses the DirectoryModuleCatalog.



        /// All modules placed within ModulePath are loaded.



        /// </summary>



        /// <returns></returns>



        protected override IModuleCatalog GetModuleCatalog()



        {



            return new DirectoryModuleCatalog()



            {



                ModulePath = ModulePath



            };



        }



    }




The Window1.xaml has been renamed to Shell.xaml. Note that using Refactor option within Visual Studio to rename the class would be the best way to go since it can track all the places where Window1 was used.



4. Now open the App.xaml in XAML View and remove the “StartupUri” attribute. You have seen that the boot strapper takes care of showing the window. Now inside App.xaml.cs, modify the OnStartup() as shown below.





public partial class App : Application



    {



        protected override void OnStartup(StartupEventArgs e)



        {



            // let the base class do whatever it does.



            base.OnStartup(e);



 



            //create the bootstrapper



            var bs = new Bootstrapper();



            //call the Run() method on the bootstrapper.



            bs.Run();



        }



    }




The bootstrapper is triggered by the Run() method which is called from the OnStartup. The bootstrapper then does a lot of things (i dont know the list exactly but it configures your container, your module catalog loader and then invokes CreateShell method in which you show the window). Thus, on startup, the shell is created and is shown. Run the application to see it works without any issues. If you are unable to see the window, then there might be two issues – not calling the method Run() on the Bootstrapper or failing to invoke Show() method in the CreateShell().



5. Now we have the shell up and running. What ever the shell hosts (user controls), they are to be implemented as a modules. Before that lets tell the shell where to put the modules.



6. To do that shell should have Regions defined. Any container that contains a region is managed by the global “RegionManager” which takes helps in adding/removing views. For our application, we have one region within the shell. To define a region, open Shell.xaml in XAML view. Since there would be only one view, we define a ContentControl and give it a region name as shown below.





<Window x:Class="tru.twitter.Shell"



        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"



        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"



        xmlns:cal="clr-namespace:Microsoft.Practices.Composite.Presentation.Regions;assembly=Microsoft.Practices.Composite.Presentation"



        xmlns:helpers="clr-namespace:tru.twitter.common.Helpers;assembly=tru.twitter.common"



        Title="tru-Twitter!"



        WindowState="Maximized"



        >



    <ContentControl cal:RegionManager.RegionName="{x:Static helpers:RegionNames.SearchRegion}"/>



</Window>




Now you can notice two additional xml namespaces being added to the Window element. The “cal” namespaces allows us to access members of the “Microsoft.Practices.Composite.Presentation.Regions” namespace where as the “helpers” namespace refers to a custom library (just a class library) which contains my RegionNames. I prefer to have all my region names stored in a separate class and exposed as static members such that changes to the names would be rather easy and prevents us from hard-coding at several places.



The above XAML shows setting the RegionName (an attached property) and also shows how to access static members of the region names class.








7. Now that the region name is ready, let us add a new module to our project. Add a new Class library project to your existing solution.



I named it as “tru.twitter.search” which is not a good choice. I often name my module projects with “modules” in the name such that it tells me that this project is a module and not to be referenced directly in any other project. The modules are great since they are completely decoupled and I could replace the modules completely as I wish. The project structure should now include the shell project, search module project and the library project(tru.twitter.common, which contains code that is shared across all the projects, like the region names wrapper, services that I use, etc).



8. Modify the project properties of the module (right click => properties) to set the build output directory to where the ModulePath property points to in the Bootstrapper.cs file. Mine points to the “Modules” folder within the shell output directory.



image



For any module that you add, you should be doing this. Also note that the setting depends on the current build configuration. If you change the configuration from debug to release, you have to reset the path again.



9. Each module should have a module initializer class which implements the “IModule” interface. So, first of to resolve IModule interface, add all the composite library dll that were in the libraries folder. Then select these dll in the references and go to the properties. Set “Copy To Output” as false. These libraries are already being used by the shell and they would be reused by the modules are runtime.



10. The module initializer class – SearchModule should implement IModule interface and should define the “Initialize()” method. Since this module has UI elements which should be loaded into the regions, the module should have access to the Region Manager. The module also can use the IOC container to resolve objects which keeps the design much simpler, so it should also have access to the IOC container. Thus the module constructor would have the region manager and container as parameters. The module loader resolves this module during which the registered container and region manager are automatically passed to the constructor.



image



You can notice that my Initialize method registers services and views. So add the stubs for these two methods. Also make sure you add private fields for IRegionManager and IUnityContainer.



11. Let us test the set up so far. Build the solution and verify if the module is copied where it was supposed to be (remember we set the project output path earlier). Now, place a breakpoint at first line of constructor and inside the Initialize() method and run the application.



When the constructor breakpoint is hit, you should see both “rm” and “ctr” to not be null and instead they would be instances of IRegionManager and IUnityContainer. These instances are singleton and the same are used across the application.



After the constructor is hit, the Initialize() method should also be hit.



12. Now in the RegisterViews() method, we create the view we want to and add it to the region manager. Let us say that we have one single view called “SearchView” which should be loaded into the SearchRegion that was defined in the Shell.xaml. The RegisterViews() method should then be implemented as shown below.





private void RegisterViews()



        {



            LoadSearchRegion();



        }



 



        private void LoadSearchRegion()



        {



            var searchView = _container.Resolve<SearchView>();



            var searchRegion = _regionManager.Regions[RegionNames.SearchRegion];



            searchRegion.Add(searchView);



            searchRegion.Activate(searchView);



            //The search view region consists of SearchInput view and a results view.



            //By default only search input region is loaded.



            //Search Results would be loaded on demand - when search button is pressed.



            LoadSearchInputRegion();



        }




We shall get back to the LoadSearchInputRegion() shortly.



To avoid confusion, look at the screenshot below. The whole UI you see is the SearchView loaded into the Window (shell). The SearchView has two regions – Search Input Region (contains the SearchInputView) and the search results region.



When the application starts, only the search input view would be shown. Thus you can only see the LoadSearchInputRegion() method being called inside the LoadSearchRegion().



When the user presses the search button, the results are retrieved and the results view would be added.



image



The search input region is marked in yellow and the search results view is marked in blue.



13. Now let us implement the SearchView (the one which contains both the search input view at the top and search results at the bottom). Add a new WPF user control and name it as SearchView.xaml. Modify the XAML as shown below.





<UserControl x:Class="tru.twitter.search.Views.SearchView"



             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"



             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"



             xmlns:cal="clr-namespace:Microsoft.Practices.Composite.Presentation.Regions;assembly=Microsoft.Practices.Composite.Presentation"



             xmlns:helpers="clr-namespace:tru.twitter.common.Helpers;assembly=tru.twitter.common"



             >



    <Grid>



        <Grid.RowDefinitions>



            <RowDefinition Height="Auto" />



            <RowDefinition/>



        </Grid.RowDefinitions>



        <ContentControl cal:RegionManager.RegionName="{x:Static helpers:RegionNames.SearchInputRegion}"



                        Grid.Row="0"



                        />



        <TabControl cal:RegionManager.RegionName="{x:Static helpers:RegionNames.SearchResultsRegion}"



                    Grid.Row="1">



        </TabControl>



    </Grid>



</UserControl>




It has two rows in the grid – one for input region and one for results region. We just defined the regions and the views are loaded into these regions when the Add(view) is invoked on the region manager and then the views appear when Activate(view) is invoked. While the input region is simple, just like the one that we defined in the shell. Note that even though the regions in search view appear as if there are regions inside the region (SearchRegion in the shell), we would still be using the same region manager but nothing any fancy. The region manager is global and it figures out the regions, however nested they are.



We have already looked at ContentControl region. Now if you notice the search results region is defined as a TabControl. This is another control whose RegionAdapter is already implemented in the CAL. Another control with ready to use region adapter is the ItemsControl. (which we would not be looking at today).





<TabControl cal:RegionManager.RegionName="{x:Static helpers:RegionNames.SearchResultsRegion}"



                    Grid.Row="1">



</TabControl>




You have already observed that the same RegionNames class is being used even in this project – therefore you should not forget to add reference to the tru.twitter.common library and set the reference property “Copy to output” to false.



14. We now have two more regions for which views has to be implemented. So first let us implement the SearchInputView which sits in the SearchInputRegion.



15. Add a new user control called SearchInputView.xaml. Also add a new C# class called SearchInputViewModel. Those familiar with MVVM can see that I am trying to burn my hands with MVVM. One advice up here is to place all views inside a “Views” folder and View models inside “ViewModels” folder within the project.



image



Let us first look at LoadSearchInputRegion() implementation inside the SearchModule.cs





private void LoadSearchInputRegion()



       {



           var searchInputView = _container.Resolve<SearchInputViewModel>().View;



           var searchInputRegion = _regionManager.Regions[RegionNames.SearchInputRegion];



           searchInputRegion.Add(searchInputView);



           searchInputRegion.Activate(searchInputView);



       }




Notice that it is the ViewModel that is being resolved first and the view is obtained via the “View” property. The region is obtained using the regionManager instance that was obtained via the constructor and passing the region name to the “Regions” property.



So first of all, the ViewModel should have a “View” property. The ViewModel also should provide the properties which the View binds to. And for the data binding to auto-manage changes between the View and the ViewModel properties, the ViewModel should implement INotifyProperty changed interface. Thus far, we can deduce that any viewmodel should implement a view property as well as the INotifyPropertyChanged interface. So we place this common functionality inside a separate class called “ViewModelBase” (place it in the commons library project).





public abstract class ViewModelBase<T> : INotifyPropertyChanged where T : UserControl



    {



        //View is of type T, which essentially is a UserControl.



        public T View { get; set; }



 



        public ViewModelBase(T view)



        {



            this.View = view;



            View.DataContext = this;



        }



 



        protected void RaisePropertyChanged(string propThatChanged)



        {



            if (PropertyChanged != null)



                PropertyChanged(this, new PropertyChangedEventArgs(propThatChanged));



        }



 



        public event PropertyChangedEventHandler PropertyChanged;



    }




The abstract class defines a parameterized constructor which takes in the instance of the View. This instance would be automatically created by the Container#Resolve<>() method. But this also tells us that the ViewModel implementation should invoke this constructor. Let us look at the SearchInputViewModel class.





public class SearchInputViewModel : ViewModelBase<SearchInputView>



    {



 



        public SearchInputViewModel(SearchInputView view)



            : base(view)



        {



            InitializeCommands();



        }



 



        private string _search;



        public string Search



        {



            get { return _search; }



            set



            {



                _search = value;



                RaisePropertyChanged("Search");



            }



        }



}




The “Search” property should be bound to the textbox which accepts the user input. The XAML for SearchInputView is shown below.





<Grid>



       <Grid.ColumnDefinitions>



           <ColumnDefinition Width="*" />



           <ColumnDefinition Width="70" />



       </Grid.ColumnDefinitions>



       <TextBox Background="#AABBCCDD"



                Foreground="Black"



                FontFamily="Verdana"



                FontSize="24"



                Text="{Binding Search}"



                Width="Auto"



                VerticalContentAlignment="Center"



                VerticalAlignment="Center"



                HorizontalAlignment="Stretch"



                />



       <Button Grid.Column="1" TextBlock.FontFamily="Impact"



               TextBlock.FontSize="15"



               Foreground="Black"



               Background="AntiqueWhite"



               Margin="5" Padding="5"



               Content="Search"



               HorizontalAlignment="Stretch"



               VerticalAlignment="Stretch"



               >



       </Button>



   </Grid>


















Again the XAML is simple and straight forward.



16. Using Commanding in Composite WPF apps.



The rule for proper implementation of the MVVM pattern is to keep the code-behind for the view with no code at all. The interaction between the ViewModel and the View would be via data binding (which we used in the Textbox which binds to Search property in the ViewModel) and the user events like button click should be implemented via "Commanding”.



To implement command, modify the button XAML in the search input view as shown.



image



The DataContext for this view was already set in the ViewModelBase class. So the “SearchCommand” would be looked in the current ViewModel which is SearchInputViewModel.



To implement commanding, add a new property of type DelegateCommand<object>. Then the command is instantiated in the constructor. The modified ViewModel is shown below.



image



The DelegateCommand<object> constructor takes in two delegates one which is used to determine if the command can be executed and one which is invoked when the command is executed. The above code shows that the command is only executed when the “Search” property has some input entered. (see second parameter). When the command is executed, the “search service” is used executed. Notice ethat the constructor is modified to include a reference to the search service that would be used. We will get there in a while.



Note that the instance of the search service is also resolved using the IOC container, which by itself is sweet! But the container has to know which implementation should be used for the ISearchService, so we register the service.



17. The Twitter Search Service – Publishing events in Composite WPF world.



The twitter service is something that we would be using throughout the application and therefore it is like a global service. So we place the implementation in the common library where as register the service in the Bootstrapper as shown.





private void RegisterGlobalServices()



        {



            Container.RegisterType<ISearchService,TwitterSearchService>(



                                   new ContainerControlledLifetimeManager()



                                   );



        }






The RegisterGlobalServices() method is invoked in the CreateShell() method ( which was previously uncommented).



Following shows the ISearchService implementation.





public class TwitterSearchService : tru.twitter.common.Services.ISearchService



    {



        private EventAggregator _eventAgg;



 



        public TwitterSearchService(EventAggregator eventAggregator)



        {



            this._eventAgg = eventAggregator;



        }



 



        public void ExecuteSearch(string searchKey)



        {



            //get twitter results



            var req = FluentTwitter.CreateRequest()



                         .Search()



                         .Query()



                         .Containing(searchKey)



                         .AsJson();



            req.CallbackTo((s, e) =>



            {



                var result = e.Response.AsSearchResult();



                _eventAgg.GetEvent<SearchCompletedEvent>().Publish(result);



            }).RequestAsync();



        }



    }




In the ExecuteSearch() method you can notice that once the result from Twitter is obtained, the result is published as an event using the EventAggregator provided by the composite application library. Note that this is not the best implementation. Because the service is now dependent on the CAL which makes it less decoupled. This is one area where the code has to be refactored (we will look into that in the future articles).



The EventAggregator can publish an event. When an event is published, those who have “subscribed” to the event would be notified. Let us first look at the SearchCompletedEvent which is a C# class that just derives from CompositePresentationEvent<>. Since the result is an instance of “TwitterSearchResult”, it is passed to the generic type. The implementation is shown below.





public class SearchCompletedEvent : CompositePresentationEvent<TwitterSearchResult>



    {



    }






Now we have a service that when executed and completed the search raises the SearchCompletedEvent. So we should have a subscriber which can be notified when the event is published. The subscriber would then create the SearchResultsView and add the view to the search results region.



18. Subscribing the events in composite WPF.



Now we shall look at how subscriber should be implemented and also look at how views are loaded into regions on demand.



image



Go to SearchModule.cs and modify the RegisterServices() method as shown above. In this method we obtain the instance of the event aggregator with the help IOC container. Then we obtain the event using GetEvent<event type> method on the event aggregator. Then using the Subscribe() method we subscribe to the event. When the search completed event is published, the Action (as a lambda) passed to the subscribe method is invoked. We also specify that the event subscription action would be invoked at the UIThread. Look into the documentation for more information on this. In this method we simply load the search results tab view.



Note that the SearchResultsTabView is just a user control like any other one. But because the SearchResults region was a tab control, the TabControlRegionAdapater comes into play and automatically adds a TabViewItem to the TabControl and sets the content to the SearchResultsView. The TabControlRegionAdapter is already implemented in the CAL and we need not worry about it. The LoadSearchResultsTabView(result) is shown below.





private void LoadSearchResultsTabView(TwitterSearchResult res)



{



            //get the view model



            var searchResultsVM = _container.Resolve<SearchResultsViewModel>();



            //set the result to the "Model" property of the view model.



            searchResultsVM.Model = res;



            //get the View using the View property.



            var searchResultsView = searchResultsVM.View;



            //get the region, add and activate.



            var searchResultsRegion = _regionManager.Regions[RegionNames.SearchResultsRegion];



            searchResultsRegion.Add(searchResultsView);



            searchResultsRegion.Activate(searchResultsView);



}






Please read the comments for the code to make more sense.



19. Implementing the SearchResultsView/ViewModel.



Add a new C# class called “SearchResultsViewModel”. This class should derive from ViewModelBase which takes in SearchResultsView as the generic parameter. The ViewModel should pass in the View to the base constructor and then also define properties like “Model” and “SearchedFor”. The whole implementation is shown below.





class SearchResultsViewModel : ViewModelBase<SearchResultsView>



    {



        public SearchResultsViewModel(SearchResultsView view)



            : base(view)



        {



        }



        private TwitterSearchResult _model;



 



        public TwitterSearchResult Model



        {



            get { return _model; }



            set



            {



                _model = value;



                base.RaisePropertyChanged("Model");



            }



        }



 



 



        private string _searchedFor;



        public string SearchedFor



        {



            get



            {



                if (_searchedFor == null)



                    _searchedFor = Model.Query;



                return _searchedFor;



            }



            set



            {



                _searchedFor = value;



                RaisePropertyChanged("SearchedFor");



            }



        }



 



    }






Add the SearchResultsView as new WPF UserControl. The XAML is simple – display the list of “Statuses”, a property that is exposed in the “TwitterSearchResult” class.





<ListView DataContext="{Binding Model}"



              ItemsSource="{Binding Path=Statuses}" 



              HorizontalContentAlignment="Stretch"



              ScrollViewer.CanContentScroll="True"



              ScrollViewer.VerticalScrollBarVisibility="Visible"



              >



        <ListView.ItemTemplate>



            <DataTemplate>



                <Border CornerRadius="5" 



                        Background="AntiqueWhite" 



                        HorizontalAlignment="Stretch"



                        Margin="5"



                        Padding="5"



                        >



                    <Border.Effect>



                        <DropShadowEffect BlurRadius="3"/>



                    </Border.Effect>



                    <StackPanel>



                        <Label Content="{Binding Id}"/>



                        <Label Content="{Binding Text}"/>



                    </StackPanel>



                </Border>



            </DataTemplate>



        </ListView.ItemTemplate>



</ListView>




Observe the ListView’s DataContext property has been set to the Model. (The user control’s DataContext property is already set to the ViewModel in the ViewModelBase). The ItemsSource property is set to “Statuses”, which is defined as a property inside “Model”. To enable scrolling, the ScrollViewer.XXX properties are set.



The ListView then defines an ItemTemplate, which tells the WPF engine on how each item (each status, of type TwitterSearchStatus) is rendered. It is the “template” for each TwitterSearchStatus item. For cosmetic reasons, I have included a Border with a DropShadowEffect applied. Inside the border is a stack panel which displays the Id of the status and the status text.



SOURCE CODE



Well, what I promised at the start of the article, I have covered the most. The source for the application is available for download at my skydrive. I have not included the dependency libraries (CAL, Tweet#) since I am not sure about their licensing. License?? Use the code as you like, you can do whatever you feel like.



What next?



1. The current implementation, though adds a new TabItem for each search, it does not display the tab header. The tab header should show the “SearchedFor” property.



2. As you type in the search, the “Search” button is not enabled until the search is tabbed out. But the ideal implementation would be when the user enters the first character, the button should be enabled and when the user presses enter, search should be executed.



3. Add the ability to auto refresh the results.



4. Implement paging, as of now, the application displays only the first 15 status. TweetSharp library, by the guys from Dimebrain (they make wonderful mini-screencasts and of course this excellent library) returns the first 15 status in the first page and they provide excellent FluentInterface to twitter which makes it easy to retrieve the rest of the pages.



5. Finally, implement a fully functional Twitter client – Yeah, Yet Another Twitter Client and I have some nice functionality ideas to implement which I would share in the future.



6. Refactoring the code to make it well designed.



If you have survived until this point, then I am doing a pretty good job at writing. I know its a long article and I have written the whole thing at one go ( after working for 8 hours, for a living). So kindly let me know for any bugs in this article.