Tag Archives: C++

Windows Resource – Access Denied

In the Windows PC industry it is very common for applications to attached resources to an executable. Resources can be anything from bitmaps, UI components, string translations and copyright information. These resources are then used by the executable at runtime and also by Windows Explorer (for icons and properties information).

Resources can be modified post compilation by using three methods provided by MSDN: BeginUpdateResource, UpdateResource and EndUpdateResource. I recently had to use these methods and painfully discovered a nasty race condition between my resource updater application and Windows Explorer. I found information on these random failures to be scarce, hence the blog post…

When you are modifying the resource of an executable or DLL and Windows Explorer is open and showing the directory of the file being updated (regardless of visibility), a file access race condition exists that produces one of the following two errors:

The system cannot open the device or file specified.

Access denied.

The numbers I collected show an average file access failure rate of 2.3% when updating a resource that Explorer is also showing. If you are experiencing these errors simply close Windows Explorer and your resource updater application will function as expected every time. Given that Windows is closed source I can’t confirm exactly what Explorer is doing but my hypotheses is that Explorer temporarily opens and reads the resources of each file in the directory (most likely so it can determine which icon to show) and refreshes that resource when it notices a change to the file. If your updater application requests a file handle during this time you will see one of the above errors.

Web Apps – The More Custom The Better

I’m a big fan of the WebKit Qt framework integration. It will without a doubt change the face of web based content delivery over the next few decades (previous post). By far the most powerful aspect of this integration is the ability to create custom JavaScript APIs for hybrid web based applications in a browser.

Put simply, browsers can customize the functionally they offer by implementing features into the browser that can be accessed by web content via JavaScript.  Web apps that exercise this functionally must be written to do so, making them “custom” web apps.  Meaning that an app written to utilize features defined in certain browsers will not work without modification in Explorer, Firefox, or Chrome. For example, when GE integrates a web browser into their next generation refrigerators, it would be beneficial to expose an API that allowed an app to check the inside temperature or level of the ice tray.

I’ve been in many debates with other engineers about this option.  Not one engineer has ever agreed with me right off the bat.  Most oppose doing it as it limits were an app can be run and defeats the purpose of web content.  The “purpose” being mass distribution and play-ability on many different standardize browsers.  Most don’t understand why you’d create a web app that can only be executed on a limited number of browsers.  Many also argue that it burdens app developers with having to learn yet another JavaScript API.  Regardless of the objection, this option is widely opposed and not fully understood by most engineers.

The engineering objections are easy to argue against.  First of all, there is no such thing as a standardized browser.  Despite standardization efforts from W3C,  the JavaScript language is a mess.  The big three, IE, Firefox, and Chrome all use a different JavaScript engine and have varying degrees of standardization completeness (some even have features not covered by W3C).  If you want your website to work across the big 3 you already have to add additional code.  I know its a stretch, but this is already a form of web app customization.

The real value add of customized web apps is from a business perspective.  I come from the embedded device world where the number of units sold is the driving factor (compared to the number of hits). By forcing apps to write to your API you are ensuring a certain level of stickiness.  It can be a competitive advantage to limit the devices an app can run on by exposing custom functionality through the browser.  GE won’t want its ice tray level app to run on LG with no modification for the same reason Apple does’t want its apps to run on Android without a rewrite.

Adding a custom JavaScript API to your Qt WebKit browser is easy.  Nokia has a great blog post on its forum here. To illustrate its simplicity I’ve included my own snippet below.

Any C++ object can be complied into the browser and exposed to the JS engine.

class FakeObject
{
public:
	FakeObject(QObject *parent);
public slots:
	posterInternalCommand(QString command, QString data);
signals:
	fakeSignal();
}

FakeObject::FakeObject(QObject *parent)
{

}

bool FakeObject::postInternalCommand(QString command, QString data)
{
	// Do something with data
	return True;
}

FakeObject::emitSignalTest()
{
	emit fakeSignal();
}

After instantiation the object is exposed to the JS engine using a QWebFrame method.

FakeObject* m_pfake = new FakeObject(webView);
webView->page()->mainFrame()->addToJavaScriptWindowObject(QString("fake"),m_pFake);

The exposed object can now be acted on via JavaScript. Public slots are methods that can be called directly from JS. Signals can also be connected to local JS methods making for more asynchronous functionality.

b = window.fake.postInternalCommand("fakeCommand", "fakeData")

function fakeCallBack(){
	x = x + 1
}

window.fake.fakeSignal.connect(fakeCallBack)

Qt & WebKit Browsers

I don’t recall if it was Nokia or Trolltech who originally decided to add a WebKit widget to Qt. Regardless, its a fantastic addition to the framework and the ramifications to the world are still not yet fully known.

We’re all familiar with web browsers primarily on our PCs and mobile phones. That is going to change… in a big way. Qt has made it simple for development teams to create custom browsers that can run anywhere and inside any application. As a result we’re going to start seeing web browser in our cars, kitchen appliances, digital picture frames, remote controls, and even exercise equipment.

Below you will find an example I wrote using the Qt WebKit support. Its a very simple “custom” browser that allows an application to instantiate the object and render any HTML.

Header file (wijibrowser.h):

#include <QtGui>
#include <QWebView>

class WijiBrowser : public QMainWindow
{
    Q_OBJECT

public:
    WijiBrowser();
    ~WijiBrowser();

    bool loadUrl(QString name, QString url);
    bool loadHTML(QString name, QString html);
    QString contentName() { return m_name; }
    QString url() { return (view ? view->url().toString() : QString("none")); }

protected slots:
    void finishLoading(bool ok);

private:
    QString m_name;
    QWebView *view;
};

CPP file (wijibrowser.cpp):

#include <QtGui>
#include <QtWebKit>
#include "wijibrowser.h"

WijiBrowser::WijiBrowser()
{
    m_name = "unknown";

    QNetworkProxyFactory::setUseSystemConfiguration(true);

    view = new QWebView(this);
    view->load(QUrl("http://www.immersivelabs.com"));
    connect(view, SIGNAL(loadFinished(bool)), SLOT(finishLoading(bool)));

    setCentralWidget(view);
    setUnifiedTitleAndToolBarOnMac(true);
}

WijiBrowser::~WijiBrowser()
{
	delete view;
}

void WijiBrowser::finishLoading(bool ok)
{
	QString status = (ok ? "OK" : "Failed");
	QString url = view->url().toString();
	QString msg = QString("finishLoading %1 - %2").arg(url).arg(status);
	qDebug(msg);
}

bool WijiBrowser::loadUrl(QString name, QString url)
{
	m_name = name;
    view->load(QUrl(url));
}

bool WijiBrowser::loadHTML(QString name, QString html)
{
	m_name = name;
	view->setHtml(html);
}

And here is a simple main.cpp to launch it:

#include <QtGui>
#include "wijibrowser.h"

int main(int argc, char * argv[])
{
    QApplication app(argc, argv);
    WijiBrowser browser;
    browser.show();
    return app.exec();
}

Thrift RPC Framework

At TechStars, Alessio Signorini and I had the opportunity to experiment with Facebook’s Thrift remote procedure call (RPC) framework. I was thoroughly impressed with the framework and feel it takes distributed computing to whole new level. Every developer regularly working on both large and small client/server architectures must be familiar with this tool.

Developers can easily specify data types (parameters) and server interface definitions (API) in a plain text file. Thrift uses this text file to create programming language independent client and server stub files. What makes this so powerful, is that system architects can now choose the appropriate programing language for each area of the system.

Not all programing languages are created equal and no one language contains just positive attributes. It is often the case that the ideal language for a server is Java or C++, but the client would best be written in Python. Thrift allows you to easily choose the best language for the job without having to reinvent the communication protocol every-time you change the language.

This framework is a game changer for software developers and system architects. If you haven’t already done so I strongly encourage you to start playing with it. Below is an example thrift file that defines several data types and one service. Once this interface is defined it can easily be converted into stubs for any language which keeps the interface API separate from the implementation. Read the whitepaper here.

#!/usr/local/bin/thrift --gen cpp:pure_enums --gen php

namespace cpp displaymanager

enum pushResult
{
  OK,
  BUSY,
  INVALID
}

struct pushUrl
{
  1:  string name,
  2:  string url
}

struct pushHtml
{
  1:   string name,
  2:   string data
}

service displaymanager
{
  pushResult fetchUrl(1: pushUrl url);
  pushResult postHtml(1: pushHtml html);
  string	 whatsLoaded();
  string	 currentUrl();
}