Friday, April 26, 2013

String Extensions: Split Qualified

Splitting on a string is easy.
Respecting qualified (quoted) strings can be hard.
Identifying escaped characters in qualified strings is very tricky.
Splitting on a qualified string that takes escape characters into account is really difficult!

Unit Tests

[Theory]
[InlineData(null,                   new string[0])]
[InlineData("",                     new string[0])]
[InlineData("hello world",          new[] { "hello", "world" })]
[InlineData("hello   world",        new[] { "hello", "world" })]
[InlineData("\"hello world\"",      new[] { "\"hello world\"" })]
[InlineData("\"hello  world\"",     new[] { "\"hello  world\"" })]
[InlineData("hello \"goodnight moon\" world", new[]
{
    "hello", 
    "\"goodnight moon\"", 
    "world", 
})]
[InlineData("hello \"goodnight \\\" moon\" world", new[]
{
    "hello", 
    "\"goodnight \\\" moon\"", 
    "world", 
})]
[InlineData("hello \"goodnight \\\\\" moon\" world", new[]
{
    "hello", 
    "\"goodnight \\\\\"", 
    "moon\"", 
    "world", 
})]
public void SplitQualified(string input, IList<string> expected)
{
    var actual = input
        .SplitQualified(' ', '"')
        .ToList();
 
    Assert.Equal(expected.Count, actual.Count);
 
    for (var i = 0; i < actual.Count; i++)
        Assert.Equal(expected[i], actual[i]);
}

String Extension Methods

public static IEnumerable<string> SplitQualified(
    this string input, 
    char separator, 
    char qualifier, 
    StringSplitOptions options = StringSplitOptions.RemoveEmptyEntries, 
    char escape = '\\')
{
    if (String.IsNullOrWhiteSpace(input))
        return new string[0];
 
    var results = SplitQualified(input, separator, qualifier, escape);
 
    return options == StringSplitOptions.None
        ? results
        : results.Where(r => !String.IsNullOrWhiteSpace(r));
}
 
private static IEnumerable<string> SplitQualified(
    string input, 
    char separator, 
    char qualifier, 
    char escape)
{
    var separatorIndexes = input
        .IndexesOf(separator)
        .ToList();
 
    var qualifierIndexes = input
        .IndexesOf(qualifier)
        .ToList();
 
    // Remove Escaped Qualifiers
    for (var i = 0; i < qualifierIndexes.Count; i++)
    {
        var qualifierIndex = qualifierIndexes[i];
        if (qualifierIndex == 0)
            continue;
 
        if (input[qualifierIndex - 1] != escape)
            continue;
 
        // Watch out for a series of escaped escape characters.
        var escapeResult = false;
        for (var j = 2; qualifierIndex - j > 0; j++)
        {
            if (input[qualifierIndex - j] == escape)
                continue;
 
            escapeResult = j % 2 == 1;
            break;
        }
 
        if (qualifierIndex > 1 && escapeResult)
            continue;
 
        qualifierIndexes.RemoveAt(i);
        i--;
    }
 
    // Remove Qualified Separators
    if (qualifierIndexes.Count > 1)
        for (var i = 0; i < separatorIndexes.Count; i++)
        {
            var separatorIndex = separatorIndexes[i];
 
            for (var j = 0; j < qualifierIndexes.Count - 1; j += 2)
            {
                if (separatorIndex <= qualifierIndexes[j])
                    continue;
 
                if (separatorIndex >= qualifierIndexes[j + 1])
                    continue;
 
                separatorIndexes.RemoveAt(i);
                i--;
            }
        }
 
    // Split String On Separators
    var previousSeparatorIndex = 0;
    foreach (var separatorIndex in separatorIndexes)
    {
        var startIndex = previousSeparatorIndex == 0
            ? previousSeparatorIndex
            : previousSeparatorIndex + 1;
 
        var endIndex = separatorIndex == input.Length - 1
            || previousSeparatorIndex == 0
            ? separatorIndex - previousSeparatorIndex
            : separatorIndex - previousSeparatorIndex - 1;
 
        yield return input.Substring(startIndex, endIndex);
 
        previousSeparatorIndex = separatorIndex;
    }
 
    if (previousSeparatorIndex == 0)
        yield return input;
    else
        yield return input.Substring(previousSeparatorIndex + 1);
}
 
public static IEnumerable<int> IndexesOf(
    this string input, 
    char value)
{
    if (!String.IsNullOrWhiteSpace(input))
    {
        var index = -1;
        do
        {
            index++;
            index = input.IndexOf(value, index);
 
            if (index > -1)
                yield return index;
            else
                break;
        }
        while (index < input.Length);
    }
}
Shout it

Enjoy,
Tom

Saturday, April 13, 2013

Report Unhandled Errors from JavaScript

Logging and aggregating error reports is one of the most important things you can do when building software: 80% of customer issues can be solved by fixing 20% of the top-reported bugs.

Almost all websites at least has some form of error logging on their servers, but what about the client side of those websites? People have a tendency to brush over best practices for client side web development because "it's just some scripts." That, is, WRONG! Your JavaScript is your client application, it is how users experience your website, and as such it needs the proper attention and maintenance as any other rich desktop application.

So then, how do you actually know when your users are experiencing errors in their browser? If you are like the vast majority of websites out there...

You don't know about JavaScript errors, and it's time to fix that!

window.onerror

Browsers do offer a way to get notified of all unhandled exceptions, that is the window.onerror event handler. You can wire a listener up to this global event handler and get back three parameters: the error message, the URL of the file in which the script broke, and the line number where the exception was thrown.

window.onerror = function myErrorHandler(errorMsg, url, lineNumber) {
  // TODO: Something with this exception!
  // Just let default handler run.
  return false;
}

StackTrace.js

JavaScript can throw exceptions like any other language; browser debugging tools often show you a full stack trace for unhandled exceptions, but gathering that information programmatically is a bit more tricky. To learn a bit more about the JavaScript language and how to gather this information yourself, I suggest taking a look at this article by Helen Emerson. However in practice I would strongly suggest you use a more robust tool...

StackTrace.js is a very powerful library that will build a fully detailed stack trace from an exception object. It has a simple API, cross browser support, it handles fringe cases, and is very light weight and unobtrusive to your other JS libraries.

try {
    // error producing code
} catch(error) {
   // Returns stacktrace from error!
   var stackTrace = printStackTrace({e: error});
}

Two Big Problems

  1. The window.onerror callback does not contain the actual error object.

This is a big problem because without the error object you cannot rebuild the stack trace. The error message is always useful, but file names and line numbers will be completely useless once you have minified your code in production. Currently, the only way you can bring additional information up to the onerror callback is to try catch any exceptions that you can and store the error object in a closure or global variable.

  1. If you globally try catch event handlers it will be harder to use a debugger.

It would not be ideal to wrap every single piece of code that you write in an individual try catch block, and if you try to wrap your generic event handling methods in try catches then those catch blocks will interrupt your debugger when you are working with code in development.

Currently my suggestion is to go with the latter option, but only deploy those interceptors with your minified or production code.

jQuery Solution

This global error handling implementation for jQuery and ASP.NET MVC is only 91 lines of JavaScript and 62 lines of C#.

Download JavaScriptErrorReporter from GitHub

To get as much information as possible, you need to wire up to three things:
(Again, I suggest that you only include this when your code is minified!)

  1. window.onerror
  2. $.fn.ready
  3. $.event.dispatch

Here is the meat of those wireups:

var lastStackTrace,
    reportUrl = null,
    prevOnError = window.onerror,
    prevReady = $.fn.ready,
    prevDispatch = $.event.dispatch;
 
// Send global methods with our wrappers.
window.onerror = onError;
$.fn.ready = readyHook;
$.event.dispatch = dispatchHook;
 
function onError(error, url, line) {
    var result = false;
    try {
        // If there was a previous onError handler, fire it.
        if (typeof prevOnError == 'function') {
            result = prevOnError(error, url, line);
        }
        // If the report URL is not loaded, load it.
        if (reportUrl === null) {
            reportUrl = $(document.body).attr('data-report-url') || false;
        }
        // If there is a rport URL, send the stack trace there.
        if (reportUrl !== false) {
            var stackTrace = getStackTrace(error, url, line, lastStackTrace);
            report(error, stackTrace);
        }
    } catch (e) {
        // Something went wrong, log it.
        if (console && console.log) {
            console.log(e);
        }
    } finally {
        // Clear the wrapped stack so it does get reused.
        lastStackTrace = null;
    }
    return result;
}
 
function readyHook(fn) {
    // Call the original ready method, but with our wrapped interceptor.
    return prevReady.call(this, fnHook);
 
    function fnHook() {
        try {
            fn.apply(this, arguments);
        } catch (e) {
            lastStackTrace = printStackTrace({ e: e });
            throw e;
        }
    }
}
 
function dispatchHook() {
    // Call the original dispatch method.
    try {
        prevDispatch.apply(this, arguments);
    } catch (e) {
        lastStackTrace = printStackTrace({ e: e });
        throw e;
    }
}

Identifying Duplicate Errors

One last thing to mention is that when your stack trace arrives on the server it will contain file names and line numbers. The inconsistency of these numbers will make it difficult to identify duplicate errors. I suggest that you "clean" the stack traces by removing this extra information when trying to create a unique error hash.

private static readonly Regex LineCleaner
    = new Regex(@"\([^\)]+\)$", RegexOptions.Compiled);
 
private int GetUniqueHash(string[] stackTrace)
{
    var sb = new StringBuilder();
 
    foreach (var stackLine in stackTrace)
    {
        var cleanLine = LineCleaner
            .Replace(stackLine, String.Empty)
            .Trim();
 
        if (!String.IsNullOrWhiteSpace(cleanLine))
            sb.AppendLine(cleanLine);
    }
 
    return sb
        .ToString()
        .ToLowerInvariant()
        .GetHashCode();
}

Integration Steps

This article was meant to be more informational than tutorial; but if you are interested in trying to apply this to your site, here are the steps that you would need to take:

  1. Download JavaScriptErrorReporter from GitHub.
  2. Include StackTrace.js as a resource in your website.
  3. Include ErrorReporter.js as a resource in your website.
    • Again, to prevent it interfering with your JavaScript debugger, I suggest only including this resource when your scripts are being minified.
  4. Add a report error action to an appropriate controller. (Use the ReportError action on the HomeController as an example.)
  5. Add a "data-report-url" attribute with the fully qualified path to your report error action to the body tag of your pages.
  6. Log any errors that your site reports!
Shout it

Enjoy,
Tom

Thursday, March 28, 2013

Run Multiple Tasks in a Windows Service

ServicesBase.Run(ServiceBase[] services) ...that sure made me think you could run multiple implementations of ServiceBase in a single Windows Service; but that is not how it works.

One Service, Multiple Tasks

I often have a very simple use case: I needed to run multiple tasks in a single windows service. For example, one task to poll some email notifications, and one task to listen to HTTP requests that might trigger those same notifications.

I like the basic setup of OnStart, Run, and OnStop, but after authoring several windows services I got tired of writing the same code over and over again. Thus I created the WindowServiceTasks library. Now whenever I need to do another task in a service, I just implement the WindowsServiceTaskBase or WindowsServiceLoopBase class, and my code is all ready to go!

WindowsServiceTasks

Run multiple tasks in a single WindowsService, and let the base library do all of the work setup and tear down for you. The WindowsServiceTasks NuGet package is simple, flexible, and extremely light weight.

Example

public static class Program
{
    public static void Main(params string[] args)
    {
        var logger = new Logger("Demo.log");
        var emailTask = new EmailServiceTask(logger);
        var failTask = new FailServiceTask(logger);
 
        var service = new Service1(logger, emailTask, failTask);
        service.Start(args);
    }
}
public class EmailServiceTask : WindowsServiceLoopBase
{
    private readonly ILogger _logger;
 
    public EmailServiceTask(ILogger logger)
    {
        _logger = logger;
    }
 
    protected override int LoopMilliseconds
    {
        get { return 2000; }
    }
 
    protected override void HandleException(Exception exception)
    {
        _logger.Log(exception);
    }
 
    protected override void RunLoop()
    {
        // TODO Send Email!
        _logger.Log("EmailServiceTask.RunLoop - Sending an email");
    }
 
    public override void OnStart(string[] args)
    {
        _logger.Log("EmailServiceTask.OnStart");
    }
 
    public override void OnStop()
    {
        _logger.Log("EmailServiceTask.OnStop");
    }
 
    protected override void DisposeResources()
    {
    }
}
Shout it

Enjoy,
Tom

Thursday, February 28, 2013

Running a Windows Service as a Console App

This is a prerequisite post before I can talk about the WindowsServiceTasks library that I recently released.

How do you test windows services?

I hope your first response was unit tests, but even if it was we both know that you still have to integration test the whole application. You could install your service into windows and then attach your debugger to it's process, but that is a lot of work. Why not just run your service as a console application? Then you can test it by just pressing play in Visual Studio!

How do you run a windows service as a console application?

Easy! Just go into your windows service project's settings and set the Output Type to Console Application. This will allow the executable to launch as a console app, but it is still completely executable as a service!

Inside of your code, you can use the Environment.UserInteractive property to determine which mode you are in. With that you can do cool things to help you debug, such as register an alternate logger with your IOC container that will write your long lines to console instead of (or as well as) to file.

static class Program
{
    static void Main(params string[] args)
    {
        var service = new Service1();
 
        if (!Environment.UserInteractive)
        {
            var servicesToRun = new ServiceBase[] { service };
            ServiceBase.Run(servicesToRun);
            return;
        }
 
        Console.WriteLine("Running as a Console Application");
        Console.WriteLine(" 1. Run Service");
        Console.WriteLine(" 2. Other Option");
        Console.WriteLine(" 3. Exit");
        Console.Write("Enter Option: ");
        var input = Console.ReadLine();
 
        switch (input)
        {
            case "1":
                service.Start(args);
                Console.WriteLine("Running Service - Press Enter To Exit");
                Console.ReadLine();
                break;
 
            case "2":
                // TODO!
                break;
        }
 
        Console.WriteLine("Closing");
    }
}
 
public partial class Service1 : ServiceBase
{
    public Service1() { InitializeComponent(); }
 
    public void Start(string[] args) { OnStart(args); }
 
    protected override void OnStart(string[] args) { }
 
    protected override void OnStop() { }
}

What other uses does this offer?

You can then also use your windows services as management utilities. I have worked with applications before where when I needed to make a configuration change to a system I was told to go run windows services with random undiscoverable command line arguments or magic number configuration settings. By launching your service as a console app you can inject simple menu systems to allow users easy access to admin functionality.

Shout it

Enjoy,
Tom

Sunday, February 17, 2013

Cache Repository for MVC

First and foremost, the CacheRepository is NOT web specific!

The CacheRepository library contains the abstract CacheRepositoryBase class, which can be implemented by any caching system that you choose. The CacheRepository.Web NuGet package includes a WebCacheRepository implementation that leverages System.Web.Caching.Cache

CacheRepository.Web

Get all of the source code, unit tests, and a complete MVC4 sample application (preconfigured to include dependency injection with Unity) from GitHub. Or to just jump in and start using it, grab the CacheRepository.Web package from NuGet.

ICacheRepository

The ICacheRepository interface has all the standard Get, Set, Remove and Clear methods. Additionally, these methods have been expanded to include enum parameters to group manage cache expiration.

Best of all, it includes GetOrSet methods. These methods will try to get the value of the specified key, and when it can not find that value it will then be loaded via the passed in Func. A key feature here is the fact that the setter of the GetOrSet will lock on load to prevent redundant data loads. (More details about this below.)

public interface ICacheRepository
{
    object Get(string key);
    T Get<T>(string key);
 
    T GetOrSet<T>(string key, Func<T> loader);
    T GetOrSet<T>(string key, Func<T> loader, DateTime expiration);
    T GetOrSet<T>(string key, Func<T> loader, TimeSpan sliding);
    T GetOrSet<T>(string key, Func<T> loader, CacheExpiration expiration);
    T GetOrSet<T>(string key, Func<T> loader, CacheSliding sliding);
 
    void Set<T>(string key, T value);
    void Set<T>(string key, T value, DateTime expiration);
    void Set<T>(string key, T value, TimeSpan sliding);
    void Set<T>(string key, T value, CacheExpiration expiration);
    void Set<T>(string key, T value, CacheSliding sliding);
 
    void Remove(string key);
    void ClearAll();
}

ThreadSafe GetOrSet

As any good cache should, the CacheRepository is thread safe and can be treated as a singleton.

Even better, the GetOrSet methods lock on set. This means that 10 threads could be trying to load the same cache value simultaneously, but only one will actually trigger a load and set. This helps redundant resource loads and database calls and keep your application running optimally.

private T GetOrSet<T>(string key, Func<T> loader,
    DateTime? expiration, TimeSpan? sliding)
{
    // Get It
    T value;
    var success = TryGet(key, out value);
 
    // Got It or No Loader
    if (loader == null || success)
        return value;
 
    // Load It
    return LockedInvoke(key, () =>
    {
        // Get It (Again)
        success = TryGet(key, out value);
 
        if (!success)
        {
            // Load It (For Real)
            value = loader();
 
            // Set It
            if (value != null)
                Set(key, value, expiration, sliding);
        }
 
        return value;
    });
}

Configurable Expiration Enums

Instead of being forced to set each of your cache expirations separately, you now have the option to use an enum value to group your cache expirations. Enums are available for both absolute expiration and sliding expiration.

You may override the duration of each cache key in your app config; this is really useful for when you want to uniformly modify your cache expirations in your QA or testing environments. Additionally, you may override the CacheRepositoryBase.GetConfigurationValue method to pull this configuration for anywhere you want, not just the ConfigurationManager.

public enum CacheExpiration
{
    VeryShort = 10,     // Ten Seconds
    Short = 60,         // One Minute
    Medium = 300,       // Five Minutes
    Long = 3600,        // One Hour
    VeryLong = 86400    // One Day
}

<configuration>
  <appSettings>
    <add key="CacheExpiration.VeryShort" value="15" />
    <add key="CacheExpiration.Short" value="90" />

ByType Extensions

Transparent cache key management is offered through a series of ICacheRepository extension methods. This makes caching even easier, as you don't need to worry about cache key collisions.

Using these extension methods, you many cache a Cat object with an Id of 1 and a Dog object with an Id of 1 in the same manner. The extension methods will create a key prefix based on the type and then use the specified identified as the suffix.

[Fact]
public void SameKeyDifferentType()
{
    var setCat = new Cat { Name = "Linq" };
    CacheRepository.SetByType(1, setCat);
 
    var setDog = new Dog { Name = "Taboo" };
    CacheRepository.SetByType(1, setDog);
 
    var getCat = CacheRepository.GetByType<Cat>(1);
    Assert.Equal(setCat.Name, getCat.Name);
 
    var getDog = CacheRepository.GetByType<Dog>(1);
    Assert.Equal(setDog.Name, getDog.Name);
}

Web Implementation & Dependency Injection via Unity

The CacheRepository.Web NuGet package includes a WebCacheRepository implementation that leverages System.Web.Caching.Cache. This is a very simple, but very effective, production ready implementation of the CacheRepositoryBase.

It should also be noted that this implementation is not only useful in ASP.NET, the System.Web.Caching.Cache is located in the System.Web library, but it still available outside of a web context. This means that this implementation can be used in other applications, including but not limited to Windows Services.

public class WebCacheRepository : CacheRepositoryBase
{
    private readonly Cache _cache;
        
    public WebCacheRepository()
    {
        _cache = HttpContext.Current == null
            ? HttpRuntime.Cache
            : HttpContext.Current.Cache;
    }

Wiring the cache repository to be injected into your controllers via Unity is also very easy. Just register the WebCacheRepository for the ICacheRepository interface, and be sure to provide a ContainerControlledLifetimeManager for optimal performance.

To use the implementation below, you will need to include the Unity.MVC3 NuGet Package to gain access to the UnityDependencyResolver.

public static void Initialise()
{
    var container = BuildUnityContainer();
    
    DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
 
private static IUnityContainer BuildUnityContainer()
{
    var container = new UnityContainer();
 
    container.RegisterType<ICacheRepository, WebCacheRepository>(
        new ContainerControlledLifetimeManager());           
 
    return container;
}

If you missed the links above, here they are again:

Shout it

Enjoy,
Tom

Sunday, January 13, 2013

WebElement Form Extensions for WebDriver

I really like Selenium 2.0!

I've been working a lot on a side project involving WebDriver, and thus I have been creating a few extension methods for working with form data that I thought others might find helpful:

  • bool IsSelected(this IWebElement element)
  • bool IsChecked(this IWebElement element)
  • void SetChecked(this IWebElement element)
  • void SetUnchecked(this IWebElement element)
  • IWebElement GetOptionByValue(this IWebElement element, string value)
  • IWebElement GetOptionByText(this IWebElement element, string text)

Extension Methods

public static class WebElementExtensions
{
    private static readonly StringComparer DefaultComparer =
        StringComparer.InvariantCultureIgnoreCase;
 
    private static readonly string[] Selected = new[] { "true", "selected" };
 
    public static bool IsSelected(this IWebElement element)
    {
        var attribute = element.GetAttribute("selected");
        return Selected.Contains(attribute, DefaultComparer);
    }
 
    private static readonly string[] Checked = new[] { "true", "checked" };
 
    public static bool IsChecked(this IWebElement element)
    {
        var attribute = element.GetAttribute("checked");
        return Checked.Contains(attribute, DefaultComparer);
    }
 
    public static void SetChecked(this IWebElement element)
    {
        if (!element.IsChecked())
            element.Click();
    }
 
    public static void SetUnchecked(this IWebElement element)
    {
        if (element.IsChecked())
            element.Click();
    }
 
    private const StringComparison DefaultComparison = 
        StringComparison.InvariantCultureIgnoreCase;
 
    public static IWebElement GetOptionByValue(
        this IWebElement element, 
        string value)
    {
        return element.GetOption(
            o => value.Equals(o.GetAttribute("value"), DefaultComparison));
    }
 
    public static IWebElement GetOptionByText(
        this IWebElement element, 
        string text)
    {
        return element.GetOption(o => text.Equals(o.Text, DefaultComparison));
    }
 
    private static IWebElement GetOption(
        this IWebElement element, 
        Func<IWebElement, bool> predicate)
    {
        return element
            .FindElements(By.CssSelector("option"))
            .FirstOrDefault(predicate);
    }
}

Unit Tests

public class WebElementExtensionTests : IDisposable
{
    public IWebDriver Driver { get; private set; }
 
    public WebElementExtensionTests()
    {
        Driver = new ChromeDriver("C:/Code/Drivers");
        Driver.Url = "file:///C:/Code/WebDriverTests/TestPage.htm";
    }
 
    public void Dispose()
    {
        Driver.Dispose();
    }
 
    [Fact]
    public void RadioTests()
    {
        var e1 = Driver.FindElement(By.Id("r1"));
        var e2 = Driver.FindElement(By.Id("r2"));
 
        IsNotSelected(e1);
        IsSelected(e2);
 
        e1.Click();
        IsSelected(e1);
 
        e2.Click();
        IsNotSelected(e1);
    }
 
    protected void IsSelected(IWebElement element)
    {
        Assert.True(element.IsSelected());
    }
 
    protected void IsNotSelected(IWebElement element)
    {
        Assert.False(element.IsSelected());
    }
 
    [Fact]
    public void CheckboxTests()
    {
        var e1 = Driver.FindElement(By.Id("c1"));
        var e2 = Driver.FindElement(By.Id("c2"));
 
        IsNotChecked(e1);
        IsChecked(e2);
 
        e1.Click();
        IsChecked(e1);
 
        e1.Click();
        IsNotChecked(e1);
    }
 
    protected void IsChecked(IWebElement element)
    {
        Assert.True(element.IsChecked());
    }
 
    protected void IsNotChecked(IWebElement element)
    {
        Assert.False(element.IsChecked());
    }
 
    [Fact]
    public void OptionTests()
    {
        var e1 = Driver.FindElement(By.Id("s1"));
 
        var option1 = e1.GetOptionByValue("a");
        var option2 = e1.GetOptionByValue("b");
 
        IsNotSelected(option1);
        IsSelected(option2);
 
        option1.Click();
 
        IsSelected(option1);
        IsNotSelected(option2);
    }
 
    [Fact]
    public void ToggleCheckedTests()
    {
        var e1 = Driver.FindElement(By.Id("c1"));
        IsNotChecked(e1);
 
        e1.SetChecked();
        IsChecked(e1);
 
        e1.SetChecked();
        IsChecked(e1);
 
        e1.SetUnchecked();
        IsNotChecked(e1);
 
        e1.SetUnchecked();
        IsNotChecked(e1);
    }
}

TestPage.htm

<html> <body> <p> <select id="s1"> <option value="a">Ant</option> <option value="b" selected="selected">Bird</option> </select> </p> <p> <input id="r1" type="radio" name="r" value="c" />Cat<br> <input id="r2" type="radio" name="r" value="d" checked="checked" />Dog </p> <p> <input id="c1" type="checkbox" name="vehicle" value="e" />Elephant<br> <input id="c2" type="checkbox" name="vehicle" value="f" checked="checked" />Fox </p> </body> </html>
Shout it

Enjoy,
Tom

Thursday, January 3, 2013

How To: Play GOG Games on Android with DosBox Turbo

Good Old Games

If you like classic games, then GOG is the online game retailer for you. Not only do they have a great selection of retro and modern games, but best of all they are provided DRM free.

Many of the old DOS games that GOG sells come preconfigured to run DOSBox behind the scenes. For those of you not familiar with DOSBox, it is the leading open source DOS emulator.

This is great because GOG can offer the original game experience without having to modify any of the game files or their content. Also, this allows users to run those same games on any platform that has a port of DOSBox available!

DosBox Turbo for Android

There are three DOS emulators available on Android, the best of which (by far) is DosBox Turbo. It costs approximately $3 dollars, but I assure you that it is worth every penny. It is feature rich, stable, and fast.

DosBox Turbo on the Google Play Store

Additionally there is a free app called DosBox Manager that helps manage your DosBox configuration profiles for game or program that you wish to run. This is extremely useful and I strongly suggest that you get it, especially because (as mentioned before) it is free!

DosBox Manager on the Google Play Store

Installation & Configuration

  1. Install Android Applications

Simply install the two applications, DosBox Turbo amd DosBox Manager, from the Google Play store.

  1. Get GOG Games

Purchase, download, and install your desired GOG games onto your computer. Not all GOG games use DOSBox, thus not all GOG games will run on Android; here is a list of games GOG games that use DOSBox.

  1. Copy GOG Games to Android

Connect your android device to your computer, create a DOS folder at the root of your storage, and then copy your GOG games to there. Note: You do not have to copy the DOSBox folder.

Here is an example of where I installed Master of Orion on my computer, and which folders I copied to my ASUS Transformer tablet.

  1. Configure DosBox Manager

If you are using DosBox Manager, then you will never have to launch the DosBox Turbo application directly. Once your games are copied over, launch DosBox Manager so that you can create profiles for your games.

  1. Copy DosBox Profile

Copy the "Default" DosBox configuration by clicking and holding down on the icon. When prompted, select "Copy Profile" and enter the new name of your game; in my example this would be "Master of Orion".

  1. Configure DosBox Profile

This is by far the most complicated step. Click and hold down on the new configuration file, and when prompted select "Edit Configuration". Each game configuration could be different, but there are at least 2 or 3 steps that will always need to be updated.

First, scroll down in the configuration and enable "Screen Scaling". This will allow your screen resolution to scale up to the full screen size of your Android device.

Second, for a game like Master of Orion, I would suggest setting your "Mouse Tracking" option to "Absolute (experimental)". This will allow you to click on the screen like a touch screen instead of moving the mouse around like a touch pad. Note: This may not be ideal for all gaming experiences.

Third, and this is the most important step, we must edit the Autoexec to launch your game! Select the "DosBox Settings" sub-menu, and then select "Autoexec". Here we can enter a series of commands that will be automatically executed whenever this DosBox profile launches. Here are the commands to launch Master of Orion from the directory that I copied it's files to earlier:

mount c: /storage/sdcard0/
c:
cd: dos/orion
orion.exe

That's it, you are done! Click "OK" and back out of the menu until you return to the DosBox Manager home screen.

 

  1. Set DosBox Profile Icon

This step is completely optional, but I like to set Profile Icons for my games. Click and hold down again on your game profile, select "Change Icon", and then navigate to and select whichever image you would like to be your profile icon.

  1. Launch Your Game

You are now ready to play GOG games on your Android device. Simply click on the game Profile that you would like to play, and have fun!

 

Enjoy,
Tom

Real Time Web Analytics