ASUS ROG G501JW recovery image

About a year ago, I tried to downgrade my ASUS G501 laptop to Windows 7. It was a miserable failure, with driver support severely lacking; I decided to give up and rather upgrade to Windows 8.1. At this point, I found out that the Windows 7 installer had apparently broken the factory recovery partition, leaving me with a laptop I couldn’t use.

I turned to Google and quickly found someone else in a similar situation on Reddit. However, no one was on hand to offer help, so I continued digging on my own. I managed to get my recovery partition working again, got Windows 8 installed, and backed up the recovery partition.

If you need to restore your G501JW, download the recovery image at https://neo.elverstone.com/asus/asus_g501jw_recovery.bin (Originally hosted at http://neo.27.am/asus/asus_g501jw_recovery.bin), write it to a 16GB+ USB flash drive with PassMark’s ImageUSB tool, and boot off it.

Fixing wadl2java

On a recent project, I was given a WADL file and wanted a way to quickly knock out some client code for calling the web service described by the file.

I quickly came across two tools that, annoyingly, have the same name: wadl2java from Java.net and wadl2java from Apache CXF. Since I have no experience with Apache CXF, I decided to try the Java.net tool. The only problem? Every time I try to run it, I get the following error:

Exception in thread "main" java.lang.RuntimeException: java.lang.ClassNotFoundException: com.sun.ws.rs.ext.RuntimeDelegateImpl
        at javax.ws.rs.ext.RuntimeDelegate.findDelegate(RuntimeDelegate.java:122)
        at javax.ws.rs.ext.RuntimeDelegate.getInstance(RuntimeDelegate.java:91)
        at javax.ws.rs.core.UriBuilder.newInstance(UriBuilder.java:69)
        at javax.ws.rs.core.UriBuilder.fromUri(UriBuilder.java:80)
        at org.jvnet.ws.wadl2java.Wadl2Java.generateEndpointClass(Wadl2Java.java:618)
        at org.jvnet.ws.wadl2java.Wadl2Java.process(Wadl2Java.java:472)
        at org.jvnet.ws.wadl2java.Main.main(Main.java:143)
Caused by: java.lang.ClassNotFoundException: com.sun.ws.rs.ext.RuntimeDelegateImpl
        at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:188)
        at javax.ws.rs.ext.FactoryFinder.newInstance(FactoryFinder.java:62)
        at javax.ws.rs.ext.FactoryFinder.find(FactoryFinder.java:155)
        at javax.ws.rs.ext.RuntimeDelegate.findDelegate(RuntimeDelegate.java:105)
        ... 6 more

After an afternoon of troubleshooting, it turns out that this is a known bug in wadl2java 1.1.3 that occurs on vanilla installs of JDK6 or JDK7, and has been around since October 2012.

To work around the problem, you need to do two things:

  1. Add jersey-client-1.13.jar to wadl2java’s lib directory.
  2. Add jersey-core-1.13.jar jersey-client-1.13.jar to the Class-Path in wadl-cmdline-1.1.3.jar‘s MANIFEST.MF file.

If you don’t want to do Step 2 yourself, you can download my modified version of wadl-cmdline-1.1.3.jar instead. Hopefully version 1.1.4 will be released soon, but until then this should get things up and running.

On silly Java mistakes

So you’re getting started with your Java EE web project and you’re using JPA, annotations, dependency injection, all that good stuff. Except when you launch your awesome web app, your Glassfish 3 server spits out something like this:

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: javax.ejb.CreateException: Could not create stateless EJB

root cause

javax.ejb.CreateException: Could not create stateless EJB

root cause

java.lang.IllegalStateException: Exception attempting to inject Env-Prop: org.example.EjbClass/emf@Field-Injectable Resource. Class name = org.example.EjbClass Field name=emf@java.lang.String@@@ into class org.example.EjbClass: Can not set javax.persistence.EntityManagerFactory field org.example.EjbClass.emf to com.sun.enterprise.container.common.impl.EntityManagerWrapper

root cause

com.sun.enterprise.container.common.spi.util.InjectionException: Exception attempting to inject Env-Prop: org.example.EjbClass/emf@Field-Injectable Resource. Class name = org.example.EjbClass Field name=emf@java.lang.String@@@ into class org.example.EjbClass: Can not set javax.persistence.EntityManagerFactory field org.example.EjbClass.emf to com.sun.enterprise.container.common.impl.EntityManagerWrapper

root cause

java.lang.IllegalArgumentException: Can not set javax.persistence.EntityManagerFactory field org.example.EjbClass.emf to com.sun.enterprise.container.common.impl.EntityManagerWrapper

If you’re reading the error message carefully, like my friend didn’t, you’ll notice that it’s complaining about trying to set an EntityManager instance on an EntityManagerFactory field.

Why, oh why, would it do this?

Because you’re using the @PersistenceContext annotation on the field, instead of @PersistenceUnit. Ouch.

How to download .NET Reflector 6 for free

If you like, you can skip the introduction and jump to Downloading .NET Reflector.

A brief history of .NET Reflector

In the beginning

In case you somehow missed it, .NET Reflector is a class browser, analyzer, and decompiler for .NET assemblies. Originally created by Lutz Roeder, it proved to be an extremely useful tool, making lists such as MSDN’s Ten Must-Have .NET Tools Every Developer Should Download Now. Best of all, .NET Reflector was released to the community for free, with Roeder developing and supporting the tool for over 8 years.

The downfall

However, in August 2008, Red Gate Software bought .NET Reflector. At the time, Roeder was told that Red Gate will continue to provide the free community version. Red Gate themselves stated that The first thing we are doing is continuing to offer the software to the community for free downloading. It didn’t stay that way. In February 2011, Red Gate announced that from version 7, .NET Reflector would no longer be free.

This might have been acceptable, but for the fact that free copies .NET Reflector expired after several months. Upon expiry, users were prompted to update to the latest version; if they declined, .NET Reflector would simply exit, although some versions contained a time-bomb that completely deleted .NET Reflector if it was too old. Effectively, all existing free users of .NET Reflector would be forced to either stop using .NET Reflector, or pay for version 7. The community backlash was immediate.

Scorched earth

After two months, Red Gate finally relented, partially reversing their decision to disable the free version of .NET Reflector. However, rather than once more releasing a free community edition, they instead only enabled existing free versions of .NET Reflector to update to a version that does not expire. For those users who had a self-deleting version, Red Gate offered no help. They also offered no way for new users to download the free version of .NET Reflector.

To date, Red Gate’s promise of maintaining a free community version remains broken. It has been more than a year since they first announced that they were going back on their word, but nothing has changed. While there are now more alternatives to .NET Reflector than ever, it is unfortunate that this whole situation came about in the first place.

A brief history of LookingGlass

Like most things developers create, LookingGlass was born out of curiosity. The question: Is it possible to download .NET Reflector from Red Gate without already having a copy? After all, old versions need a way to download updates somehow. Updating an old copy of .NET Reflector while running Wireshark quickly provided the answer: .NET Reflector makes two HTTP requests to Red Gate’s servers, the first to determine the URL of the update, and the second to actually download it.

LookingGlass is a small program that reproduces .NET Reflector’s requests to Red Gate’s servers and saves the result to a file. A few hacks were necessary to perfectly emulate how .NET Reflector makes its HTTP requests (See line 87), including not reusing the HTTP connection despite the Keep-Alive headers (.NET Reflector’s built-in updater launches as a separate process). From Red Gate’s side, it should be impossible to tell the difference between the two.

Downloading .NET Reflector

Simply save the below code as a file (For example, LookingGlass.cs), compile it and run the resulting program. It will save the downloaded file to the same directory as the program itself. If necessary, you can download Visual C# Express for free, or use the C# compiler (csc.exe) that is included with every version of the .NET framework to compile this code. LookingGlass should work perfectly on .NET 2.0 and above.

// This is free and unencumbered software released into the public domain.
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Reflection;

namespace LookingGlass
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length == 0)
                QueryDownloadUrl(@"http://reflector.red-gate.com/Reflector.version");
            else
                Download(args[0]);
        }

        static void QueryDownloadUrl(string versionUrl)
        {
            Console.WriteLine("Phase 1: Getting download URL...");

            HttpWebRequest request = GetHttpWebRequest(versionUrl);
            string downloadUrl = null;
            string data;

            using (WebResponse response = request.GetResponse())
            {
                data = ReadResponse(response);

                foreach (string line in data.Split('\n'))
                {
                    if (line.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                    {
                        // If this version number stops working, search for other known .NET Reflector version numbers; Red Gate's own forums mention a few
                        downloadUrl = line.Trim('\r').Replace("{Client}", "Reflector").Replace("{Version}", "6.1.0.11");
                        break;
                    }
                }
            }

            if (downloadUrl == null)
            {
                Console.WriteLine("Failed to find download URL. Returned data was:");
                Console.WriteLine(data);
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("Launching download process...");
                Process.Start(Process.GetCurrentProcess().MainModule.FileName, downloadUrl);
                Console.WriteLine("Phase 1 complete.");
            }
        }

        static void Download(string downloadUrl)
        {
            Console.WriteLine("Phase 2: Downloading...");

            HttpWebRequest request = GetHttpWebRequest(downloadUrl);
            string path;

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                path = GetDownloadFilename(response);

                if (response.StatusCode == HttpStatusCode.OK && !string.IsNullOrEmpty(path))
                {
                    Console.WriteLine("Saving to {0}...", path);
                    SaveResponse(response, path);
                    Console.WriteLine("Done!");
                }
                else
                {
                    Console.WriteLine("Download failed; server returned status code {0}. Returned data was:", response.StatusCode);
                    Console.WriteLine(ReadResponse(response));
                    Console.ReadLine();
                }
            }
        }

        static HttpWebRequest GetHttpWebRequest(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Headers.Add("Cache-Control: no-cache, no-store, max-age=0");
            // Emulate the manner in which the headers are handled
            FieldInfo usesProxySemantics = typeof(ServicePoint).GetField("m_ProxyServicePoint", BindingFlags.NonPublic | BindingFlags.Instance);
            usesProxySemantics.SetValue(request.ServicePoint, true);
            return request;
        }

        static string GetDownloadFilename(HttpWebResponse response)
        {
            string contentDisposition = response.Headers["content-disposition"];

            if (string.IsNullOrEmpty(contentDisposition))
                return null;

            string filenameField = "filename=";
            int index = contentDisposition.IndexOf(filenameField, StringComparison.CurrentCultureIgnoreCase);

            if (index < 0)
                return null;

            return contentDisposition.Substring(index + filenameField.Length).Trim('"');
        }

        static string ReadResponse(WebResponse response)
        {
            using (Stream netStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(netStream))
                {
                    return reader.ReadToEnd();
                }
            }
        }

        static void SaveResponse(WebResponse response, string path)
        {
            byte[] buffer = new byte[4 * 1024];
            int bytesRead;

            using (Stream netStream = response.GetResponseStream())
            {
                if (File.Exists(path))
                    File.Delete(path);

                using (FileStream fileStream = File.Create(path))
                {
                    while ((bytesRead = netStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        Console.Write(".");
                        fileStream.Write(buffer, 0, bytesRead);
                    }
                }
            }

            Console.WriteLine();
        }
    }
}

Where to from here?

Once you have .NET Reflector up and running, be sure to try out some of the many free community add-ins available on .NET Reflector’s site and Codeplex. Tell your friends about it. And above all, don’t always believe a company when they tell you they’ll keep a product free.

Gmail From Sorter 1.6 unleashed

Having released Gmail From Sorter 1.4 the other day, I continued fiddling with it based Robert’s feedback.

One thing I hadn’t realized was that, as a user of Google Multiple Sign-In, the URLs I see differ slightly from the URLs non-Multiple Sign-In users see. To fix that, I simply relaxed the Greasemonkey @include scope from http://mail.google.com/mail/u/* to http://mail.google.com/mail/*.

I also played around with different methods of hooking into Gmail. Gmail loads in From address fields dynamically, which GFS historically handled by looking for them on the mousedown event. This seemed horrible, so I investigated using other events, such as DOMNodeInserted, DOMContentLoaded and other DOM* events. While some of these events worked, the performance impact they had was horrendous; they caused Gmail to become noticably laggy. Turns out, these DOM mutation events are deprecated for this very reason. I decided to stick with mousedown, and added the keydown event to support those that use Gmail keyboard shortcuts.

In the pursuit of efficiency, I changed the initial Gmail hook-in from using an interval-based check to using the load event, which Firefox dutifully fired. The only problem is that Chrome seems to execute Greasemonkey scripts after the load event has fired, rendering the approach useless. Naturally, there’s always more than one way to do it, but the interval-based approach isn’t that bad, so GFS 1.6 reverted the hook-in changes introduced in GFS 1.5.

Finally, I found out that Opera is also capable of running Greasemonkey scripts, although the installation process is not as seamless as that of Firefox or Chrome. After correctly configuring everything, I tested GFS on Opera and it works just fine. I also updated the GFS Userscripts.org page to include installation instructions for all three supported browsers.

As always, you can download version 1.6 from the Gmail From Sorter Userscripts.org page. Hopefully I don’t need to fiddle with it again for at least another 6 months. :)

Gmail From Sorter 1.4 released

I recently noticed that my Gmail From Sorter Greasemonkey script stopped working, but as usual “out of sight, out of mind”; having sent the email, I promptly forgot about the problem. I was reminded again tonight when Robert emailed me about the issue, so I set about correcting it.

A few hours later, and GFS 1.4 resolves the problem. You can download it from the Gmail From Sorter Userscripts.org page, or you can wait for the auto-updater to kick in, which should take a week at most. Thanks Robert!

The Legend of FinkyPieheimer@zoobatz.com

Occasionally, you want a quick disposable email address for registering on suspicious websites, or in my case, for testing your own website’s registration system. While there are several options, I use Mailinator because you don’t need to set up anything first. You just enter whatever you want, followed by @mailinator.com as your email address, and it just works.

This is what I was doing last week when I noticed that all the email sent by my website’s registration system was apparently from FinkyPieheimer@zoobatz.com. That’s definitely not what I set, and I confirmed that a valid from address was being used. The only recent change was that a friendly display name was now being included, instead of just the email address by itself. So what gives?

Upon examining the raw email (When viewing an email in Mailinator, click the Text View button), I noticed a linebreak in the From header.

...
MIME-Version: 1.0
From: "Quux Baz"
 
To: test@mailinator.com
...

While that’s unusual, other email programs and systems handle it just fine. Mailinator, however, doesn’t like it one bit. It seems to regard it as invalid, and as such, replaces the field with FinkyPieheimer@zoobatz.com as a sort of placeholder.

So what can you do about it? If you’re just registering on a website, don’t worry about it. If you’re working on your own website, see if you can change how the From email address is set.

In my case, I was using .NET’s SmtpClient, MailMessage and MailAddress classes. I found a StackOverflow question about the strange carriage return & line feed, which only appears when you set the DisplayName property of a MailAddress instance. This only happens under .NET 4.0, and you can see the hardcoded “\r\n ” are the end of the MailAddress.Encode(Int32) method. To resolve this, either convert the project to .NET 3.5, remove the display name, or, if you have an intermediate delivery system, add a processing step to fix this after it leaves the .NET SmtpClient.

Getting to the (Reparse) Point: Notes

These are the links, notes and resources for my presentation Getting to the (Reparse) Point, which I’ll be giving at Microsoft Devs4Devs on Saturday, 20 August 2011 at 09:30.

Code

Applications

Documentation

Announcing Manta

It’s taken much too long, but I’ve finally created an online project for Manta, which until recently didn’t even have an official name. Manta is an open source .NET library that currently features a variety of I/O- and web-related classes that simplify and ease solving hard problems.

On the I/O side, Manta offers support for managing hardlinks, reparse points, junctions, symbolic links. It also comes with unit tests and documented methods and classes.

On the web side, Manta enables easy manipulation of URLs, RSS feeds and phpBB posts. It too features unit tests and documentation.

You can find out more about Manta or download it from CodePlex.

Buying a Dremel in South Africa

I’d been wanting to get myself a Dremel rotary tool for ages, but only started looking into it recently. Immediately, I was overwhelmed by the variety of options thrown at me – do I get the tool by itself and then buy the accessories separately, or do I go for one of the kits? Which option is the cheapest?

Firstly, kit codes appear to be in the format of <Tool series>-<Number of attachments>/<Number of accessories>. As far as I can tell, there are four kits available in South Africa, although I could only find information on Dremel’s website about the 300-1/55, the 4000-1/45 and the 4000-4/65; the fourth kit, which I saw in Builder’s Warehouse, is a 300-2/40 and contains a Dremel 300 bundled with various accessories and a mini-workbench.

To help myself decide what to go for, I went through Dremel’s website and put together a spreadsheet detailing the accessories each kit contains. You can view the spreadsheet online. Note that the total accessories count is less than the number the kit code indicates; this is probably due to inaccuracies on Dremel’s website, as the kit I got included the correct number of accessories.

Hopefully, this spreadsheet will help your decision. In the end, I went for the 300-1/55; the value it gives at its price-point bested the Dremel 4000 kits easily.