Monday 18 May 2009

Removing Process Instances - Apparently I Am Clever

A good year ago i posted on Daniweb (to whom I actively help) a code snippet for using the office interops and creating a wrapper class for them (you can see that post here). Anyway a few private comments and some posts later I received feedback that it was pretty clever, get that eh! So I thought seeing as I may need it sometime and am moving all my useful artifacts over to this blog account I would post it up. The "clever-bit" apparently is in working out a processes unique number so it can be killed later on if there are problems with it. This comes in handy when performing server side or hidden client side interactions with other interops such as Microsoft Office (creating Excel spreadsheets and such) without destroying a users existing session or other sessions that a server may be using (such as threading multiple requests).

The following code function basically works out all existing process' total for a given instance.


<summary>Function to calculate the total sum of process ID's for a given process name.</summary>
<param name="instanceName">The instance to count</param>
Private Shared Function GetTotalProcessID(ByVal instanceName As String) As Integer
For Each diaProc As System.Diagnostics.Process In System.Diagnostics.Process.GetProcessesByName(instanceName)
GetTotalProcessID += diaProc.Id
Next
End Function


This does not seem to special but when performing this before and after we can subtract the first from the second to give us our process' unique number. Bingo! The following code demonstrates this showing an example creating a Microsoft Word instance.


' Get Total before app exists
Dim totalProc As Integer = GetTotalProcessID("winword")
Dim wordApp As Word.Application = New Word.Application()
' Hide alerts and screen updating
wordApp.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone
wordApp.ScreenUpdating = False

' Get New Total and subtract to get out ID
totalProc = GetTotalProcessID("winword") - totalProc

' ... Do some magic with the word instance ...

' When finished you should call 'worApp.Quit()'
' And also 'Marshal.ReleaseComObject(wordApp)'
' But incase that instance just wont go away... Kill it!
System.Diagnostics.Process.GetProcessById(totalProc).Kill()


So there we have it you now have the process' ID and assuming everything goes right you wont have to kill it, but for thos times everything fails you can always fall back on calling "System.Diagnostics.Process.GetProcessById().Kill()" to get rid of that pesky instance.

Sunday 17 May 2009

Background Flickr - Update Your Android Background

As a side project having finished university and wanting to get to grips with the awesome Android SDK I am working on a background photo changer which connects to the public Flickr services. The application will periodically download images from tagged flickr accounts and switch them as often as required for your phones background. The project has a way to go yet but I am looking forward to man handling the Android internals. For more information on the development you can see the project site hosted at Google Code. Also if anybody feels interested in lending a hand your more than welcome and can contact me through the project site.

Thursday 14 May 2009

Java URLEncode

After working on an android project for Google's G1 phone I came across a problem using the java.net.URLEncoder class whereby it was not correctly encoding 3 values in conformance to the RFC 3986. The function URLEncoder.encode(s, enc) does not encode *, ~ or + (asterisk, tilde and plus) which was causing trouble when accessing particularly picky web services with strict definitions on content encoding. So with a bit of botchery you can make the string compliant by encoding them seperately using java Strings built in replace method. The example below shows a bare bones example of encoding a value.


String value = "beans+pies*with~fries"; // Mind the awful scentence
String encoded = URLEncoder.encode(value, "UTF-8");
encoded = encoded.replace("*", "%2A");
encoded = encoded.replace("~", "%7E");
encoded = encoded.replace("+", "%20");
// The output is "beans%20pies%2Awith%7Efries" all done!

Monday 4 May 2009

jQuery Image Preloading with Callbacks

Googling for image preloaders? Yes that was me and I couldn't find anything which fitted the bill. Needing some form of JavaScript to preload an image and then have a callback function trigger when the image had finished loading (for some pretty transitional effects) I set about writing myself a jQuery plugin (as I use jQuery alot!). The code snippet below could easily be adapted for other libraries and I have tested it in all modern browsers and the onload event seems to trigger nicely in all. Its definately not the best way to add an event handler but as mentioned before it seems the most cross-browser friendly.

So here it comes, what you have been waiting for... Just copy the following into your page or seperate JavaScript file (you can even minify it if its too big for you).

* Update: After the glorious Internet Explorer 8 release it seems my code was causing a sporadic race condition bug. It is due to the code executing so fast that it preloaded the image before it appended it to the DOM causing the code to attempt to remove the element before it existed in the document. Not that this was too much of a problem, it simply left several hidden nodes in the DOM. Not to worry though I have updated the script accordingly to stop this in the future by adding a loaded flag to check if the handler has been triggered.


(function($) {
$.extend(jQuery, {
preloadImage: function(src, callback) {
var i = new Image();
var f = false;
i.onload = function() {
f = true;
if(callback !== undefined) { callback(this); }
$(this).remove();
};
if(!f) {
$(i).attr('src', src).css({
position: 'absolute',
display: 'none',
width: 1,
height: 1
}).appendTo(document.body);
}
}
});
}(jQuery));

The above probably needs a little explanation and rightly so. I use the JavaScript onload event property directly on the image object as jQuery's event handling is a little more advanced and for some reason setting this through addEventListener or attachEvent does not result in the desired effect. Also setting the elements position to absolute and its size to 1x1 might appear to be (stupid) adding extra css for the sake of it, the idea is that on a large image I have had some issues with a flicker and a quick resizing of the page before the browsers rendering kicks in so by setting it to 1x1 and absolute we avoid this eventuality.

So you want to use it in page now eh? Then call it using...


var url = 'http://.../yourimage.jpg';
$.preloadImage(url, function(image) {
alert('The image from ' + $(image).attr('src') + ' has finished preloading...');
});

And there you have it. Image preloading made a doddle. I would like to point out that the above will only work if you are using jQuery but as mentioned before it would be very very (very) easy to modify for another library.

And thats all folks.

Saturday 2 May 2009

The Dissertation... It's Over!

Well it is over. Four years, eighteen modules and apparently 2160 hours study time (yeah right) , but seriously I have hit the end of my degree and I can't help but feel like an age is coming to it's end. I'll be no doubt proverbally filling my pants over the next few months awaiting the results but it just would not be the same if it did not have some sort of suspense.

The only milestone to mark that it is truly over is the hand in of the dissertation. To summarise it was "one hell of a" report! Those who wish for a copy can email me as im sure everyone is up for a thrilling read (along with the going rate for the average dissertation... I'll make it a level £1k). (Yes the last sentence was sarcastic and no I will not be giving out my dissertation).

I also have been meaning to get around to working on my personal website lately and its just about finished so you can now see it in all its glory at www.designdotworks.co.uk