Tuesday, 23 September 2008

Debugging .NET Compact Framework Part 1 - Remote Performance Monitor

The Remote Performance Monitor (RPC) application is truly awesome !  Ever had your Windows Mobile applications report memory problems?  Well this baby can show you where your problems could reside.   This blog will show you how to setup the RPC with Visual Studio and remotely check its performance (without even using a proper PDA) !

For this you will need Power Toys for .NET Compact Framework 3.5 which can be downloaded from;

http://www.microsoft.com/downloads/details.aspx?familyid=C8174C14-A27D-4148-BF01-86C2E0953EAB&displaylang=en

Create the SmartDevice Application

In Visual Studio, select File->New->Project.  From the list, select the SmartDevice item and give it a Meaningful name.

Once the designer has finished loading, drag a Button and a TextBox onto the main form.

Double click the Button to create an On Click event handler in the codebehind.

Next, add a private string to the Form1 class (any name will do)

In the newly created event handler, enter the following snippet

private void button1_Click(object sender, EventArgs e)
{
_simpleString
+= Guid.NewGuid().ToString();
textBox1.Text
= _simpleString;
}



So now, we have an event handler which will add a new Guid to the _simpleString every time we press the button.  I used string, as its an immutable type and will create a new reference to the string value every time we call the += operator.  We should see how this effects the memory on the PDA using the RPC.



Deploy to Emulator



Now, open up the RPC. 



image



 



 



 



 



 



 



 



 



 



 



 



 



 



 



 



 



 



 



 



 



Next press the Green Play button. You will be presented with the following Dialog;



image



Now, in the "Deploy Application From" TextBox, type the path of the newly created SmartClient (debug or release, whichever solution configuration you chose).



In the "Application Text Box" enter the executable name, then press "OK".



 



This will deploy the application to the PDA (Emulator) and run it. (You may have to deploy the .NET CF Framework first, do this from the Device Menu option, select the Visual Studio tree node and then select the "Windows Moile 5.0 Pocket PC R2 Emulator".  Then press CTRL-I).



When your application runs on the PDA, you will see the RPC spring into action.  Now select the "GC- Managed Objects allocated" and press the Button1 on the PDA Emulator.  You will see the amount of Allocated memory increase.  Now, you can keep clicking this and watching the memory increase until the GC reaches its 1st level of collection, a re-cycles.



image 



To check the heap out, click the GC Heap button on the toolbar of the RPC;  you can then drill down to specific objects on the heap; Choose System.String and hit the refresh button.



image



 



Awesome, you can now poke around in the PDAs Memory, JIT, GC etc all remotely.  How awesome is that?  you can of course deploy your troublesome application in the same way, and run through the motions until you reproduce the problem.  Keeping an eye on the PDA's .NET workings at the same time, you should be able to get one step closer to finding out what the issue is.



 



Enjoy !

Monday, 22 September 2008

Fun with Expression Trees

I have just been looking through some old code, and found a classic method that most people will use at some point;

public static int CalculatePercentage(int done, int total)
{
return (done * 100) / total;
}



Now,  I gots a thinking... Instead of using a method (or indeed a property) for this type of "expression", why not use the C# 3.0 Expression Tree functionality?  So just for a larf I came up with;




Expression<Func<int, int, int>> percentage = (done, totalCount) => ((done * 100) / totalCount);



The problem here is that in order to use the expression tree I have to call Compile() on the expression before invoking it. 



Expression<Func<int, int, int>> percentage = (done, totalCount) => ((done * 100) / totalCount);
var completed
= percentage.Compile()(3, 15);


So in this case, I think using an Expression is a little overkill.  So I opted to have a static Func<> in a static class; (some may argue expressing this as a Func<T,K> rather than the original method may be overkill, but I think its cool ;) ). 




class SimpleFunctions
{
public static readonly Func<int, int, int> CalculatePercentage = ((done, totalCount) => ((done * 100) / totalCount));
}



Again, its down to personal preference.  This is just an example of using the Func<> class instead of creating a method to do a specific job.  And working out a percentage isn't exactly a taxing calculation, but you get the idea ;). 



 



Full Code




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Samples.ExpressionTrees
{
class Program
{
static void Main(string[] args)
{

int total = 15;
for (int done = 0; done < total; done++)
{
Console.WriteLine(
string.Format("{0} out of {1} done -- {2}% Complete", done, total, SimpleFunctions.CalculatePercentage(done, total)));
}

}
}

class SimpleFunctions
{
public static readonly Func<int, int, int> CalculatePercentage = ((done, totalCount) => ((done * 100) / totalCount));
}
}



Output



image



Refrences



http://davidhayden.com/blog/dave/archive/2006/12/21/BuildExpressionTreesTutorialAndExamples.aspx

Fun with Extension Methods

I've recently been brushing up on my c# and .NET skills, and have started to post some blogs on my findings.  To start I have been looking at Extension methods, and how they can be useful in every day coding.

To demonstrate these I have chosen simple conversion methods.  Specifically, converting an integer to Hex, Octal and Binary strings and converting a binary string into an int32 value.  I re-iterate that these are simple, but they demonstrate how quick and easy it is to create extension methods for your existing objects, and to the .NET native types.

Firstly, a few rules.

MSDN states that ;

"Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on, and the parameter is preceded by the 'this' modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive."

So, to start with we will create 2 static classes (in this example the static classes are in the same namespace as the console application).

static class IntExtensions
{
public static string ToHex(this int value)
{
return Convert.ToString(value, 16);
}

public static string ToOctal(this int value)
{
return Convert.ToString(value, 8);
}

public static string ToBinary(this int value)
{
return Convert.ToString(value, 2);
}
}

static class StringExtensions
{
public static int ToInt(this string value)
{
return int.Parse(Convert.ToInt32(value, 2).ToString("X"));
}
}



Lets deal with the IntExtensions class first.  Here I have created 3 extension methods, ToHex() ToOctal() and ToBinary().  These are REALLY simple methods that use the System.Convert static class to convert the int values to strings using ToString() and passing the base as a parameter.  The key thing to note here is the 'this' modifier in the parameter list for the methods.  This tells the compiler that this is an extension method to the specified type (in this case int).



Now, why not just use the System.Convert static class explicitly in the code?  Why not indeed, there is no real reason why you can't.  But I'm sure that you agree that calling;




int value1 = 16;
string asHex = value1.ToHex();



reads a lot better than;



int value1 = 16;
string asHex = System.Convert.ToString(value1, 16);


 



The same principle applies to my StringExtensions class.  Here I have a ToInt() conversion which converts a binary string to an int32 value. 



string value3 = "00000001";
int toInt = value3.ToInt();


Full Code



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Samples.ExtensionMethods
{
class Program
{
static void Main(string[] args)
{
int value1 = 10;
int value2 = 16;
var asHex
= value1.ToHex();

string value3 = "00000001";
string value4 = "00000010";
string value5 = "00000100";
string value6 = "00001000";

Console.WriteLine(
"===================");
Console.WriteLine(
"To Base 2, 8 and 16");
Console.WriteLine(
"===================");
Console.WriteLine(
string.Format("{0} as base 16 = {1}",value1, value1.ToHex()));
Console.WriteLine(
string.Format("{0} as base 16 = {1}",value2, value2.ToHex()));

Console.WriteLine(
string.Format("{0} as base 8 = {1}", value2, value1.ToOctal()));
Console.WriteLine(
string.Format("{0} as base 8 = {1}", value2, value2.ToOctal()));

Console.WriteLine(
string.Format("{0} as base 2 = {1}", value1, value1.ToBinary()));
Console.WriteLine(
string.Format("{0} as base 2 = {1}", value2, value2.ToBinary()));

Console.WriteLine(
"==========================");
Console.WriteLine(
"To int from Binary strings");
Console.WriteLine(
"==========================");
Console.WriteLine(
string.Format("{0} as int = {1}", value3, value3.ToInt()));
Console.WriteLine(
string.Format("{0} as int = {1}", value4, value4.ToInt()));
Console.WriteLine(
string.Format("{0} as int = {1}", value5, value5.ToInt()));
Console.WriteLine(
string.Format("{0} as int = {1}", value6, value6.ToInt()));
}
}

static class IntExtensions
{
public static string ToHex(this int value)
{
return Convert.ToString(value, 16);
}

public static string ToOctal(this int value)
{
return Convert.ToString(value, 8);
}

public static string ToBinary(this int value)
{
return Convert.ToString(value, 2);
}
}

static class StringExtensions
{
public static int ToInt(this string value)
{
return int.Parse(Convert.ToInt32(value, 2).ToString("X"));
}
}

}


Output



image



 



Anyhoo, this is just a an example of using Extension Methods for simple type conversions.  The same principles can be applied to any object.



Have fun!