Tuesday, 28 September 2010

C# .net method call performance

I’ve recently been in a conversation with another dev about a code base and had an alarming exchange regarding method calls and performance.

Alarming because he claimed that the reason that the methods in the system were so long was because someone higher in the dev chain 'tech lead' or 'architect' had claimed that it was expensive to make method calls???

I’ve seen my fair share of long methods, awful things that destroy reuse, developer productivity, and introduce many, many tangled bugs. These usually evolve because the devs are under pressure to get things out of the door on tight schedules, or by inexperienced devs who unfortunately don’t know much better. Personally I like to try and keep my methods short <20 lines, to keep to the principal that a method should only do one thing, do it clearly and well (so its easy to read, understand and change), you know all the usual stuff. But I’ve never seen the justification for long methods to be because of performance...

so i thought what is this performance gain of long methods? After googling around I didn’t find anything (if you do let me know) so i wrote a program.

Essentially it consisted of 2 loops, one to do a simple calculation in line and one to call a method to do the same calculation.

for (int i = 0; i < LoopCount; i++ )
{
fakeCalculationVariable++;
}


for (int i = 0; i < LoopCount; i++ )
{
Calculate();
}

i took timings before and after each loop and recorded the results

LoopCount= 100000000
elapsed time = 234.447 milliseconds
elapsed time = 640.8218 milliseconds
Method call loop took 406.3748 millisecs longer than inline loop for 100000000 calls
Thats a cost of 0.0000041 millisecs per method call

i wasn’t sure about the results so i decided to run it again, this time with ten billion iterations of the loop, these performance penalties must show up with that many calls.

LoopCount= 1000000000
elapsed time = 2250.6912 milliseconds
elapsed time = 6376.9584 milliseconds
Method call loop took 4126.2672 millisecs longer than inline loop for 1000000000 calls
Thats a cost of 0.0000041 millisecs per method call

its quite conclusive, method calls don’t really add up to all that much overhead, as we all expected.

Sunday, 12 September 2010

Azure Learnings

A few months ago I played with Azure, experimented with all the storage options (table, queue, blobs) web and worker roles, made things interact and generally got to know what was possible, not possible and how to do things. It was interesting, i gave a few presentations to the company I was contracted to at the time but in the end it was all just exploration, they were never going to take it up (they own lots of their own hardware, i mean Lots, and besides in my view there are issues with going to Azure as a solution for that enterprise problem), also I didn't see any use for it in my own personal projects.

I had a MSDN account which at the time entitled me to 750 compute hours a month (a compute hour is just a measure of how long your roles have been deployed in the cloud), and was careful with my deployments, always take test deployments down to minimise the total compute hours.

Anyway two problems:

1st. I didnt check my subscription(why would i?) it turned out i had the basic "starter" subscription (50 free compute hours) not the MSDN package (750 free hours).

2nd. I did a demo and someone wanted to use it afterwards so i left it up (one web role and one worker role) and then forgot about it... opps. To add to my woes my hotmail account is not my primary email account so the billing was not coming to me, i only just found it when I happened to be on hotmail.

To cut a long story short I got charged £50 + £120 + £120 for the honour of having my dummy website sat doing nothing on the azure application fabric... I;ve since talked to Microsoft and cancelled my azure account, i see no need for it, I'm not going to use it any time soon, and wanted to make double sure all my web instances were gone. but after talking to them i have got last months money back, better than nothing but still... i guess it was my fault for not checking my package, my running instances and my email, stupid boy.

Morale of the story to all you perspective Azure developers out there, check your subscriptions, and always take down your test deployments, always.

Wednesday, 1 September 2010

Site creation with google sites

Just been through the process of setting up a new website http://sites.google.com/site/stangerphotography/ new picasa site and new flickr account http://www.flickr.com/photos/oliverstanger/ for my brother who is setting up a photography business.

It was actually quite easy to do once you get used to navigating your way around the site and the wysiwyg editors. Managed to fully set up google analytics and web master tools also.

Now I just need to make sure my brother updates his content.

Thursday, 26 August 2010

Vodafone, HTC Desire fiasco update

Talked to Vodafone customer support again, (its my twice weekly activity now, well has been for 3 months) and have been told I'm not a priority, basically there is a supply problem (i know) and there is a waiting list (makes sense) but as I'm an existing customer (not a new one, or getting an upgrade) then i cant be put on the list, therefore the only way to get the phone is for me to ring up every other day and enquire if they have any stock to send me yet...

They did get 3 HTC Desires in today, but all went to new customers on the list. What this tells me is this: If you receive your new phone from vodafone but there is a problem with it cancel your contract ASAP (before the 14 day cooling off period) and once you have sorted that out do the new customer thing again. it seams that if i had done this i would have the new phone by now. just a warning to you folks, don't accept the promise that a new one will be coming your way any time soon.

On a slightly different note the Vodafone lady in the call centre was very nice, apologetic and honest, its definitely a system problem, not a people problem, why cant i be put on the list? clearly its a money problem, existing customers don't make the company any more money.

Tuesday, 17 August 2010

Vodafone, HTC Desire fiasco

So I've had a contract with Vodafone for over 3 months now. I think it was early may that I actually signed up for a contract with them and got my shiny new HTC Desire, I was pleased. Very pleased :-)

But after a day or 2 I found it was broken :-( if you used it for any length of time it would just quit, turn off, then not turn on for a while whilst it cooled down, oh and there was the strange squeeze thing I mentioned in another blog post.

I complained only 2 or 3 days after I received the original, I thought it would be straight forward, new for new, but unfortunately no stock, the desire is very desirable and there were supply problems.

So I waited and waited, I rang back twice a week to check on progress, I was not using my desire at this point as it was unusable, switching itself off randomly. Back to my trusty old nokia (7 years and still going strong)

And I waited.
Finally, finally after ringing twice a week for 2 months i got a replacement phone :-) yay at last, but I was told to keep my batery, sim and memory card from my other phone, strange, oh well, got my new phone now. :-)

But no, still broken, still with exactly the same problems as before.... ARRRRG, it was the battery all this time, i told them i thought it was, dam it.

And wait what's this, there is as small scuff mark on the base of the phone, its brand new isn't it?

So rang Vodafone back and said it still doesn't work, and also is this phone I have new? there is a scuff mark on it? after much a to-do I got the answer that its a reconditioned phone, and we will send you a battery (which they did but I suspect its not a new one as it came in a jiffy bag).

Anyway after some challenging discussions I got agreement that it was an error to send me a reconditioned phone, apparently an error in the system (problems with phones over 1 month into the contract get refurbished replacements), since I was 2 months into my contract I get a reconditioned one... even though id reported the problem on day 3... But the supervisor on the other end was reasonable in the end and agreed I should have had a new phone sent not a reconditioned one, and so I'm waiting, again.

And waiting and waiting, I ring back twice a week again, try to get a date but again they are out of stock, out of stock, out of stock.
Do Vodafone ever sell the HTC Desire? I know its a popular phone, that there are supply problems but in effect its been over 3 months now, you cant tell me you have not had any stock in 3 months? really?

I suspect its far more profitable to sell that new handset to a new customer than to sort out your existing ones?

I'm a bit disappointed really, as you can imagine, cause I've been using Vodafone for all my mobile life, years and years, even whilst abroad, and always had excellent service. I've had friends with orange who had trouble and problems with the provider and I've always said come to Vodafone, they are great, but seams like things change, or just maybe I've just got really unlucky.

Thursday, 13 May 2010

HTC Desire shut down problems

So ive got a brand new HTC Desire, and instantly loved it, but its not right...


If you talk on the phone for 5-10 minutes the phone will just switch off? if you use the internet or any other functionality the phone will soon enough just switch off. sometimes if you just gently squeeze it will just shut down.


Once it has shut down the status light flashes green and orange, sometimes it wont even shitch back on for ages...


So ive got in touch with vodafone, and they have been really good about sorting it out. they have quickly agreed to replace it :-) but there are none in stock at the moment, and none due in till the 23rd i think... boo


video of the squeeze



As you can see it works pretty well, quick navigation, just dont squeeze it.

Wednesday, 27 January 2010

Spring.net and asp.mvc, Getting started with dependency injection

This small tutorial gives you the quickest route (that i know) to getting microsofts mvc working with spring.net for simple DI (Dependency injection) or IOC (Inversion of control) to aid in testing and maintanance. Yes i know spring.net can do much more but this is just a very basic how to.

Download Prerequesits
First get asp.mvc, download and install from here (im assuming you have vs2008 or like wise for this tutorial)
http://www.asp.net/mvc/download/
At the time of writing im using vs2008, xp and mvc 1
downloaded here
http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=53289097-73ce-43bf-b6a6-35e00103cb4b
but im sure mvc 2.0 would be much the same to set up DI

right click on your existing solution (or alternativly create a new one)
then add, new project, web, pick 'asp.net mvc web appication' from the list of templates contained
this will make a brand new mvc web app, all configured and ready to go, build and run it you should see the default mvc site out of the box.
now to get spring running and injecting goodness into it.

first download spring.net
http://www.springframework.net/download.html
im going for the latest production release 1.3.0

then download MVCContrib from
http://mvccontrib.codeplex.com/
im using the latest stable release for mvc 1.0 here
http://mvccontrib.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=33401
get both the main download and the extras package (the spring IOC assembalies are contained in the extras package)

reference the following assemblies from the solution: spring.core, mvcContrib and MCVContrib.spring

Substitute the default controller factory for the spring factory provided by mvcContrib
Add the following to the head of global.ascx
using Spring.Context.Support;
using MvcContrib.Spring;

add IOC to your global.ascx so that application_start creates a spring context

protected void Application_Start()
{
ConfigureIoC();
RegisterRoutes(RouteTable.Routes);
}

private static void ConfigureIoC()
{
ContextRegistry.RegisterContext(new XmlApplicationContext(false, "assembly://MvcApplication1/MvcApplication1/objects.xml"));

var ctx = ContextRegistry.GetContext();
SpringControllerFactory.Configure(ctx);

ControllerBuilder.Current.SetControllerFactory(typeof(SpringControllerFactory));
}

add an objects.xml file that will hold all the spring configuration

<?xml version="1.0" encoding="utf-8"?>
<objects xmlns="http://www.springframework.net"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.net
http://www.springframework.net/xsd/spring-objects.xsd">
</objects>

This objects.xml must be an embedded resource into the assembly, right click the file, properties, and change it to an embedded resource. If you miss this step you will get an error stating 'Could not load file or assembly Spring.Core.....' basically stating that the assembly didn't contain the objects.xml, which is the dependency spring is looking for.

at this point if you ran the code you would get the error
No object named 'HomeController' is defined : Cannot find definition for object [HomeController]
This is good, it means that spring is looking for a definition of your home controller but cant find one.
so letes tell it about it

add this to your objects xml
<object id="HomeController" type="MvcApplication1.Controllers.HomeController, MvcApplication1">
</object>


now when you run the app you should get the same boring default mvc home page again, brilliant, looks like its working, now to test the dependency injection, this is what we have been waiting for.

Inject a custom object into the homeController
So the easiest way to demo this is to echo some text out onto the screen that comes from a dummy data
add 2 objects to the model folder

using System;
namespace MvcApplication1.Models
{
public interface IHelloDAO
{
String Hi();
}
}

namespace MvcApplication1.Models
{
public class HelloDAO : IHelloDAO
{
public string Hi()
{
return "This is data straight from HelloDAO";
}
}
}



now we are going to use this DAO (Data Access Object) in the controller to get some data from the model by using the Hi method on the IHello interface.
the class should now look like this
public class HomeController : Controller
{
public IHelloDAO HelloDAO { get; private set; }

public HomeController(IHelloDAO helloDAO)
{
HelloDAO = helloDAO;
}

public ActionResult Index()
{
//ViewData["Message"] = "Welcome to ASP.NET MVC!";
ViewData["Message"] = HelloDAO.Hi();

return View();
}

public ActionResult About()
{
return View();
}
}


We added a new constructor which takes an instance of IHelllo (this is the think that is being injected in), and we have used the instance to get the message by using HelloDAO.Hi()
finally import the relevent model namespace at the top of the file.

again if you were to run the app at this point you would get the following error:
Cannot instantiate a class that does not have a no-argument constructor [MvcApplication1.Controllers.HomeController].
which indicates quite clearly that the controller is not configured correctly. Basically spring is expecting a no argument constructor, but the real class dosent have one.

Configure Spring
Now all that remains is to wire the dependencies in the objects.xml which should now look like this

<?xml version="1.0" encoding="utf-8"?>
<objects xmlns="http://www.springframework.net"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.net
http://www.springframework.net/xsd/spring-objects.xsd">

<object id="HomeController" type="MvcApplication1.Controllers.HomeController, MvcApplication1">
<constructor-arg ref="HelloDAO" />
</object>

<object id="HelloDAO" type="MvcApplication1.Models.HelloDAO, MvcApplication1">
</object>
</objects>

you can see we have added a parameterised constructor to the controller through wich we are injecting in an implementation of the HelloDAO interface.
The index remains the same as it was out of the box and should display our message instead of the default 'Welcome to ASP.NET MVC!'

lets run it.
magic, you have configured your first and hopefully not last controller through spring.net and asp.mvc

now your ready for part 2 (Spring.net and asp.mvc, even more dependency injection)

Tuesday, 7 July 2009

Death and life of a netbook (Acer Aspire One)

I've got an acer aspire one
This isn't really a review but ever since i've got it, its been great. Small, light, perfect for travelling and storing photos on, its been round the world with us.

I really don't have a bad word to say about it, the Intel atom 1.6 GHz processor is great and the 1 gig of ram perfect for running xp home (yes sorry i had to get the Microsoft XP version, i did really want the linux one, but it wasn't just me using it and everyone else knows xp so xp it was), and the 160gig HD is perfect for storing the photos on.

small, fast, strong, light, good looking
all good praise
so why the post?

well it broke, i didn't do anything to it, didn't install anything nasty, didn't mess with its innards (i know better than to do that to a perfectly good working laptop) but it broke. i shut it down one day, proper full shut down (not hibernation or sleep) and that was it, next time i pressed the power button nothing happened, no splash screen, no BIOS info, just a black screen :-/ eek.

Well after searching the interweb it appears it happens now and again to this perfect specimen of a nettop laptop. luckily there were some instructions on how to fix it too :-) thank god for google...

I wont go into details here, see the link below, i just thought id better let other unfortunates know that sometimes a dead laptop isn't really dead. i was dreading sending it back to the manufactures though...

Detailed instructions here
http://www.qrpcw.com/2009/01/acer-aspire-one-bios-recovery.html

Download BIOS update from here
http://support.acer-euro.com/drivers/notebook/as_one_150.html

happy days
now don't do that again. Speaking of which, if anyone knows why this happens could you let us know, im worried it might happen again, proper backups from now on then...

Wednesday, 17 June 2009

JQuery and ASP.Net

Ive been playing with JQuery alot lately and am loving the ease of use and the feature rich toolset, you can get some realy good effects with it.

i know sometimes .net developers get, i dont know scared about trying new things that arnt born of microsoft, but JQuery is now being actively endorsed by microsoft and is actually shipped with the latest versions of the framework, so how do you use it.

1. If you dont have it get a copy of jquery.js its quite small (im currently using 'jquery-.3.2.min.js' which is 56Kb)
2. Include it in your web app
3. There are 2 ways to use it in a page
3a Add a script reference into your head section of the aspx page
<script src="Js cript/jquery -1.3.2.min.js" type="text/javascript"></script>
3b If you are using asp.net AJAX you can let the script manager handle it by:
3b.1 Adding a script manager to the form in the body of the aspx page
3b.2 Adding a scripts element
3b.3 Adding a script reference to the jquery file
3b.4 The result would look like this (remember it needs to go in side the pages form element
<asp:scriptmanager runat="server">
<scripts>
<asp:scriptreference path="~/Jscript/jquery-1.3.2.min.js">
</asp:scriptreference>
</scripts>

You are all set to use Jquery on the page

4. The most common way to initialise things is through the body onload, but this executes when the page is fully loaded, images and all, JQuery uses a special piece of script that executes when the page DOM is ready.

$(document).ready(function()
{
// do stuff when DOM is ready
});

This is where you can set styles, set up events to occur on different user actions all sorts of good stuff.
1st a couple of notes on the above code block:
1 it needs to be inside a sscript element
2 it needs to be located AFTER the scrip ref we declared in step 3 so if using the script manager it needs to be located inside the form after the script manager elements.
You can search the net for all the things you can do with JQuery, i wont repeat them all here, google is most definatly your friend.

But for now a simple example.

say you want to set up a click event to a group of radio buttons so that when clicked a javascript event is fired off to show or hide related DIV elements

<script type="text/javascript">
$(document).ready(function(){
$(":radio").click(function(event){RBEvent(this)});
$(".radioClass").hide();
});

function RBEvent(obj)
{
$(".radioClass").hide("slow");
$("#Div" + obj.id).show("slow");
}
</script>

And here is the aspx elements that go along with it

< asp:RadioButton ID="RBBus" runat="server" Text="Bus" GroupName="RB" />
< asp:RadioButton ID="RBTube" runat="server" Text="Tube" GroupName="RB" />
< div id="DivRBBus" class="radioClass">
Bus details
< br />
< /div>
< div id="DivRBTube" class="radioClass">
Tube details
< br />
< /div>

The neat thing that JQuery gives us, as in this example, is the ability to put all your page script into one place, and to have JQuery attach the events dynamically at run time making your javascript much easier to maintain. You could of course put all your script into a separate file as well which can be cached on the browser making the pages even quicker to load up.

Tuesday, 28 April 2009

Log4Net inside code run with MSTest unit testing

This was confusing me for a while so chances are it was also confusing someone else out there.

I could not get logging using log4net to output to the configured logger inside my unit tests
i tried
[assembly: log4net.Config. XmlConfigurator()]
in the unittest projects assembalyinfo but still log4net would not pick up the config

i found that the answer is to place an assembly initialise inside the unit test project, only one mind in the whole project. In fact if you do add 2 its an error

[AssemblyInitialize]
public static void AssemblyInitialize(TestContext testContext)
{
log4net.Config.XmlConfigurator.Configure();
}