Molokai on 256-Color Terminals

Link. January 4, 2009. Comments [2]. Posted in: Linux | Vim

I’ve posted an update for my Molokai color scheme for Vim that now supports the terminal version of Vim on terminals capable of displaying 256 colors.

I don’t use the terminal version of Vim as often as GVim, but it is still occasionally useful, and I hated having to use two different color schemes; one on the GUI version and one on the terminal.

Of course, both are not exactly the same, since the terminal capabilities are still restricted, but they look fairly similar. The following screenshot shows GVim (left) and Vim on gnome-terminal (right) running side by side with the new molokai version:

molokai_console

You can get the updated script from the Vim site or from my dotfiles repository at GitHub.

BizTalk 2009 Testing Features

Link. January 1, 2009. Comments [0]. Posted in: BizTalk

Warning: This post is about a beta product. Details might change before final release.

The beta of BizTalk Server 2009 brings a welcome new feature: Some basic support for Unit Testing BizTalk artifacts; specifically for Pipelines, Maps and Schemas.

You can read the basics about how the new feature works in the product documentation; there’s not too much yet, but it’s enough to get a good idea of how you use it.

I’d like to now share a few thoughts on this feature. Note: This is just my personal opinion from playing with the API for a bit.

The Good

The first really good part about this feature is the fact that it even exists at all. Facilities for creating and automating tests of BizTalk artifacts has been a sorely lacking area of the product.

While Visual Studio had the Test option for maps and schemas since BizTalk 2004, and it was sort of useful, it required way too much manual intervention and there was no way to decently drive it through automation, making it useless for either unit or regression testing.

The second thing I like about the unit testing feature is that, in it’s current incarnation, it’s not intrinsically tied to MSTest (i.e. the Visual Studio Team System stuff). This means you can use it with NUnit, xUnit, or your favorite testing tool.

The third interesting thing about the API is that it is a very simple API. In most cases it really consists of just a single method call. Here’s an example of testing a schema:

string fin = @"c:\temp\test1_in.xml";
Schema1 schema = new Schema1();
Assert.IsTrue(schema.ValidateInstance(fin, OutputInstanceType.XML));

The Not-so-Good

Not everything is rosy in BizTalk-land. Personally, I was somewhat underwhelmed by the implementation of the Unit Testing features available in beta 1; particularly since some of it could be addressed with fairly minor adjustments.

API Issues

Let’s start with the API: I mentioned before that the new testing API was simple. However, it’s actually too simple. For example, consider the small test for a schema I presented above: You simply create an input file to test with, call ValidateInstance() and check the result. Great, no?

Well, if the test succeeds, then yes, it’s just fine. If it fails, however, because the input file does not pass validation, then, it turns out, it’s missing one extremely important functionality: There’s no way to get any details about why the schema validation failed [1].

This means that diagnosing a failed test involves, at the very least, changing your project settings in VS to use the failed input file as input to the schema in VS, use the Validate Instance option in the IDE and examine the results in the output window, where fortunately you do get more detailed error information.

This is extremely sub-optimal and requires way too much manual work. Can you imagine if a change in a schema broke tens of tests and having to do this for each and every single one of those? Ouch!

Another place where I feel the current API is not as nice as it could be is that it’s strictly file-based. That is, you need to create actual files on disk to represent inputs to the tests and store the resulting outputs. This is somewhat convenient for many scenarios, and matches the existing functionality in BizTalk pretty well. It does, however, make it very inconvenient to deal with dynamically generated inputs or inputs stored someplace else.

The classic example here, would be, resources. For example, I very much like to keep my unit tests as independent from the environment and as self-hosting as possible. One very nice way of doing this is to store necessary input files as embedded resources on my testing assembly. I do this all the time with PipelineTesting and it works great. However, since you can’t provide streams instead of file paths to the BizTalk 2009 testing features, you’d need to first save the embedded resource to a temporary file, which adds a bit of friction to the process.

Compilation Changes

My biggest gripe with the Unit Testing features, is that enabling them implies a change in the build process, that changes the generated code for the BizTalk artifacts themselves.

When you enable the Unit Testing option in Project –> Properties –> Deployment, the compilation process will change the generated CLR types so that they inherit from the TestableXXX classes defined in the Microsoft.BizTalk.TestTools.dll assembly, instead of the normal BizTalk artifact classes.

These new Testable base classes, in turn, derive from the original BizTalk classes, so the change isn’t all that big. However, it does smell wrong. Could it introduce any problems/bugs if you were to enable the testing features for all builds? Hopefully no, but no way to know until you run into them.

Of course, you could just enable Unit Testing for debug builds, but then you can’t run your unit tests on the release builds of your BizTalk assemblies. It also introduces yet another asymmetry between development and deployment builds which, to be honest, makes me somewhat nervous.

Conclusion

The new Unit Testing features in BizTalk Server 2009 are a sorely needed and welcome feature, if somewhat lacking in the first beta.

Will it improve? On one hand, I’m somewhat optimistic that some improvements might make an appearance in forthcoming builds. However, I’m also not getting my hopes up, as MS is notable for trying to avoid significant API changes during after beta 1 hits the street (BizTalk, unfortunately, doesn’t use the CTP model, where significant API change requests are more likely to be considered).

[1] TestableMap.TestMap() does throw exceptions on failure instead of a Boolean return value, but said exceptions might not contain detailed error information.

D820, Ibex and Hibernate

Link. December 30, 2008. Comments [0]. Posted in: Linux

I recently mentioned that I had installed Ubuntu 8.10 Intrepid Ibex on my Dell D820 and that it was working mostly fine, except for the hibernate functionality.

Last Monday (Dec. 22nd), the mainboard on my D820 died. Fortunately, it was still under warranty, so I called Dell Service the next morning and on the afternoon of the 24th someone came by and replaced the board. Definitely a lot speedier than I expected and it was a very nice touch.

Anyway, couple of days later I figured out why hibernate didn’t work: I had no swap partition at all! I had simply ignored it when installing Ubuntu because I wasn’t sure if I was going to keep it that way or format it later to install something else.

So I fired up GParted, added a new swap partition and enabled it, roughly following this guide, properly adjusted to my system.

After that, I just needed to edit my GRUB configuration (/boot/grub/menu.lst) so that the kernel boot options included the “resume” option pointing to the new swap partition (in my case, “resume=/dev/sda4”).

For the most part, seems to be working nicely now. I still wish the system had just issued a warning or error when I tried to hibernate it without an active swap partition. I mean, if it’s not supposed to work, it shouldn’t fail so miserably.

BizTalk Server 2009 MSBuild Tasks

Link. December 26, 2008. Comments [1]. Posted in: BizTalk

I’ve been looking around the new project system introduced in the BizTalk Server 2009 beta. As you might have heard before, it’s now based on MSBuild. This is an extremely welcome change from the obscure compilation model in previous BizTalk versions that caused so much frustration.

BizTalk Projects now look much like regular C# projects (they even have the same icon in solution explorer) but they can contain BizTalk artifacts like schemas, orchestrations, maps and pipelines.

Opening up the .btproj file reveals some of the differences and custom MSBuild tasks used by the new BizTalk project system. Two things are initially important to mark an MSBuild file as a BizTalk project.

The first one is the <ProjectTypeGuids/> value:

<ProjectTypeGuids>{EF7E3281-CD33-11D4-8326-00C04FA0CE8D};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

This means:

  • {EF7E3281-CD33-11D4-8326-00C04FA0CE8D}: This represents the BizTalk project factory, and tells VS where to find the item templates for BizTalk artifacts and so on.
  • {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}: This represents the C# project system.

So, in fact, a BizTalk Project is a C# project. Right now you can’t add C# artifacts to the project without editing the .btproj file by hand, but one can hope this will be supported in upcoming builds.

The second part important to making a .btproj is importing the BizTalk MSBuild tasks, which is accomplished by this line:

<Import Project="$(MSBuildExtensionsPath)\Microsoft\BizTalk\BizTalkC.targets" />

If we look at the BizTalkC.targets file, we can see that the BizTalk MSBuild tasks are implemented in the Microsoft.VisualStudio.BizTalkProject.BuildTasks assembly, which you'll find in your 'Microsoft BizTalk Server 2009\Developer Tools' folder.

Global Project Properties

There are several properties that will get set in the project files depending on your project settings that are BizTalk-specific:

  • <BpelCompliance/>: This is a Boolean (true, false) property that indicates if the generated assembly should be marked as BPEL compliant (I think).
  • <EnableUnitTesting/>: Corresponds to the Enable Unit Testing option in the Deployment tab of the project settings dialog, and controls whether the unit testing features for pipelines, schemas and maps are enabled.

Other settings are per-user settings and stored in the .btproj.user file:

  • <Server/>: The name of the SQL Server instance that has the BizTalk databases for deployment.
  • <ConfigurationDatabase/>: The name of the BizTalkMgmt database.
  • <ApplicationName/>: The name of the BizTalk application you want to deploy to.
  • <Redeploy/>: Boolean property that indicates if you want to allow redeployments from within Visual Studio.
  • <RestartHostInstance/>: If true, the BizTalk hosts will be restarted after each deployment.
  • <Register/>: If true, the generated assembly will be registered in the Global Assembly Cache (GAC).

Per-File Project Properties

The per-user project file (.btproj.user) can also include a bunch of item-specific properties, which are visible when you select a file in Solution Explorer and open the Properties window.

In this category you’ll find properties for setting paths for map input and output files for testing/debugging as well as paths for input and output files for testing schemas.

Here’s an example:

<File Path="E:\Projects\BizTalk\PipelineTesting\SampleSchemas\Map1.btm">
   <ValidateTestMapInput>True</ValidateTestMapInput>
   <ValidateTestMapOutput>True</ValidateTestMapOutput>
   <TestMapInputInstanceFilename></TestMapInputInstanceFilename>
   <TestMapOutputInstanceFilename></TestMapOutputInstanceFilename>
   <TestMapSourceType>0</TestMapSourceType>
   <TestMapTargetType>0</TestMapTargetType>
   <EditorOutputInstanceFilename></EditorOutputInstanceFilename>
   <EditorInputInstanceFilename></EditorInputInstanceFilename>
   <GenerateInstanceOutputType>0</GenerateInstanceOutputType>
   <ValidateInstanceInputType>0</ValidateInstanceInputType>
   <PropertySchemaFileName>PropertySchema.xsd</PropertySchemaFileName>
   <AutoRefreshSchema>0</AutoRefreshSchema>
</File>
<File Path="E:\Projects\BizTalk\PipelineTesting\SampleSchemas\NoNS.xsd">
   <ValidateTestMapInput>True</ValidateTestMapInput>
   <ValidateTestMapOutput>True</ValidateTestMapOutput>
   <TestMapInputInstanceFilename></TestMapInputInstanceFilename>
   <TestMapOutputInstanceFilename></TestMapOutputInstanceFilename>
   <TestMapSourceType>0</TestMapSourceType>
   <TestMapTargetType>0</TestMapTargetType>
   <EditorOutputInstanceFilename></EditorOutputInstanceFilename>
   <EditorInputInstanceFilename></EditorInputInstanceFilename>
   <GenerateInstanceOutputType>0</GenerateInstanceOutputType>
   <ValidateInstanceInputType>0</ValidateInstanceInputType>
   <PropertySchemaFileName>PropertySchema.xsd</PropertySchemaFileName>
   <AutoRefreshSchema>0</AutoRefreshSchema>
</File>

Building Pipelines

To build a pipeline, you can use the PipelineCompilerTask:

<ItemGroup>
   <Pipeline Include="CSV_FF_RecvPipeline.btp">
      <Namespace>SampleSchemas</Namespace>
      <TypeName>CSV_FF_RecvPipeline</TypeName>
   </Pipeline>
</ItemGroup>

Building Schemas

BizTalk Schemas can be compiled using the new SchemaCompiler task:

<ItemGroup>
   <Schema Include="Schema1_NPP.xsd">
      <Namespace>SampleSchemas</Namespace>
      <TypeName>Schema1_NPP</TypeName>
   </Schema>
</ItemGroup>

Building Maps

BizTalk Maps can be compiled using the new MapperCompiler task:

<ItemGroup>
   <Map Include="Map1.btm">
      <TypeName>Map1</TypeName>
      <Namespace>SampleSchemas</Namespace>
      <SubType>Task</SubType>
   </Map>
</ItemGroup>

I'm not sure yet what the <Subtype/> element does.

Building Orchestrations

BizTalk Orchestrations can be built with the new XLangTask:

<ItemGroup>
   <XLang Include="BizTalk Orchestration1.odx">
      <TypeName>BizTalk_Orchestration1</TypeName>
      <Namespace>SampleSchemas</Namespace>
      <SubType>Task</SubType>
   </XLang>
</ItemGroup>
<ItemGroup>

PipelineTesting and BizTalk 2009

Link. December 24, 2008. Comments [0]. Posted in: BizTalk

Now that the a public beta release of BizTalk Server 2009 is out, I thought I’d download it and try building and testing PipelineTesting on the new release.

After downloading and installing the beta, I proceeded to import the existing Visual Studio 2005 project file into Visual Studio 2008 with the new BizTalk project system (a huge improvement over the old one, if I may say so [1]). The import worked just fine overall.

The only change I had to make was remove the reference to PipelineObjects.dll from the projects and add it again with the new version in BizTalk 2009. The new version seems to be slightly different than the one in R2 (it’s 3KB smaller), but I haven’t looked closely to see what the differences might be.

In either case, PipelineTesting builds perfectly with the new version, and all Unit Tests are still passing in the green!

[1] I did hit a small snag with the project system: When building the imported solution, only the SampleSchemas project gets built, though all are selected to build in the configuration manager. Had to manually build the other projects from the project context menu.

Crashing your Process with Timers

Link. December 22, 2008. Comments [0]. Posted in: .NET

Here’s a bug I had to diagnose this weekend that had me scratching my head for a bit before getting it. Consider this sample piece of code [1]:

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Principal;
using System.Text;
using System.Threading;

namespace Winterdom.Samples {

   class Program {
      private const int LOGON32_PROVIDER_DEFAULT = 0;
      private const int LOGON32_LOGON_NETWORK = 3;

      [DllImport("advapi32.dll", SetLastError = true)]
      public static extern bool LogonUser(
          string lpszUsername, string lpszDomain, string lpszPassword,
          int dwLogonType, int dwLogonProvider, out IntPtr phToken
          );

      static void Main(string[] args) {
         AppDomain domain = AppDomain.CurrentDomain;
         domain.UnhandledException += (sender, e) =>
            Console.WriteLine(e.ExceptionObject.ToString());

         WindowsIdentity wi = new WindowsIdentity(GetLogon());
         WindowsImpersonationContext wic = wi.Impersonate();

         Timer timer = new Timer(
               (state) => {}, // do nothing on the callback!
               null, 3000, 3000
            );

         wic.Undo();
         // If we remove this line, no crash happens!
         wi.Dispose();

         Console.WriteLine("Wait for the crash!");
         Console.ReadLine();
      }

      static IntPtr GetLogon() {
         String user = "<USER HERE>";
         String pwd = "<PASSWORD HERE>";

         IntPtr token = IntPtr.Zero;
         bool success = LogonUser(
            user, ".", pwd, LOGON32_LOGON_NETWORK,
            LOGON32_PROVIDER_DEFAULT, out token
            );
         if ( !success )
            throw new System.ComponentModel.Win32Exception();
         return token;
      }

   }
}

Now put a valid username/password in GetLogon() and run it. Then watch the application crash with an unhandled exception in a secondary thread. You should’ve spotted an exception like this one:

System.ObjectDisposedException: Safe handle has been closed
   at System.Security.Principal.Win32.ImpersonateLoggedOnUser(SafeTokenHandle hToken)
   at System.Security.Principal.WindowsIdentity.SafeImpersonate(SafeTokenHandle userToken, WindowsIdentity wi, StackCrawlMark& stackMark)
   at System.Security.Principal.WindowsIdentity.Impersonate(StackCrawlMark& stackMark)
   at System.Security.SecurityContext.SetSecurityContext(SecurityContext sc, SecurityContext prevSecurityContext, StackCrawlMark& stackMark)
   at System.Threading.ExecutionContext.SetExecutionContext(ExecutionContext executionContext)
   at System.Threading.ExecutionContext.runTryCode(Object userData)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading._TimerCallback.PerformTimerCallback(Object state)

Why does it happen?

The problem appears because we impersonate an identity and soon after destroys the WindowsIdentity instance used to create impersonation token.

Between those two moments, we start a timer. When that happens, the runtime will capture the state of the calling thread, including its SecurityContext, and save it so that it can restore it on the background thread used to invoke the timer callback.

Since we destroy the WindowsIdentity instance soon after starting the timer, by the time the callback tries to fire, the authentication token has been closed already. The problem is that the framework makes no attempt to verify that the security context it saved is still valid before trying to impersonate the identity on the callback thread as well.

This leads to an unhandled exception which, on .NET 2.0, will cause your process to crash inevitably. It’s fair to say, though, that even if the framework actively checked for this condition and found that the authentication token was no longer valid, there would not be much else it could do, since it might be a bit dangerous to simply ignore it and invoke the thread on the original process security context (or at least it would lead to some unexpected behavior).

The bad part

The bad part about this issue is that you really don’t know who might be starting a new timer (or any other framework facility that saves the SecurityContext for later use) in between your Impersonate() and Undo() calls.

For example, the original code I was tracking this problem in was a lot more complex, involving a custom Windows PowerShell host and the invoke-sqlcmd cmdlet that comes with SQL Server 2008. In that scenario, the problem wasn’t invoke-sqlcmd per se.

It just turned out that the ADO.NET Connection Pooling facilities will create background timers to handle cleanup of the connection pools the first time you get a new connection from the pool.

The really nasty part, however, was that the timer is created with a random interval, which meant you could never be sure when the process would crash: Sometimes it would happen just a few seconds after disposing the WindowsIdentity instance, sometimes several minutes later. This made figuring out the problem a lot harder.

[1] Yes, I’m aware the sample is leaking a handle, but that’s not really the problem.

Using NetBeans

Link. December 21, 2008. Comments [0]. Posted in: Java | Tools

A few months ago I mentioned I had started using NetBeans 6.1 for my java development instead of Eclipse, which was my tool of choice until then. The reason for the change at that time was that I needed to look into some JBI stuff and using NetBeans + Glassfish was a natural choice for that.

By the time I was through with that project and had started to work on other things I realized that I had grown rather used to NetBeans and actually preferred it over Eclipse! Both are excellent developer environments, but I actually like the NetBeans UI a little better and sort of found it nicer to use overall.

A couple of weeks ago I finally moved to NetBeans 6.5, the latest release, and it’s been working pretty nicely for me. A few things have contributed to this:

A decent color scheme

The default NetBeans configuration isn’t very usable for someone that prefers dark color schemes on their editor like me; and doesn’t include many default choices.

However, I found the additional Ruby themes plugin, which includes the Aloha and Dark Ruby Pastels schemes. I disliked the second (too similar to Vibrant Ink, which I hate), but Aloha was fairly nice.

With a bit of customization of Aloha to tweak it a bit for Java code I ended up with something looking like this:

netbeans

You can install the extra ruby themes from the Tools –> Plugins menu option.

jVi

It’s not secret I’m a Vim user, and I rather like the way Vim handles editing text and the its modal behavior. In Visual Studio, I use the most excellent Viemu plugin, which is the only plugin I consider a must-have these days. I’ve written about Viemu before.

NetBeans, however, didn’t have anything like this, or so I thought, until I ran into jVi on sourceforge. What a fantastic tool! It’s actually a subset of Vim embedded into NetBeans and supporting the modal editor behavior and all the common key bindings and operations.

I downloaded the alpha for NetBeans 6.5 and it’s been extremely stable for me and working great! I love it!

jvi

One downside with jVi I ran into is that it’s configured through it’s own set of settings, some of which overlap (and take precedence) over the NetBeans one, like the tab behavior. But once you’ve configured it to your liking it works very nicely, though occasionally conflicts a little bit with NetBeans functionality (not often, though).

What I don’t like about NetBeans

NetBeans does have a couple of issues that nag me. One is that memory usage is still fairly high (usually around 200MB), however, the slowdowns that I used to see after extended use with 6.1 don’t seem to happen with 6.5 anymore, but I’m not sure if that’s because of changes in NetBeans itself or because I finally bit the bullet and installed JDK 1.6 to run it.

The second issue is startup time: It still takes forever to load from scratch. Fortunately, performance once it finishes loading is quite acceptable and the editor is usually very responsive, so it hasn’t been that much of an issue. It helps a lot that I usually just leave it open and save the state of my VMs instead.

I still turn to Vim whenever I need to do some quick editing and don’t need the full IDE, but then again, I also do that for C# code. That said, VS 2008 usually loads a lot faster than VS2005 for me, so this is less of an issue there (it helps that I don’t install as much crap as I did for 2005).

get-hash

Link. December 19, 2008. Comments [1]. Posted in: PowerShell

I’ve been recently working a lot with cryptographic hashes and sometimes it was useful to be able to check results or hash strings on my own while debugging or diagnosing something.

I started doing this so much, that ended up creating a few Windows PowerShell functions to deal with this:

function convert-tobinhex($array) {
   $str = new-object system.text.stringbuilder
   $array | %{
      [void]$str.Append($_.ToString('x2'));
   }
   return $str.ToString()
}
function convert-frombinhex([string]$binhex) {
   $arr = new-object byte[] ($binhex.Length/2)
   for ( $i=0; $i -lt $arr.Length; $i++ ) {
      $arr[$i] = [Convert]::ToByte($binhex.substring($i*2,2), 16)
   }
   return $arr
}
function get-hash($value, $hashalgo = 'MD5') {
   $tohash = $value
   if ( $value -is [string] ) {
      $tohash = [text.encoding]::UTF8.GetBytes($value)
   }
   $hash = [security.cryptography.hashalgorithm]::Create($hashalgo)
   return convert-tobinhex($hash.ComputeHash($tohash));
}

Not very efficient, but does the trick.

Syndicate

About

Tomas Restrepo is a software developer located in Colombia, South America. His interests include .NET, Connected Systems, PowerShell and lately dynamic programming languages. More...

tomasrestrepo @ twitter My Flickr photostream My saved links on delicious My Technorati Profile

email: tomas@winterdom.com
msn: tomasr@passport.com

View my profile on LinkedIn

MVP logo

Ads


Categories

Statistics

Total Posts: 1050
This Year: 1
This Month: 1
This Week: 0
Comments: 826

Archive

Other

Copyright © 2002-2008, Tomas Restrepo.

Powered by: newtelligence dasBlog 2.2.8279.16125

Sign In