Friday, August 14, 2009

Teched 2009: .Net 4

There have been a lot of talk on the upcoming release of .Net 4 and Visual Studio 2010. Here are some features that I have seen at Teched and have been looking forward to:
  • Parallelism (have chatted on previous post on this)
  • MEF - this is the extensibility framework provided by Microsoft. This looks very promising (have chatted about this in previous post as well)
  • Visual Studio - they have numerous small enhancements like Removing recent projects from start page!!! I have waited so long for this.
  • ASP.NET 4 - they have included some nice small enhancements such as having support for having multiple config files and aggregated to common config file, ASP.NET and javascript code snippets, One Click Deployment, Search Engine optimization and URL routing support (similar to ASP MVC framework).
  • JQuery - this is a huge addition they have provided web developers. Microsoft has even gone as far to support this Open Source library. For those who havent worked with this yet, please check it out here.
Other features that I am not sure will work well (but we will have to see):
  • Optional Parameters
  • Dynamic Keyword
  • EF4
  • WF4

Teched 2009: Entity Framework 4

I know what you are thinking, and NO - we have not missed version 2 and 3 of the Entity Framework (even though sometimes we wish we had). They have just tried to remove the confusion of talking of .Net 4 and EF2 (although I think more people are confused now).

As with the previous post - some good news. They have completely rewritten EF4. Yes, they have built EF4 on top of T4. For those people that have no idea what I am talking about - T4 is a code generation template provided by Microsoft that has been available from the days of Visual Studio 2005.

The most shocking news is still to come however. The data guys from Microsoft have been listening to all those angry developers (like me and all my colleagues) and have now support for POCO classes (how revolutionary). We will now be able to design a model without being tied to the database (seems simple I know - sarcasm runs in my blood)!!!! Perhaps I will try it out again but I am still so scarred from my previous experiences of EF. We shall see.

They have also included Model First development. This will allow the user to build the model first and then generate a database schema from this. Once again, I am not sure I will use this. It is very rare that we deal with solutions where the domain model should have 1-1 relationship with the database. This becomes just a basic and overrated CRUD system.

EF will still have a long way to go in my opinion to compete against other products like NHibernate.

Teched 2009: Workflow Foundation 4

I have some good news and some bad news regarding WF. The good news is that the guys at Microsoft have completely rewritten WF. The bad news is that because its a complete rewrite, there is currently no upgrade support from the current WF to WF4. Sorry for those current WF developers. That sucks I know.

I heard some scary statistics from some of the presenters at Teched. Apparently, WF is nice to have in theory but as soon as you try to scale it to a realistic solution then everything starts falling apart and you are faced with some difficult challenges. The major challenge (according to me) is the performance issue. WF currently is between 100 and 1000 times slower than normal .Net code execution!!! That is shocking!!!

The good news is that with the rewrite of WF to WF4 the performance has been kept on par with normal .Net execution. I won't count my chickens until they are hatched however. I will do some serious performance testing before embarking on any new project with WF.

They have also redone the WF designer. They have completely done away with the Code activity which will promote better designed workflows. They have also included a type of nested workflow IDE. This means you can drilldown into activities (such as while loops and if statements) and thus your design surface will not be too cluttered (as it is currently).

Ps. Those guys writing products on top of Workflow Foundation (like K2) - I feel for you.

Teched 2009: Parallelism

While attending Teched 2009 in South Africa, I attended a very good presentation by Bart de Smet on Parallelism. He discussed the history and the need for parallelism as well as what the future entails.

It looks like the end goal is to create a framework that supports parallelism natively. This will unfortunately require the whole .Net CLR to be rewritten. In the mean time they have created a library of sorts that can be used with the latest version of the CLR - .Net parallel extensions. These will be included with .Net 4 and Visual Studio 2010 release. These extensions can also be downloaded and be used with the current .Net 3.5 runtime.

They have provided 3 main parallel enhancements:
  • TPL (Task Parallel Library)
  • System.Threading.Parallel
  • PLINQ
All three of these extensions I find very fascinating.

1) Task Parallel Library (TPL)

This, as I understand it, is the foundation of the parallel extensions for .Net. The Task Parallel Library (TPL) is designed to make it much easier to write managed code that can automatically use multiple processors.Using the library, you can conveniently express potential parallelism in existing sequential code, where the exposed parallel tasks will be run concurrently on all available processors. Usually this results in significant speedups.

A simple example: For loop

for (int i = 0; i < 100; i++) {
a[i] = a[i]*a[i];
}



This code will be executed in sequence. There is no support currently for multiple CPU processing. The following snippet shows how easy it is to provide support for parallelism using the Parallel keyword:

Parallel.For(0, 100, delegate(int i) {
a[i] = a[i]*a[i];
});



Only two changes were required. One, add the Parallel keyword to the for statement. Two, use an anonymous delegate to execute the code.

A nice article on the TPL can be found at MSDN magazine

2) System.Threading.Parallel

This extension allows you to use a .Net threadpool in a true parallel fashion. In our current framework we spawn multiple threads on a single CPU. When executing high volumes, check the system usage. For instance, if you have a dual core CPU, you will notice that CPU usage never peeks over 50%. With this new extension the threads will be load balanced over all available CPUs. You also have the option to specify which CPU to use.

This enhancement is also quite simple to implement in code. All that is necessary (similar to TPL) is the addition of the .AsParallel() extension method.

3) PLINQ

Using PLINQ is almost exactly like using LINQ-to-Objects and LINQ-to-XML. You can use any of the operators available through C# 3.0 and Visual Basic® 9.0 query comprehension syntax or the System.Linq.Enumerable class, including OrderBy, Join, Select, Where, and so on. PLINQ supports all of the LINQ operators, not just those available in language comprehensions. And you can query any in-memory collection such as T[], List, or any other kind of IEnumerable in addition to XML documents loaded using the System.Xml.Linq APIs. If you already have a bunch of LINQ queries, PLINQ is equipped to run them.

LINQ-to-SQL and LINQ-to-Entities queries will still be executed by the respective databases and query providers, so PLINQ does not offer a way to parallelize those queries. If you wish to process the results of those queries in memory, including joining the output of many heterogeneous queries, then PLINQ can be quite useful.

Aside from writing LINQ queries the same way you're used to writing them, there are two extra steps needed to make use of PLINQ:
  1. Reference the System.Concurrency.dll assembly during compilation.
  2. Wrap your data source in an IParallelEnumerable with a call to the System.Linq.ParallelEnumerable.AsParallel extension method.
Here is a simple example on PLINQ. You will notice that the only addition was the .AsParallel() extension method.

var q = data.AsParallel().Where(x => p(x)).Orderby(x => k(x)).Select(x => f(x));
foreach (var e in q) a(e);



A nice article on this can be found at MSDN magazine.

As you can see, there are some nice enhancements coming the .Net for parallelism support. We will keep an eye open for this in the near future.

Monday, August 3, 2009

TechEd 2009: Silverlight 3 Part 2: New Controls

One thing that has always been frustrating with Silverlight 2 is the limited amount of controls that you received out of the box. I am happy to announce that this has changed. Silverlight 3 is shipping with a bunch of new controls and other controls that can be downloaded.

Mature
  • AutoCompleteBox,
  • Calendar,
  • ChildWindow,
  • DataGrid,
  • DataPager,
  • DatePicker,
  • GridSplitter,
  • HeaderedItemsControl,
  • TabControl,
  • TreeView
Stable
  • DockPanel,
  • Expander,
  • HeaderedContentControl,
  • Label,
  • NumericUpDown,
  • Viewbox,
  • WrapPanel
Preview
  • Accordion,
  • Charting,
  • DataForm,
  • DomainUpDown,
  • ImplicitStyleManager,
  • LayoutTransformer,
  • Rating,
  • TimePicker,
  • TimeUpDown,
  • 11 Themes
Experimental
  • GlobalCalendar,
  • TransitioningContentControl,
  • TreeMap

TechEd 2009: Silverlight 3 Part 1: Out of Browser

As promised I am here writing about the nice things I have seen so far at TechEd 2009. I am so dedicated that I am in my hotel room after day 1 doing this :). I am going to start off with writing on the “What’s new in Silverlight 3” presentation.

There are some very nice new features in Silverlight 3. I will start off with the Out of Browser support of Silverlight. Some people may have heard of this before but I will just show what the final verdict on was between the beta phases and final version. As you might have suspected, Out of Browser allows the user to detach (install) the Silverlight application from the web browser and run it from your desktop. There is no fundamental change in how Silverlight works – it still runs out of the sandbox.

This is quite a simple and straight forward technique. You create a Silverlight application, go to properties and mark “Enable running application out of browser”. You can then select the “Out of Browser Settings” button. This button will allow you to specify details about the Silverlight app when running out of browser like Name, Width, Height, Icon, etc. Once the user browses to the Silverlight web site, he is able to right click the application and select to install the application.

There is some additional functionality that you can provide. There is support for manual installation of application and determining if the application is already installed. There is also support for the application to determine when network connectivity changes or IP address changes. This will then allow the application to store data offline (in Isolated storage) until the application is online again. Once online, the user can be prompted to synchronize data back to the server. The isolated storage space has also been increased from 1MB to 25MB.

There is also support for the application to check the server if new updates are available for the application.


Here is an example:

Application app = Application.Current;

public MainPage()
{
InitializeComponent();
LayoutRoot.DataContext = Deployment.Current.OutOfBrowserSettings;
UpdateUI();
app.CheckAndDownloadUpdateCompleted += App_CheckAndDownloadUpdateCompleted;
app.InstallStateChanged += (s, e) => UpdateUI();
NetworkChange.NetworkAddressChanged += (s, e) => UpdateNetworkIndicator();
}

private void UpdateUI()
{
UpdateNetworkIndicator();

installButton.Visibility =
app.InstallState == InstallState.NotInstalled ?
Visibility.Visible : Visibility.Collapsed;

updateButton.Visibility =
app.IsRunningOutOfBrowser ?
Visibility.Visible : Visibility.Collapsed;

isRunningOutOfBrowserTextBlock.Text = app.IsRunningOutOfBrowser.ToString();

installStateTextBlock.Text = app.InstallState.ToString();
}

private void UpdateNetworkIndicator()
{
networkIndicator.Visibility =
app.IsRunningOutOfBrowser ?
Visibility.Visible : Visibility.Collapsed;

bool online = NetworkInterface.GetIsNetworkAvailable();

networkIndicator.Text = online ? "ONLINE" : "OFFLINE";

updateButton.Visibility = online ? Visibility.Visible : Visibility.Collapsed;
}

private void installButton_Click(object sender, RoutedEventArgs e)
{
try
{
app.Install();
}
catch (InvalidOperationException)
{
MessageBox.Show("The application is already installed.");
}
}

private void updateButton_Click(object sender, RoutedEventArgs e)
{
app.CheckAndDownloadUpdateAsync();
}

private void App_CheckAndDownloadUpdateCompleted(object sender, CheckAndDownloadUpdateCompletedEventArgs e)
{
if (e.UpdateAvailable)
{
MessageBox.Show("An application update has been downloaded. Restart the application to run the new version.");
}
else if (e.Error != null && e.Error is PlatformNotSupportedException)
{
MessageBox.Show("An application update is available, but it requires a new version of Silverlight. " +
"Visit the application home page to upgrade.");
}
else
{
MessageBox.Show("There is no update available.");
}
}


More information can be found here at the presenter’s (Eben de Wit) blog. This blog also contains the slides and code for all the new features of Silverlight 3.

Saturday, August 1, 2009

Teched 2009

I am very excited to be going to this year's Teched hosted in Durban, South Africa. I am leaving tomorrow and will be back on Thursday (the 6th of August). I will be writing a couple of articles on the presentations that I will be attending which I am sure will be great.

My major focus areas while I am there:
  • Silverlight 3
  • Architecture and Patterns
  • .NET 4.0
  • ASPNET 4.0 and JQuery
  • WCF and WF
These should be exciting topics so can't wait to come back and share them.

Decorator Pattern

A colleague and I were doing a solution design earlier this week and came across an interesting problem. As always we reverted to patterns to solve our problem and I am still amazed of how easy things become when you have solid literature to fall back on.

Our problem: We were designing a system which would provide live stock data from various stock exchanges to various clients. We decided to use Martin Fowler's event sourcing pattern to help with our distributed architecture. Greg Young's articles and presentations on practical implementations on this pattern has helped a lot as well.

What we ended up with was a "Server" (Gregg young would call this the database) domain and a "Client" domain. I'm not going into detail on why we made this decision but our problem was that the Client domain was very similar to the Server domain. Actually the Client domain was a subset of the Server domain.

Both the Server and Client domain had entities: MarketDepth which contains Bids and Offers. The major difference was the behavior associated with inserting and removing bids from MarketDepth. The server domain receives raw data from the stock exchanges and translates those messages into domain specific events. Only the required domain events (like BidsChanged, OffersChanged, TradesChanged, etc) get routed to the client domain because that are the only events the client domain are interested in.

So the problem is that both the server and client domain have the same entities but the behavior around them (input and output of events) are different. We decided to use the decorator pattern to solve this problem. This pattern wraps a class around the entity and associates behavior to the entity. This allows you to have multiple decorators but only one entity.

An Example:

As discussed before, we have a MarketDepth entity:

public class BidDTO
{
public BidDTO(string symbol, int price)
{
Symbol = symbol;
Price = price;

}
public string Symbol { get; private set; }
public int Price { get; private set; }
}

public class MarketDepth
{
private readonly IList<BidDTO> _Bids;

public MarketDepth()
{
_Bids = new List<BidDTO>();
}

public bool SaveBid(BidDTO bid)
{
if (!_Bids.Contains(bid))
{
_Bids.Add(bid);
return true;
}
return false;
}
}


Next I declare a base decorator class that I will use. As you can see it is an abstract class with an abstract method (which will be entry point for saving a bid) and it contains a protected MarketDepth variable.

public abstract class Decorator
{
protected MarketDepth _MarketDepth;

public Decorator(MarketDepth marketDepth)
{
_MarketDepth = marketDepth;
}

public abstract void HandleBidEvent(object e);
}


I have two events defined: one for raw data coming into my Server domain and a domain event that Server domain raises and Client domain will receive:

public class ServerEvent
{
public ServerEvent(string rawMessage)
{
RawMessage = rawMessage;

}
public string RawMessage { get; private set; }
}

public class BidChangedEvent
{
public BidChangedEvent(BidDTO bidDTO)
{
Bid = bidDTO;

}
public BidDTO Bid { get; private set; }
}


Next I have the ServerDecorator. This decorator will be used at the Server domain to save MarketDepth data based on messages received from the stock exchange:

public class ServerDecorator : Decorator
{
public ServerDecorator()
: base(new MarketDepth())
{
}

public override void HandleBidEvent(object e)
{
var serverEvent = (ServerEvent)e;

BidDTO bid = GetBidFromMessage(serverEvent.RawMessage);

if (_MarketDepth.SaveBid(bid))
{
//raise outgoing event
BidChangedEvent domainEvent = new BidChangedEvent(bid);
//raise domain event
}
}

private static BidDTO GetBidFromMessage(string message)
{
string symbol = message.Substring(0, 4);
int price = Convert.ToInt32(message.Substring(4, 4));

return new BidDTO(symbol, price);
}
}


And lastly, the ClientDecorator that will be used to listen for domain events from the server and apply those events to the MarketDepth on the client domain:

public class ClientDecorator : Decorator
{
public ClientDecorator()
: base(new MarketDepth())
{
}

public override void HandleBidEvent(object e)
{
var domainEvent = (BidChangedEvent)e;

if (_MarketDepth.SaveBid(domainEvent.Bid))
{
//raise another event to client user
}
}
}


As you can see, this makes the code re-usable and clearly separates the responsibilities of the various classes. Hopefully this will be useful for someone in the future. Feel free to pop me an email or leave a comment if you would like the source code or more explanation on the pattern and how it is used.

Till next time.