Apr 27 2013

Listening to cricket in New Zealand

Category: How Do I | TravelDerek @ 17:03

I like cricket, and now I have relocated from the UK to New Zealand I’ve had to find methods of listening to cricket. Not watching, I cannot give up days watching cricket, but on the radio I can have it on and still get things done.

England International Cricket

My usual method of listening England international cricket was Test Match Special on 5live. However its usually region locked so to listening requires some sort of UK VPN. I use expat shield, though I would not recommend installing in into anything other than a virtual machine with an undo disk as it does tend to make a mess of your machine. Then TMS can be accessed. In practice this means using a computer and is a bit fiddly. It is worth noting that England home tests are not region locked, only the overseas ones.

A simpler solution is to use Test Match Sofa. It’s a bit sweary and shouty but a viable alternative and by using TuneIn Radio app for a smartphone you have an easy to use portable radio, I have even used it on the bus over 3G.

Domestic Cricket

Domestic cricket is another matter. Its not region locked, however the BBC don’t make it easy to listen. The county cricket schedule is available on the ECB site or on the BBC site. Once you have the schedule, locate the game you are interested in and click on the link. It will then play in flash – which is fine if you want to listen on a computer. I like to use my phone as a portable radio and sometimes use a sleep timer to go to sleep to.

To do this, hover over the “Windows Media version of this stream” link, you should see on the status bar or tooltip a link that ends in intXX.asx, if you are doing this on a phone you will probably have to click on the link and download the asx file. Either way what you need it the number after int and before .asx. If for example it says int7.asx then the number is 7. Now go to TuneIn and search for BBC Live Event 7 and you can listen. If you are listening to a four day county game then it will probably be on the same number for all four days.

Other Countries

Sometimes I listen to Australian cricket and to get ABC I use clover.fm as a proxy.

Tags:

Mar 23 2013

Windows Media Center in NZ using DVB-S

Category: Gadgets | General | TravelDerek @ 22:28

I’ve blogged about getting Windows Media Center to work in New Zealand using an aerial, DVB-T. Of course as soon as I got it to work properly we moved house again and this time there isn't any coverage using an aerial. Instead the house does have a satellite dish, so I set about trying to get Media Center to work with a DVB-S decoder.

I bought an AVerMedia AVer3D Satellite TV Tuner, I have to largely because I could buy it over here. It seems to work fine, I have to say that reception using a satellite dish is a lot better than using an aerial even in a good reception area.

Of course the setup needed some magic numbers to get it right. The first task was to setup the tuner in Media Center. When you are setting up the TV source in Media Center select Satellite as the signal type, select No for More Than One Tuner. Then you need to select Opus D1 NZ as the satellite, a Custom Single LNB and the frequency needs to be 11,300. I don't know if this changes across the country but this works for me here in Porirua. Then let it scan for stations, you should get lots of stations.

This is fine, but you also need to setup EPGCollector so that you get the guide, this is my EPGCollector.ini file

[GENERAL]
Output=C:\ProgramData\Geekzone\EPG Collector\TVGuide.xml
Timeouts=10,300,5
Option=USENUMERICCRID,USEIMAGE,DUPLICATESAMECHANNELS,WMCIMPORT,AUTOMAPEPG,ALLSERIES,WMCSTARSPECIAL

[DVBS]
Satellite=1600
Dish=11300000,11300000,0
TuningFile=160.0°E Optus D1.xml
ScanningFrequency=12483000,22500,3/4,H,MHEG5

The scanning frequency was the hard one to get, I ended up trying all of the ones that were specified in the tuning file.

From what I can tell having used it for a month, this is a far better option than using a DVB-T decoder, the picture is much better.

Tags:

Feb 24 2013

TextByNumbers

Category: Development | Mobile | WebDerek @ 18:29

I’ve been taking a break from PodcastUtilities to start work on a new project TextByNumbers. TextByNumbers is designed to enable people putting together letters / emails / SMS messages from snippets that the user can easily produce. Its should be useable on phones with or without a data connection.

I did think of writing a native app, I guess it would be an android app as I have an adroid phone but then I thought that I could do something cross platform if I used HTML5. I selected JQuery Mobile and Knockoutjs for my architecture. So I have come up with the first cut version of the app. The basic functionality has been done and the app does work and has a couple of users already

tbn1

Key features

  1. As its HTML5 it works on modern smartphones and desktops and tablets
  2. It is entirely client side code there is no server side code at all, the web server is just used to deliver static content.
  3. It is an offline app using an appcache so that it will work when disconnected from the network
  4. The format of the snippets is a JSON packet meaning that its pretty easy to drop in a new set of snippets – see below

Catagories

[
{"CatagoryId":1,"Display":"Query Type"},
{"CatagoryId":2,"Display":"Impact"},
{"CatagoryId":3,"Display":"Action"},
{"CatagoryId":4,"Display":"Timescale"}
]

Snippets

[
{"CatagoryId":1,"Display":"I have got your email"},
{"CatagoryId":1,"Display":"I have received a report from a customer on {DATE} at {TIME}"},
{"CatagoryId":2,"Display":"The system is completely down"},
{"CatagoryId":2,"Display":"I cannot reproduce this problem"},
{"CatagoryId":2,"Display":"There is an issue, however there is a workaround"},
{"CatagoryId":2,"Display":"I do not understand the impact of the problem yet"},
{"CatagoryId":3,"Display":"We must fix production as soon as possible"},
{"CatagoryId":3,"Display":"We can live with the workaround until tomorrow"},
{"CatagoryId":3,"Display":"This needs to be raised as a defect"},
{"CatagoryId":4,"Display":"I will contact you again in one hour"},
{"CatagoryId":4,"Display":"We can discuss this tomorrow"},
{"CatagoryId":4,"Display":"Let me know the issue number and I will prioritise the fix"},
]

Main things I learnt

  1. appcache is not a configured MIME type by default in IIS7 – sigh
  2. Chrome is by far and away the easiest browser to debug in – it has direct support for appcache files
  3. The appcache must be updated to force the browser to reload all the content from the server – only after the new appcache is downloaded will the new content be fetched, this meant when a new version is deployed you will have to press F5 twice in the browser
  4. In general phone based browsers are a bit more flaky than desktop, for instance some times I have to manually empty the cache to get the app updated, sometime my local storage will go away etc.
  5. I used JQuery Mobile and Knockoutjs and at times they got in each others way. I will do a separate blog post of the tweaking that I found myself doing.
  6. Prepopulating an SMS message does not work on older Samsung phones due to a bug in its implementation of the SMS protocol, I’ve had no problems with my HTC handsets and apparently Samsung have fixed this in their handsets that use version 4 of Android. It does not work on iOS – as far as I can tell this is by design so it will probably never be fixed. However a manual cut and paste method can be used and is still quicker than typing text from scratch

Conclusion

In general the platform was pretty much what I was expecting its still an immature architecture by comparison to .NET development or even native development however I think that the results are completely acceptable (I’ll will await user feedback) and I can see that for some scenarios that the significantly lower cost against native development will be compelling. As it stands at the moment I think that a native app will deliver a more polished solution, but will require multiple implementations across the market place (iOS, Android, Windows Phone etc). 

Tags:

Jan 19 2013

Windows Media Center in New Zealand

Category: Gadgets | General | TravelDerek @ 16:33

Last year I moved from the UK to New Zealand. I brought with me my Media Center hoping that I could get it to work.

It turns out that TV is broadcast over here using DVB-T (and DVB-T2 for HD) just like Freeview in the UK so it does work to the extent that I can watch live TV. However getting the EPG working was another matter all together and the results are mixed, is does work – sort of.

First of all in New Zealand the full 5 day EPG is broadcast in MHEG5 format and Windows Media Center (WMC) does not support this format. There is a piece of software called EPG Collector that can be used to get the EPG and then load it into the WMC guide database. I have to say that it is a very impressive piece of software and is very well supported.

I just installed EPG Collector and then I have this script that I run as administrator

c:
cd "\Program Files (x86)\Geekzone\EPG Collector"
pause
EPGCollector.exe
pause

The collector is configured using an INI file. The DVBT section is specific to the transmitter that I use (I live in Wellington) if you look in “C:\Program Files (x86)\Geekzone\EPG Collector\Configuration\TuningParameters” you will see that there are a large number of files.

[GENERAL]
Output=C:\ProgramData\Geekzone\EPG Collector\TVGuide.xml
Timeouts=10,300,5
Option=USEIMAGE,DUPLICATESAMECHANNELS,WMCIMPORT,AUTOMAPEPG,ALLSERIES,WMCSTARSPECIAL

[DVBT]
TuningFile=New Zealand.Wellington - Kaukau (After June 2012).xml
ScanningFrequency=578000,8,MHEG5

[LOOKUPS]
MovieLookupEnabled=no
TVLookupEnabled=no
TVImage=poster
LookupMatching=Exact
LookupNotFound=yes
LookupReload=no
LookupIgnoreCategories=no
LookupProcessAsTVSeries=no
LookupErrors=5
LookupTimeLimit=60

You can use the EPG Collector UI to generate this file or just edit it in notepad. There are full instructions here.

I just run the script every week and I have a complete EPG, scheduled recordings and series recording all work fine.

There are a couple of problems. The first is that reception is not always great, I get digital breakup on some channels to the point that its not really watchable. It is strange and I do have line of sight on the Kaukau mast. Luckily it is only a few channels that are affected and for instance TV One is pretty bad but TV One +1 is fine so I just exclude TV One

The other problem is more annoying, The dots. This is a problem that has been much discussed and the general consensus is that it is caused by WMC downloading EIT data and overwriting the EPG Collector data. It certainly seems to be the problem, the guide data will be fine and then after a couple of days some of the channels will just have dots (.) as the program title for all programs. I have applied the registry settings to disable WMC from downloading the EIT data

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Media Center\Service\BackgroundScanner]
"PeriodicScanEnabled"=dword:00000000

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Media Center\Service\GLID]
"DisableInbandScheduleLoading"=dword:00000001

However it still happens intermittently, sometimes it will happen for three successive days and sometimes not at all for weeks. It is driving me nuts and I still haven't got a proper solution.

Actually while writing this post I have noticed that one of the settings might be wrong, this post seems to think the the setting should be like this

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Media Center\Service\BackgroundScanner]
"PeriodicScanEnabled"=dword:00000000

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Media Center\Service\GLID]
"DisableInbandSchedule"=dword:00000001

I will try this setting and see if the dots stay away.

Tags:

Dec 25 2012

Refactoring code using default parameters

Category: Code Review | DevelopmentDerek @ 02:22

Recently I have come across code that had been refactored using default parameters in C#. The refactoring had taken place in a DLL and it caused an interesting problem in the calling client code. When I looked at the code at first I could not understand how the refactoring had broken the client code so I experimented with this code to reproduce the problem.

The original code looked something like this.

namespace Library
{
    public class Utility
    {
        public string TestMethod()
        {
            return "original";
        }
    }
}

The client code like this

namespace CallError
{
    class Program
    {
        static void Main(string[] args)
        {
            var util = new Library.Utility();
            Console.WriteLine(util.TestMethod());
            Console.Read();
        }
    }
}

This was refactored to this

namespace Library
{
    public class Utility
    {
        public string TestMethod(System.Uri uri = null)
        {
            return "new";
        }
    }
}

Now I thought this would just work, After all there is no need to change the client code as the missing parameter will be defaulted. However when the client code was executed against the new Library DLL I got the following error.

Unhandled Exception: System.MissingMethodException: 
Method not found: 'System.String Library.Utility.TestMethod()'. at CallError.Program.Main(String[] args)

However when I recompiled the CallError client code it ran fine. Then when I though about it there error made sense: even with a default parameter the method signature has actually changed.

It made me think that care need to be taken when using default parameters in an external api interface.

Tags:

Nov 17 2012

Ajax requests in HTML5 offline applications

Category: Development | WebDerek @ 22:31

I’ve started having a look at writing offline applications. Its good fun to write using different technology and I am discovering that the whole HTML5 stack is still very immature. The stack I’d settled on for my first attempts is: HTML5, jQuery, jQueryMobile and Knockoutjs.

The first stumbling block I came across was that ajax calls work differently when in offline mode. It turns out that jQuery returns a status code of zero when the request is satisfied from the cache which upsets the usual code where we are looking for 200 (OK).

One possible solution suggested in the jQeryMobile documentation, is to attach an ajaxPrefilter that will set the isLocal flag to get jQuery to process the zero status correctly. However I did not want to alter the jQuery ajax mechanism completely, I wanted to just affected the ajax calls I was making. Also setting the isLocal flag does achieve the desired result at the moment however it may not work correctly in the future.

I decided to detect the process the zero status code myself using code like this.

function JsonDataSource(url,dataCallback) {
    var self = this;
    self.url = url;
    self.dataCallback = null;
    self.reloadFromServer = false;

    self.getData = function(reloadFromServer, dataCallback) {
        self.dataCallback = dataCallback;
        self.reloadFromServer = reloadFromServer;

        $.ajax({
            type: "GET",
            url: self.url,
            cache: !reloadFromServer,
            contentType: "application/json",
            dataType: "text",
            error: function (jqXHR, textStatus, errorThrown) {
                self.processErrorResult(jqXHR, textStatus, errorThrown);
            },
            success: function (data) {
                self.processDataResult(data,false)
            }
        });        
    };

    self.processErrorResult = function (jqXHR, textStatus, errorThrown) {
        if (jqXHR.status === 0 && jqXHR.responseText.length > 0)
        {
            // the approved method of detecting the cache
            // is a zero return code and data being returned
            self.processDataResult(jqXHR.responseText, true);
            return;
        }
        self.errorResult(jqXHR,textStatus,errorThrown);
    };

    self.errorResult = function (jqXHR, textStatus, errorThrown) {
        if (jqXHR.status === 0) {
                alert('Not connect.\n Verify Network.');
            } else if (jqXHR.status == 404) {
                alert('Requested page not found. [404]');
            } else if (jqXHR.status == 500) {
                alert('Internal Server Error [500].');
            } else if (textStatus === 'parsererror') {
                alert('Requested JSON parse failed.');
            } else if (textStatus === 'timeout') {
                alert('Time out error.');
            } else if (textStatus === 'abort') {
                alert('Ajax request aborted.');
            } else {
                alert('Uncaught Error (' + jqXHR.status + ') .\n' + jqXHR.responseText);
            }
    };

    self.processDataResult = function (data,fromCache) {
        var object = eval('(' + data + ')');
        self.dataCallback(object,fromCache,self.reloadFromServer);
    };
}

Then I can call it like this

    self.catagoryDataSource = new JsonDataSource('viewmodel/catagory-json.txt');

    self.loadCatagories = function (catagories, fromCache, reloadFromServer) {
        for (var i = 0; i < catagories.length; i++) {
            self.catagories.push(
                new Catagory(catagories[i].CatagoryId,catagories[i].Display));
        }
    };

    self.catagoryDataSource.getData(false, self.loadCatagories);

This struck me as a neater solution. This will load data from a text file that can either be obtained from the server of from the local cache if we are offline. I use eval rather than JSON.Parse as it is supported on more browsers and I have complete control over both ends of the link.

Tags:

Oct 20 2012

appcache MIME type for IIS

Category: Development | WebDerek @ 16:31

This month I have a rant, I am not a big fan of rants in blog posts as they never really seem to achieve much and really just seem to be be a bit self promoting. However I’ve not had one before and last month I came across a topic that is worthy.

I’ve started a pet project to write a browser based HTML5 app. In the past we have produced a version of a Windows Mobile app that ran in a browser it was interesting but not really a great experience. Its advantage was nothing needed to be installed and it worked on most devices however it did required an internet connection.

I’ve always thought that an app the can handle online and offline operation would be useful and interesting to produce, I need to get better at using Javascript and at last HTML5 seems to have progressed to the point that its useable. So I started putting together some proof of concept code, the part of HTML5 that makes offline apps possible is appcache. Its a file that you include in your web site and reference from HTML its main purpose is to specify to the browser which parts of your app can be cached and which cannot, a part being a URL.

Part of the magic depends on the appcache file being returned with the correct MIME type, as it says on w3schools

A manifest file needs to be served with the correct MIME-type, which is "text/cache-manifest". Must be configured on the web server.

My host (godaddy) is windows IIS7 based, and given the background reading I’d done that the recommended file extension was changed from manifest to appcache to avoid a clash with a Microsoft used extension almost two years ago I thought that all would be well. Wrong. The MIME type is still not set by default in IIS.

Here is my rant.We download megabytes of data every “patch Tuesday” and two years later IIS still has not had its MIME types updated.

Luckily I came across this life saving post and added this to my web.config and offline apps work.

  <system.web>
    <httpHandlers>
      <add verb="GET,HEAD" path="*.appcache" type="System.Web.StaticFileHandler" />
    </httpHandlers>
  </system.web>
  <system.webServer>
    <staticContent>
      <mimeMap fileExtension=".appcache" mimeType="text/cache-manifest" />
    </staticContent>
  </system.webServer>

Tags:

Sep 11 2012

PodcastUtilities: New Version

Category: PodcastUtilities | DevelopmentDerek @ 02:25

We have just completed a new version of PodcastUtilities, it now supports a post download command. Using this command its easy to hook up utilities such as MP3Gain or any other post processing command. This build also contains some bug fixes including support for running the utilities from UNC paths.

There is a ready-to-go compiled Windows version available to download, which includes the utilities and documentation.

We are planning to take a bit of break from working on the utilities but we will still continue to maintain the code and fix bugs.

Tags:

Aug 17 2012

Exception handling in services in a production environment

Category: Development | GeneralDerek @ 16:40

I have written about using Enterprise Library to log exceptions in a production environment, specifically how to cope when the loggers will not write to files or event logs.

Recently I came across a problem where the whole logging framework was failing to initialise in a production environment. What we got was the usual generic error message and nothing useful in the event logs and obviously the logging framework did not receive anything.

service

In this instance the problem was that the config file (which was being rewritten between deployment environments) was malformed. However in principle the logging framework could fail to start for any number of reasons.

Since this has happen as a matter of routine I always wrap the logging framework initialisation in a try catch the will write any errors to the debug console so that I can use DbgView to see what has gone wrong.

        static private void OutputToDebugConsole(string format, params object[] args)
        {
            Trace.Write(string.Format(format, args));
        }

        protected override void OnStart(string[] args)
        {
            OutputToDebugConsole("RemoteControlService Starting");

            try
            {
                _iocContainer = InitializeIocContainer();
                _logwriter = _iocContainer.Resolve();
            }
            catch (Exception ex)
            {
                // we have no other method of communication - lets try the debug console
                OutputToDebugConsole("RemoteControlService Error creating logger: {0}", ex.Message);
                throw;
            }

Writing to the debug console is a good choice because DbgView does not require any installation, just copy the EXE and run it. This means that operations are more likely to allow it to be run in a production environment. To be able to see the errors that are produced when trying to start the service you must run DbgView as administrator and also enable “Capture Global Win32” on the Capture menu of DbgView.

For example this is what we see if an arbitrary error was thrown by trying to initialise the _logwriter.

dbgview error2

Its also worth noting that Trace.Write is used rather than Debug.Write as calls to Trace will still produce output when we compile for release whereas Debug will not.

Tags:

Jul 25 2012

Using OpenCover and nUnit

Category: Development | How Do IDerek @ 01:59

Previously I have written about using OpenCover with xUnit. It struck me that I should probably also do the same for nUnit as that is what we use in PodcastUtilities

The structure of these scripts is slightly different from the xUnit scripts as they have to work both 16 and 32 bit.

The master script looks like this

call SetProgramFilesEnv.bat
if "%ProgramFilesPath%" == "" exit 1
set opencovercmd="%LocalAppData%\Apps\OpenCover\OpenCover.Console.exe"
set nunitcmd="%ProgramFilesPath%\NUnit 2.6\bin\nunit-console-x86.exe"
%opencovercmd% -register:user -target:%nunitcmd% -targetargs:"/noshadow /apartment:mta PodcastUtilities.nunit" -targetdir:"." -output:coverage.xml -filter:"+[PodcastUtilities.Common]* +[PodcastUtilities.Presentation]* -[PodcastUtilities.Common]PodcastUtilities.Common.Platform* -[PodcastUtilities.Common]PodcastUtilities.Common.Exceptions*"
rem this is a generator available from http://reportgenerator.codeplex.com/
.\Tools\ReportGenerator\ReportGenerator.exe coverage.xml .\Coverage

OpenCover installs into the %LocalAppData% path which does make writing scripts easy. Once again I have used the /noshadow option just for speed

If I did not specify the /apartment option then I got the following error as by default it attempts to run the tests in the STA and the PodcastUtility tests need to be run in the MTA

1) SetUp Error : PodcastUtilities.Common.Tests.TaskPoolTests.WhenATaskCompletesAndThereAreStillTasksLeftToRun.ItShouldStartTheNextTask
   SetUp : System.NotSupportedException : WaitAll for multiple handles on a STA thread is not supported.
   at System.Threading.WaitHandle.WaitMultiple(WaitHandle[] waitHandles, Int32 millisecondsTimeout, Boolean exitContext, Boolean WaitAll)

To accommodate 32 bit and 64 bit users the SetProgramFilesEnv.bat sets up the correct path like this

set ProgramFilesPath=

if not "%PROGRAMFILES(x86)%" == "" goto win64
if not "%ProgramFiles%" == "" goto win32
echo Cannot find program files environment variable
pause
goto end

:win32
set ProgramFilesPath=%ProgramFiles%
goto end

:win64
set ProgramFilesPath=%PROGRAMFILES(x86)%

:end

The excellent ReportGenerator is “installed” (unzipped) in a sub folder

Tags: