Signing your clickonce application with a certificate created by your own CA root

I have been investigating how to sign a clickonce application using a certificate signed by our own corporate w2k3 Certification Services. Easy enough you would think? True… but unfortunatly quite a lot of time passed between the idea and the signed application :-) Most of the samples and documentation assume you will be buying an AuthentiCode certificate from VeriSign or the likes.

The two pieces of the puzzle that made everything click are the following two url’s (in order of appearance):

Creating a certificate for code signing

http://www.leastprivilege.com/W2K3CAAndCodeSigningCertificates.aspx

Converting the certificate to a .pfx file that can be used by Visual Studio

http://www.softinsight.com/bnoyes/PermaLink.aspx?guid=78d107d1-3937-4d8d-81d9-73cb6ae18eee

Here are the steps that I took to create a certificate that can be used for signing (based on the information found at the above two links):

Step 1: Enable the code signing template

Before requesting a certificate from your CA service, you first have to enable the code signing template by using the certtmpl.msc MMC snapin. This link describes how to do that.

Step 2: Request the certificate

Go to your certificate services website and request the certificate the way you normally would, choose the options for requesting an advanced certificate. The following screen will appear (click the image for a bigger version):

There are some things to do before you click the request button though:

  • Choose Code signing under certificate template
  • Select the Mark keys as exportable checkbox
  • Select the Export keys to file checkbox that will appear
  • Enter a path and filename in the Full path name textbox (for example c:MyKey.pvk)

Leave all the other settings to their defaults (unless you know what you are doing, which I myself do not) and press the submit button.

Step 3: Ignore all the security warnings

Just click yes to all the browser based whining :-)

The browser will save the file with your private key (the one with the .pvk extension) to the location that you specified in step 2.

Step 4: Enter password and save certificate

In the screen that appears next, enter a password. After you click ok you will be presented with the option to download the certificate file (with a .cer extension). Save this file somewhere on your hard-drive, preferably at the same location as the one that you entered in step 2.

Step 5: Follow the steps on Brian Noyes’s blog

Brian Noyes has an excellent post on his blog describing the steps that need to be taken to create a pfx file. In short the steps are:

  • Download and install pvkimprt.exe
  • Run pvkimprt.exe MyCert.cer MyCert.pvk
  • Enter the password that you choose in step 4
  • Next » Next » Finish » OK
  • Run certmgr.exe from the VS Command Prompt
  • Select your imported certificate and click the export button
  • Next » (important) choose the yes, export the private key option
  • Next » Next » enter password » enter location and filename to save pfx file to » Next

Step 6: Sign your application

That’s it! You have just created a pfx file that you can use for signing your ClickOnce application. Your CA certificate needs to be trusted as a CA root by your clients and your publisher certificate (the .cer file that you created in step 2) needs to be trusted as a publisher. This can be accomplished by manually importing the certificate on the client machines or pushing the certificate out through your infrastructure tooling.

You can now take the pfx file and apply it on the signing tab of your project properties.

Remarks

Do not forget that the certificate that you created will expire in one year (unless you changed the template in certtpl.msc). There is a specific issue with ClickOnce if you re-issue a certificate with a new public/private key-pair. If you simply renew your certificate this should not be too big of an issue.

 

Hope this helps,

 

Waseem

Tagged

Edward Smit was kind enough to think of me by including me in his 5 people to tag list, so I guess it’s my turn to tell you 5 things about me that you probably didn’t know.

  • Since all the geek blogs talk about their first computer experience, I might as well keep up that tradition by telling you about my very first Compaq Pressario CDS 524 486DX2 66 Mhz. You know how all the kids watch the ads for all their favourite toys for hours; knowing that their dad probably wouldn’t get them that toy anyway… well I sure got mine :-) 

    The reason I wanted to program was because I wanted to create my own Mario Brothers clone… something that is still on my todo list today.

    My very first program was written in QBasic (which came for free with MS-DOS 6.11) and was typed over from a book that I borrowed from a local library (altough I can’t remember what the program exactly did).

    My very first real programming experience was when I created my very own ‘strafwerk-generator’  (for the dutchies) :-)

  • My parents are originally from Pakistan, my dad used to be an electrical engineer. I guess that’s where my geekiness came from.
  • I am getting maried May 2nd with the love of my life.
  • Just like Phil Haack I used to be a breakdancer during high-school. My favourite move also was the dreaded headspin… unfortunatly I never really learnt to master it.
  • I am compared to a lot of my (ex-)colleagues (except these two guys) quite young: 24 as we speak. This kind of makes it hard for me to convince people to believe me when they look at my resumé :-)

Well not really that interesting now is it? You know what I will do for a change: stop this werid tagging game, right here, right now..! Besides, most of the people that I was going to tag have been tagged allready anyway.

ps. I am getting a few blog posts ready about programming media centre addins… stay tuned

Hunting for window handles

I am working on a fairy large WinForms project and after a certain build our application suddenly started crashing. Click, click, boem… gone…. no exception, no event log entry, nothing. The annoying part was that this didn’t happened while executing inside the debugger, only when the testers were clicking around inside the application and even then very undeterministically.

If you get problems like this the first thing to do is to attach a event handler to the Application.ThreadException event to try to figure out who is causing this error:

Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);

Inside this event handler you can basically do diagnostics to find out what exception is being raised by looking at the ThreadExceptionEventArgs parameter.

So in this case the exception was “Error Creating Window Handle“… exactly the kind of exception that scares me. As Julia Lerman writes in a blog-post:

”Error Creating Window Handle” is a Win32 error, therefore the first thing I should have been looking at was any code that did anything with unmanaged items.

And it just so happened to be that one of the changes that we made to the application involved some GDI+ brushes and stuff like that. The first thing I did was making sure every brush and bitmap was disposed after being used by including them in the using pattern. Unfortunatly that alone didn’t help much.

The specific part where we were using GDI+ drawing was inside a renderer for a given tabcontrol from a third party product that we are using in this application. Our application also needs to clear this tabcontrol and re-create all the tabs again quite often (for instance when the user navigates to a new area).

My huntch was that somehow every time this tabcontrol was refilled again the old tabs were still floating around somehwere in memory and not being garbage collected, it turned out that I was right… after changing the code from simply doing a:

leftTabControl.TabPages.Clear();

…to removing and disposing each individual item…

foreach (TabPage tab in leftTabControl.TabPages)
{
    leftTabControl.TabPages.Remove(tab);
    tab.Dispose();
}

…the problem went away.

Hope this helps.

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Using generics to easy the pain of (xml) serialization

Sometimes it happens (especially when writing application frameworks) that you need to write a piece of code that needs to perform something as generically as possible. Being the OO guys that we are we tend to work a lot with polymorphism to accomplish this. Unfortunatly, polymorphism and xml serialization don’t nescessarilly go hand-in-hand that well.

Say for instance that you have a class called Response which has has a derived class called DerivedResponse1:

public class Response
{
}
public class DerivedResponse1 : Response
{
}

Nothing fancy here. The code to serialize this DerivedResponse1 class would be something like the following:

void SerializeResponse(Response response)
{
    using (MemoryStream ms = new MemoryStream())
    {
        XmlSerializer ser = new XmlSerializer(typeof(Response));
        ser.Serialize(ms, response);
    }
}

Unfortunatly this doesn’t work because the XML serializer complains about an error in the XML document (look at the InnerException to find out what the real error message is, which in this case is “The type DerivedResponse1 was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.“)

To fix this you need to exactly what the error message sais and that is to add the XmlInclude attribute to the base type like this:

[XmlInclude(typeof(DerivedResponse1))]
public abstract class Response
{
}

Ok, now comes the part where you have 70 classes deriving from Response like I did… it would be very annoying to have to attach each and every class using the XmlInclude attribute. This was kind of the problem that I had.

What I did was create a generic ‘helper’ class that I used as a container for the Response object. The class looks very simple kind of like this:

public class SerializationContainer<T> where T : Response
{
    private MemoryStream ms = new MemoryStream();
    
    public T Instance;
    
    public SerializationContainer(T instance)
    {
        Instance = instance;
    }
    
    public void Serialize()
    {
        ms.Seek(0, SeekOrigin.Begin);
        
        XmlSerializer ser = new XmlSerializer(typeof(T));
        ser.Serialize(ms, Instance);
    }
    
    public void Deserialize()
    {
        ms.Seek(0, SeekOrigin.Begin);

        XmlSerializer ser = new XmlSerializer(typeof(T));
        Instance = (T)ser.Deserialize(ms);
    }
}

The trick here is that this is a generic type and each time the serializer is invoked it creates a new serialization assembly specific to the generic type (T) using which this type is created. This way the Response base-class doesn’t need to know about all its descendants in order to be able to serialize itself. There is a performance penalty though, the Xml serializer will create a so-called serialization assembly for each generic type. Fortunatly there are ways to improve the Xml serializer’s performance.

The real power of this approach becomes apparant when doing late instantiation of the generic parameter type (ie; not knowing the exact generic parameter type at compile-time).

I have created a small sample project to demonstrate this approach. You can download it here.

Hope this helps somebody.

Firing Atlas UpdatePanels from a Flash movie

Technorati tags: , , ,

A friend of mine asked me about how to solve the following problem:

He has a Flash movie in which he can call javascript but needs to trigger an Atlas (or rather ASP.NET Ajax… sigh) UpdatePanel. In his code-behind he wants to load a different user-control based on the button that was clicked in his Flash movie.

I cooked him up a solution that generates a single line of javascript which he can copy/paste in his Flash movie and use to trigger the UpdatePanel.

The magic happens by implementing the IPostBackEventHandler interface. I created a simple control that implements this interface and exposes an event that gets called so that external observers can be notified when a postback occured:

   1:  public class RaisePostbackProxy : Control, IPostBackEventHandler
   2:  {
   3:      public event EventHandler<NewPostBackEventArgs> HandlePostback;
   4:      
   5:      public void RaisePostBackEvent(string eventArgument)
   6:      {
   7:          
   8:      }
   9:  }
 

I added this control to my aspx page and wired the HandlePostback event, now I can be notified when the user clicks any link or button in the flash movie and load the appropriate usercontrol by looking at the Argument property of the NewPostBackEventArgs parameter.

I have created a sample solution demonstrating this (very simple) approach. The solution can be downloaded here.

Hope this helps somebody.

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Google code-search

As developers we often need to look up code-samples or ways to use a certain class. There have been a few offerings in this arena, for example krugle, koders and o’reilly code search (and a few others). Now Google has weight in with their own offering called google code search. Quite interesting to see Google actually doing this since they undoubtfully have one of the biggest (if not the biggest) full-text databases out there.

It seems that at present they are only indexing a bunch of open-source projects (from the FAQ):

We’re crawling as much publicly accessible source code as we can find, including archives (.tar.gz, .tar.bz2, .tar, and .zip), CVS repositories and Subversion repositories.

The number one use of Google search when wearing the developer hat, in my opinion, seems to be searching for error messages though. I would love to see Google crunching code-related error-messages, or even better, maybe even a dedicated error message search engine? :-)

The product is still in a very early stage of development so keep an eye on it. This might just become my homepage at the office when this product matures.

Technorati tags: , ,

The .NET Framework 3.0 is here folks…

Microsoft has always had quite a bad rep with screwing up utterly cool product names (think Avalon and Indigo just to name a few) into very dull and boring names. But this time they have really outdone themselves. Not by thinking up a bad name, no sir… by thinking up a completly illogical name.

The wise people at Microsoft have decided to rename all the WinFX technologies to "the .NET Framework 3.0"… And to get back to the dull and boring naming conventions, they have decided to rename InfoCard to "Windows CardSpace (WCS)"… that even tops "Windows Communication Foundation".

So the .NET Framework 3,0 actually contains technology which requires the .NET Framework 2.0 to run… like the CLR 2.0, C# 2.0, Visual Studio 2005…. etc, now isn’t that werid? To install the .NET Framework 3.0 you need the ,NET Framework 2.0.

The thing is that having the .NET Framework 3.0 isn’t bad per sé but renaming a product to just that out of nowhere isn’t the smartest thing to do. They claim they have done this to reduce confusion amongst customers… I say it will only create more confusion…

It will be interesting to see if the next version of C# will skip the 3.0 version and go straight to 4.0 so that they can get their act together on the product versioning schemes. Bad move Microsoft.

Oh well, in the end we will all just adjust and live on.

WinFX runtime beta2 installation fails

I am upgrading my WinFX installation (including the VS tools, the SDK, etc… quite a painful process) to the latest version, which at this time is the beta2 version. But the runtime fails to install and crashes!

When looking at the error message that the installer wants to send to Microsoft you see something about a file not being signed correctly (this message can also be found in the logfile the installer wants to attach). Seems that the WinFX installer wants to install the localized dutch files for the WinFX runtime… but Microsoft is saying they will only support German and Chinese until RTM. Weird stuff.

Anyway, if you run into a failing install, try downloading the full WinFX redistributable (I didn’t even knew this one existed). It can be found on the same download page as the regular internet install, under the heading "Instructions" and is called "winfxrc.exe".

Running XQuery in a OR-Mapper world

I have a SQL2005 database based on more or less a relational model, except for one column which is of type Xml. The problem with most ORMappers is that they are unaware of the SQL2005 specific (or even Oracle-specific for that matter) features for querying and updating Xml-typed data. ORMappers look at every columns as being a property/field of your domain-object. Good enough, that’s what they are for.

But if you need to retreive a domain-object where some property should be matched against an XQuery predicate… you kind of have a problem. Here is one solution I found for this problem:

I am using Paul Wilson’s excellent ORMapper with out-of-the-box support for .NET 2.0 features (I can’t live without generics). This ORMapper has a specific feature called "Interceptors" (I know that NHibernate also has a feature which basicly does the same). By implementing the IInterceptCommand I can create a plugin that gets called before the command gets sent to the database.

Here is my code to rewrite the Sql statement in the form "where PropertyBag = @Something" to "PropertyBag.value(… @Something)". Keep in mind that this is more or less a sample and won’t work for every scenario (especially if you have queries in the form of "FirstName = @Something and PropertyBag = @SomethingElse"). But untill our ORMappers start to get aware of Xml typed data inside the database, this is one way to tackle this problem.

public class EntityLoginNameInterceptor : IInterceptCommand
{
       public void InterceptCommand(Guid transactionId, Type entityType, CommandInfo commandInfo, System.Data.IDbCommand dbCommand)
       {
            
if (entityType == typeof(Entity))
             {

                    #region Validate request parameters

                    string[] queryParts = dbCommand.CommandText.Split(new string[] { "WHERE" }, StringSplitOptions.None);

                    if (queryParts.Length == 0)
                           return;

                    if (queryParts[1].IndexOf("PropertyBag") == -1)
                           return;

                    #endregion

                    // Contains the whereClause of the CommandText
                    string whereClause = queryParts[1];

                    // ToDo: this code will stop working if the where clause has any other
                    // predicate then just ‘PropertyBag = ‘, could fix this by using regexes

                    string[] parts = whereClause.Split(‘=’);

                    if (String.IsNullOrEmpty(parts[1]))
                    {
                           throw new ArgumentNullException("PropertyBag predicate does not have a value!");
                    }

                    // Contains the XQuery to query against the PropertyBag XML column
                    string xQuery =
                           String.Format("PropertyBag.value(‘(/properties/property[@name="NTLoginName"])[1]’, ‘nvarchar(30)’) = {0}", parts[1]);

                    // Save new sql statement to the CommandText property of the IDbCommand,
                    // Watch the extra ‘(‘, this is required for the query to parse
                    dbCommand.CommandText = String.Format("{0} where ({1}", queryParts[0], xQuery);
             }
       }
}

If anybody knows a better way (or a good OR-Mapper that understands this problem), do let me know :-)

WCF services and type names

If you get the following error message while trying to run a WCF service:

Service ‘SomeServiceType‘ has zero application (non-infrastructure) endpoints.  This might be because no configuration file was found for your application, or because there was a problem with the type in the configuration file, or no endpoints were defined in the configuration file.

You might want to try to change your name attribute of your service (this attribute used to be called the type attribute in the pre-feb ctp’s) from the assembly-included name to only the class-name. You need to do the same thing with a contract.

If you had a service called Services.Foo in an assembly called Services.dll and a contract called Services.Contracts.IFoo in an assembly called Services.Contracts.dll you will get the following service configuration:

<service name="Services.Foo">
    <endpoint
        address="http://localhost:8000/FooService"
        binding="wsHttpBinding"
        contract="Services.Contracts.IFoo" />
</service>

As you can see, the assembly names aren’t mentioned. IMHO this is the right thing to do but is not quite evident becase a lot of the documentation if still pre feb-ctp. I found the solution for this problem here.

Another one of those things that kept me going for a while :-)