Tuesday, 22 July 2014

Enums in C#; Doing More Than You Thought!

I have been developing for a while now and use Enums on a daily basis (nearly) and was quite happy in my understanding an Enum definition had a set number of values and of those values they could be cast to the related integer value (or another under-lying type) and back again.

And then I saw the following piece of code (condensed down for example):

System.Net.HttpStatusCode value = (System.Net.HttpStatusCode)429;
var result = (429 == (int)value);

There is no corresponding value in System.Net.HttpStatusCode which relates to 429 and the value of result variable was true when when the enum value was cast to an int!

So why is this possible? Enter the C# specification!

Quick side note; no need to search the internet for the C# language specification if you have Visual Studio 2013 installed locally you already have it. It can be found:

C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC#\Specifications\1033

A quick browse to section 1.10 Enums answered, high level, why it is possible straight away.

“The set of values that an enum type can take on is not limited by its enum members.”

The rest of the section is quite interesting as well with regards to the underlying type of the enum type. On further reading of chapter 14 – Enums there are a lot of bits which as a developer you take for granted and use without really thinking it about. It’s actually quite interesting.

Makes me wonder what else I’m missing out on, maybe I should read more of the specification? Maybe the whole specification?

Thursday, 6 February 2014

Updated Json.Net and now OWIN errors

I took the step on an Asp.Net MVC 5 application last night to update all of the nuget packages in the entire application to be the latest. The main reason for this was I added SignlR to the solution and it required a newer version of OWIN which is fine. With the update of all packages came the update to Json.Net to the newly released version 6 and on fire up of the application I got the following error:

Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Using the information in the error message I added the following snippet into the runtime element in the web.config to resolve the issue:

<dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.5.0.0" newVersion="6.0.0.0" />
</dependentAssembly>

I think nuget is a great concept but I still think there is a bit of an issue when it comes to multi packages which rely on a specific package which then is updated later if you update all. In the future I will be more selective on which packages to update.

Wednesday, 22 January 2014

RavenDB Import / Export in code

The recommended way of doing backups automatically is using Smuggler on the server in a scheduled job or if you do manual backups and restores it’s through the RavenDB management studio but what happens if you’ve not got the ability to do either of those? It’s time to build in import/export functionality into your application.

This was a requirement that I was looking at a while back and then when I did some further investigation more recently I had found a thread on the RavenDB Google group and the associated pull request to allow for smuggling functionality without the http server running; problem solved! So how can it be used?

The changes that were made extracted out an interface ISmugglerApi to allow for a common mechanism for both the server/http version and the internal embedded implementations.

So how do we backup? This is an implementation from an MVC application perspective. Context is a way to determine the difference in implementation if you require to develop and/or deploy onto the different platforms.

public async Task<ActionResult> Backup()
{
    SmugglerOptions smugglerOptions = new SmugglerOptions { BackupPath = Server.MapPath(ServerMapPath) };
    switch (Context)
    {
        case Context.Embedded:
            DataDumper dumper = new DataDumper(((EmbeddableDocumentStore)MvcApplication.Store).DocumentDatabase, smugglerOptions);
            var embeddedExport = dumper.ExportData(null, smugglerOptions, false);
            await embeddedExport;
            break;

        case Context.Server:
            var connectionStringOptions = new RavenConnectionStringOptions
            {
                ApiKey = “insert ApiKey”,
                DefaultDatabase = “db_name,
                Url = “http://localhost:8080”
            };

            var smugglerApi = new SmugglerApi(smugglerOptions, connectionStringOptions);
            var serverExport = smugglerApi.ExportData(null, smugglerOptions, false);
            await serverExport;
            break;
    }

    return File(Server.MapPath(ServerMapPath), "application/binary", "backup.dump");
}

For the embedded version you specify the mapped server path on the local machine at the location the server will write the file to, initiate a new instance of the DataDumper class and call ExportData. There is no need for a stream or to get the incremental flag for this basic usage.

The hosted server version you have to specify they api key, database name and the url of the server to use. These are all bit of information you should know if you or can get access to if you are developing in this way. Once this is established you can call ExportData in the same way as the DataDumper call.

Restoring the backed up file is very similar but in reverse.

public async Task<ActionResult> Restore()
{
    SmugglerOptions smugglerOptions = new SmugglerOptions { BackupPath = Server.MapPath(ServerMapPath) };
    switch (Context)
    {
        case Context.Embedded:
            DataDumper dumper = new DataDumper(((EmbeddableDocumentStore)MvcApplication.Store).DocumentDatabase, smugglerOptions);
            var embeddedImport = dumper.ImportData(smugglerOptions);
            await embeddedImport;
            break;

        case Context.Server:
            var connectionStringOptions = new RavenConnectionStringOptions
            {
                ApiKey = “insert ApiKey”,
                DefaultDatabase = “db_name”,
                Url = “http://localhost:8080”
            };

            var smugglerApi = new SmugglerApi(smugglerOptions, connectionStringOptions);
            var serverImport = smugglerApi.ImportData(smugglerOptions);
            await serverImport;
            break;
    }

    return View("Index");
}

There are many other options which can be used but the above is one of the simplest implementations.

When I was doing some research on how to use this mechanism there were no examples I could find in the blogosphere however reading the the code and looking at the unit tests of the RavenDB source it was enough of an example to work with. I’d highly recommend reading the unit tests and the source of open source if you are struggling to find examples of how to use it; it is good documentation especially if the mechanism you are trying to use is used in the software itself.

Sunday, 5 January 2014

New Years Resolution Gym Goers; Don’t Join!

I am writing to all the people who’s new years resolution is to “get fit” or “lose weight” and this usually means they think they should join a gym … don’t! Well not initially anyway. If you’re already a member of a gym then I’m sure you can relate to this.

Let me explain why I think you shouldn’t join a gym …

The way this usually works is people think they need to join a gym, so they join at £xx per month and get locked into a 12 month starter contract. They then start to go in January with the aim to go 3 to 4 times a week and do this class and that class. They do it for maybe two to three weeks but then work gets in the way, they remember they want to go to the pub and socialise instead of doing squats and crunches and before they know it they’re paying their membership fees so they can say to their friends “I’m a member of a gym”.

Don’t get me wrong there are people out there who start in January, get fit, get ripped, be happy etc. but a majority flounder and give up.

So people end up paying a lot of money for not going to the gym and for January the people who take it up and stop in February just annoy and get in the way of regular gym goers.

Let me be fully clear I am a member of a gym and have been for many years; although it wouldn’t show looking at me. I dip in for a few weeks/months at a time and then something comes up etc. and don’t go for a while so I look at the issue from both sides depending on where I am.

So what can people do to get fit and save money?

To get fit you don’t need to join a gym although joining eventually can help. You can start off by doing free activities such as running. You can get a number of apps now a days which will help you train from couch to xkm and apps which will track you such as RunKeeper. If you want to run with people there are many ParkRuns world wide which you can sign up for and go to for free.

If you want to be more serious about training then look to get a personal trainer who comes to your house and can train you in the garden or local park. This way you are paying purely for their time and not paying the gym *and* a personal trainer.

If once you get to the point where you want to join a gym and you’re already getting fit and have built in the time into your weekly schedule then please do. When you do try not to feel self conscious about going to the gym if you aren’t model thin or can only lift a couple of kgs people are there for themselves and don’t care what others are doing. So take some music and lose yourself in the exercise.

It doesn’t matter if you train at the gym or not but you do feel better for doing exercise so I encourage you to keep with your new years resolution.

Happy exercising and money saving in 2014!

Thursday, 29 August 2013

Feeling overwhelmed and like a phony? Chill out!

Do you ever feel overwhelmed by the amount of new technology which is coming out all the time? The new framework to do this, and the new improved way of doing that. The new blog posts about this and that, the never ending Pluralsight courses by John Sonmez? It can be too much!

Recently I’ve been feeling this way as well as losing the motivation I use to have to code. I’ve not lost the joy of coding or problem solving but the combination of being overwhelmed by all the bleeding edge technology and information coming out of the developer community and in contrast the recurring day to day coding on brownfield code bases running VS2010 (and every so often VS2005) can get you down.

Recently I’ve got to a point in my life/career where I feel like a bit of a phoney. I’ve worked very hard to get where I am today and at only 30 years old I potentially still get seen by some as the opinionated upstart when I’m not. I know I have a lot more to learn but I think everyone does whether that’s new processes in your day to day life, understanding ways of doing tasks in new positions etc. You should always be learning and adapting.

The realisation of trying to learn everything is just not practical. Reading code is a great way to learn new techniques which you can apply to your day to day developer life but learning the ins and outs of every framework is just not possible. The other aspect of learning is you can run through a Pluralsight course on this or that but if you’re not using it every day all day at work or at least a couple of hours in the evenings each week on a personal project you’ll very quickly forget it. This, I think, is my main frustration.

So as I see it there are a couple of ways to solve this issue which range from minor to life changing. You can ignore all new technology, carry on with your day to day life, not do anything outside of work; essentially put your head in the sand. This will however leave your skills becoming slowly stagnant and make future career progression hard. On the complete other end of the scale you can move jobs, go and work for a company where they are using the latest and greatest, always starting new greenfield projects, this will help improve your skill set and keep it up to date but that will impact your life completely which isn’t always the answer either. Changing jobs, whether forced through redundancy or by choice, is a big change!

So what can you do? Learn every 3rd new technology which appears on the Pluralsight new course listing? This isn’t practical. Maybe try and influence technology at work? Spend time during the day (lunch time, 30mins before heading home) reviewing new technology? Both of these are possible but will depend on personal situation.

I’ve been thinking over this conundrum recently, and the near future birth of my first child has helped my thinking on this subject, the biggest issue is I’ve been putting too much pressure on myself. Too much pressure to learn new technologies, too much pressure to read every blog post about every technology. Also when I do look at a technology and write pet/personal projects such thoughts as “it needs to be production ready code straight away”, “you need to get it done now”, “it needs to be perfect first time” aren’t the thoughts which will aid motivation but in fact demotivate.

So if you find yourself in a similar situation as I have recently and don’t know what the answer is then use the realisation that has only hit home to me recently; chill out! Don’t put yourself under unrequired pressure. Yes, continue to read blog posts. Yes, continue to play with new technologies as/when you can … just don’t pressure yourself into having to do it all the time as it can be harmful as well as beneficial.