Sunday, 4 October 2009

SVN Notify by Email

Svn hook to email you information in post commit hook.

Install svnnotify which will be used to send the email

yum install perl-CPAN
perl -MCPAN -e 'install SVN::Notify'
perl -MCPAN -e 'install SVN::Notify::HTML::ColorDiff'


The post-commit script


#!/bin/sh
for i in 'email1@domain.co.uk' 'email2@domain.com'
do
svnnotify --repos-path "$1" \
--revision "$2" \
--to $i \
--from account@example.co.uk \
--handler HTML::ColorDiff -d \
done

Saturday, 26 September 2009

jqRunner Snapshot - Running Javascript Unit test with NUnit

One of the nice things about unit tests is that you can use continuous integration so that you don't have to run them yourself. At work we use CruiseControl.NET to automate our builds and run our unit tests. Now as a number of our projects are web based we use a fair amount of javascript, mainly jQuery, though in-house plugins. In order to test these we use jqunit, this works great and allows us to use TDD when writing javascript. However as development goes on the unit tests get forgotten about as they are not automatically ran.

In order so solve this I decided to experiment to find a method of getting cruise control to run our jqunit tests for me. To run the tests I looked at wrapping the jqunit tests with nunit tests.

jqRunner

jqRunner is designed so that you can us your existing jqunit tests in their existing location without changing them. jqRunner required that all the scripts that are needed to run are registered. The full path to the file is required. jqRunner then executes the tests and returns the results, which are then parsed by nunit as tests using the TestCaseSource attribute.

var sampleTestCase = new jqUnit.TestCase('Sample Test Case', function() {
/*setup*/
// this.yep(1);
}, function() {
/*teardown*/
// this.ok(1)
});
sampleTestCase.test('Sample Test 1', function() {
this.ok(1);
});
sampleTestCase.test('Sample Test 2', function() {
this.ok(0);
});



using System;
using System.Collections.Generic;
using NUnit.Framework;
using jqRunner;
using System.IO;
using System.Reflection;

namespace jqRunner.Tests
{
[TestFixture,RequiresSTA]
public class TestCaseSourceTests
{
[Test, TestCaseSource("GetTestResults"), RequiresSTA]
public void CheckTest(ITestResult result)
{
Assert.IsTrue(result.Pass, result.Name);
}

private static ITestResult[] GetTestResults()
{
string jsFile = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase) + @"\jqUnitTests\SampleUnitTest.js";
TestBed target = new TestBed();
target.RegisterScript(jsFile);
return target.Execute().ToArray();
}
}
}



This is an initial development snapshot and is bound to have plenty of problems.

Download
http://static.yeticode.co.uk/blog/downloads/jqRunner-snapshot.zip

Related Reading











Wednesday, 16 September 2009

Pirate Day! Arr

So talk like a pirate day is coming around soon and saw a brilliant method of converting web pages from boring English to cool Pirate talk. So having nothing better to do at the moment I knocked up a small plugin that will convert your blog posts to pirate talk on the 19th, to give your readers something nice to look at.

Plugin can be found at http://wordpress.org/extend/plugins/pirate-talk/

Feel free to make it better.

Monday, 14 September 2009

Epic Fail, but with a good note.


So last Sunday was the 2009 Yorkshireman Off Road Marathon. Everything was going great, even though the course was nothing like I had run on before, but it was not meant to be. I injured my knee running down a hill and had to drop out at 18 mile mark. Although I failed Tom managed to man it up and complete it with enough energy at the end to call me gay whilst running up the last hill towards the finish line. So the entire event was not a complete waste of time.


Although I didn't complete it, I did however run further and for longer than previously. If I hadn't injured myself I'm absolutely positive that I would have completed the race. The course did give me areas that I need to work on, such as running off road more. And finding some really big ass hills to run up and down.


The failure to complete this marathon has certainly given me more than enough drive to enter the Brighton marathon and fully prepare myself for it so that I will be able to complete it without issue.

Monday, 24 August 2009

More Django Plugin Stuff

MonoDevelop Django

So I've been working more on the support for django within monodevelop. Heres some screenshots of it.


MonoDevelop Django

MonoDevelop Django

Monday, 17 August 2009

Hacking on Monodevelop for Django

MonoDevelop Django

So I started to implement support for django with MonoDevelop. It currently has pretty good support for Python via PyBinding addon. At the moment I have only managed to add the ability to create a new django project, which acts in the same way as running


django-admin.py startproject projectname


But I aim to provide support to add new django apps to the project, once I get familiar with the MonoDevelop code base.

Friday, 17 July 2009

Plugin Crazy!

So after creating my first proper plugin, post-to-facebook, I decided to have a go at creating another one. This one was created after I set up a blog for my dad to post updates and photos to so that he wouldn't have to resend the same emails to different people. The after giving him a brief overview of how to post items and upload photos I noticed that the images he was uploaded were to large to be correctly displayed, when using the light box plugin. So from this I decided to write a plugin that would allow for the maximum size an uploaded image can be, and if it is larger it is resized. I'll submit it to wordpress for download. This plugin is ideal for people who don't want to worry about resizing their images before they post them to wordpress, this is ideal with. The plugin homepage is can be found on the page resize-on-upload-plugin

Tuesday, 14 July 2009

'Post to Facebook' Wordpress Plugin

post-to-facebook screenshot

After wanting to be able to post stuff to my facebook account from my blog for no other reason than "I Can", I looked around at the plugins that exist at the moment. The ones that I found worked but they were not what I wanted. The closest I got was the plugin Publish To Facebook. What I didn't like about this plugin was that it highjacked the publish/update button. What I wanted was the ability to press a button and publish to facebook for only the posts that choose. So I decided to write my own plugin, that add a button to the edit page to do just this.

The can for the moment the source code can be checked out from bazaar repository, then simply upload the folder to the wp-content/plugins and you're good to go. If you don't like or use bazaar you can download the tar ball.

Download: post-to-facebook.tar.gz

bzr branch http://bzr.yeticode.co.uk/post-to-facebook

Monday, 13 July 2009

Python and CCTray Again

So after creating a python script that would use my tux droid to notify me when a build failed I decided to extend the script a little further. I decoupled it from the tux droid code and added in a status menu. It still requires that CruiseControl.NET has the webdashboard installed. This is my first venture into using GTK with python, as well as threads.

One of the problems that I encountered when trying to use thread was that they were not behaving correctly. The Thread would appear to start however it would not run. This was easy to fix but adding the following line to initialize the threading.


gtk.gdk.threads_init()


In addition to this the class that was running the thread not only had to inherit from the threading.Thread object but had to explicitly call the init on the threads base class


class ccnetworker(threading.Thread):

# init
def __init__(self,xmlPath,pycctray):
threading.Thread.__init__(self)
self.xmlPath = xmlPath
self.pycctray = pycctray


Below is a screen shot of the system tray menu, listing the projects that are available to be force built.

pycctray screenshot


# example usage
python pycctray.py http://localhost/ccnet/XmlServerReport.aspx


You can get the latest source from the bazaar repository


bzr branch http://bzr.yeticode.co.uk/pycctray


Alternatively you can download the source files on their own: pycctray.tar.gz

Friday, 10 July 2009

Tux Droid with Cruise Control .NET

Tux Droid

So after having my tux droid for a while I decided to put it to good use, opposed to making it swear at my housemates, which no matter how entertaining it was did not seem very productive.
I decided to write a small script that would notify me when a build from Cruise Control.NET failed, or when a broken build has successfully been built. At the moment the tux droid speaks a simple message and flaps it wings a little.

The script uses the tux droid python API to make the noises and pulls down an Xml file, via CruiseControl.NET, using urllib and xml.dom, fairly simple stuff.

You can get a copy of the source, which might be more up-to-date, frm the bzr repository.

# bzr branch http://bzr.yeticode.co.uk/ccnet-tuxbot



Usage:
# python ccnet.py http://localhost/ccnet/XmlServerReport.aspx


download ccnet.py
Update 11-07-2009 12:00AM: update notifcations in ccnet.py script.

#!/usr/bin/python
import sys
import urllib
import time
from xml.dom import minidom
from tuxisalive.api import *

def main(xmlPath):
# load the inital settings that we will use to compare against
projects = []

dom = minidom.parse(urllib.urlopen(xmlPath))
for node in dom.getElementsByTagName('Project'):
projects.append({
'name': node.getAttribute('name'),
'lastBuildStatus': node.getAttribute('lastBuildStatus'),
'lastBuildTime': node.getAttribute('lastBuildTime')
})

# start a loop that will check for a build event every 10 seconds
while True:
try:
dom = minidom.parse(urllib.urlopen(xmlPath))
new_projects = []
for node in dom.getElementsByTagName('Project'):
new_projects.append({
'name': node.getAttribute('name'),
'lastBuildStatus': node.getAttribute('lastBuildStatus'),
'lastBuildTime': node.getAttribute('lastBuildTime')
})
for project in new_projects:
# check to see if the project is in the current list
projectFound = False
for p in projects:
if p['name'] == project['name']:
projectFound = True
# check the status of the project against the old status
# ignore if the old status is failed
if (p['lastBuildStatus'] != 'Failure') and (project['lastBuildStatus'] == 'Failure'):
display_message_fail(project)
if (p['lastBuildStatus'] == 'Failure') and (project['lastBuildStatus'] == 'Success'):
display_message_success(project)
if (project['lastBuildStatus'] == 'Success') and (project['lastBuildTime'] != p['lastBuildTime'] ):
display_message_success_build_again(project)

# reset the project status
p['lastBuildStatus'] = project['lastBuildStatus']
p['lastBuildTime'] = project['lastBuildTime']
if not projectFound:
projects.append(project)
display_message_newproject(project)
time.sleep(10)
except KeyboardInterrupt:
# exit time
break

def display_message_fail(project):
msg = 'Someone has broken the %s build' % (project['name'])
speakPhrase(msg)

def display_message_success(project):
msg = '%s is now fixed' % (project['name'])
speakPhrase(msg)

def display_message_new(project):
msg = '%s has been added to cruise control' % (project['name'])
speakPhrase(msg)

def display_message_success_build_again(project):
msg = '%s has successfuly been built' % (project['name'])
speakPhrase(msg)

def speakPhrase(msg):
tux.mouth.open()

tux.tts.setLocutor("Lucy")
tux.tts.speak(msg.encode('utf-8'));
print msg
tux.flippers.on(4)

tux.mouth.close()

def tuxConnect():
""" Wait connected """
tux.server.autoConnect(CLIENT_LEVEL_RESTRICTED, 'TuxPidgin', 'NONE')
if tux.server.waitConnected(10.0):
if tux.dongle.waitConnected(10.0):
if tux.radio.waitConnected(10.0):
return True
else:
print "radio not connected"
return False
else:
print "radio not connected"
return False
else:
print "server not connected"
return False

def printUsage():
print "ccnet.py [url]"
print "\turl - Url of CruiseControl.NET"
print "\t\t eg. http://localhost/ccnet/XmlServerReport.aspx"

if __name__ == "__main__":
if len(sys.argv) == 2:

tgp_ip = "127.0.0.1"
tgp_port = 270
tux = TuxAPI(tgp_ip, tgp_port)
if not tuxConnect():
sys.exit(1)
tux.tts.setEncoding("utf-8")

speakPhrase("Starting Build Bot")
main(sys.argv[1])
speakPhrase("Stopping Build Bot")
tux.server.disconnect()
tux.destroy()
sys.exit(0)
else:
printUsage()

Tuesday, 30 June 2009

Three Mobile On Linux Update

UPDATE: After installing three mobile on Fedora 11 I noticed that the DNS servers had changed. The new one are as follows

DNS Server: 4.2.2.1,4.2.2.2





One thing that I forgot to mention in my previous post about setting up mobile broadband on Fedora 11 is that three do not always set the correct DNS servers. This was annoying as it would appear that the connection was working however any attempt to access a website would timeout. In order to do so edit the connection via NetworkManager and add in the follow DNS server in the IPv4 tab.

DNS Server: 172.31.76.69, 172.31.140.69

The server addresses are comma seperated so you can add DNS server of your choice. I have used the DNS servers that Three normally set up you can use OpenDNS.

Network Manager IPv4 Settings

Sunday, 28 June 2009

Professional ASP.NET MVC 1.0

At work we have been looking at the ASP.NET MVC, model-view-controller, framework. After looking around at various different tutorials and articles we found a sample chapter from the wrox book Professional ASP.NET MVC 1.0. The sample chapter took the hello world example and create a full application. The application, NerdDinner is an application that allows you to create dinner parties and RSPV to them. The sample covers a lot of the functionality that is within ASP.NET MVC. The sample chapter can be found online at Wrox's website with the source code hosted at codeplex.



Professional ASP.NET MVC 1.0



Reading though the sample chapter is a good way to get started with ASP.NET MVC as the chapter explains what it is doing in a easy to understand manor, but more importantly it explains why they are being done. The chapter is a comprehensive walk through of how to create the NerdDinner application. Throughout the chapter the authors provide titbits of useful information, for example the use of the repository pattern and dependency injection. Throughout the chapter the authors trying to enforce good coding practice and often make reference to test driven development which in a later chapter they go into more detail about, discussing different development techniques.

The sample chapter is more than enough to get anyone started with ASP.NET MVC and follows the development process from start to finish including a section on unit testing the application. The following chapters delve into more detail about specific areas of the ASP.NET MVC framework. The second and third chapters go into detail about the MVC pattern, detailing its background and its use on the web. The chapter also provides an overview, albeit brief, of other frameworks that are available. Although their coverage was brief they were not mentioned as either superior or inferior rather just as alternatives to the ASP.NET MVC framework. This tone was subsequently repeated in the third chapter when the authors compare ASP.NET with WebForms to ASP.NET MVC. They often mention that MVC is not a replacement for WebForms rather it is a different approach. These two chapters are extremely useful as they allow you to make an informed decision whether ASP.NET MVC is the right choice for you.

I've still to finish reading the rest of this book so I'll update this post the more I read of it.

Saturday, 20 June 2009

Python and MSSQL

I have been playing about with django a fair bit over the last week. After written a small app with django I wanted to import some data from an existing MSSQL database. To get the data into the django model I created a seperate python script to perform the import. Below is a script to import data from a table compaines in a mssql data to a django model called Company. To connect to the mssql server I used the pymssql library.


#!/usr/bin/env python
import sys,os
os.environ['DJANGO_SETTINGS_MODULE'] ='settings'
# import the modules needed to start the import
import pymssql
from datetime import *
import unicodedata
from django.core.management import setup_environ
import settings

setup_environ(settings)

#import the django models
from apps.clients.models import *

def importCompanies(conn):
cur = conn.cursor()
cur.execute("""SELECT
liCompanyPk,
szCompanyName
FROM companies""")
row = cur.fetchone()
while row:
company = Company()
company.pk = row[0]
company.Name = row[1]
company.save()
row = cur.fetchone()

if len(sys.argv) != 5:
print 'data_import.py [server] [username] [password] [database]'
else:
print 'host=%s, user=%s, password=%s, database=%s' % (sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4])
conn = pymssql.connect(host=sys.argv[1], user=sys.argv[2], password=sys.argv[3], database=sys.argv[4])
importCompanies(conn)
conn.close()


After this I started to play around with pymssql I wanted a quick way to execute simple sql queries, not knowing of an linux alternative to the mysql console client I write another simple script to provide this basic functionality.


#!/usr/bin/env python
import sys,os
import _mssql

if len(sys.argv) != 5:
print 'data_import.py [server] [username] [password] [database]'
else:
print 'host=%s, user=%s, password=%s, database=%s' % (sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4])
conn = _mssql.connect(server=sys.argv[1], user=sys.argv[2], password=sys.argv[3], database=sys.argv[4])
print '>',
cmd = raw_input()
while cmd != 'exit':
if cmd != '':
print cmd
try:
conn.execute_query(cmd)
for row in conn:
for i in range(0,( len(row) / 2 )):
print row[i],'|',
print ''
except _mssql.MssqlDatabaseException,e:
print e
print '>',
cmd = raw_input();

conn.close()

You can download mssql_client.py here

So after only using for python for a couple of weeks It's definitely powerful and fun to code with. Now to try out for all of the libraries that provide bindings such as pysvn or pyldap.

Tuesday, 16 June 2009

Fedora 11 and Mobile Broadband



When I was previously running F10 I managed to get my three mobile broadband setup without any hassle, which I conveniently forgot how to do when I install Fedora 11. After a quick search I found a comment on the redhat bugzilla. I have the ZTE MF622 usb modem from Three. Here the steps I followed to get it up and running.

Install usb_modeswitch, this changes the device from a CD Drive to a usb modem.

#as root
yum install usb_modeswitch


Edit the /etc/usb_modeswitch.conf and uncomment the section that related to your specific modem. This tells usb_modeswitch which modem you are using.

# ZTE MF622 (aka "Onda MDC502HS")
#
# Contributor: "andylog"

DefaultVendor= 0x19d2
DefaultProduct= 0x2000

TargetVendor= 0x19d2
TargetProduct= 0x0002

MessageEndpoint=0x04


Now edit the udev rules to add a new line to automatically call the usb_modeswitch when the device is plugged in.

vi /etc/udev/rules.d/70-persistent-cd.rules


Append the following to the end of the file

ACTION=="add", ATTRS{idVendor}=="19d2", ATTRS{idProduct}=="2000",
RUN+="/usr/bin/usb_modeswitch"


Once this has been done run the following and then plug your modem in


udevadm control --reload-rules


You should now be ready to create a mobile broadband connection via NetworkManager.

Saturday, 13 June 2009

Fedora 11 is out, upgrade time

So Fedora 11 has been out for a little while now and I'm getting ready to upgrade. Previously I have tried using the upgrade facility however I normally end up having to perform a clean install. So now I'm currently backing up my home directories to my external storage ready to wipe everything and start again. Ill update how this goes.

Update: Install was painless simple selecting of packages that wanted to install. However my internet connection was playing up which meant that it hung whilst trying to download packages from the net. Currently installing the nvidia packages from rpmfusion.

Update Everything is up and running and I have restored all my data back on. A few problems and annoyances. There is a problem with the non-free nvidia driver. The only other annoyance is the System -> Preferences menu is not split into further sub menus which creates a menu that doesn't fit on my screen. I have yet to have a proper play with everything else but so far it all looks good.

Friday, 12 June 2009

Django and Python

I have recently started having a play about with django. After reading loads of about it and have a little play about with snowy (a django based note sync for tomboy). After getting used to coding in python I found django really quick to develop in. But the documentation is by far the best thing about the project. There's loads of the stuff, and its brilliant. Its readable. Its completely unlike reading other tech documents. If this isn't a good selling point for checking it out then I don't know what is because RTFMing has never been so easy.

Unit testing jQuery plugins with jqunit

Whilst creating a plugin for jquery, that would provide auto formatting for a textbox for numeric values, I was looking for a way to run the tests for confirm its functionality. After getting sick of running the tests manually the penny dropped that I could unit test the plugins functionality. After a little searching I came across jqunit that seems to fit the bill perfectly.

The project is hosted over at google code. The tests them self run from a html file but the a template is provided with the jqunit library. The tests are simple to create and follow the jquery syntax style. Below is a smple test case with unit test


var numericTestCase = new jqUnit.TestCase('jQuery.numeric - decimal',function(){
/*setup*/

},function(){

/*teardown*/

});
numericTestCase.test('T1: Null Value ',function(){
var txtInput = $("");
txtInput.numeric(true);
txtInput.blur();

jqUnit.equals(txtInput.val(),"0.00");
});


Tests can quickly be written to test the functionality of your code. With the testing being able to run form a single location it provides a quick an easy way to check your plugins work across multiple browsers, that is, as long as you have written the correct tests.

Tuesday, 26 May 2009

Ubuntu UK Podcast

So despite being a fedora user I've recently checked out the uk ubuntu podcast after my lecturer touted my cctray project to them. I've tried listening to tech podcasts before and most of them are dull and tedious to listen to. However the guys who do the ubuntu uk podcast are easy to listen to and quite entertaining. Definitely take the time to check out their latest podcast you won't be disappointed.

Sunday, 24 May 2009

NUnit and NMock

Whist working on a piece of course work for uni I started using NMock as part of some unit tests written using nunit. Having mainly used MSTests for unit tests at work I decided to use nunit as everyone has said that they are very similar. I'm extremely impressed with the potential power that NMock has given me during testing. For the assignment I wrote a small spider application that crawly a site and stores all the link. Using NMock it allowed me to test the structure of the site without requiring internet access. During this assignment I also tried to use the test driven development approach, opposed to my normal sit down and hack away. Not only were there less bugs at the end, the overall quality of my code was noticeable higher. This was largely due to the fact that I had tests already created for what it was meant to do, which required me to put more effort into the implementation. Hopefully I'll keep this style of programming up, and not just forget it as soon as I get back to work.


Here's a sample nunit test that uses nmock. The nmock object mocks the calls that request specific urls and loads the data for local files.

[Test()]
public void MockLinkFinderTest()
{
IMock mockWebClient = new DynamicMock(typeof(IWebClient));
mockWebClient.ExpectAndReturn("GetPage",File.ReadAllText("HTML/1.htm"),new object[]{"http://domain.example/1.htm"});
mockWebClient.ExpectAndReturn("GetPage",File.ReadAllText("HTML/2.htm"),new object[]{"http://domain.example/2.htm"});
mockWebClient.ExpectAndReturn("GetPage",File.ReadAllText("HTML/3.htm"),new object[]{"http://domain.example/3.htm"});

string domain = "domain.example";
string url = "http://domain.example/1.htm";

LinkFinder linkFinder = new LinkFinder();
LinkItemCollection linkCollection = linkFinder.Find(url,domain,(IWebClient)mockWebClient.MockInstance);

int expected = 3;
Assert.AreEqual(expected,linkCollection.Count);
}

Wednesday, 20 May 2009

More Running

So I've managed to keep this running thing up. Not only have I been more than once but I have started to increase the distance I've been continuously running. I am however still trying to get into a regular training pattern as it seems to be a couple of days running, then a break for a couple of days, then running again. I have created a running route that will easily allow me to extend it as I get fitter. So far its only 1.9 miles, according to google, with a half mile run to warm up, and a quarter mile run to warm down. But it is still early days yet and I should have enough time to be ready for the marathon in September. I hope so anyway.

Tuesday, 12 May 2009

New GTK# Project

I've started a new project, RssNotify, to try and learn more about developing applications using GTK. I'll still be developing cctray-gtk as this project is useful, but the RssNotify is more of a project to satisfy my curiosity.

The RssNotify project aims to provide an easy way for a user to receive notifications when an rss feed has been updated. the idea is to use notify-sharp to display the new news items. The rest of the interface will be used to try to explore the features widgets that GTK# offers.

Saturday, 9 May 2009

Running!

So I have now officially started training for the marathon that my brother has convinced me to run. Its a hill marathon, which as far as I've been told it doesn't matter how slowly you do it, as long as you finish. So I'll try and keep a log of my training, although this will mainly be for myself to stop myself slacking off.

Heres the marathon I'll be running
http://www.runnersworld.co.uk/events/viewevent.asp?sp=&v=2&EN=48185.

Wednesday, 6 May 2009

CCTray updates and Mono musings

Impleneted some more to the CCTray-gtk project with the ability to add build servers that communicate over HTTP. This did involve commenting out some of the code in the CCTrayLib project, which was unavoidable. The issue occurred as the library added a delegate to the Service point manager


ServicePointManager.ServerCertificateValidationCallback = delegate{ return true; }


These were causing an exception to be thrown as it is currently not implemented in mono. This so far is the only part of mono that I've found that has caused any problems.

https://bugzilla.novell.com/show_bug.cgi?id=346561

I've also started to implement the ability to remove a project, at the moment it removes the project from the preferences window but does not yet remove the associated project monitor or remove it from the main window's treeview.

Once this has been implemented I will create a release or something for testing.

Thursday, 23 April 2009

33% Additional Disk Space

Hurray! The nice fokes at linode have decided to give all of their customers 33% Additional Disk Space. Now if only all hosting companies were as nice as this.

Wednesday, 22 April 2009

Final Year Project

I've just handed in my final year project, nicely bound and professional. Now that that's out of the way, until the poster day, I can concentrate on getting the gtk-cctray project to work properly using build servers that are not connected via .NET Remoting.

Tuesday, 14 April 2009

SVN Log to Latex

Needed to add a table of my svn log into my project write up so created a simple style sheet that would parse the xml output from svn. The xslt only generates the table

svnlog-gen.sh

#usage svnlog-gen.sh [repo-path] [output-file]
svn log --xml $1 > tmp.out; xsltproc svnlog.xslt tmp.out > $2; rm tmp.out

svnlog.xslt

Example Output

Thursday, 9 April 2009

C# Style for lstinputlisting

After getting latex to format my code nicely I noticed that it did not have build in support for C#, which read of the manual and knocked one up. Share and Enjoy


\lstdefinelanguage{cs}
{morekeywords={abstract,event,new,struct,as,explicit,null,switch
base,extern,object,this,bool,false,operator,throw,
break,finally,out,true,byte,fixed,override,try,
case,float,params,typeof,catch,for,private,uint,
char,foreach,protected,ulong,checked,goto,public,unchecked,
class,if,readonly,unsafe,const,implicit,ref,ushort,
continue,in,return,using,decimal,int,sbyte,virtual,
default,interface,sealed,volatile,delegate,internal,short,void,
do,is,sizeof,while,double,lock,stackalloc,
else,long,static,enum,namespace,string, },
sensitive=false,
morecomment=[l]{//},
morecomment=[s]{/*}{*/},
morestring=[b]",
}


Usage

\lstinputlisting[language=cs]{test-class.cs}

Wednesday, 8 April 2009

New Hosting

Got myself some new hosting over at lindoe. Virtual linux server all to myself. Spent a day trying out the configuration and decided to go with a Ubuntu 8.10.

Wednesday, 1 April 2009

Simple SVN WordPress Widget

After getting bored on working on my final year project I decided to take a look at creating widgets word my blog. There are SVN hooks on my repositories that store the commit details in a SQL database. I thought I would create a widget that would pull out the last message and display it.


/*
Plugin Name: LastCommit
Plugin URI: http://blog.yeticode.co.uk/
Description: Gets Last Commit Message
Author: John Tindell
Version: 1
Author URI: http://blog.yeticode.co.uk/
*/
function lastCommit_widget() {

$server = 'localhost';
$link = mssql_connect($server, 'username', '************');
echo '
  • ';
    echo "

    Last Commit

    ";
    if($link)
    {
    mssql_select_db('svnyeti', $link);
    $query = mssql_query('select top 1 * from SVNLog order by liLogEntryPk desc', $link);
    $row = mssql_fetch_array($query);
    print '

    ' . $row['lszLogEntry'] . '

    ';
    }
    echo '
  • ';
    }
    function init_lastCommit(){
    register_sidebar_widget("LastCommit", "lastCommit_widget");
    }
    add_action("plugins_loaded", "init_lastCommit");


    When I get more time I will develop this a bit more.

    Problems With Yum On Fedora 10

    So every now and again YUM stops working and throwing out error messages usually after I've been to uni.

    rpmdb: Thread/process 4348/3087935168 failed: Thread died in Berkeley DB library
    error: db4 error(-30975) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
    error: cannot open Packages index using db3 - (-30975)
    error: cannot open Packages database in /var/lib/rpm
    Traceback (most recent call last):
    File "/usr/bin/yum", line 29, in
    yummain.user_main(sys.argv[1:], exit_code=True)
    File "/usr/share/yum-cli/yummain.py", line 229, in user_main
    errcode = main(args)
    File "/usr/share/yum-cli/yummain.py", line 84, in main
    base.getOptionsConfig(args)
    File "/usr/share/yum-cli/cli.py", line 184, in getOptionsConfig
    enabled_plugins=self.optparser._splitArg(opts.enableplugins))
    File "/usr/lib/python2.5/site-packages/yum/__init__.py", line 192, in _getConfig
    self._conf = config.readMainConfig(startupconf)
    File "/usr/lib/python2.5/site-packages/yum/config.py", line 774, in readMainConfig
    yumvars['releasever'] = _getsysver(startupconf.installroot, startupconf.distroverpkg)
    File "/usr/lib/python2.5/site-packages/yum/config.py", line 844, in _getsysver
    idx = ts.dbMatch('provides', distroverpkg)
    TypeError: rpmdb open failed


    After a quick search I found a solution. Deleting the __db.* files in /var/lib/rpm fixes it


    $ sudo rm /var/lib/rpm/__db.*

    Saturday, 28 March 2009

    Get PDF Word Count In Linux

    Quick easy way to get the word count of a pdf.


    # pdfwc.sh
    # usage ./pdfwc.sh filename.pdf
    #
    TMPFILE=___tmpfile.tmp
    pdftotext $1 $TMPFILE
    wc $TMPFILE -w
    rm $TMPFILE

    Wednesday, 25 March 2009

    Latex Coloured Code Listings

    Easy way to include code in your latex document and have the syntax coloured correctly


    \usepackage{color}
    \usepackage{listings}

    \lstset{
    tabsize=4,
    language=matlab,
    basicstyle=\scriptsize,
    %upquote=true,
    aboveskip={1.5\baselineskip},
    columns=fixed,
    showstringspaces=false,
    extendedchars=true,
    breaklines=true,
    prebreak = \raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}},
    frame=single,
    showtabs=false,
    showspaces=false,
    showstringspaces=false,
    identifierstyle=\ttfamily,
    keywordstyle=\color[rgb]{0,0,1},
    commentstyle=\color[rgb]{0.133,0.545,0.133},
    stringstyle=\color[rgb]{0.627,0.126,0.941},
    language=Java
    }
    \begin{document}
    \lstinputlisting[title=\textbf{Source Code: filename.java}]{filename.java}
    \end{document}

    Monday, 23 March 2009

    Cruise Control Tray For Linux Update

    Basic functionality has been implemented with the ability to add project to monitor and receive notifications of the build as and when they occur. At the moment there is not the ability to delete a project that is being monitor this will be implemented next. There is also the ability to force a build of a project, however there is not the ability to abort the build, this will also been implemented in the next couple of days hopefully. Here are some more screen shots of what it currently looks like. The build notification have also been attached to the tray icon.




    Wednesday, 18 March 2009

    Cruise Control.NET Tray Tool on linux

    I started looking at creating a port of the cctray tool for CruiseControl.NET but after looking at how it was implemented i decided that it might be easier, and more fun, to implement one myself using mono and GTK#. At the moment the application has the ability to display notification when a build event occurs and to display the list of projects that are being watched. The source code will be available on Launch Pad when I figure out how to use bzr.

    https://code.launchpad.net/~john-yeticode/cctray-gtk/trunk

    here are some screen shots of how it currently looks.





    Cruise Control.NET home page