Category Archives: WCF

Create A Self-Signed SSL Certificate In .NET

A problem that I have commonly run into is trying to secure communications using SSL or other encryption for a intranet application. In this scenario, it is unnecessary to have a secure certificate signed by an expensive Internet authority. And often it is intended for deployment in a small-scale scenario where there might not be a Certification Authority running on a Window Server. In this case, you want to create a self-signed certificate and use the thumbprint of the certificate for phishing prevention.

Microsoft does provide a utility, makecert, which can create a self-signed certificate. However, it isn’t distributed with Windows, is command line only, and definately NOT end user friendly. I wanted a method for creating a certificate just by clicking a button, without using a shell calls and distributing a copy of makecert with my applications.

To this end, I created a VB.Net class that calls out to the CryptoAPI and creates a self signed certificate with a 2048-bit RSA key. The certificate and private key are stored in the Local Machine store. In the Local Machine store it can be accessed by system processes and services. I’ve attached an example of the class to this post, feel free to use it as you see fit.

Certificate Creator (2362)

Monitoring a WCF Service Host

One problem I’ve been running into is my ServiceHosts failing out in my long running background services. I’ve written the following class to help monitor the service hosts and restart them if they fail. This is still experimental, and I’m not sure how well it’s going to work, so any feedback would be appreciated.

The delegate is used to recreate the host whenever it needs to be created. Just pass in a delegate to a function that creates the ServiceHost and initializes all of its bindings, etc.

Public Delegate Function ServiceHostCreateDelegate() As ServiceHost

Public Class ServiceHostMonitor
    Implements IDisposable

    Private _del As ServiceHostCreateDelegate
    Private WithEvents _host As ServiceHost
    Public ReadOnly Property Host() As ServiceHost
        Get
            If _host Is Nothing Then
                CreateHost()
            End If

            Return _host
        End Get
    End Property

    Public ReadOnly Property HostCreated() As Boolean
        Get
            Return _host IsNot Nothing
        End Get
    End Property

    Private _hostName As String
    Public ReadOnly Property HostName() As String
        Get
            Return _hostName
        End Get
    End Property

    Public ReadOnly Property State() As CommunicationState
        Get
            Return Host.State
        End Get
    End Property

    Public Sub New(ByVal createDelegate As ServiceHostCreateDelegate, ByVal hostName As String)
        If createDelegate Is Nothing Then
            Throw New ArgumentNullException("createDelegate")
        End If
        If hostName Is Nothing Then
            Throw New ArgumentNullException("hostName")
        End If

        _del = createDelegate
        _hostName = hostName
    End Sub

    Protected Overrides Sub Finalize()
        Dispose(False)
    End Sub

    Protected Sub CreateHost()
        If HostCreated Then
            Close()
        End If

        _host = _del.Invoke()
    End Sub

    Public Sub Open()
        Try
            CreateHost()
            Host.Open()

            Logger.LogMessage("Opened Service Host " & _hostName)
        Catch ex As Exception
            Logger.LogException(ex, "Error Opening Service Host " & _hostName)
        End Try
    End Sub

    Public Sub Close()
        Try
            If HostCreated Then
                If State = CommunicationState.Opened Then
                    Host.Close()
                End If

                _host = Nothing
            End If
        Catch ex As Exception
            Logger.LogException(ex, "Error Closing Service Host " & _hostName)
        End Try
    End Sub

    Private Sub _host_Faulted(ByVal sender As Object, ByVal e As System.EventArgs) Handles _host.Faulted
        Logger.LogError("Service Host Faulted " & _hostName)
        Open()
    End Sub

#Region "IDisposable"

    Private disposedValue As Boolean = False        ' To detect redundant calls

    ' IDisposable
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                Close()
            End If

            ' TODO: free shared unmanaged resources
        End If
        Me.disposedValue = True
    End Sub

#Region " IDisposable Support "
    ' This code added by Visual Basic to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
#End Region

#End Region

End Class

Please note that the Logger.LogError and Logger.LogMessage calls are for the custom error logging in my application. You should replace this with your own error logging as you see fit.

Odd WSHttpBinding Scenario

I was having lots of trouble recently with a WCF WSHttpBinding scenario on a server. It had been working, and the only thing I had changed recently was to the base address of some of the bindings. On top of that, everything was working in my test environment. When I did trace logging on the server, I wasn’t seeing any messages at all other than stating that listening had been started on the correct base addresses. On the client side, I was receiving the following message during the negotiation for the secure session (I’m using message encryption via certificates):

An error occurred while receiving the HTTP response to http://xx.xx.xx.xx:yy/AdvWebClient/CapacityManager. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.


I replaced the ip and port numbers for security purposes.

I worked on this for almost a day, restarting the windows service, changing configuration, staring at trace logs, etc. Finally, as a last ditch effort, I rebooted the server and everything started working. Apparently, there was some kind of hang up in the http.sys that was preventing it from processing the traffic. This is despite the listeners opening and closing (I watched using netstat) when I started and stopped the service.

Hopefully this helps anyone else who encounters this problem. If anyone knows of a way to reset the http.sys system without rebooting the entire computer, please let me know. Thanks.