Saturday, May 30, 2009

Debuggable Self-Host Windows Service Projects

When developing self-hosted WCF services, you really need two things:

  1. A windows service project that will be the host for the deployed environment.
  2. A console self-host project for easy debugging while developing the service.

Yes, there is also the option to use a WCF Service Library project with its associated WcfServiceHost.exe process that self hosts the service for debugging. However, I have run into too many occasions where something is going wrong and not having direct access to the hosting code wastes more cycles than it takes to set up my own service host, so other than quick demos, I never use the WcfServiceHost.exe in production development.

Having two separate projects to address 1 & 2 above is not really that great either, but if you try to run a service project in the debugger, you get an error telling you it can only be run through the services panel in Windows.

However, through a quick and easy pattern, you can make your service projects so they run as a console for development, but run as a service just fine when installed.

Step 1: Create a Windows Service project for the self host environment.

This is just the standard selection in the project dialog for a Windows Service project. Once you have your service class, rename it as appropriate and right click on the designer surface to add an installer class for the service. Standard stuff here.

Step 2: Implement your hosting code in a separate class from the service class itself.

For example, here is a very simple hosting class that can be used for any service in any project (with some appropriate exception handling and logging added in for production purposes):

public class SelfHost<T>
{
    ServiceHost m_Host;
    public void Start()
    {
        m_Host = new ServiceHost(typeof(T));
        m_Host.Open();
    }

    public void Stop()
    {
        m_Host.Close();
    }
}

From the service class itself, you can just instantiate an this class and call its Start and Stop methods.

public partial class SimpleServiceHostService : ServiceBase
{
    SelfHost<SomeService> m_Host = new SelfHost<SomeService>();
    public SimpleServiceHostService()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        m_Host.Start();
    }

    protected override void OnStop()
    {
        m_Host.Stop();
    }
}

Now when you install this service, the service host will be started and stopped through the services panel or automatically depending on the service configuration.

Step 3: Modify the Main method to start conditionally as a Console or a service.

Modify the default main declaration with no parameter to the signature for a main that takes a string[] of arguments. If arguments are present, run the code as if you are in a console app. If no arguments, call the default code for starting it as a service. For the console host mode, just call the Start and Stop methods on an instance of your host class just like the windows service did.

static void Main(string[] args)
{
    // Run as console if there are command line arguments
    if (args.Length > 0)
    {
        SelfHost<SomeService> host = new SelfHost<SomeService>();
        host.Start();
        Console.WriteLine("Press Enter to Exit...");
        Console.ReadLine();
        host.Stop();
    }
    else // run as service
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] 
        { 
            new SimpleServiceHostService() 
        };
        ServiceBase.Run(ServicesToRun);
    }
}

 

Step 4: Modify the project properties to be a console application and add a debug command line parameter.

ApplicationType

DebugOptions

That is basically it. Change the code shown above to use your service type, add an app.config with the appropriate WCF service code, and you are ready to run as a console app in the debugger, but when you build and install your service as a service, it will run fine as that as well.

You can download a full sample application here.





Saturday, May 30, 2009 4:35:29 PM (GMT Standard Time, UTC+00:00)
Comments [9]  | 


  Wednesday, May 13, 2009

TechEd SOA401 – Developing Service Oriented Workflows

This morning I am giving the subject session at TechEd. For those of you that attended, thanks! You can probably jump to the link at the bottom for the demos unless you want a quick review of what we covered by reading the rest of this post.

This session discusses .NET 3.5 Workflow Services, and I also touch on what is different in .NET 4.0 throughout and at the end. I also have a brief discussion at the end about cloud workflows, using workflow activities from .NET Services and running workflows in the cloud with Windows Azure.

In the talk, I demonstrate the use of the ReceiveActivity for exposing service operations from a workflow. I show how to add the receive activity to a workflow, hook it up to a service contract and the operations on that contract, how to bind the incoming parameters to other workflow properties and how to retrieve the return result from workflow properties through a binding. I then show how to host the workflow as a service using the WorkflowServiceHost class, how to get a reference to the WorkflowRuntime from the host (to hook up to workflow events), and how to configure the right bindings (context bindings) to expose the workflow. Then I write a quick client that is able to call the workflow to get it running and pass parameters to it.

Then I jump to a more complicated workflow that represents a loan application process as a state machine workflow. The loan application is submitted through a service call, and then approve or reject actions can be taken through service calls. I show how calls from the same client work out automatically through the passing of the instance ID through the context bindings, and how to allow multiple clients to interact with the same workflow by setting and getting the instance ID out of the context.

Then I show that the loan application workflow also needs to make service calls out to another credit checking service. So I demonstrate how you can use a SendActivity to act as a dynamic proxy in the workflow to call another service. Like the ReceiveActivity, you use bindings on dynamic properties to provide values for the outgoing parameters and to deal with any returned values.

I also discuss the limitations of the SendActivity and how to work around it by creating a simple custom activity to encapsulate a normal WCF proxy over which you have complete control.

Then I show an application that is composed of two workflows, a parent workflow and a child workflow. The parent invokes the child workflow and gets results back from the child. The trick with this scenario is how you need to pass the context to the child workflow of the receive activity that the call will come back into in the parent workflow so that the workflow runtime can reassociate the incoming call with the right instance and right receive activity.

If you want to take a look at the demos that do all of the above, here you go.





Wednesday, May 13, 2009 2:44:43 PM (GMT Standard Time, UTC+00:00)
Comments [4]  | 


  Thursday, May 07, 2009

NoVa Code Camp – 23 May

Update: Apparently I found a wormhole this morning and stated January instead of May. That would be May 23!

We have a code camp coming up on Saturday 23 May in Northern Virginia at the Reston Microsoft Training Center at 12012 Sunset Hills Rd, Reston, VA. There is a great line up with 4 tracks and over 20 speakers.

I’ll be giving a session on Developing Service Oriented Workflows, come out and expand your brain!





Thursday, May 07, 2009 11:26:37 AM (GMT Standard Time, UTC+00:00)
Comments [0]  | 


  Friday, May 01, 2009

Selecting the Right Client Technology Interview

Last year at TechEd, I was interviewed for ARCast TV about selecting the right client technology for your application, which I also gave as a breakout session at the conference. I don’t know why it took almost a year to produce, but that interview is now available. You can check it out here:

http://channel9.msdn.com/shows/ARCast.TV/ARCastTV-Brian-Noyes-on-Selecting-the-Correct-Client-Technology/

Some of the key points from the discussion included:

- WPF is really your best choice for any new smart client application development over Windows Forms if you care about building your team’s skill set where it matters for the long term.

- Windows Forms is still relevant for evolving existing applications, and even for new applications that are intensive on data editing but not visualization, where you have an existing team with deep knowledge in Windows Forms but no experience with WPF, and where you can justify that you will never need to have enhanced graphics, user experience, or advanced data visualizations.

- Silverlight is the way to go for anything where you want both broad reach in the browser and rich graphics. Particularly with the announcements of features in Silverlight 3 since this interview occurred, there are many applications that in the future with Silverlight 3 will be just as well off as a Silverlight application as they would be with WPF for businesses.

- ASP.NET (using AJAX features for better user experience) can still go a long way in delivering what you need for broad reach applications, and is certainly the way to continue if you have a good investment in web application development with .NET.

- Mixing ASP.NET and Silverlight for where their strengths lay is the sweet spot for web

- Starting to invest in WPF knowledge now is the right choice for the future with smart client development

Nothing too earth shattering will cause Nostradamus to rise from his grave, but hopefully helps cement some tough technology choices for people who were not sure which direction to head. 





Thursday, April 30, 2009 11:50:25 PM (GMT Standard Time, UTC+00:00)
Comments [0]  | 


  Wednesday, April 22, 2009

Building Composite WPF Applications at Evansville .NET Users Group

I presented a session last night at the Evansville .NET Users Group in Indiana on building composite applications with Prism 2. It was a great little group with a lot of really good questions.

For those that were there, thanks!

For those who are interested, here are the slides and demos:

Slides

Demos





Wednesday, April 22, 2009 8:36:51 PM (GMT Standard Time, UTC+00:00)
Comments [3]  | 

Composite Extensions for Prism 2

I figured that since I wrote my original composite extensions for Prism 1 on an airplane, I should keep up the tradition. On the way home from speaking in Evansville Indiana last night (not surprisingly on Prism), I got all the code in my composite extensions updated to Prism 2.

So if you like the modularity and pub-sub events story from Prism and would like to be able to do those same things in a Windows Forms or other kind of .NET application, you can easily do so now with these CompositeExtensions.

These extensions allow you to use the modular loading patterns and capabilities of Prism as well as the pub/sub events in a Windows Forms application, or any other kind of application (even console apps, WCF services, etc.).

The key pieces remain the same:

A CompositeEvent class that has all the same capability as the CompositePresentationEvent class in Prism2, but is not tied to the WPF libraries at all. For the UI thread dispatching capability, it uses the SynchronizationContext class (which is used under the covers by both WPF and Windows Forms, so this class will also work with WPF).

A SimpleUnityBootstrapper class that removes the tie to WPF in the bootstrapper by removing the creation of the shell and the region adapter stuff.

The  code also include a sample Windows Forms application that uses the extensions to load a module and fire and handle pub-sub events. As mentioned in the original post, I also demonstrate a simple way of using the DI container (Unity in this case) to achieve a Region-Manager like UI composition ability in Windows Forms.

Check it out and let me know if you have any feedback.





Wednesday, April 22, 2009 7:34:08 PM (GMT Standard Time, UTC+00:00)
Comments [4]  | 


  Thursday, March 05, 2009

TFS Build Node Problem Fix

Yesterday (in the midst of trying to get some builds done to get to a release), the Build node of my Team Explorer window for all Team Projects under my main user account went stupid and was displaying a red X for unavailable. Very frustrated, I did some searching and found very little other than one post suggesting that killing my user account and recreating it from scratch would clear the problem. That would also have cost me hours of reconfiguring other programs and settings that are customized under my account, so I dismissed that.

Based on that though, I went and created a separate user account and was able to run builds from there and switch back and forth with Switch User to get through the day.

The sweet thing was that when I fired up VS 2008 this morning and went to Team Explorer with no project loaded, I noticed a bunch of stuff get spit into my output window. Looking closely, it was a nice little error message from Team System telling me the BuildPackage was not being loaded due to previous errors, and if I wanted to have it try again, just launch VS from the command prompt with the following line:

devenv /resetskippkgs

Worked like a charm and my environment is totally happy again.

You gotta love software that detects its own problems and suggests simple things that actually work to fix it.

Well done VSTS team!





Thursday, March 05, 2009 2:37:31 PM (GMT Standard Time, UTC+00:00)
Comments [3]  | 


  Thursday, February 26, 2009

Prism 2 Bits Refresh

Update: Great post by Julian Dominguez from the Prism team here that tells exactly what files changed in case you just want to update those in your source control: http://blogs.southworks.net/jdominguez/2009/02/prism-20-download-bits-refreshed-whats-changed/

In case you have already jumped on downloading Prism 2 (Composite Application Guidance for WPF and Silverlight) when it released about a week ago, time for you to go get some fresh bits. There were a couple of minor issues that have been fixed and the download links now have the updated code behind them.

So remove what you have for Prism 2, go to the download links and get the latest.

In WPF the main thing affected was that certain containers, TabControl in particular, did not bring their View to the foreground with an Activate call on the region. There was also a build issue for Silverlight projects that was fixed.

So go get yer fresh hot bits!





Thursday, February 26, 2009 10:53:40 PM (GMT Standard Time, UTC+00:00)
Comments [6]  | 


  Sunday, February 08, 2009

Avoiding Login Dialogs with TFS Remote Access

I’ve been working on a project for a remote customer for a number of months and something that constantly bugged me is the way TFS wants you to log in every time you open your solution or fire up Team Explorer. Unlike other login dialogs in Windows and Internet Explorer, the one presented by TFS does not have the magic checkbox to “Remember my password”. But at some point I did something on one machine and it stopped asking and was logging me in automatically if I was online. Excellent! Now how to get it to behave the same on my other two dev machines?

I did a little thinking and realized that TFS just uses HTTP Web Services for it remote access. The team project I was working on was using SSL and a particular port, lets say it was 8089.

So I just fired up the browser, hit http://tfs.somecompany.com:8089 and I got the standard IE login dialog which does have the Save password checkbox. Checked that box, got and error of course because the web service is not designed to be used from the browser, but now whenever I hit the team project in VS through opening the source controlled solution or opening Team Explorer, viola it logs me automatically now.

10 seconds of effort on any machine to avoid the repeated hassles of logins. Nice.





Sunday, February 08, 2009 9:42:23 PM (GMT Standard Time, UTC+00:00)
Comments [1]  | 





















Sign In
Copyright © 2006-2007 Brian Noyes. All rights reserved.
designed by NUKEATION STUDIOS