LimeLM
wyBuild
Support forum
Wyatt Says...
wyDay Home

"Wyatt Says..." is a collection of articles by Wyatt O'Day talking about wyDay products and the things we've learned along the way.


Wyatt Says...

Archive for the ‘C#’ Category

Windows ServiceOver the last couple of months I’ve gotten a surprising number of questions asking about the same thing: how to debug a Windows Service like you would debug a normal Window Forms application. There are lots of hacks to pseudo-debug a Windows service like running your code from a console, or even adding a massive amount of logging throughout your code.

But what if you need to run your Windows Service as it normally runs (i.e. as an actual service) in order to track down bugs?

The good news is that’s there’s a little snippet of code to make debugging Windows Services a snap. The first thing to do is to add the following DebugMode() function to your app:

C#

/// <summary>Helper function to attach a debugger to the running service.</summary>
[Conditional("DEBUG")]
static void DebugMode()
{
    if (!Debugger.IsAttached)
        Debugger.Launch();

    Debugger.Break();
}

Visual Basic .NET

''' <summary>Helper function to attach a debugger to the running service.</summary>
<Conditional("DEBUG")>
Shared Sub DebugMode()
    If Not Debugger.IsAttached Then
        Debugger.Launch()
    End If

    Debugger.Break()
End Sub

When you call the newly added DebugMode() function within your Windows Service, if there isn’t already a debugger attached to your service it gives you the option of adding a debugger:

Moneybookers a.k.a. Skrill

Now you can debug your service like you would a Windows Forms application. Also, because you’re using the [Conditional("DEBUG")] attribute on the DebugMode() function when you compile your service in “Release” mode all the calls to the “DebugMode()” function will be removed.

Pretty cool, huh?

Moneybookers a.k.a. SkrillMoneybookers is quickly becoming a viable competitor to PayPal. And because of this our LimeLM customers have been asking for a completely automated payment form example similar to how our PayPal example works. That is, the customer enters the number of licenses they want, they click “Buy now”, they enter their info on the PayPal page, then they click “Order”, and a few seconds later the customer is magically sent their shiny new product key.

With PayPal this whole process is simple — just use the PayPal IPN (instant payment notification). That is, you specify an URL for PayPal to talk to once the order is complete. From there you can validate the order and take any action you like (e.g. sending product keys).

Moneybookers has a similar process except there are hardly any examples showing how to use it properly. And the example code that is on the web is riddled with very serious security vulnerabilities (SQL injections, failing to validate the order comes from Moneybookers, etc., etc.).

This article will show you how to use the Moneybookers equivalent to PayPal’s IPN. That is, you’ll be able to automatically generate product keys once a customer orders your software using Moneybookers. The code I post will be for both C# (ASP.NET) and PHP. If you would rather download a fully built payment form that lets you user switch between payment methods (credit card, bank transfer, PayPal, or Moneybookers), then you can signup for LimeLM and download the LimeLM Web API Pack. Here’s a screenshot of what payment form example looks like:

Payment example included in the LimeLM Web API Pack

Or, you can read on for the example that’s not specific to LimeLM.

Step 1. Signup for a Moneybookers test account

The first thing you need to do is get a test “merchant” account from Moneybookers. Unfortunately Moneybookers still doesn’t have a streamlined process for creating a test account, and their support staff is rather surly, so follow the instructions carefully:

  1. Sign up for a Moneybookers “Business account”. Do not use the same email you’ll be using for your real account.
  2. Sign up for a Moneybookers “Personal account”. Use a different email than the “Business account”. Do not use the same email you’ll be using for your real account.
  3. Contact Moneybookers and ask them to convert these 2 accounts to test accounts. It doesn’t need to be a long email. Just something simple like:

    We need you to turn 2 accounts to test accounts:

    “Buyer account”:
    Email: buyer-email@example.com
    Customer ID: 12456789

    “Merchant account”:
    Email: merchant-email@example.com
    Customer ID: 98765421

Step 2. Create a “secret word”

In your new merchant account you’ll need to create a “Secret Word” on the “Merchant tools” page:

Creating a Moneybookers secret word

Now that you’ve created your test Moneybookers accounts and set your secret word you’re ready to add the payment form to your website.

Step 3 (option 1). Use our pre-built payment form

If you’re using LimeLM you can use our pre-built payment form. Just configure a few settings, add the payment form to your site, and you’re ready to go. See the “Automate license generation with Skrill (a.k.a. Moneybookers)” article.

Step 3 (option 2). Create your own payment form

If you don’t want to use the pre-built payment example in the LimeLM API Pack, or you’re not using C#, VB.NET, or PHP, then you can still automate your orders with Moneybookers. The first step is to add the Moneybookers payment form to your website:

<form action="https://www.moneybookers.com/app/payment.pl" method="post">
  <input type="hidden" name="pay_to_email" value="merchant-email@example.com"/>
  <input type="hidden" name="status_url" value="http://example.com/verify.cgi"/> 
  <input type="hidden" name="language" value="EN"/>
  <input type="hidden" name="amount" value="Total amount (e.g. 39.60)"/>
  <input type="hidden" name="currency" value="Currency code (e.g. USD)"/>
  <input type="hidden" name="detail1_description" value="YourApp"/>
  <input type="hidden" name="detail1_text" value="License"/>
  <input type="submit" value="Pay!"/>
</form>

Change the “status_url” field to point to your script that will verify and generate the product keys and change the “pay_to_email” field to the test “merchant email” you created earlier. Then configure the price, currency code, and product name.

Optionally set your logo

You can customize the Moneybookers payment screen with your own logo. The logo must be hosted on a secure site — that is, the link must start with https:// not http://. Also, the logo must be at most 200px wide and 50px tall. If you have a logo that meets those requirements then add a “logo_url” field to your form. For example:

<input type="hidden" name="logo_url" value="https://example.com/logo.png"/>

This is an example showing what the wyDay logo looks like on the Moneybookers checkout page:

wyDay logo as seen on a Moneybookers checkout screen

Step 4. Verify the Moneybookers order

After a customer has completed their order through Moneybookers, Moneybookers will contact the script you provided in the “status_url” argument (e.g. “http://example.com/verify.cgi”). Moneybookers will POST the order information to your script and it’s up to you to verify that it’s a valid order and not just some hacker trying to get free product key from you.

Luckily Moneybookers gives the prescribed method for verifying orders in their gateway integration manual. Quoting from their manual:

A hidden text field called md5sig is included in the form submitted to the Merchant’s server. The value of this field is a 128 bit message digest, expressed as a string of thirty-two hexadecimal digits in UPPERCASE. The md5sig is constructed by performing an MD5 calculation on a string built up by concatenating the other fields returned to the status_url. Specifically the MD5 hash is a concatenation of the following fields:

  • merchant_id
  • transaction_id
  • the uppercase MD5 value of the ASCII equivalent of the secret word submitted in the “Merchant Tools” section of the Merchant’s online Moneybookers account.
  • mb_amount
  • mb_currency
  • status

PHP example code

In PHP this looks like (taken from paychecker.php):

// Validate the Moneybookers signature
$concatFields = $_POST['merchant_id']
    .$_POST['transaction_id']
    .strtoupper(md5('Paste your secret word here'))
    .$_POST['mb_amount']
    .$_POST['mb_currency']
    .$_POST['status'];

$MBEmail = 'merchant-email@example.com';

// Ensure the signature is valid, the status code == 2,
// and that the money is going to you
if (strtoupper(md5($concatFields)) == $_POST['md5sig']
    && $_POST['status'] == 2
    && $_POST['pay_to_email'] == $MBEmail)
{
    // Valid transaction.

    //TODO: generate the product keys and
    //      send them to your customer.
}
else
{
    // Invalid transaction. Bail out
    exit;
}

C# (ASP.NET) example code

In C# (for ASP.NET) this involves a bit more work. First create a simple helper function that creates the uppercase MD5 hash of a string:

static string StringToMD5(string str)
{
    MD5CryptoServiceProvider cryptHandler = new MD5CryptoServiceProvider();
    byte[] ba = cryptHandler.ComputeHash(Encoding.UTF8.GetBytes(str));

    StringBuilder hex = new StringBuilder(ba.Length * 2);

    foreach (byte b in ba)
        hex.AppendFormat("{0:X2}", b);

    return hex.ToString();
}

Then, the validation code will look something like this:

// Validate the Moneybookers signature
string concatFields = Request.Form["merchant_id"]
    + Request.Form["transaction_id"]
    + StringToMD5("Paste your secret word here")
    + Request.Form["mb_amount"]
    + Request.Form["mb_currency"]
    + Request.Form["status"];

string MBEmail = "merchant-email@example.com";

// Ensure the signature is valid, the status code == 2,
// and that the money is going to you
if (Request.Form["md5sig"] == StringToMD5(concatFields)
    && Request.Form["status"] == "2"
    && Request.Form["pay_to_email"] == MBEmail)
{
    // Valid transaction.

    //TODO: generate the product keys and
    //      send them to your customer.
}
else
{
    // Invalid transaction. Bail out
    return;
}

Step 5. Further verification, generating product keys, etc.

There’s one further step of verification I didn’t talk about: making sure the customer paid the correct amount. That is, verifying the “mb_amount” field is correct. For instance you don’t want to send a user a product key if they only pay 1 penny instead of the full amount. Also, you can further extend the payment form and the verification code to handle quantity. But this is a bit beyond the scope of the article. If you want to see that in action then download the example payment form included in the LimeLM Web API Pack.

Once you’ve verified the order you can use the limelm.pkey.generate web API function to generate product keys and email them to your customer.

Step 6. Test the payment form

Now that you have everything configured you’re ready to test your Moneybookers payment. Run through the complete payment process to see everything works how you expect it to work.

Step 7. Create a real Moneybookers account, change the setting

After you’ve finished testing your payment process you’re ready to sign up for a real Moneybookers “Business account” and change the “pay_to_email” field to the email you used to create this account.

Download full example code

We have a fully built payment page for PHP and ASP.NET (for C# and VB.NET) included in the LimeLM Web API Pack (get it on your API page). If you haven’t already signed up for LimeLM then sign up now. All plans have a 30-day free trial. Or, if you’re just putting your toes in the water, there’s even a free plan that has no time limit and doesn’t require a credit card.

In today’s article I’m going to talk about an interesting problem: detecting .NET assemblies. More than that, I’ll be talking about detecting some features of .NET assemblies and how you can expand and mold our code for your own uses. The code’s at the bottom of the article, it’s written in C# and licensed under the BSD license. Go get it.

I’ve seen this question pop up in a few different forms:

  • How do I detect .NET assemblies?
  • How can I detect the difference between .NET 2.0 and .NET 4.0 assemblies?
  • How can I detect the difference between x86, x64, and AnyCPU .NET assemblies?

And the list goes on and on. But this raises the question…

Why detect .NET assemblies?

We detect .NET assemblies because we respect humans’ time. Let me explain.

When wyUpdate (our open source updater) installs updates it can do a few things beyond simple patching, registry changing, and file copying. Namely it can:

  • NGEN assemblies
  • Install & update COM assemblies using RegAsm
  • Install & update assemblies in the GAC (Global Assembly Cache).

Which means wyUpdate needs to know whether the executable (or dll) is a .NET assembly, whether it’s strong signed, and what platform target it is (i.e. x86, x64, or Any CPU).

We could ask the user for every file, but that’s such a hassle. Who wants to waste time checking boxes for every exe and dll in their project? Rather than wasting the users’ time we quickly scan the .dll and .exe files for their details when the update is built inside wyBuild.

How not to do .NET detection

Do not use LoadLibrary(), or Assembly.Load() functions to load an assembly in memory to then parse it. This breaks when you have an x86 process trying to a load an x64 assembly (or vice versa).

How to detect .NET

Instead of using LoadLibrary (or one of its brethren) we’ll just treat the executables as dumb files. That is, just run a simple loop over the file and skip over the unneeded parts. You can check out the C# code posted at the bottom of this article, but you should be aware of 2 resources we used when designing the .NET detection algorithm:

The PECOFF spec gives you the general layout of .exe and .dll files, and the CLI Partition II gives .NET specific features that we detect. Namely, is the assembly strong signed, is it built for Any CPU or x86 alone, and what base version of the .NET framework is it built for (2.0 or 4.0).

Also, when you check out the code, notice how the code handles PE32 files versus how it handles PE32+ files. That is to say, 32-bit assemblies have a subtly different layout than 64-bit assemblies.

Tell me if you find this useful – how are you using it?

If you find this code useful, tell me how you’re using it in the comments.

Get the C# source

Download the AssemblyDetails C# source. It works with .NET 2.0, 3.0, 3.5, 4.0.

Example usage:

AssemblyDetails ad = AssemblyDetails.FromFile(filename);

// ad == null for non .NET assemblies
if (ad != null)
    Console.WriteLine(Path.GetFileName(filename) + ": " + ad.CPUVersion + ", " + ad.FrameworkVersion);
else
    Console.WriteLine(Path.GetFileName(filename) + ": Not a .NET 2.0+ executable.");

Update 7/3/2010: There was a slight bug in the first version. Re-download the code.