Wednesday, January 28, 2009

WCF WPF and not IIS - net.tcp

I found that we could convert our XAML into an image (png was my choice) in WPF. I wrote a WPF library, but could not call it in ASP.NET because IIS complained about the threading when the code added any Visual (subclassed) element (image, lines, other controls like canvas, etc) to the drawing pad's Canvas. WPF can't be called directly in ASPX server-side code-behind, or from an ASMX Webservice, or from an http WCF Webservice.

So the ultimate solution was to write a net.tcp WCF to WPF Webservice; not hosted in an http (IIS7 hosted) Windows Service, again, because of the threading issue.

Instead, I wrote a simple console application (exe) as the host for the WCF to WPF libraries.
To get net.tcp in the app.config instead of http, I declared net.tcp like this in the configuration section (found details here http://www.codeproject.com/KB/WCF/WCFMultipleHosting.aspx):

< system.serviceModel>
< services>
< service name="a.ImageMaker" behaviorConfiguration="a.ImageMakerBehavior">
< host>
< baseAddresses>
< add baseAddress="net.tcp://127.0.0.1:1111"/>< /baseAddresses>
< /host>
...

Now this runs on startup, and is a ServiceHost for ImageMaker.
ImageMaker is the WCF interface that is called from anywhere and then calls the WPF library.
The WPF library is a limited port of a Silverlight control to WPF, with only the limited bit of code required for initial "fitted" display.

The ported-to-WPF control (XAML code with C# initialization) never displays, so it would not render to its XAML Canvas resulting in blank images every time. The trick to getting WPF to render was to call Measure and Arrange before generating the image:
DrawingCanvas.Measure(size);
DrawingCanvas.Arrange(new Rect(size));

Here's a neat client side PNG generation lib for Silverlight, but since you can't get pixels, it doesn't help for taking a printable snapshot of the display:
http://blogs.msdn.com/jstegman/archive/2008/04/21/dynamic-image-generation-in-silverlight.aspx

Collaborate with me at LinkedIn.com/danwygant twitter.com/danwygant
Dan Wygant, Sr. Software Consultant - Silverlight 2 ASP.NET 3.5 SP1 LINQ WCF WPF MVP
04'-08' Windows Customer Experience Founder HUNTUG.org VSdotNetUG.org
HowToVS.NET INETA Mentor for Al/Ms/La

No comments:

Post a Comment