LBD: C# Basic Authentication to SubSonic API

The Problem

I have decided that I want to write a C# wrapper around the Subsonic API. Should be easy enough, but as with all things whilst I still have my programming “training wheels” back on at the moment there are some challenges. The first one being how to call the API using Basic Authentication?

The API does provide the option of passing the username and password in the query string:

I really don’t like the thought of passing the unencrypted credentials with every call to the server so I want to implement the Basic Authentication option.

The Solution

The idea of these posts was to write down everything that I did to get to the solution to show people all of the pitfalls they might have. However, in this case I tried so many different things before I got a working solution it just isn’t feesible to put them all in a single post that isn’t about 3000 words long! So this is the abridged version.

The first thing I did was ask the question “How do I call a web service using Basic Authentication?” The first answer from Google was from Stackoverflow.

Using this information I came up with the following ‘Spike’ test to check I could get the response I was looking for from the server:

        public void CallApi()
                var url = "";
                NetworkCredential creds = new NetworkCredential("username", "password");

                WebRequest request = WebRequest.Create(url);
                request.Credentials = creds;

                // Get response
                using (var response = request.GetResponse())
                    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            catch (WebException Ex)


Very quick, very dirty, not my best work, but I was just trying to prove the concept before I go trying to setup the whole project and start implementing all of the API calls.

Unfortunately this didn’t work. I was getting an error message with the value 10 returned indicating a required parameter was missing, as per the API documentation.

This is the point where I lost track of all the things I was trying. I knew it had to be the passing of the credentials as when I added them to the query string of the call and ran the test it worked perfectly and returned OK for the status.

Eventually I stumbled across a post from a Subsonic Developers Google Group from a few years ago. It had a sample in VB which I tested out and worked perfectly. From looking at the code it was the way I passed the credentials with the request. From what I read about using NetworkCredentials it would encode the string and pass it in the headers, but I couldn’t get it to work. This manual method of encoding and then adding to the headers worked so I went with it.

After a bit of cleaning up I now have the following:

public class ServerConfiguration
        public string ServerUrl { get; set; }

        public int Port { get; set; }

        public string RestApi { get; set; }

        public string ApplicationName { get; set; }

        public string UserName { get; set; }

        public string Password { get; set; }
public class SubsonicResponse
        public string Status { get; set; }

        public string Version { get; set; }

        public string Xmlns { get; set; }

 public class ApiCalls
        private readonly ServerConfiguration _server;

        public ApiCalls(ServerConfiguration serverConfiguration)
            _server = serverConfiguration;

        public string Call(string call)
            var jsonString = string.Empty;
                var callUrl = string.Format("{0}:{1}/rest/{2}?v={3}&c={4}&f=json",
                                            _server.Port, call,

                var request = WebRequest.Create(callUrl);
                request.Headers["Authorization"] = "Basic " + EncodeCredentials(_server.UserName, _server.Password);

                // Get response
                using (var response = request.GetResponse())
                    jsonString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                    var json = JObject.Parse(jsonString);
                    var status = JsonConvert.DeserializeObject<SubsonicResponse>(json["subsonic-response"].ToString());
                    if (status.Status != "ok")
                        //handle error here
            catch (WebException Ex)
                //handle error
            return jsonString;

It’s still not the prettiest code, but it works and I can refine the error handling part as I go.

I can pass the API call to this method and it will request a JSON result from the Subsonic server. I can then deserialize this using the Newtonsoft.Json library into strongly typed objects. Well that’s the plan, I haven’t managed to get any further than just checking the ‘Ping’ command works so I am a long way to finished.


This looks like an easy fix, and it was. It just took me a long time to find it. I am sure there must be a way to make it work using NetworkCredentials and a credential cache as all the documentation says it is meant to work for Basic Authentication. I just haven’t figured it out yet.

The next problem is how to unit test this, which will be the topic of the next post.

LBD: Adding Datetimepicker control to MVC project

Note: Learning By Doing (LBD) is an ongoing series of posts I am writing where I work through an everyday problem that I am having while coding. I try to document everything that I do, including all the things that don’t work. You can read more about why here.

The problem

I have a form in MVC5 that sets a date and time and I need a popup control to allow users to easily enter it.

I don’t want to have two controls, one for date and one for time.

The solution v1

As the project is using MVC5 it has Bootstrap built in, so the first thing to do was check what it could offer me. From a quick search it seems I could use either the Bootstrap-datepicker.js or jquery-ui version, they are both wired up the same way, I chose jquery:

Add the ‘datepicker’ class to the control

<div class="col-md-10">
                @Html.TextBoxFor(model => model.StartTime, new {@class = "form-control datepicker "})
                @Html.ValidationMessageFor(model => model.StartTime)

Note in the code above the control is @Html.TextBoxFor. When MVC scaffolds a view for a model normally it uses @Html.EditorFor. I had to change the type of control so that the CSS classes were applied to it properly, when it was @Html.EditorFor then the javascript we are about to add was not be able to find the correct control to work with.

Javascript to wire it up:


Finally add the correct include to the BundleConfig.cs file:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(

The result was not great:

I had a datepicker, but the formatting was off.

This, I realised, was because I hadn’t included the jquery css files. That could be fixed in the BundleConfig.cs file:

 bundles.Add(new StyleBundle("~/Content/css").Include(

Which gave me what I wanted:

Except for one problem; there was no way to enter the time!

The Solution v2

After thinking about what I was trying to achieve and how best to get there, and a little searching, I decided to get rid of the jquery scripts . Whilst it appears to be possible to add a time picker component to the datepicker, it didn’t look all that easy. I also found a Bootstrap DateTimePicker component that seemed to do everything in one simple step. I didn’t want to mix other Bootstrap functions with jquery, I wanted to keep to one library if possible.

I had to just adjust the class on the control I wanted to use (technically this didn’t need to be done, but I wanted it to be as clear as possible):

<div class="col-md-10">
                @Html.TextBoxFor(model => model.StartTime, new {@class = "form-control datetimepicker "})
                @Html.ValidationMessageFor(model => model.StartTime)

Then update the javascript:


Add the two files that come in the zip, one css and one javascript to the project (I wasted some time here as I added them to the wrong project within the solution!) and then update the BundleConfig.js file to include them:

bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(

bundles.Add(new StyleBundle("~/Content/css").Include(

and it didn’t work. No popup when I clicked in the control. Time to debug.

Turns out I hadn’t actually updated the javascript to setup the datetimepicker control. Once that was sorted we had this:

A picker stuck in the top corner and a bunch of javascript errors. More debugging required.

After some Googling and reading code I found the problem was that this version of the datetimepicker was built for Bootstrap v2, MVC5 upgrades Bootstrap to v3 which is what causes the errors I was seeing.

Back to square one!

The Solution v3

A bit more searching lead me to this. A different datetimepicker, and one that works with Bootstrap v3.

Even better, this one can be installed via Nuget.

Install-Package Bootstrap.v3.Datetimepicker

Running this command added new versions of bootstrap-datetimepicker.js and bootstrap-datetimepicker.css to my project. The only additional configuration I needed to do was add moment.js to the BundleConfig.cs file:

bundles.Add(new ScriptBundle("~/bundles/moment").Include(

Ensure this new bundle is added before the bootstrap bundle as bootstrap requires moment to be loaded before it does.

NOTE: I didn’t have to change the HTML or javascript in the view as it was still setup for the previous controls I tried and this one works in exactly the same way.

This gave me (drumroll please……):

With working time section:

As I am going to need to add this control to both the creation and editing pages the simplest thing to do was to pull the javascript out to its own file. This means all of the default values I want are in a single place that I only have to update once for all of the datetimepickers to change in the app:

    pickDate: true,                 //en/disables the date picker
    pickTime: true,                 //en/disables the time picker
    useMinutes: false,              //en/disables the minutes picker
    useSeconds: false,              //en/disables the seconds picker
    startDate: moment().subtract('days', 1)// a minimum date

The startDate option allows me to set the control so only dates in the future can be selected. To set this I use the substract() method from moment.js. The control will only then allow the setting of the current day or any day in the future which is perfect for my needs.

I then just need to add the newly created file (datetimepicker-setup.js) to the Bootstrap bundle in BundleConfig.js:

bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(



The whole process took me about 90 minutes, but at least half of that was because of picking the version of the control that was incompatible. But then that is the point of posts like this, putting down what worked and when it didn’t why not, and how did I fix it.

If I had found the correct Bootstrap version of the control with my first search and installed it with Nuget it would have been done in about 10 minutes.

What I think I can take from this whole experience is that I need to start searching Nuget first when I am looking for a component or control as that is the safest and easiest place to get it from that will require the least amount of configuration.

WatiN Test Recorder on Windows 7 Enterprise (x64)

So it was time to write some functional tests, time to fire up WatiN Test Recorder, but I was presented with the following error:


This was then followed with about 100 similar error boxes stating the app couldn’t find the WatiN.Core assembly. After hunting about for a while on Google, I found the beginnings of the solution here:

The final comment had the write answer, running the following command:

corflags /32bit+ “C:Program Files (x86)WatiN Test RecorderTest Recorder.exe”

However, I didn’t have a bin directory under my Windows SKDs6.0a folder. A bit of investigation later showed that if I ran the Visual Studio Command Prompt then I could access the corflags command from there, and voila Test Recorder fired up perfectly.

Excel Worksheet as a Linked Server

As part of our testing process we periodically randomise names and details in our test database to prove that our systems aren’t dependent on a particular data set.

To achieve this I have a SQL script that randomises things like names, email addresses, phone numbers, bank details etc. To randomise the names I have an Excel spreadsheet with 1200+ first and last names and the SQL script will use these to generate completely new names.

But how to get the data into SQL from the Excel Spreadsheet? Answer Linked Servers!

The following two Microsoft links give the info:

The main bits I needed were:

Using SQL Server Management Studio or Enterprise Manager to configure an Excel data source as a linked server
SQL Server Management Studio (SQL Server 2005)
  1. In SQL Server Management Studio, expand Server Objects in Object Explorer.
  2. Right-click Linked Servers, and then click New linked server.
  3. In the left pane, select the General page, and then follow these steps:
    1. In the first text box, type any name for the linked server.
    2. Select the Other data source option.
    3. In the Provider list, click Microsoft Jet 4.0 OLE DB Provider.
    4. In the Product name box, type Excel for the name of the OLE DB data source.
    5. In the Data source box, type the full path and file name of the Excel file.
    6. In the Provider string box, type Excel 8.0 for an Excel 2002, Excel 2000, or Excel 97 workbook.
    7. Click OK to create the new linked server.

Note In SQL Server Management Studio, you cannot expand the new linked server name to view the list of objects that the server contains.

And then for reading in the info from the file:

The following code imports the data from the Customers worksheet on the Excel linked server “EXCELLINK” into a new SQL Server table named XLImport1:



MSCOMCT2.OCX On Windows 7 x64 Enterprise

So being the trail blazer in the office I decided to install Windows 7 x64 Enterprise on my work laptop when it came time for a re-install, previously I had been on Vista x86 Enterprise, but we have added an additional 2GB of memory to our laptops so I wanted to take advantage of the full 4GB.

I hadn’t had any major issues with the install until it came time to get our Time and Billing database to work which although is in Access 2007 is actually based on the original Access ‘97 version so has dependencies on VB6 controls, so I needed to register the two common control files for VB6 in Windows 7: MSCOMCT2.OCX and COMCTL32.OCX

I tried the usual: placing them in c:WindowsSystem32 and calling regsvr32 on them, however this wasn’t working and I kept getting an error saying the files couldn’t be opened.

After some searching about I found a few kind of related issues, but when I put them together it gave me the answer. The Microsoft site states that Windows 7 supports VB6 controls in a WOW environment, so the solution turned out to be placing the files in the C:WindowsSysWOW64 folder and then calling:

regsvr32 c:windowsSysWOW64MSCOMCT2.OCX


regsvr32 c:windowsSysWOW64COMCTL32.OCX

This is my first x64 OS, so I am guessing this is probably obvious to those people that have been using 64-bit for a while!

Xdebug On Windows

So I needed to get some PHP work done on the newly installed Windows 7 laptop. Netbeans was already installed, just needed a server and Xdebug setup for everything to be hunky dorey.

Firstly I tried Wamp, which is easy to install and easy to create Aliases, but no matter which version of Xdebug I tried and what options I put in php.ini I could not get it to load, so the next step was to try XAMPP.

So much easier, installed the package, checked out the php.ini file and just uncommented the lines to enable the Xdebug extension and then uncommented and edited the settings:



xdebug.remote_mode=req xdebug.remote_host=


Restarted Apache and then checked phpinfo() to find:

Success, job done!

However, unlike Wamp, getting Aliases to work is a complete and utter pain in the backside, I have spent about 90mins now struggling with a 403 Access Forbidden problem, when the exact same alias worked without issue in Wamp. Seems I can’t win at the moment.

Hunt for the Perfect PHP IDE

After an extended stint in VB6 land I came back to the 21st Century to find a couple of websites that needed work carried out on them, one was a personal project, one professional.

So when I say I am looking for the perfect IDE I am potentially looking for 2; one for personal use where I am prepared to put up with more setup and fiddling around to make it work to compensate for a lower price point and one for work where paying to get something that does everything I want quickly and easily will mean me being more productive.

The basic features I need are: Decent file handling, the ability to deploy a site to remote servers, view remote files, work locally or over SMB, FTP, SFTP etc. Debugging, using Xdebug/DBG be able to debug my sites locally or remotely, Javascript debugging would be a bonus but not essential.

The work projects will need to integrate with Subversion as a minimum, although I can use TortoiseSVN it would be nice to have basic Update/Commit functionality in the IDE. The baseline I am using for these tests is Dreamweaver, it’s what I have used since the UltraDev days, and I keep coming back to it for my HTML/PHP needs. It doesn’t do everything I need, but what it does do it has always done better than the competition. Its file-handling/manager/deploy support is great. I can view the remote site, download files, upload single files, upload the whole site. It can work reliably, and also quickly with remote servers. I can also setup local, testing and production configs and switch between them for deploying at different points in the lifecyle. Basically the project/file management rocks. For a reasonable price you can also make it integrate with Subversion. There is no Debugging support but as Meatloaf once sang “Two out of three ain’t bad”. Now I am going to lump the first lot of IDE’s together in a group called Eclipse IDE’s as there are several that all use Eclipse as a base, there is the Europa PDT version, Aptana Studio, Zend Studio and EasyEclipse. I am sure there are others but these are the ones that I tried. They all do different things well, but none of them are perfect. The biggest problem is, and bear in mind I only spent a few days playing with them and I may just not understand the way the Eclipse mind is meant to work, they don’t seem to appreciate that you will need to upload your files to a server. There seems to be no concept at all that you will need to run your files elsewhere. I did manage to get the PDT version to work via SMB on a test server we have on our network, and that in turn allowed me to get the debugging working. It still didn’t feel right though, there was never a copy of the files on my laptop. Again, maybe I am just not getting “it”, but when I view the properties of a PHP project and look under servers to see if I can setup a remote testing server and I see the message “This project cannot be used on servers.” then something is wrong!! Excuse me, a PHP project that isn’t used on servers?? When you right click on a file and chose either run or debug on server you get the helpful message “There is nothing that can be run on a server.”??? What the…..Where am I meant to run my files?? All of the IDE’s allow you to run a local Apache host e.g XAMPP or WAMP and test/debug your files that way, which is OK for initial prototyping and possibly my own personal projects, but for work stuff it’s not acceptable. I don’t run Windows XP on my production servers so it is not a relevant test. I have built test servers that are as close as I can make them to the production servers I use, one Windows/IIS and one Linux/Apache. I want to use these for my testing, this is what clients see during development not links to my laptop, whilst it is possible to get Eclipse to talk via SMB to the servers if they are in my local network, if I am at a clients and need to test on our server, or working from home and have to access the servers remotely that all goes out of the window with no decent FTP support for synchronising files. Now in its defence Aptana does offer the option to synchronise with an external server, which does work very well, but Aptana doesn’t offer the PHP Debugging functionality I need, and it is also $99, not a huge amount but I am hoping to find better. All in all Eclipse based IDE’s have turned out to be a bit of a bust. They do also offer Subversion integration, but as the file handling and debugging is not up to much what’s the point? If I can’t actually produce and test any files I will have nothing to put into SCC!! Next in the list is VS.PHP which is a plugin for Visual Studio that adds support for PHP projects, including debugging (both PHP and Javascript). It costs $99, and is also available in a standalone version for those people without Visual Studio. Now this is a very promising option. Being a .NET shop at work, when I am not in VB6land I am in Visual Studio World, so integration with that would be fantastic for the familiarity factor. The latest version also integrates with 2008, so far so good. Once the plugin is installed there are a minimum of options to getting a project setup, there is the notion of deploying to remote servers, and also local and remote debugging options. Using the configuration manager it is also possible to setup multiple servers for testing, production etc. There is some Subversion integration, although I could not get it to integrate with AnKH it did work work with VisualSVN which at $49 is not too expensive, and there is always the option of TortoiseSVN which I can live with if I need to. All in all this option seems to tick all the boxes, and on XP it certainly does just that. Once I figured out how to get the Javascript debugging to work (PICNIC error: although I added the files into the project folder on the file system I didn’t add them into the project in VS, d’oh, hence no breakpoints hit when the files were run), everything was great, sometimes the JS debugging didn’t work but only if the script was embedded within a PHP page, and as the pages I was working on were an absolute mess of jumbled HTML, PHP and JS it may well not have been the IDE’s fault. It worked flawlessly when the JS was in its own file. When the debugger stops you can view all of the available variables in the same way you would a normal C#/VB project. Vista was another issue though, the basic plugin worked, but there were several bugs, like the code highlighting wasn’t right and the options to change the colours were not initially displayed in the options panel with the others until I ran: devenv /setup from the Visual Studio command line as Administrator. Not generally a big issue, but as I use the Vibrant Ink colour scheme with a black background and the default colour of PHP code is black, you can see my problem. The next issue was the inability to add files to the project, now I couldn’t work out if this was an interaction with VisualSVN or just a bug in the plugin as it appeared when I selected Add->Existing Item from the right-click menu that the files I selected were Added to SVN as they got the blue + sign icon on them. They did not, however, end up in my project. I am going to try the standalone version to see if that solves the problem, and also remove VisualSVN. I am only using Vista on my own laptop though so these problems are not applicable for work. I am prepared to forgo the SVN integration at home if by removing VisualSVN the file add starts to work again. The only other slight issue (and it is the same for XP and Vista) is that the first time you try to debug or deploy a site once the project is loaded it checks every single file on the server, which isn’t too bad if the server is local, but having a remote site with 3500 files takes an age, and if the connection is dropped or it has an error, like not liking .htaccess files, it starts all over again from scratch. It only does it the first time you run the site after loading (assuming it completes successfully), but it would maybe be nice to have an option to stop it doing that; if I am the only person working on the site then I know the files are the same as the ones I worked on last time I opened the project. Dreamweaver is much quicker at performing this operation if you want it to, but it also isn’t default to check every file. It isn’t, however, a deal breaker, I can always exclude the files I know not to have changed in the project when I load it, and so far this IDE has my vote. For only $99 it is an option for home use too if I can work around the other bugs. Next on the hit list was Komodo IDE, this is a dedicated PHP IDE, built as a PHP IDE from the start and with a price tag of $299 I was expecting big things. I was, however, left slightly underwhelmed. Whilst there is support for SVN, I couldn’t find an option to create a project from an SVN repository, VisualSVN has this option for VS.PHP, so I would expect it here. I also couldn’t get the ‘Import from folder’ option to work, nothing happened when I clicked the menu option, not exactly a big thing, but with a big price tag I am expecting the features it says it has to work! Once I managed to get my files added to the project I set about trying to get the debugging to work. There didn’t appear to be any Javascript debugging, as its a PHP IDE I wouldn’t really expect it and it’s not essential. The PHP debugging used the DBG debugger, which I have no problem using. The problem I did have was setting it up, I spent an hour and hadn’t figured it out. I will hold my hands up and say that I didn’t read any manuals or search for the answers on Google, but I think I have seen enough IDE’s in my time to be able to work things out and manage to get something working in an hour and then look for help to fine tune it. I set up the remote server, but there seemed to be far too many options to get the thing working. This is probably a good thing, as an expert will probably have the time and patience to make this work, and I am sure in the long term would actually produce a more productive IDE than VS.PHP with its limited options. Getting the local server and debugging via that seemed easier, but as I explained at the start that is of little to no use for me in a work environment. My overall impression was that whilst it was better than the Eclipse IDE’s it still didn’t feel natural enough, with VS.PHP I had basic debugging on a remote server working in 10 mins. The file management also wasn’t as intuitive as Dreamweaver, and as I couldn’t import from SVN I couldn’t really test out the SCC control. However, I am not going to say it is a bad product, if somebody fires up VS2008 for the first time they will be lost too, over time I am sure I would learn how to use the tool effectively. There are a wealth of options contained within it that may well justify the price tag, I was, however, on a deadline to complete my PHP projects so I couldn’t afford the learning curve to get something productive out of it. The final contender was NuSpere’s PhpED, to cut a long story short you could re-read the above paragraphs for Komodo and you wouldn’t be far off. It again costs the best part of $300, has a wealth of options, but the fact it comes with its own versions of PHP 4 and 5 for local install suggests it is more geared towards development on your local machine than remote work. As with Komodo though once you get past the learning curve I am sure it is a fully fledged and very powerful PHP IDE, but I still can’t budge the feeling that it’s just being forced and isn’t natural, maybe that is just me though. So in conclusion, from all of the IDE’s I tried out none of them really met all my needs and was perfect. The closest I came was with VS.PHP, however, since I started writing this post a while ago I have had more time to play with it and found that the PHP debugging to be a bit flakey, I am hoping it is just because of the plethora of other PHP IDE’s that are currently on my system, some of which have installed their own debuggers which could be compromising VS.PHP’s ability to communicate correctly. If you have the time to spend with Komodo or PhpED then I am sure they will turn out to be competent enough, just for me at least the fact that even the standalone version of VS.PHP is $200 cheaper than both of the others and it is also quick to set up means that I could never justify the money for them considering the limited amount of PHP I do these days. At $99 VS.PHP is also cheap enough to offer an improvement over Dreamweaver, the debugging can save masses of time, so it will pay for itself in a very short period. I will have to use TortoiseSVN for my version control, but I do that anyway with Dreamweaver just now as I have never gotten round to buying the plugin so I am no worse off. There is still room for one PHP IDE to rule them all, which is intuitive, reliable, fast, debugs, handles file management both locally and remotely and works with SCC. Aptana could be that IDE if the developers ever add PHP Debugging abilities as it also supports Javascript and Adobe AiR development so has an awful lot of extras. However, I will say once more that maybe it is my interpretation of how IDE’s should be that is wrong, if all the IDE’s are doing it then maybe I need to change. I would say though that both Dreamweaver and Visual Studio work as I would expect them to with regards remote servers and deployment, so I can’t be that far off with my thoughts. UPDATE: Having already written this post about a week ago and having the time to use the VS.PHP plugin even more I have come to a slightly different conclusion. I have decided to forgo a PHP Debugger for my own personal projects, all the sites I maintain for friends and family are in Drupal, which I was unable to get VS.PHP to debug reliably. Also being in Drupal I generally am more concerned with layout and themes, so will stick to Dreamweaver at the moment, I cannot justify $100 for something that I can’t get to work reliably with the one thing I would actually use it for. I am also more inclined to look into using ASP.NET to build any future sites from scratch both personal and work, mainly due to the better debugging features built into Visual Studio with Javascript too, even the express versions. I have to say it is the first time for me that I would pick a particular language based on what tools it has available over another. For my work projects that are generally inherited custom CMS code I have recommended that we have at least one license on site for VS.PHP to allow debugging of some of the tangled messes we end up having to deal with.