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!

Monday 21 April 2008

Importing an Excel spreadsheet using C#

Here is a simple snippet which shows how to import data from an excel spreadsheet into your domains objects using c#. 

The following code snippets form part of a static helper class called ExcelImport.cs.  We make use of generics here, in that we assume the developer is aware of the type of object they are trying to populate from the excel spreadsheet. 

Snippet 1 - Static import Class, Parse<K> Method.

Our static class will have a generic method called "Parse<K>".  This method, as you can see, is a generic method which takes two parameters (fileName and workSheetName). The method makes use of the OleDbConnection and OleDbDataAdapter ADO classes to in effect "query" the spreadsheets data.

public static IEnumerable<K> Parse<K>(string fileName, string workSheetName) where K : class
{
IEnumerable<K> list = new List<K>();
string connectionString = string.Format("provider=Microsoft.Jet.OLEDB.4.0; data source={0};Extended Properties=Excel 8.0;", fileName);
string query = string.Format("SELECT * FROM [{0}$]", workSheetName);

DataSet data = new DataSet();
using (OleDbConnection con = new OleDbConnection(connectionString))
{
con.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
adapter.Fill(data);
list = PopulateData<K>(data);
}

return list;
}



As you can see, this method hands off the actual population logic to a private static method called "PopulateData".  Parse<K> hands the type of 'K' down to the PopulateData method along with the new DataSet which has been read from the spreadsheet.



Snippet 2 -PopulateData<T> method.




private static List<T> PopulateData<T>(DataSet data) where T : class
{
List<T> dtos = new List<T>();

foreach (DataRow row in data.Tables[0].Rows)
{
T dto = Activator.CreateInstance<T>();

PopulateFieldsFromDataRows(row, dto);
dtos.Add(dto);
}
return dtos;
}



The PopulateData method instantiates a List<T> ('K' from the Parse<K> method) and iterates through each row in the DataSet.  It then uses the Activator.CreateInstance<>() to create a new dto (Of type T).  We then hand off to yet another method which uses reflection to map the data to the business object, called PopulateFieldsFromDataRows().



Snippet 2 -PopulateFieldsFromDataRows()  method.




private static void PopulateFieldsFromDataRows(DataRow row, object o)
{
foreach (DataColumn col in row.Table.Columns)
{

string name = col.ColumnName;
System.Reflection.FieldInfo field = o.GetType().GetField(name);
if (field == null)
{
PropertyInfo prop = o.GetType().GetProperty(name);
if (prop != null)
{
if (prop.CanWrite)
{
if (prop.PropertyType.Equals(typeof(DateTime)))
{
DateTime d = (DateTime)row[name];
if (d.Equals(new DateTime(1900, 1, 1)))
{
d = DateTime.MinValue;
}

prop.SetValue(o, d, null);
}
else if (prop.PropertyType.Equals(typeof(int)))
{
prop.SetValue(o, Convert.ToInt32(row[name]), null);
}
else if (prop.PropertyType.Equals(typeof(decimal)))
{
prop.SetValue(o, Convert.ToDecimal(row[name]), null);
}
else
{
string value = row[name].ToString();
prop.SetValue(o, value, null);
}
}
}
}
else
{
if (field.FieldType.Equals(typeof(DateTime)))
{
DateTime d = (DateTime)row[name];
if (d.Equals(new DateTime(1900, 1, 1)))
{
d = DateTime.MinValue;
}

field.SetValue(o, d);
}
else if (field.FieldType.Equals(typeof(int)))
{
field.SetValue(o, Convert.ToInt32(row[name]));
}
else if (field.FieldType.Equals(typeof(decimal)))
{
field.SetValue(o, Convert.ToDecimal(row[name]));
}
else if (field.FieldType.Equals(typeof(bool)))
{
if (row[name] == DBNull.Value)
{
field.SetValue(o, false);
}
else
{
field.SetValue(o, Convert.ToBoolean(row[name]));
}
}
else
{
field.SetValue(o, row[name]);
}
}
}
}



Here, we simply reflect over the object and access any public fields, or properties.  We then try and populate the objects property/field based on its name.



Below is an example of how the static class is used.  I have implemented a CreatenewBusinessObject<> static class here, just to because I think that handing object creation off to a factory is a good thing ;).




class Program
{
static void Main(string[] args)
{
IGenericObject o = BusinessObjectFactory.CreateNewBusinessObject<GenericObject>();
GenericObject obj = new GenericObject();
obj.Records = new List<GenericObjectDto>(ExcelImport.Parse<GenericObjectDto>("d:\\test.xls", "test"));

foreach (GenericObjectDto dto in obj.Records)
{
Console.WriteLine(string.Format("FirstName: {0}, LastName:{1}", dto.FirstName, dto.LastName));
}
}
}



GenericObject classes:




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

namespace ExcelImportSample
{
public interface IGenericObject
{
string Name { get; }
Guid Id { get; }
List<GenericObjectDto> Records { get; set; }
}

public class GenericObject : IGenericObject
{
public GenericObject()
{
this.Id = new Guid();
}

public List<GenericObjectDto> Records
{
get;
set;
}

public string Name
{
get
{
return "Test Object";
}
}

public Guid Id
{
get;
private set;
}
}

public class GenericObjectDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
}

public static class BusinessObjectFactory
{
public static T CreateNewBusinessObject<T>() where T : class
{
return Activator.CreateInstance<T>();
}
}
}



Again, a very simple and elegant solution to reading an Excel spreadsheet into your c# application, but one step further.  By utilizing the power of Generics and Reflection we can simply hand off the processing to a static helper.



 



Have Fun !



 




 


 

Tuesday 15 April 2008

Hosting Windows Forms Controls in WPF (Threading)

The threading model in WPF differs somewhat from the conventional Win32 application model.  WPF objects belong to the thread that created them, and cannot be accessed directly by any other thread.  As most objects in WPF inherit from the DispatcherObject class, we can get at an objects Dispatcher property to update any properties on the object from another thread.

So how do we allow access to our object from a Windows form control?  Well, the answer is relatively simple.  Windows forms controls MUST be embedded inside a WindowsFormsHost object (A WPF wrapper for Windows Forms controls).  As the WindowsFormsHost object is  a WPF object, it therefore has a Dispatcher property which can be accessed.

The below example is not a full code sample, what I am trying to highlight here is the use of the Dispatcher to gain access to a Windows Form Control's thread.

 

Example

Below is a simple Windows Forms User control, which is hosting the Windows Media Player ActiveX control.

Create a new Windows Forms Library project within your WPF solution.  Here we will create our custom Windows Forms Control.

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AxWMPLib;

namespace WmpAxLib
{
public partial class WmpAxControl : UserControl
{
public AxWindowsMediaPlayer MediaPlayer
{
get
{
return this.axWindowsMediaPlayer1;
}
}
public WmpAxControl()
{
InitializeComponent();
}
}
}



As you can see, I have exposed the AxWindowsMediaPlayer object as a property Called MediaPlayer.  This is so we can access the Media Player directly in our example from the WPF code.  For now, we will not do anything else with this control but it is worth noting that we could expose events on this object for any Media Player events (for example we could just expose the Ctlcontrols property directly for controlling Play, Stop etc.



Now that we have our simple media player, we can host it inside our WPF application. 



<Window x:Class="MediaPlayer.MainPlayer"
xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wfi
="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
xmlns:wf
="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
xmlns:AxWMPLib
="clr-namespace:WmpAxLib;assembly=WmpAxLib" Loaded="Window_Loaded"
Title
="MainPlayer">
<Grid>
</Grid>
</Window>


The XAML markup shown above has references to the Windows.Forms.Integration and the Windows.Forms assemblies.  These assemblies are needed in order to host a Windows Form control within your WPF application.  There is also a reference to the Windows Forms Library assembly we created earlier, called AxWMPLib.



Now, personally I prefer to programmatically create a WindowsFormsHost control in the codebehind as a private field.  It is perfectly valid to create a control in your XAML if you wish, either way will work fine.



The next step is to add your Windows Forms control to the newly created WindowsFormsHost control.  To do this, in XAML, you simply embed your control inside the WindowsFormsControl control.  This example will show how to do it in codebehind.



1. Create two private fields ;



WmpAxLib.WmpAxControl _axWmp = new WmpAxLib.WmpAxControl();
WindowsFormsHost _host
= null;


2. In the Window_Loaded event handler, initialise the _host and _axWmp objects and add the _host control to the Windows Children collection;




_host = new System.Windows.Forms.Integration.WindowsFormsHost();
_host.Width
= 0;
_host.Height
= 0;
_host.Child
= _axWmp;
this.MainGrid.Children.Add(_host);



3. Setup a handler for the _axWmp controls "OpenStateChanged" event.




_axWmp.MediaPlayer.OpenStateChange += new AxWMPLib._WMPOCXEvents_OpenStateChangeEventHandler(MediaPlayer_OpenStateChange);



4. In the newly created handler, we want to set the _host width and height to full screen.



void MediaPlayer_OpenStateChange(object sender, AxWMPLib._WMPOCXEvents_OpenStateChangeEvent e)
{
string name = string.Empty;

_host.Dispatcher.Invoke(DispatcherPriority.Send,
new ThreadStart(delegate
{
_host.Margin
= new Thickness(0, -90, 0, 0);
_host.Height
= this.Height;
_host.Width
= this.Width;
name
= string.Format("Now playing {0}", _axWmp.MediaPlayer.currentMedia.name);
}));
}


In order to access the ActiveX control which is hosted inside our Windows Forms Control, we need to access its thread.  As the thread is not the same as the current UI Thread, we need to ask the dispatcher object to post a message to the control.  We do this by creating a new ThreadStart() object and rather than pass a delegate , we use an anonymous delegate to do the work.  We are also settings the DispatcherPriority to "Send" which tells the dispatcher to process BEFORE other asynchronous operations. 



The delegate then sets the _host's Margin, Height and Width properties.  It also accesses the MediaPlayer property we set on our Windows control, in order to get the name of the media we are playing and sets it to our locally declared string.



Further Reading



http://channel9.msdn.com/ShowPost.aspx?PostID=283473



http://msdn2.microsoft.com/en-us/library/system.windows.threading.dispatcher.invoke.aspx

Monday 17 March 2008

My First Blog !

Hi all,

This is my first global blog.  I've been a bit rubbish at getting on the whole blog scene and thought it was about time I jumped on the bandwagon.

This blog will mainly be my .NET coding experiences, including samples and in some cases video blogs.  However there is non .NET side to me which will also be blogged here.  This is the Video editing/screen writing/comedy side.

New Technologies

I have been keeping a close eye on Silverlight and its progress over the last 6 months.  All I have to say is WOW!  The boys at Microsoft have really put a lot of thought into this technology, and it is going to seriously change the way we use the web.  Move over Flash, there's a new boy in town. !