Move a form without borders in C#


Code snippet that demonstrates how to move around a borderless form, by using the mouse events of the form or other control contained in it. The code below assumes you have a form with a label called label1, and have hooked the mouse down, mouse move, and mouse up events of the label appropriately.

        bool mouseDown = false;
        Point cursorPosition;
        Point formLocation;

        private void label1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                cursorPosition = Cursor.Position;
                formLocation = this.Location;
                mouseDown = true;
                label1.Text = string.Format("{0}, {1}", cursorPosition.X, cursorPosition.Y);
            }
        }

        private void label1_MouseMove(object sender, MouseEventArgs e)
        {
            if (mouseDown)
            {
                int x = Cursor.Position.X - cursorPosition.X;
                int y = Cursor.Position.Y - cursorPosition.Y;
                this.Location = new Point(formLocation.X+x, formLocation.Y+y);
                label1.Text = string.Format("{0}, {1}", x, y);
            }
        }

        private void label1_MouseUp(object sender, MouseEventArgs e)
        {
            mouseDown = false;
        }

Getting started with Corona SDK


This post has links and references for getting started with Corona SDK on a Mac, and running your apps on an iOS device.

Download and install Corona SDK. You’ll need a free starter or a paid account at coronalabs.com to activate the SDK.

You can write your own app in Lua, or execute sample applications using Corona Simulator application. Corona SDK has several libraries at your disposal. I am particularly interested in UI development, and bridging Lua and C to access external hardware such as Bluetooth LE peripherals. That ability to build native extensions requires a paid enterprise license.

You can build and deploy the app to an iOS device for further testing. The build process happens online and requires an internet connection.

Learning Android by Marko Gargenta and Masumi Nakamura; O’Reilly Media


Learning Android is a relatively short book that leads you through building a real-world application. It is a book for beginners to Android who want to start building end-to-end applications now. It does not cover server-side programming, or cloud programming as we’re increasingly apt to call it, but reuses existing services developed by the authors.

The books starts with an overview of Android in Chapter 1, with topics such as its history and marketshare. That chapter is followed by a review of Java programming in Chapter 2, which I read because I have been away from Java programming a while.

Chapter 3 provides an overview of Android’s architecture. I wasn’t aware of the Binder RPC mechanism, that the Bionic libc was implemented to avoid L-GPL licensing restriction of glibc, nor that Dalvik is a register based Java virtual machine named after a village in Iceland.

Chapter 4 contains instructions on downloading and installing Java and the Android SDK. The book uses Eclipse IDE in all how-to discussions but does mention Android Studio. Chapter 5 dives into the main building blocks available to developers such as Activities, Intents, Services, Content Providers, Broadcast Receivers, and Application context. The remaining chapters thoroughly explore these building blocks as you build an application called Yamba.

You get introduced to the Yamba application in Chapter 6. Chapter 7 builds the main user interface using Activities. It also discusses performing tasks in the background using AsyncTask. Chapter 8 delves into composing UI using Fragments. Chapter 9 delves into managing preferences stored in the filesystem. Chapter 10 discusses a background service to refresh data obtained over the internet. Chapter 11 discusses SQLite database and content providers to manage and provide data. Chapter 12 delves into list views and adapters to present large amounts of data efficiently. It also discusses building a landscape version of the Yamba app.

Chapter 13 delves into receiving intents using broadcast receivers to periodically refresh data over the internet and to notify the user. Chapter 14 discusses creating a Widget for the app, that can be placed on the home screen. Chapter 15 delves into accessing data over the internet using HTTP. Chapter 16, the final chapter, shows you how to create live wallpapers and handle user interactions using handlers.

To keep up the pace, I wasn’t actually coding the app. Readers who did, have reported inconsistencies in the code. Look at the book’s errata page, and report any new problems you encounter. I thank O’Reilly Media for providing me an e-book for review.

Lua dofile and globals


I have been doing dissector development for Wireshark in Lua for a while now. Lua’s mechanism for reusing code organized across multiple files comes in two flavors, dofile and require. For historical reasons, we’ve been using dofile quite exclusively.

Our dissector files mostly contain global functions, and local or global tables. The tables are used to determine which function should be called to dissect a particular message, to look-up names that map to particular key values, and so on. If a script file needs a function or table in another file, we simply dofile the other file at the top. Lua interpreter will recognize all globals (functions and variables without local) of the other file from that point onwards.

Let’s consider an example. Here’s file1.lua

function f1()
  print("f1 called")
  f2()
end

dofile("file2.lua")

f1()

Here’s file2.lua, located in the same folder as file1.lua

function f2()
  print("f2 called")
end

When you run file1.lua, this is what you get

$ lua file1.lua
f1 called
f2 called

Lua only encounters call to global f2 inside function f1 when we call function f1 towards the end of file1.lua. If we call f1 right at the beginning of file1.lua we get

$ lua file1.lua
lua: file1.lua:2: attempt to call global 'f1' (a nil value)
stack traceback:
	file1.lua:2: in main chunk
	[C]: in ?

If we move dofile towards the end of file1.lua we get

$ lua file1.lua
f1 called
lua: file1.lua:3: attempt to call global 'f2' (a nil value)
stack traceback:
	file1.lua:3: in function 'f1'
	file1.lua:7: in main chunk
	[C]: in ?

Summing it up, a global exists only when Lua has encountered it, whether within the same or another script file.

Let us explore one other characteristic of dofile with another example. This is file1.lua

dofile("file2.lua")
hello['world'] = 'hello!'
print(hello['world'])

function f1()
  print(hello['world'])
  f3()
end

dofile("file3.lua")

f1()

It requires a certain global table in file2.lua, which it updates before using. It also requires a certain function f3 in file3.lua. This is file2.lua

hello = {['hello']='world!'}

function f2()
  print("f2 called")
end

This is file3.lua

dofile('file2.lua')

function f3()
  print('f3 called')
  f2()
end

It needs function f2 in file2.lua. You shouldn’t need dofile because file1.lua has already loaded file2.lua, but whoever coded file3.lua probably doesn’t know that. Let’s execute file1.lua and see what happens

$ lua file1.lua
hello!
nil
f3 called
f2 called

By the time function f1 gets called, the value of key 'world' in the hello table ceases to exist. Why? Because, right before f1 is called, when we dofile file3.lua it will dofile file2.lua. Since file2.lua gets interpreted again, the global hello is replaced by a new table.

Summing it up, Lua will load and execute the same file again when it encounters dofile, redefining all globals in it.

That is why, for reusing code in other script files, use require. Lua will not reinterpret a script file that has already been encountered before. Modifying the example scripts above is straightforward. Replace all dofile with require and drop the lua extension. Thus dofile('file2.lua') will become require('file2'). Execute file1.lua thus

$ export LUA_PATH=$PWD/?.lua
$ lua file1.lua
hello!
hello!
f3 called
f2 called

Globals now work without side-effects! Note the use of LUA_PATH environment variable to specify the search path for Lua scripts. You can also set search path inside a Lua script by modifying package.path.

What if you have already invested in dofile and don’t want to change things for now? In the example above, modifying file2.lua thus, eliminates our problem

if hello == nil then hello = { } end
hello['hello']='world!'

function f2()
  print("f2 called")
end

Monthly news review


This post reviews news in the month that has passed. Comment below to leave your opinion.

$150 Smartphone spectrometer can tell the number of calories in your food

Not a day goes by without a new accessory for Smartphone being unveiled. We now have accessories for everything from health to payments. A miniature spectrometer is however something unheard of, especially one backed by a cloud service that learns from every scan. One step closer to the tricorder. Awesome.

The perfect iOS email app finally exists

Accompli is being touted as a better (nay perfect) e-mail app. Like Outlook, it has mail, calendar and contacts, all working seamlessly. The attachments view is fantastic to quickly find and send attachments. There are a few rough edges, which is to be expected in a freshly baked app.

HTML5 apps can be just as speedy as native apps with the new Famo.us Javascript framework

The Famo.us open source framework is tackling performance of mobile browsers as a platform problem aka HTML5 head-on. Currently, their site is invite-only, which I received a couple of days back. I’ve been through their demos using Chrome for Desktop and iOS and they are stellar.

Car-hacking: A New Fear For Drivers of Tech-Loaded Vehicles

As our cars get more tech savvy and connected, they’ll be more prone to the same kinds of vulnerabilities that affect other computing devices. While you are still driving around in your old(ish) car you can still do some neat things this month: use CarPlay if you have the right system from Pioneer, control your Smartphone hands-free using Bluetooth LE, evaluate your driving performance, and get haptic feedback to avoid running into trouble. The latter is rather ambitious.

Massive Security Bug In OpenSSL Could Affect A Huge Chunk Of The Internet

I hope you have heard of this flaw already. Otherwise, stop whatever you’re doing, update your computer systems, review what your service providers have done about it, and change your passwords on compromised services. It is serious and needs immediate action. The sad thing is that the flaw has been known to some for a while.

Now, when did our governments decide they could spy on us without using the legal system? Brazil has taken the first steps to prevent that kind of thing from happening by passing an Internet Bill of Rights (text in Portuguese).

Amazon unveils Fire TV

Amazon has taken a leap over Apple’s hobby by creating a device for its Prime subscribers. It also looks like a nice low-end game console, no console (pun intended) there for Nintendo and others. If I were Nintendo, I would stop making consoles (sold at cost) and make money on mobile games. Amazon has also subtly changed their branding by not calling it Kindle Fire TV.

Microsoft Launches .NET Foundation

Microsoft is recognizing the fact that the .NET community is keen on using C# everywhere. A C# programmer can now target several platforms thanks to Xamarin. Reuse is the keyword that comes to mind when thinking of .NET these days. It used to be so with Java, and thanks to Google and Android it still is (somewhat). Oracle, though, wants to litigate instead of fanning the embers.

In related news, Microsoft has also announced that Windows for the internet of things will be free. That includes all devices with screen size under 9 inches. And, PC users can now update Windows 8.1. Slowly and steadily Microsoft has made Windows 8 more PC-user friendly.

Gifting e-books


Not all e-book retailers allow gifting. At work, we’re using gifting so that our centralized purchase department can pay for books and gift back to whoever requested the purchase.

Here’s a list of retailers that allow gifting:

  • amazon.com
  • smashwords.com
  • iTunes Store

Common calls in a communications API


Inspired by several generic interfaces in the Unix/Linux world such as the socket API, and event-driven programming, I have been using the following calls (functions or methods, and event notifications) in my communications APIs.

  • init – May be replaced by the constructor of a class. Creates resources that are held for the lifetime of this object. A corresponding call destroy may also be implemented for deterministic finalization of resources.
  • connect(configuration, callback) – Where configuration provides whatever configuration information is required for connection. It may also be passed to init or obtained by some other means. callback is invoked when connection is established. If implementing a server API, use onConnect for notification of incoming connection.
  • onConnect(connection) – Event notification when an incoming connection is established.
  • disconnect(callback) – Finalizes communication, and calls callback when done. In a server API disconnect may receive an additional parameter indicating which connection to disconnect from.
  • onDisconnect() – Event notification when a disconnection happens and disconnect has not been invoked.
  • onReceive(data) – Event notification when incoming data is received.
  • send(data) – Called when data needs to be sent. If data is an array of bytes, it may receive additional parameters such as start index and length. It may additionally receive a callback that is called when data is sent out (if the API buffers data).
  • onError(error) – Event notification when an error needs to be communicated.

Event notifications can be implemented differently in various languages. I have used callback function in C, delegates in .NET, event listeners (observers) in Java, Blocks in Objective C, and EventEmitter in Node.js.