Wednesday 7 March 2012

Nitin's blog: How to Access ApplicationResources in Windows host...

Nitin's blog: How to Access ApplicationResources in Windows host...: Scenerio : - If you have a WPF application and you are running it standalone, you can see all static as well as dynamic resources like Image...

How to Access ApplicationResources in Windows hosted WPF application

Scenerio: - If you have a WPF application and you are running it standalone, you can see all static as well as dynamic resources like Images, converters etc. When you host this it to native Win32 or Windows application all images vanish from the UI.

Reason: - The reason is very simple. When you run WPF application, there's a class called App.xaml (app.xaml.cs) which is the entry point of any WPF application during build. Apparently, this class does not has any information how to run the application, But if you goto App.g.cs in obj folder of WPF app, you can see what I mean.
When you host WPF app to windows app, MSbuild knows nothing about how to set the entry point of WPF application rather its set the entry point of windows app which is obvious.

Solution: - Load the WPF application resources at runtime. Open the usercontrol.cs (it could be any form or control) file where your are hosting WPF control inside ElementHost. Now, after initializeComponent() in the constructor load the resource dictionary using the following code.


StreamResourceInfo sri = System.Windows.Application.GetResourceStream(
    new Uri("/assemblyName;component/Resources/ButtonStyles.xaml", UriKind.Relative));
            var resources = (ResourceDictionary)BamlReader.Load(sri.Stream);

assemblyName is the name of your assembly. BamlReader is a static class used to load resources from stream


public static class BamlReader
    {
        public static object Load(Stream stream)
       {
           var pc = new ParserContext();
           MethodInfo loadBamlMethod = typeof (XamlReader).GetMethod("LoadBaml",
                                                                      BindingFlags.NonPublic | BindingFlags.Static);
            return loadBamlMethod.Invoke(null, new object[] { stream, pc, null, false });
       }
    }


So now, we have resources with us, we need to set it to the appropriate control

var designerView = new WorkflowDesignerView();
designerView.Resources.MergedDictionaries.Add(resources);

Where designerView is the WPF control you are hosting in windows app.

Lastly add this designer to Elementhost as a child

elementHost1.Child = designerView;

and you're done. Now you can see all images & converters are available and working properly.

Tuesday 6 March 2012

Nitin's blog: Host Workflows stored in database as WCF services ...

Nitin's blog: Host Workflows stored in database as WCF services ...: Today I am going to show you how to host WF4 workflows in WCF which are stored in database. We'll be using ASP.Net MVC as the solution proje...