Category : Development

Gradle Generate Release Notes from Git

I thought my ‘Gradle Generate Release Notes’ script might be useful for others, so here you go:

If you are using the built in Gradle tool for Android Studio and you want to automagically generate release notes (or a list of commit messages) from Git then this little script might help (whilst it is pretty specific for Android Studio, it could easily be modified for any Gradle

AndroidStudio

I got the inspiration from this post over at coders kitchen – but it seemed a little to complex for my needs, so I cut it right back to just text based, and just dates and commit messages between the tags. More than sufficient for my needs.

Git – Push to a new remote server repository

Short reminder to myself on how to create a new server repo and do the initial push to it from a workstation.

On the Server:

cd Repositories
mkdir Project.git
git init –bare

On the Workstation:

cd Project
git init
git add *
git commit “Initial commit”
git remote add origin username@server.com/disk/shares/repositories/project.git
git push –u origin master

Done.

Drag and Drop from a TreeView to a DataGridView

imageAn application I was working on recently needed the ability for the user to drag a TreeView node onto a DataGridView, and when ‘dropped’ create a new row in the DataGridView.image

It is not difficult, but took me a while to put all the relevant pieces together, so I thought I’d post it in case someone else finds it useful.

image

There are four key aspects to it, summarized as :

  1. Call ‘DoDragDrop’ in the ‘ItemDrag’ event of the source control.
  2. Setting the ‘DragDropEffect’ in the ‘DragEnter’ event of the destination control
  3. Setting ‘AllowDrop’ to true on the destination control
  4. Handling the ‘DragDrop’ event on the destination control.

Inside the ‘ItemDrag’ event we call the DoDragDrop function, this initiates the whole drag drop feature. Setting the DragDropEffect in the DragEnter event on the destination control gives the user a visual clue as to whether it is a move, copy, shortcut etc, by changing the pointer to the correct icon.
Setting ‘AllowDrop’ to true enables the destination control to ‘accept’ the item being dropped onto it, and finally in the DragDrop event of the destination control we do the actual work (get the details of the item that was dragged and put it into the DataGridView in our case).

Another thing to consider is whether you just want to add the dragged item to the destination control, or whether you want to insert it at a particular location based on where the item was dropped.
To insert at a particular location, you’ll need to get the X and Y co-ords of the drop location, then translate this to the correct X and Y location with reference to the control itself, and from that get the current item that lives at that location on the control and use that as the reference for inserting the new item.

The code below shows the relevant bits :

void treeView1_ItemDrag(object sender, System.Windows.Forms.ItemDragEventArgs e)
{
    DoDragDrop(e.Item, DragDropEffects.Copy);
}

void dgvSteps_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
    e.Effect = DragDropEffects.Copy;
}

private void dgvSteps_DragDrop(object sender, DragEventArgs e)
{
    TreeNode treeNode = (TreeNode)e.Data.GetData(typeof(TreeNode));
    if (treeNode.Tag == null)
    {
        return; // ignore the category nodes
    }

    // Find out where the drop occurred
    Point pnt = dgvSteps.PointToClient(new Point(e.X, e.Y));
    DataGridView.HitTestInfo info = dgvSteps.HitTest(pnt.X, pnt.Y);
    if (info.RowIndex == –1)
    {
        // it was dropped on an empty area so add at end
        InsertNewRowAtEnd((MyObj)treeView.Tag);
    }
    else
    {
        // it was dropped on an existing row, so insert before that row
        InsertNewRow((MyObj)treeView.Tag, info.RowIndex);
    }
    RefreshDataView();
}

Hope someone finds this useful. Drop me a line in the comments with any questions, or if you found this useful.

GEO: 51.4043807983398 : -1.2872029542923

 

Android Development / Hundred Pushups App

android_logoThis is a bit of a mixed post, Eclipse / Android development versus Visual Studio / Windows development, and a bit of self promotion of my ‘Hundred Pushups’ app.

I have been a fan of the Hundred Pushup Challenge for some time, having done weeks 3 – 6 a number of times and completed the challenge a few times.
A few months ago while I was on the site I noticed there was an iPhone app for it but no Android app. I had been looking for excuse to build ‘something Android’ for a while and this looked like an ideal candidate (I am a massive Android fanboy !!).

The application requirements were not too complex, provide the 6 week, times 3 day, time 3 level schedule, a way of recording workouts and tests and some figuring out accelerated advancement of weeks based on test results. A bit of database back end, a bit of schedule / table UI and a couple of screens each for workouts and test.

I downloaded the Android SDK, tools and development environment (Eclipse) and got started. I use subversion for source control and there is a well integrated SVN plugin for Eclipse, so that was all fine. The first hurdle was the framework / API, but that is fairly common when looking at a new framework / toolset – and is simply down to experience. So, although things took longer than I expected, I have no complaints there – plenty of online examples on how to do various tasks.visual_studio_logo

The next hurdle was the UI – it has to be said that the UI tools for Android are nowhere near the sophistication of the Visual Studio experience. This is not down to developer experience, or understanding different methodologies – the UI design tools are just not there – there is no visual layout tool. I found this to be the most frustrating aspect – rework the xml layout definition, trial run, scratch head as to when certain elements were just not visible – rinse and repeat.

As a comparison, I just finished a client component for some back end technology I have been working on – this has treeview controls, three interlinked datagrids, toolbars and menus with buttons, dropdowns and dropdown buttons – this took around 3 days, compared to over two weeks with Android for a main ‘switchboard’ screen with button branching off to four ‘task’ screens – no complex UI elements al all.

The reason Microsoft and .NET are so ubiquitous is the barrier to entry is so low – they give the tools away for free (express SKUs) and the UI design / prototyping is so fast – I can have a complex desktop UI application up and running in hours, not days. Android has some way to go before it can match this, and , unfortunately, I feel that even though a Microsoft / Windows tablet may be technically inferior (i.e. more bloated), it will win in the end because the development tools are easier making applications more readily available / pervasive.

Gratuitous Self Promotion

So, unfortunately, when I got my Hundred Pushups app completed the guy responsible for Hundred Pushups had already agreed to give the digital rights to someone else. He asked me not to release my app in the Android Market, which I can respect. However, I do believe that (right now – April 2011) my app is better than the paid for version available from the people who have the digital rights. I have included some screenshots below. If you want to test this out then drop me a mail and I’ll left you have a copy…

ss1ss2ss3ss4ss5

GEO 51.4043388366699:-1.2875679731369

Twitter oAuth from C#

A while back I was working on a ‘post to Twitter’ function that used the original Basic Authentication that the Twitter V1.0 API allowed.

Unfortunately, at the end of Aug 2010 they discontinued support for this and forced everyone to use their oAuth authentication. There are a number of services around (such as SuperTweet) that will proxy your Basic Auth to Twitters oAuth, but really your best bet is to upgrade your code to support oAuth.

It is actually not as difficult as it may sound – here’s how I upgraded my code :-

First go to http://dev.twitter.com/apps/new and register your application. When complete you’ll get the details you need in a page like this :

image

You do need to make sure that you have enabled both Read and Write access if you plan to post updates from your application.

Next, grab this zip file with the oAuth.cs and oAuthTwitter.cs classes that Eran Sandler wrote and Shannon Whitley extended, and add those to your project (make sure you change the namespace !)

Now in your class you need to create an oAuth object and assign the ConsumerKey and ConsumerSecret properties to the values given to you in the Twitter API settings page. Now when someone wants to Authorize your app to work with their account you need to get the authorization link and fire up a browser navigating to that link :

oAuthTwitter _oAuth = new oAuthTwitter();

_oAuth.ConsumerKey = "AAAAAAAAVGJTAZerhSFsafvg";
_oAuth.ConsumerSecret = "AAAAAAAgSgLfwFZDSQ3AZNDA5LwMfPnmPJud7kbCzo";

string authLink = _oAuth.AuthorizationLinkGet();
System.Diagnostics.Process.Start(authLink);

The result of them clicking ‘Allow’ in the web browser is a PIN. You need to use that PIN in a call to AccessTokenGet which finally populates the Token and TokenSecret properties of the oAuth object.

_oAuth.AccessTokenGet(_oAuth.OAuthToken, thePin);
string Token = _oAuth.Token;
string TokenSecret = _oAuth.TokenSecret;

Now (very important) you need to save the Token and TokenSecret for later use (you don’t want your user having to authorize for every update).
To send an update is now a simple affair – create an oAuthTwitter object, set the properties and then use the oAuthWebRequest function:

oAuthTwitter _oAuth = new oAuthTwitter();

_oAuth.ConsumerKey = "12345GJITAZerhSFsafvg";
_oAuth.ConsumerSecret = "lkjghKJGHblgLfwFZDSQ3AZNDA5RLwMfPnmPJud7kbCzo";
_oAuth.PIN = thePin;
_oAuth.Token = theToken;
_oAuth.TokenSecret = theTokenSecret;

string url = "http://twitter.com/statuses/update.xml";
string tweet = System.Web.HttpUtility.UrlEncode("status=" + "Tweet from my application!");
string xml = _oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, url, tweet);

We’re done ! Less than 20 lines of code.

GEO: 51.4043862206013 : -1.28720283508302

CurrentCost Power Monitor Software – Take 2

cc128-large_01

This post is an update to my previous one about the CurrentCost Energy Monitor and the software I built for it.

After posting brief details about it, I agreed with the guys over at the MSDN Coding for Fun site to write a full project article  for them. The suggested a couple of changes – using the Managed Extension Framework (MEF) stuff available in .NET 4 and a Windows Phone 7 client, to make it more generally appealing.

I had not seen the MEF stuff before, but it turned out great – very simple framework that allows a full ‘plugin’ style architecture in around 10 lines of code. I also had little experience with the Xaml stuff required for WinPhone 7 apps, but it is actually pretty simple.

There are a number of plugins and clients for it now including :

            • A plugin to post to Twitter every X minutes (using oAuth)
            • A plugin to post to Pachube streams
            • A plugin to post to a web service
            • A web page to display the latest readings sent to the web service
            • A Windows Phone 7 application to display the latest reading sent to the web service
            • A Windows Sidebar Gadget to display the latest reading sent to the web service

I have also had submissions from a couple of other developers, one for a plugin that posts to Google PowerMeter and another that records the readings in a database – both of these will be uploaded to the Codeplex site when I have them integrated into the source and working correctly.

Anyway, you can read all about it here. There is also a Codeplex site for all the source code and binaries.

Post in the comments if you have suggestions for other plugins or features, or want to get involved.

GEO 51.4043388366699:-1.2875679731369

CurrentCost Power Monitor Software

cc128-large_01 I recently bought a device to monitor our household energy consumption. After looking at a few I lumped for a CurrentCost Envi. this is a great little device that comes in two parts – a transmitter with jaws that wrap around the main power cable coming into your home and a desktop display unit. The communication is all wireless and I have found that it works okay through two thick brick walls.

the reason for going with this particular unit was that it has a data port that can connect to a USB port and feed it’s readings to a PC – I wanted to be able to monitor the readings on my PC and chart/analyse them at will.

imageThe communication to the PC is basically via USB, but emulating a serial port COM connection – the CurrentCost website has links to the drivers you’ll need for this.

I wanted to, not only, record the readings but to chart them (on my website), get regular updates via various notification methods and a few other bits. Unfortunately, none of the software applications listed on their website covered all the items that I wanted – so I set about writing something myself…

My initial thoughts were around just sending the data to Google PowerMeter, but at that stage the API was not public and their forums/groups were not very active (6 posts in about 18 months), so I abandoned that and decided a ‘DIY’ approach was needed.
UPDATE: It looks like there may be some substance to it now, so that is another area to look at (another plugin)…

imageThe requirements were pretty simple – I wanted a service that grabbed the readings as they came in, decoded them into something intelligible and then pushed them out to a number of ‘modules’ that would do something with the reading. the ‘modules’ would be self contained and new modules could be added at any time. The initial modules would be :-

  • Tweet the reading at a regular interval
  • Record the reading (in a database, Xml file or the like)
  • Send the reading to a website / webservice

It seemed a simple Windows Service with a COM port would be enough to grab the reading, the readings are all in Xml so another class to parse the Xml would be needed and then for the ‘modules’ a ‘plugin’ type architecture was called for. I came up with an interface that all plugins would implement and a method of loading them in dynamically.

Each plugin would inherit from the IPowerMonitorPlugin interface and to load the plugins, each one would be specified in the app.config file with a filename and classname. The service would look at each plugin entry, load the DLL and create an instance of the plugin class :-

    private void LoadPlugins()
    {
        plugins = new ArrayList();

        NameValueCollection appSettings = ConfigurationManager.AppSettings;
        foreach (string key in appSettings.AllKeys)
        {
            if(key.ToLower().StartsWith("plugin"))
            {
                string path = AppDomain.CurrentDomain.BaseDirectory;
                string[] config = appSettings.Get(key).Split(':');
                Assembly ass = Assembly.LoadFile(path + config[0]);
                IPowerMonitorPlugin plugin = (IPowerMonitorPlugin)ass.CreateInstance(config[1]);
                if (null == plugins)
                {
                    plugins = new ArrayList();
                }
                if (!plugins.Contains(plugin))
                {
                    plugin.Init();
                    plugins.Add(plugin);
                }

            }
        }
    }

When the service was working and decoding the readings correctly, I started adding plugins – first was a simple ‘RawXmlWriterPlugin’ – this simple wrote the raw Xml reading data (Reading.RawXml) out to a text file – just to make sure it was working and we were decoding the Xml correctly.

imageThe next service was posting the data to a website – I found this great website (pachube.com) which allows you to track environmental data measurements, have multiple feeds, multiple measurements and has a lot of options for getting data in and out. The API that they provide is pretty simple to push data into and their website allows plenty of ways to visualize the data – for example here is a link to my last 24 hours energy consumption in a chart format, here is my latest temperature reading and here is an archive of all the energy data I have ever posted. there are also mash up to things like iGoogle widgets, Google’s Visualization API, Google Sketchup, iPhone Apps, Android Apps and this rather neat gauge.

From there I started the Twitter service….

 

imagePachubePosterPlugin

The plugin for posting to Pachube requires that you have already create a feed with two datastreams (datastream 0 is energy and datastream 1 is temperature). You will need an API Key and the feed id. Both these items are configured in the app.config file also.

TwitterPlugin

The plugin for ‘tweeting’ to twitter is also pretty simple – all you need is an account (username and password) and the ‘handle’ of the person/account you want to send the message to (if you want to send a direct message). You also specify the message text you wish to send (with placeholders for the energy and temperature values) an the interval (in minutes) of how frequently you wish to send the tweets.

SQL / Xml Storage Plugin

Watch this space … 😉

Source and Package

For the time being either send me an email or post in the comments if you’d like access to the source code.

If you want to run this software yourself then here is a link to a zip file containing the full package. To get it installed, do the following :

  • imageUnzip the package contents into a folder (“C:Program FilesPowerMonitorService” would be good)
  • Open a command prompt and change to the folder above
  • Run the following command line…

“C:WindowsMicrosoft.NETFramework64v2.0.50727InstallUtil.exe” PowerMonitorService.exe (if you are running a 64 bit machine… or)
“C:WindowsMicrosoft.NETFrameworkv2.0.50727InstallUtil.exe” PowerMonitorService.exe (if you are running a 32 bit machine… or)

 

  • Open the PowerMonitorService.exe.config file (in Notepad) and edit your configuration as needed – save when done.
  • Now start the service (Windows..Run..services.msc, find the one named PowerMonitorService, right click and choose “Start”)

Enjoy…

GEO 51.4043388366699:-1.2875679731369

Access ODBC Connection Strings

I was working on an old (classic) ASP page the other day. It was pulling data from an Access database file and using an ODBC driver to get the connection.

It was working fine on a Windows 2003 server, but when I pulled the file into a local website on my Windows 7 machine (with Office 2010 beta) it kept failing at the ODBC layer. The reported error message was :

Microsoft OLE DB Provider for ODBC Drivers error ‘80004005’
[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

Looks like the driver specified in my connection string couldn’t be found. I was using the following :

    objConn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=c:inetpubwwwrootpstdiscovery.mdb;"

This all looked correct and checking the excellent “ConnectionStrings.com” website they were saying the same thing – strange. It then struck me that I’m using Win 7 and Office 2010, either of which could have changed the ODBC driver or installed a new driver, so checking the “Data Sources (ODBC)” tool I see that the driver also works with .accdb files, so I’m guessing this is an updated driver.

Changing the connection string (adding the *.accdb) was the next step.

objConn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ=c:inetpubwwwrootpstdiscovery.mdb;"

Testing with this new connection string worked fine – problem solved….

image

GEO51.4043502807617:-1.28752994537354

 

WebApp KeepAlive Service

image Recently I have been working with DotNetNuke. This is a superb open source CMS platform running on ASP.NET with a SQL back end, simple to install, easy to use and there is a thriving community around it. It is also available in a ‘Professional’ version which costs around £2000 per year and provides additional workflow features, a support contract and various other benefits.

image I choose not to go for the pro version, just because I don’t see much point in having some aspects of a website/webapp covered with a support agreement, but not others (any third party controls/extensions are not covered, and I had bought the excellent DataSprings Suite and was using multiple components from it).

Anyway, when I had everything working the way I wanted, I started to look at performance. There are many websites providing tools and tips around maximizing performance of DNN sites – this includes caching strategies, output compression, turning off none essential ‘housekeeping tasks’ and the like.
One of the tweaks (for low traffic sites) was to ‘kick’ the site every few minutes to ensure that IIS does not unload it (and therefore need to spin it up again the next time someone visits – this can take a good few seconds).image

  My initial thoughts were around a scheduled PowerShell command – simple to come up a one liner to request a page and thus keep the web app in memory.

(new-object “System.Net.WebClient”).DownloadString(“http://www.website.com/”)

Then I thought I might have it ‘kick’ a few websites, and make it configurable, so I started thinking ‘Windows Service’. It turns out that there are a load of these apps and services available to buy, some targeted specifically at DNN, some more generic. Reluctant to spend $20/year on a service I decided to craft my own.

It is basically a windows service, that reads an XML file for a timeout and a list of urls to kick. It implements a 1 second timer and counts down the timeout value, when it reaches 0 it kicks each of the urls (recording how long the response took). I haven’t done anything with the measured response time, but it would be fairly easy to write out to a DB or file for later analysis…

Here is a .zip file with everything you need – binaries, sample configuration file, install instructions and full source. It is Creative Commons license so knock yourself out.

WebAppKeepAlive.zip

GEO 51.4043197631836:-1.28760504722595

TimeSnapper Plugin

Yesterday on Leon’s Blog, secretGeek, I noticed they had released v3.4 of TimeSnapper. One of the features that caught my eye was the ability to develop/add plugins to it.timesnapper_screen

I love plugins, I’ve written plugins for Windows Live Writer, Outlook, dasBlog, and more.  Everything should have an SDK or plugin’able architecture. I championed it at work and we were one of the first Archiving Vendors with a ‘real’ SDK (I’ve built demo Vista Gadgets, integration scripts, federated search providers and PowerShell commandlets for it).

Anyway, the TimeSnapper plugin model looked really clean and easy to use. Read the one page description and your ready to go (didn’t even download the sample code – it was so clear how things worked there was no need).

twitpic_logoI wanted a little play around with it, so I though upload a snapshot to TwitPic would be a good idea. Opening a new project in Visual Studio, adding a reference to the ITimeSnapperPlugin.dll, create a new inherited class from ITimeSnapperPlugin and implement the interface :

 

    #region ITimeSnapperPlugin Members

    bool ITimeSnapperPlugin.Configurable
    {
        get { return true; }
    }

    void ITimeSnapperPlugin.Configure()
    {
        System.Windows.Forms.Form frm = new TwitPicPluginConfig();
        frm.ShowDialog();
    }

    string ITimeSnapperPlugin.Description
    {
        get { return "Uploads snapshots to TwitPic"; }
    }

    string ITimeSnapperPlugin.FriendlyName
    {
        get { return "TwitPic Plugin"; }
    }

    object ITimeSnapperPlugin.HandleEvent(TimeSnapperEvent TimeSnapperEvent, EventArgs args)
    {
        switch (TimeSnapperEvent)
        {
            case TimeSnapperEvent.SnapshotSaved :
                // upload it it to TwitPic
                if (IsTimeToUpload())
                {
                    string fileName = ((TimeSnapperPluginAPI.SnapshotSavedEventArgs)(args)).Activity.Filename;
                    Debug.WriteLine("Uploading " + fileName + " to TwitPic");
                    XmlDocument xmlDoc = UploadToTwitPic(fileName);
                }
                break;

            default :
                Debug.Assert(false, "Should never occur");
                break;
        }
        return null;
    }

    TimeSnapperMenuItem[] ITimeSnapperPlugin.MenuItems()
    {
        return null;
    }

    Guid ITimeSnapperPlugin.PluginID
    {
        get { return new Guid("50744334-C5A0-44f1-BE64-5BBF32FDA79D"); }
    }

    TimeSnapperEvent[] ITimeSnapperPlugin.SubscribesTo()
    {
        return new TimeSnapperEvent[] { TimeSnapperEvent.SnapshotSaved };
    }

 

All that was required was to give it a new Guid and name/description and then subscribe to the ‘SnapShotSaved’ event and handle the event when it was triggered.yedda_logo
To get the image uploaded to TwitPic I used some code from the excellent Yedda Twitter C# Library (just the stuff for posting image data to a url).
That all worked a breeze, but it was sending images (and posting to my twitter account) every 10 seconds (and of course it was hard coded to my username/password) – what was needed was a bit of configuration…

Luckily the plugin model provides an excellent and easy way to do this (set the Configurable property to true, and handle the Configure event). A bit more jiggery pokery, one modal dialog and an XML config file later, it was all working (configurable username, password, twitter message and frequency of updates) – although I really should do something better than store the username/password in clear text in an XML file…

If you want the plugin, just drop this dll into your %install%plugins folder and restart TimeSnapper.

GEO: 51.4043006896973 : -1.28754603862762