QR Code generation

For some time now, most people here in Belgium are beginning to notice the new bar code thing that is popping up all over the place… I’m talking about QR codes!
They are not difficult to spot, because of there special resemblance. But it’s not the fact that they are more advanced in resemblance that makes them useful 🙂 It’s the fact that they can contain data value and data metadata!!

In other words not every QR code represents the same thing… you can have it represent:

  • Text
  • Website URL
  • Telephone Number
  • SMS Message
  • Email Address
  • Email Message
  • Contact Details (VCARD)
  • Event (VCALENDAR)
  • Google Maps Location
  • Social Media ( like a facebook profile )

And accordingly to the content type your mobile phone or computer will perform the needed action to represent the data value correctly!

Now most people don’t know exactly how to use these QR Codes, let alone how to generate them… because of this you see service website like this one popping up all over the place.
But the funny thing is, everybody can get these QR Codes for free from a very nice online service! It’s called Google Chart API.
We are currently using it in a small ASP.Net MVC application at our company and we are using it to get Google maps location data represented through a QR Code.

The only thing you need to do is read the instructions up on the Google Chart website here!
You just have to ‘create’ the correct http request url and when ‘executed’ you’ll get back an image.
If you use it correctly you can for instance represent longitude-latitude coördinates on Goolge maps by using following code:


This will give you following QR Code, just try to scan it with your iPhone or Android smartphone 🙂

Charts with Asp.net MVC and jQuery through jqPlot

Asp.Net MVC is a great way to get dynamic data presented inside a web browser and thanks to the great integration of jQuery now in Visual Studio, we have many programming tools right at hand!

To show of the possibilities, I’ll give an example on how to get data from Asp.net MVC into your client jQuery code. This example will also use jqPlot to draw a dynamical graph from the given data.

First up, you’ll need to download the jqPlot plugin for jQuery from the jqPlot site: http://www.jqplot.com/ !
I have to say, this graph plugin just looks stunning and is easy enough to use with much tweaking options!!
When this is done, create your MVC project inside Visual Studio.

To get jqPlot working in your MVC project, make sure to create a subfolder jqPlot inside your Scripts folder and copy all .js files from the jqPlot download inside this subfolder!
After that, just add following inside your Site.Master page to get the correct reference to your jqPlot plugin.

Small side note, when you need to edit js files inside Visual Studio and you like to have intellisense for jQuery, be sure to add following line on top of each js file!

Next thing you’ll need to do is add a new controller inside the Controllers section. Inside this controller we will have all calls needed to get a new webpage and also for retrieving data. You add a new controller by right clicking on the Controlles folder and selecting Add>Controller! Give it a meaningful name and click OK.( in this example GraphController.cs )

Add following code inside the controller, this will give us the new web page.

Add following code inside the controller, this will present a JSON data stream back to the client. This data stream represents all markers that will be used by the jqPlot graph to draw lines ( in this example. You can also draw bar or pie charts and many other )

The class used here is called GraphData, it’s created inside the Models section and only contains 2 properties.

Now that the code is in place, right click on the HearthRate() method and select Add View. This will create a new view inside the Views section.

Edit this newly added View ( this example Views>Graph>HearthRate.aspx ) and add following code inside the asp:Content tag! This div will be used by the jqPlot, it indicates where the graph needs to be visible.

The other line is a reference to a new js file that we need for processing the JSON data and presenting it correctly to the jqPlot plugin.

Now the only thing left to do is create the js file with all the jQuery code that will process the JSON stream and draw the line chart.

With all this in place, you can start up your website and browse to the http://localhost/Graph/HearthRate site. If everything goes well, you should get following image.


[Tags]Asp.net, MVC, jQuery, jqPlot[/Tags]

Entity Framework – usage hurdles and tips

Well… let me start with a counter to this blog title! I actually like Entity Framework and don’t mind spending time on getting things done with it.
But, I have to be honest, some things just don’t seem to be right when I’m using it.
It could all just be me, but let me get my message out and share my experience. So here goes… my current hurdles with Entity Framework.

First of, some common issues are already listed on other sites. So first go check this list of issues and then read this post on how to tackle some of those items!

Secondly, most of my ‘problems’ are related to the interaction of the Winforms DataGridView control with EF, so maybe not everything is really due to EF itself.

  • Missing metadata
  • This element is not actually true, because EF has all the metadata a programmer needs. But it’s to far hidden, in my opinion!
    Lets give an example… in my program I want to have several managing forms that actually do nothing more than CRUD actions. So the setup of each form is almost the same, the only thing that is different is the Entity Objects being used in the Grid to show the data.
    But due to the nature of the DataGridView and the usage of ObjectQuery as BindingSource, you will get all the columns that are defined in the ObjectQuery. Meaning Key columns and relational mapping columns will appear inside the grid!
    This is something I don’t want to show inside my grid ( this is my setup, so maybe for some people those columns can be relevant ).

    So I wanted to hide these columns and I didn’t want to do this manually in the designer of the DataGridView for each form. I even didn’t want to know about the names of those fields/columns and write something against that. So the only way I could make this generic was by using the EF metadata of the Entity Object. But that’s where I was stuck… how could I get this information quickly?

    Well my solution uses Extension so I don’t have to type much code to get the metadata

    public static EntityType MetaData(this EntityObject entity, ObjectContext entityContext)
    return entityContext.MetadataWorkspace.GetItemCollection(DataSpace.CSpace).GetItem(entity.GetType().FullName);

    What this allows me to do is get the metadata of an entityobject instance like this

    var col = fooObjectEntity.MetaData(DataContainer.GetInstance().DataEntities).KeyMembers;

    One small problem with this solutions is that you have to pass along the ObjectContext.
    Some people solve this by adding something similar to the ObjectContext itself, take a look here ( it are some thoughts on a question Julie Lerman asked ).
    Passing the ObjectContext is needed, because it’s not possible to get it from the EntityObject itself, as talked about here! ( although I haven’t checked out Patrick’s version of a possible solution yet… look here )

  • Setting the bindingsource
  • I don’t know why, but for some reason I can’t just bind the ObjectQuery to the DataGridView.DataSource directly! Ok maybe wrong again, I can do this and the grid will show the data, but when I add a EntityObject to the given ObjectContext and do a .SaveChanges(), the grid will not refresh the data!! ( after the SaveChanges() I reset the DataSource of the grid to the ObjectQuery )
    I don’t have a clue why this is… updating data will work fine, but adding rows/objects won’t!
    The only solution I found, that solves this is to use Object instantiator of the ObjectQuery. In my case the .ToList() method.

    this.categoryBindingSource.DataSource = DataContainer.GetInstance().DataEntities.Category.ToList();

  • Using related data inside the DataGridView
  • Something that annoyed me was the fact that DataGridView didn’t pick up related data fields as columns.
    For example when you have some EntityObject Member that has a relationship to Address, doing following in code will not get the Address fields as columns inside the grid.

    this.memberBindingSource.DataSource = DataContainer.GetInstance().DataEntities.Member.Include("Address").ToList();

    A pity it doesn’t do this… because when I want to get a row back from the grid I still want to have a EntityObject of type Member, so writing some ObjectQuery myself with all the data seems not the good solution.
    For this little problem I asked what Julie Lerman would do. And she pointed out that the way she does it, is by inserting the values manually during the moment that the grid gets populated. Details are in the comments here. So the solution I used was getting hold of the CellFormatting event and pasting the needed values in the correct cell.

    private void gridSchool_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    if (!this.gridSchool.Rows[e.RowIndex].IsNewRow && this.gridSchool.Columns[e.ColumnIndex].Name.Equals("addressStreet", StringComparison.OrdinalIgnoreCase))
    School currentSchool = this.gridSchool.Rows[e.RowIndex].DataBoundItem as School;
    e.Value = currentSchool.Address.addressStreet;

Well that’s it for the moment… like you see most of the things I stumbled upon are also stuff other people noticed, so maybe they will get addressed during v2 of the Entity Framework ?
On the other hand I still do like the EF as a concept and I hope Microsoft will invest much time and effort into it :).

[Tags]Entity Framework, C#[/Tags]

Culture sensitivity in List<string> – how to do comparison

I recently stumbled upon a small c# problem I thought would have been easy to fix… But even now with the .Net framework 3.5, I can’t find a good solution!

So first the details on the problem. When you are using Generics, it’s very easy to construct lists of strings! Example: List<string> foo = null;
And when you want to search for a specific value inside this string list, you would most likely use the .Contains() method… But this has one huge drawback, it will only use the default equality comparer!
Details can be found in the MSDN information of the .Contains() method on List<T>.

In other words, you can’t search for Culture insensitive stuff, nor can you search for Case insensitive stuff!!
To illustrate, in following example the boolean value of contains will be FALSE, because “test” is not the same as “TEST” based on the case sensitivity of the default equality comparer.

List<string> foo = new List<string>();
bool contains = foo.Contains("TEST");

But thanks to the Exists method on List<T>, we are able to write some extra code that will allow us to check against case insensitive strings.

List<string> foo = new List<string>();
bool containsValue = foo.Exists(delegate(string argument)
return argument.Equals("TEST", StringComparison.OrdinalIgnoreCase);

In this last example, after the Exists method, the boolean value of containsValue will be TRUE… This because now we use the StringComparer class with the indication that we are not interested in case sensitivity!

The given problem has already been brought up by “Andrew Webb” as an enhancement request for the .Net framework ( cfr. his comment in this BCL Team blog post for .Net 4.0 ) and it seems the BCL team will take a look at it. ( fingers crossed )

[tags]c#, Generics[/tags]

SelectionChangeCommited event on Combobox not triggered

There seems to be a problem with the .Net Combobox control ! Microsoft is stating it isn’t actually a real problem, but still it is something a programmer should know and if needed take care of.

Let me first explain the problem… If you use the mouse to open a combobox, but then use the arrow keys to navigate in the list and change focus with the tab key, the combobox will select the highlighted value, but will NOT trigger the SelectionChangeCommited event !!
So in other words, even though the programmes subscribes to this event to know when a user has selected a value, the program will not notice it.

According to this post : http://weblogs.asp.net/grobinson/archive/2005/09/21/425711.aspx, Microsoft is aware of this and regards it as standard behaviour. So we are left with the only option to write a workaround ourselves.

I’ve found a good starting solution here : https://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3409311&SiteID=1, but I think this can be improved ! Because with this given solution, if a user still would use the mouse to select an item we would get the SelectionChangeCommited event twice.
So the workaround is to suppress the base event and only trigger our own. Here is the code…

[tags]SelectionChangeCommitted, combobox, c#[/tags]

Serialize/Deserialize objects in .Net – don’t forget to initialize

Recently in our project I had a weird exception popping up in C#. We found the problem and fixed it… but the problem was something we didn’t expect ! So I’ll post my findings here so other people can benefit from it.
I must say, I don’t know if this behaviour is anywhere described in MSDN, so could be I missed the information.

Consider this class Foo with only 1 member O1 that is Serializable.

public class Foo
private object _O1;

public object O1
get { return _O1; }
set { _O1 = value; }

public Foo()
O1 = new object();

Now we are going to save an instance of this Foo class to file through Serialization ! ( here done through unittesting with NUnit )

public void SerializeTest()
Foo foo = new Foo();

BinaryFormatter formatter = new BinaryFormatter();
formatter.AssemblyFormat = FormatterAssemblyStyle.Simple;
FileStream stream = new FileStream(@"c:\temp\foo.dat", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, foo);

Now we have a binary representation of Foo on file, called foo.dat !
After this, we change the Foo class and add a second member called O2.

public class Foo
private object _O2;

public object O2
get { return _O2; }
set { _O2 = value; }

private object _O1;

public object O1
get { return _O1; }
set { _O1 = value; }

public Foo()
O1 = new object();
O2 = new object();

And now for the big problem… we Deserialize the foo.dat file with this new Foo class code.

public void DeserializeTest()
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(@"c:\temp\foo.dat", FileMode.Open, FileAccess.Read, FileShare.Read);
Foo foo = (Foo)formatter.Deserialize(stream);

And what do you notice ? The test wil FAIL !! Yes… what we didn’t expect was the fact that .Net somehow can initialize the Foo object without going through it’s default constructor !!
Resulting in a Foo object with a O2 member that equals NULL instead of new Object() !

This would mean that if you need to deserialize newer class versions of existing binary objects, you should use the interface ISerializable and use protected Foo(SerializationInfo info, StreamingContext context) to be sure all members ( and new members ) are serialized and initiated ?

Can anyone shed some light on this ?

[Update] Jelle has given me the correct link to the MSDN documentation that gives the answer to this phenomenon !! Thanks Jelle ! http://msdn2.microsoft.com/en-us/library/4abbf6k0(VS.71).aspx

[tags]C#, .Net, Visual Studio[/tags]