Archive for the '.NET' Category

Escaping characters for an XML string in .NET

Wednesday, December 10th, 2008

From the stuff I should know but didn’t until yesterday dept:

Handy method in the System.Security namespace for replacing invalid XML characters with their escaped equivalents:

SecurityElement.Escape(string str)

JScript.NET

Thursday, April 24th, 2008

From the things I didn’t know department comes JScript.NET.  What is JScript.NET?  In a nutshell, it’s a .NET version of JScript, i.e. a .NET version of JavaScript!  Why should you care about JScript.NET?  Well, here’s a scenario I had recently:

The company I work for uses Nagios to monitor it’s mission critical systems.  One common use is to simulate a user logging into a web application by POSTing credentials to a login form and checking for specific strings in the response.  This usually gives you an end-to-end check that all systems (web server, database server, etc.) related to the app are functioning.

I was asked to investigate how we could monitor one app in particular that couldn’t be checked with the simple tools included with Nagios.  This application was encrypting the user’s password two different ways using JavaScript before submitting it to the server.  To make matters worse, it was using a random key generated by the server each time the login page was opened.

Since I’m primarily a .NET developer and have very little experience with *NIX systems and PERL (most Nagios plug-ins are written in PERL), my approach was to build a simple web page that Nagios could check that would act as a proxy to this particular app.  This still left me with the problem of how to simulate what the browser was doing in JavaScript. 

One solution would be to translate the JavaScript to C#.  Another would be to try to host the Windows scripting engine in my .NET app and invoke the existing scripts as-is.  Or maybe I could write a "classic" ASP page using JScript.  None of these options appealed to me much, so I consulted Google.

I eventually came across JScript.NET.  I knew about J# (Microsoft’s attempt to lure Java programmers to the .NET platform), but what the heck is JScript.NET?  When I create a new project in Visual Studio, there’s no JScript options…

Hidden away in the .NET SDK is jsc.exe, the JScript.NET compiler.  So, now it was just a matter of taking the JavaScript code I wanted to use from C# and compiling it using jsc /t:library <source file> and I had a DLL I could reference and call.  A few minor tweaks were needed, like wrapping stuff in a class, but overall it was pretty painless and it worked!

Not sure if I’ll ever need to do something like this again, but it’s nice to know JScript.NET is there…

Crash Course in VSTO

Thursday, December 6th, 2007

I’ve inherited yet another project at work. This latest one includes a series of reports all done in Excel with VBA macros. The code for these macros is almost unmaintainable, so I’m trying get these rewritten using Visual Studio Tools for Office (VSTO). This is my first experience with VSTO and right now I’m in the “proof of concept” stage, struggling with deploying a test case using ClickOnce.

So far, here’s what I’ve learned:

  • Visual Studio 2008 ships with VSTO “in the box”
  • There are several options, depending on if you want to target Office 2003, 2007, .NET 2.0, 3.0, 3.5
  • You can’t target 2007 specifically and use anything but .NET 3.5
  • Only .NET 3.5 supports deploying VSTO solutions using ClickOnce

As I write this, I’m testing using IIS 7 running under Vista (yes, I’m a glutton for punishment) for my publishing location and have Windows XP running under Virtual PC with Office 2003 for testing the deployment. So far I’ve had several attempts at getting the bootstrap to download and install .NET 3.5 and the VSTO runtime. To work around a couple of the problems I had to manually add application/octet-stream MIME types to IIS for the .MSP and .MSU files that are part of the .NET Framework redistributable.

Everything is downloading now, but the install failed with a “Status of package ‘.NET Framework 3.5′ after install is ‘InstallFailed’” in the installer log file. I’ll update this post once I get that figured out…

UPDATE: Rebooted the VPC and now the .NET Framework installed. Gotta love it.

UPDATE: Needed another MIME type set up for .vsto files: http://msdn2.microsoft.com/en-us/library/bb608629(VS.90).aspx

UPDATE: And after all of that, it doesn’t work with Excel 2003. I get the error: The common language runtime could not be loaded by Excel file path. Contact your administrator for further assistance. I thought maybe if I used the Office 2007 VSTO project template, but saved the Workbook using the 97-2003 compatible format I could open it in Excel 2007 or 2003. No such luck. Looks like if you want to use VSTO + ClickOnce, you have to target Office 2007 users…

Got Athlon? No Silverlight For You!

Friday, October 12th, 2007

Bummer. We’ve got an older 1.4Ghz Athlon PC here in our family room and Silverlight does not run on this chip, according to this thread: http://silverlight.net/forums/t/5590.aspx

Someone should update the Silverlight system requirements, as there’s no mention of this. That page says all you need is a “X86 or x64 500-megahertz (MHz) or higher processor with 128-megabytes (MB) of RAM”. Apparently, Silverlight needs a processor that supports SSE instructions, witch the original Athlon chip lacks. AMD added that feature in the Athlon XP.

Tafiti - Microsoft Live Search with Silverlight

Friday, October 12th, 2007

This is pretty cool: http://www.tafiti.com/

I think my favorite feature is the newspaper layout for the news results. This might actually get me to use Live search once in while instead of Google, although I’m not so sure about the usability. The font size for the web results seems a bit small and I’m not so sure about the two-column layout (but this might be because I’m so used to seeing the summary below each result). The tree view seems to be there purely as eye candy, I can’t how this is usable at all…

Another Workaround for Expired ClickOnce Code Signing Certificates

Wednesday, May 16th, 2007

Daniel Margetic has posted a workaround for updating a ClickOnce application that has been deployed with an expired Authenticode certificate.  I wrote about this problem back in January and came up with a kludge that involved automatically uninstalling the app and reinstalling from a new location.

Daniel’s solution uses a newer version of the code signing tool, included in the Windows Server R2 SDK, that allows you to sign with two different keys - one for Authenticode and one for the manifest’s “strong name”.  Basically, you continue to sign the manifest using the key from the expired cert and generate the Authenticode signature using the renewed certificate.

Details at Daniel’s blog:
http://blogs.msdn.com/danielma/archive/2007/03/19/clickonce-and-expired-certificates.aspx

ASP.NET Version Mismatch

Saturday, April 28th, 2007

A colleague was modifying an in-house ASP.NET 1.1 application this past week to use a corporate authentication service. This service works via HTTP redirects from the application to the service and then back to the application, once the user is authenticated. A “ticket” is returned to the calling application, where it is validated and stored in a cookie using ASP.NET Forms Authentication.

My colleague modified the web.config file of his app to use Forms Authentication (it had previously used Windows authentication) and setup a login page that redirected to the corporate authentication service. Everything worked fine, until the next day when he reopened his Visual Studio 2003 solution for this app and was greeted by an “ASP.NET Version Mismatch” dialog that claimed his web server was configured for ASP.NET 1.0. The choices where to cancel opening the web project or make the application “1.0″ compliant (whatever that means).

ASP.NET Version Mismatch

He then sought out my assistance and I suggested we use aspnet_regiss.exe to re-register ASP.NET 1.1 with his web server (thinking that the IIS configuration somehow got mangled). That didn’t help. We then turned to Google for answers and after following several wrong turns, each providing clues as to what the real problem was, came up with a solution.

This MS knowledge base article provides some clues as to what is really going on: http://support.microsoft.com/kb/827074

Although the suggested workaround didn’t work, the important piece of information is the reference to the Get_aspx_ver.aspx ASP.NET page. See, Visual Studio 2003 does a GET on this non-existent page using your web project’s virtual folder. You can verify this by examining the IIS logs. Since my colleague had enabled Forms Authentication, this request got redirected to the login page which in turn REDIRECTED VISUAL STUDIO TO A SITE THAT WAS NOT EVEN RUNNING ASP.NET (the corporate authentication server). Visual Studio checks for the ASP.NET version in the HTTP response headers and displays the dialog above when the version doesn’t match the expected ASP.NET 1.1 version.

The fix is simple. Add the following to the web.config file to allow anonymous users (in this case, Visual Studio) to access get_aspx_ver.aspx:

<location path=”get_aspx_ver.aspx”>
   <system.web>
     <authorization>
       <allow users=”?”/>
     </authorization>
   </system.web>
</location>

(this goes after the system.web section)

iTunes 7.1.x Causes LoaderLock Exceptions When Running Windows Forms in the Debugger

Thursday, April 5th, 2007

I got burnt by this today.  Seems that the latest version of iTunes for Windows (which I installed this morning) really messes with Visual Studio 2005.  The 1st keystroke entered into a Windows Forms app running in the VS debugger causes VS to throw a “LoaderLock” exception.  This only happens if iTunes is running - shut it down and everthing works normally.

Here’s a discussion about the problem on the MSDN forums:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1332045&SiteID=1

The last comment is from someone at Microsoft pointing the finger at one particular iTunes DLL, named iTunesKeyboardCompatibility.dll.  Maybe they should have named it iTunesKeyboardIncompatibility.dll.

Taking this bit of info, I tried deleting the file and running iTunes.  But the self-healing Windows Installer technology restores the dll on startup.  I shut down iTunes and deleted the file once more, but this time I created a zero-length file of the same name to take its place.  This prevented the original file from being restored when iTunes was started back up.  It immediately complained about the “dll” I created, but after dismissing the error, iTunes and Visual Studio both worked just fine.

I could once again listen to The LOST Podcast with Jay and Jack while debugging my code.

ClickOnce and Expiring Code Signing Certificates

Thursday, January 18th, 2007

There’s a really nasty bug in .NET 2.0’s ClickOnce deployment technology. If you deploy a smart client as availaible “off line” (launchable from the start menu) and you sign your manifest with a certificate from an official certificate authority (such as Thawte or VeriSign), you cannot renew your certificate and deploy to the same location! If you do, the next time someone starts your client it will barf up an error and won’t start. Examining the log will reveal the problem in the somewhat cryptic message “The deployment identity does not match the subscription”.

The problem is that the certificate authorities issue “renewed” certificates with a different private key. This makes up part of the ClickOnce app’s “identity” and ClickOnce validates this when starting an app to prevent tampering.

The only workaround is to uninstall and reinstall the app via the add/remove programs control panel applet. This really puts a kink in the whole “click once” thing, doesn’t it? I ran into this issue recently at work, as our code signing certificate was set to expire. Since I’m experienced enough to never trust Microsoft to do the right thing, I tested the “renewed” certificate in a test environment. Several Google searches later, I see that I’m not alone in discovering this problem.

To avoid having over 200 users fart around in the “add/remove programs” control panel applet, I came up with a kludge to have the client application uninstall itself and launch the ClickOnce installer, signed with the new certificate, from a new location. So after deploying the client signed with the new certificate, I deploy an update with the old certificate that contains the “reinstall” logic. Part of this trickery involves obtaining the “Public Key Token” for your app (I believe this comes from the certificate used to sign the ClickOnce manifest). The following snippet illustrates how to determine the public key token programmatically:

/// <summary>
/// Gets the public key token for the current ClickOnce app.
/// </summary>
private static string GetPublicKeyToken()
{
    ApplicationSecurityInfo asi =
        new ApplicationSecurityInfo(
                    AppDomain.CurrentDomain.ActivationContext);
    byte[] pk = asi.ApplicationId.PublicKeyToken;
    StringBuilder pkt = new StringBuilder();
    for (int i = 0; i < pk.GetLength(0); i++)
        pkt.Append(String.Format(“{0:x}”, pk[i]));
    return pkt.ToString();
}

Next, we need to find the uninstall string in the registry, based on the PublicKeyToken:

/// <summary>
/// Gets the uninstall string for the current ClickOnce app from the
/// Windows Registry.
/// </summary>
/// <param name=”PublicKeyToken”>The public key token of the app.
/// </param>
/// <returns>The command line to execute that will uninstall the app.
/// </returns>
private static string GetUninstallString(string PublicKeyToken,
  out string DisplayName)
{
    string uninstallString = null;
    string searchString = “PublicKeyToken=” + PublicKeyToken;
    RegistryKey uninstallKey = Registry.CurrentUser.OpenSubKey(
        “SoftwareMicrosoftWindowsCurrentVersionUninstall”);
    string[] appKeyNames = uninstallKey.GetSubKeyNames();
    DisplayName = null;
    foreach(string appKeyName in appKeyNames)
    {
        RegistryKey appKey = uninstallKey.OpenSubKey(appKeyName);
        uninstallString = (string)appKey.GetValue(“UninstallString”);
        DisplayName = (string)appKey.GetValue(“DisplayName”);
        appKey.Close();
        if(uninstallString.Contains(searchString))
            break;
    }
    uninstallKey.Close();
    return uninstallString;
}

I then launch the uninstaller, using the Process class, and use some Interop calls to the Win32 API to find the uninstaller window and automatically “push” the “OK” button (would have been nice if the was a /silent switch so I wouldn’t have to do this). Finally, I launch ClickOnce for the new version of the client, signed with the new certificate, to update the user’s workstation. A zip file with this source code can be found here: ClickOnceReinstall.zip Using these utility classes, I just insert the following code into the client’s startup routine to make it reinstall itself:

// Self-uninstall
Utils.DeploymentUtils.UninstallMe();
Utils.DeploymentUtils.AutoInstall(
  “http://host-name/deployment-folder/MyApp.application”);
Application.Exit();
return;

Napkin Look & Feel for Java Prototypes

Thursday, December 28th, 2006

Java Swing is often criticized for its lack of native widgets. Controls in Swing are rendered by Java code, rather than the underlying OS. This can create problems like having a Java app that doesn’t have the same “look & feel” as applications that run natively on any given OS. Java Swing addresses this issue by supporting pluggable “look & feel” libraries. Basically, for each operating system/windowing system that you want to support with a native look & feel, you have to obtain/write a look & feel library. There are a few that come with the Java runtime, depending on what OS the runtime is for (i.e. the Apple OS X Aqua look & feel only come with Apple’s JRE). Swing has also had a bad reputation for being slow, although in the latest JRE this seems to be a thing of the past.

The “Napkin Look & Feel” project uses Swing’s lack of native widgets to it’s advantage. It’s a Java pluggable look and feel that makes your application’s UI look like it was scrawled on a napkin. Novelty of it aside, this is great for making prototype UIs that really convey the message: “This is a prototype and nowhere near a completed application”. Kathy Sierra wrote a great post about the various reasons you want to send this message.

Anyway, I thought this was a great example of turning a weakness (or perceived weakness) into a strength. Now I wish I could do this in .NET…