March 2009

Debugging Windows Services in the Visual Studio IDE

In one of our current projects we made  the decision to move our WCF services from an IIS hosted environment into a Window Service hosted environment.  This move gave us greater flexibility in mangement and distribution of our WCF services, and allowed us to use multiple endpoints (http, net.tcp, pipes) without the need for Windows Activation Services (WAS) which would have required that our clients be running Vista and/or Server 2008.

One of the major pains about working with developing Windows Services, however, is that you can’t start a windows service project from within the debugger.  You have to instead install and start the service to execute it.

I have a workaround for this that allows us to test our WCF services from within the IDE without installing the service.

Steps:

1. In the Windows Service, put any code you’d normally put in the OnStart and OnStop events into their own functions:

private void OpenWCFServices()
{
    householdHost.Open();
}

private void CloseWCFServices()
{
    householdHost.Close();

}
protected override void OnStart(string[] args)
{
    OpenWCFServices();
}

protected override void OnStop()
{
    CloseWCFServices();
}

2. Using precompiler directives, specify 2 public functions that also call your start and stop methods.  This allows these methods to be publicly available at debug time only (you’ll see why in Step 3).

#if DEBUG
        public void DebugStart()
        {
            OpenWCFServices();
        }

        public void DebugStop()
        {
            CloseWCFServices();
        }
#endif

3. Create a new Windows Form in your service project.  Alter the constructor so that it requires an instance of your service to be created.  Add a Button to stop your WCF services to the form.

    public partial class DebugForm : Form
    {
        private FEEAApplicationServiceHost service;
        public DebugForm(FEEAApplicationServiceHost service)
        {
            InitializeComponent();
            this.service = service;
            this.service.DebugStart();
        }

        private void ExitButton_Click(object sender, EventArgs e)
        {
#if DEBUG
            service.DebugStop();
#endif
        }
    }

 

4. Alter your Program.cs to use this form as your running application instead of the Service using the same #if DEBUG directives.

       /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {

#if DEBUG
            Application.EnableVisualStyles();
            Application.Run(new DebugForm(new FEEAApplicationServiceHost()));
#else
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new FEEAApplicationServiceHost()
            };
            ServiceBase.Run(ServicesToRun);
#endif

        }
    }

This allows you to launch your service from the IDE and debug during development, while still having the ability to compile and distribute your service without changing a line of code.  (Although I’d probably recommend removing this code from anything that is truly production-level.

So now, when you right click your service project and select Debug –gt; Start new instance, you see the following form:

 

image

Once this is up, you can start an instance of your code that accesses the service, and you’re all set.

.NET Framework
WCF

Comments (0)

Permalink

Interesting Links - RoR and MVC.NET

A couple topics I have been looking into lately are Ruby on Rails and ASP.NET MVC.

Here are some helfpul links I found along the way.

Visual Studio Add-ins - I have heard of quite a few of these. The link is kind of old but some of the tools are still relevant.

http://msdn.microsoft.com/en-us/magazine/cc300778.aspx

Free Chapter on MVC in Action - This book comes out in August but some of the content is available now.

http://www.manning.com/palermo/

MVC.NET - Interesting article. I like the last section where they talk about MVC vs. Web Forms.

http://msdn.microsoft.com/en-us/magazine/cc337884.aspx

ASP.NET vs. Ruby - Decent comparison between the two technologies.

http://dotnetaddict.dotnetdevelopersjournal.com/ruby_vs_aspnet_1.htm

http://dotnetaddict.dotnetdevelopersjournal.com/aspnet_ruby_agility.htm

http://dotnetaddict.dotnetdevelopersjournal.com/aspnet_ruby_datadriven.htm

General

Comments (0)

Permalink

WCF Security Part 1

A few months ago I was given the task of setting up security for some WCF services we had created. After a couple days of scouring the internet for ideas and solutions, I ended up purchasing a book on WCF. Although there is a lot of information on the web about WCF and what security methods are available to us as developers, the information was always incomplete, and connecting the dots wasn’t the easiest. The example below shows how we can setup message based WCF security for a service which will be accessed over the internet, although the same code could be used for an intranet application as well. The example will require both user authentication and an x509 certificate.

For our WCF service, we’re using the wsHttpBinding. This binding provides much of the same functionality as a basic web service, with added service features such as reliable messaging, WS-Addressing, and WS-Security. Since this post is mainly on setting up security for a WCF service, I won’t go into too many details of the other features of wsHttpBinding.

After creating the WCF service, open up the web.config file for the WCF Service Application project. After scrolling down for a long time, you should come across a System.serviceModel tag. This tag contains all of the configuration settings for the WCF services contained in this project. Here’s what you should be looking at now:

<system.serviceModel>

<services>

<service name=WcfService1.Service1 behaviorConfiguration=WcfService1.Service1Behavior>

<!– Service Endpoints –>

<endpoint address=“” binding=wsHttpBinding contract=WcfService1.IService1>

<!–

Upon deployment, the following identity element should be removed or replaced to reflect the

identity under which the deployed service runs. If removed, WCF will infer an appropriate identity

automatically.

–>

<identity>

<dns value=localhost/>

</identity>

</endpoint>

<endpoint address=mex binding=mexHttpBinding contract=IMetadataExchange/>

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior name=WcfService1.Service1Behavior>

<!– To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment –>

<serviceMetadata httpGetEnabled=true/>

<!– To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information –>

<serviceDebug includeExceptionDetailInFaults=false/>

</behavior>

</serviceBehaviors>

</behaviors>

</system.serviceModel>

By default, a WCF service will use the wsHttpBinding, this is what we want to continue using. We need to make a few modifications to this web.config in order to provide the additional functionality we want. First take a look at the serviceBehaviors section. By default we already have a behavior for our Service1. Here is an example of a modified behavior:

<behavior name=WcfService1.Service1Behavior>

<serviceCredentials>

<serviceCertificate findValue=CN=ServiceCertificate storeLocation=LocalMachine

storeName=My x509FindType=FindBySubjectDistinguishedName />

<userNameAuthentication userNamePasswordValidationMode=Windows/>

</serviceCredentials>

</behavior>

There is a lot of info in this behavior pertaining to security. The first bit describes the x509 certificate we would like to use that is already installed on our machine. We can create our own test x509 certificate for development purposes if need be. We can also describe the user authentication mode, in this case we are just using Windows authentication.

The next section extends the wsHttpBinding to provide some additional features not turned on be default:

<bindings>

<wsHttpBinding>

<binding name=wsHttpBindingSettings messageEncoding=Text>

<security mode=Message>

<message clientCredentialType=UserName />

</security>

</binding>

</wsHttpBinding>

</bindings>

Here we can describe the transport type, as well as the client credential type. This is fairly simple, we are using Message based transport with UserName security.

Finally we need to tie these sections together with Service1:

<service behaviorConfiguration=WcfService1.Service1Behavior name=WcfService1.Service1Behavior>

<endpoint address=“” binding=wsHttpBinding bindingConfiguration=wsHttpBindingSettings

contract=WcfService1.IService1 listenUriMode=Explicit>

<identity>

<dns value=ServiceCertficate />

</identity>

</endpoint>

<endpoint address=mex binding=mexHttpBinding contract=IMetadataExchange />

</service>

The only changes we made here are in the bindingConfiguration property and the dns value. The bindingConfiguration allows you to bind our binding configuration to this service, and the dns value should match the x509 certificate name.

I’ll be posting some more on this topic, including writing your own custom username validation code for WCF, and creating your own test x509 certificate. Hope this helps!

-Jon

.NET Framework

Comments (0)

Permalink

Java could be a pain to C# developers (Pass by Reference)

In C++ and C#, developers have freedom to modify variables by directly having access to memory location.

In C++,

#include <stdio.h>

void swapnum(int &i, int &j) {
int temp = i;
i = j;
j = temp;
}

int main(void) {
int a = 10;
int b = 20;

swapnum(a, b);
printf(”A is %d and B is %d\n”, a, b);
return 0;
}

In C#,

int a = 1;
modify(ref a); //now a=2
void modify(ref int a)

{
a = 2;
}

In Java, however, there’s no such thing as pass by reference. Even the so-called pointers (created by ‘new’ operator) are passed by copy of the reference.

Thus, if you do the following,

String a = “a”;
modify(a); //a doesn’t change, since a is being passed as a copy of the pointer a.
void modify(String a)
{
a = “b”
//this a is a different pointer, thus does not affect the real ‘a’ pointer outside of the method.
}

As you can see, there’s no direct way of modifying the variable. This has become a problem for me in many cases, since from time to time, it is necessary to have direct access to the variables.

The answer is by using a wrapper.

Here’s an example.
String a = “a”;
System.out.println(a); // ‘a’ gets printed
String[] array = new String[]{a}; //add a copy of the pointer variable a to String array
modify(array);
System.out.println(array[0]);

void modify(String[] array) {
array[0] = “b”;
}
This is not the most elegant way of doing it, but you get the idea. :)

One thing to remember is that String[] array contains a copy of pointer ‘a’. When you assign, or add, items to any collections such as array, you’re passing a copy of a pointer. So the variable ‘a’ in the example above still is pointing to the value ‘a’, whereas array[0] points to ‘b’. In order to finalize the pointer modification, you need to assign

a = array[0].

So, the basic idea is this: In Java, when you pass variables around, whether they are pointers or primitive values, you’re always dealing with a copy of the variables, not the variables themselves. If you understand the basic idea of it, you can take advantage of the true “Pass by Reference”.

I hope this sort of ‘trick/hack’ can be of help to you all. :)

-Seung Kim (SK)

General

Comments (0)

Permalink