How to Set BoundField.DataField to a Nested Property

Very often, we need to bind a property of a nested object in a GridView column. Suppose you have OrderItem class that has a reference to Order class. Imagine you have a List of OrderItems that is bound to a GridView and you wanted to display a property from the Order class. ASP.NET GridView (or to be precise bounded fields) does not support this. A familiar situation? We will fix this soon. Let's create a little class and call it NestedPropertyBoundedField. We will use Reflection and BoundField as the basis (you could also use DataControlField as a super class, but let's stick to BoundField).

I recently needed this type of function in my GridViews. Mostly I use GridViews from code, so this class needs some more bells and whistles to be design-time friendly or if you want to use declaratively. However, the core functionality is the same. Without much ado, the source code is given below:


public class NestedPropertyBoundedField : BoundField
{
protected override string FormatDataValue(object dataValue, bool encode)
{
return base.FormatDataValue(dataValue, encode);
}

protected override object GetValue(Control controlContainer)
{
string[] pathItems = DataField.Split('.');
object currentDataObject = null;

if(controlContainer is IDataItemContainer)
{
currentDataObject = (controlContainer as IDataItemContainer).DataItem;

foreach (string item in pathItems)
{
PropertyInfo[] propertyInfos = currentDataObject.GetType().GetProperties();
PropertyInfo propertyInfo = propertyInfos.FirstOrDefault(i => i.Name == item);
if (propertyInfo == null)
{
throw new System.Web.HttpException("A field or property with the name '"+item+"' was not found on the selected data source.");
}
currentDataObject = propertyInfo.GetValue(currentDataObject, null);
}

return currentDataObject;
}

return null;
}
}


This is the beauty of OOP and inheritance in particular. The possibilities are endless. For example, I also use a whole array of other data bound fields for my GridViews. In of of the upcoming posts I will write about a composite data bound field which is really cool.

MVVM and the WP7 ApplicationBar

If you have spent some time with MVVM, you should know that MVVM is a nice pattern and the best way to build your Silverlight apps for Windows Phone 7. I am a purist and if I choose some approach I stick to it completely. Unfortunately, there is one aspect in Windows Phone 7 that does not fit in the MVVM pattern fully. You have guessed correctly. We are speaking about the ApplicationBar.
The Windows Phone 7 ApplicationBar is not a Silverlight element and thus it does not obey the rules of the game. You cannot use binding and this brings a lot of problems. The ApplicationBar destroys the whole concept of MVVM.

Unfortunately, the range of our options to solve this problem is not big. So, we have to resort to the plain old SmartUI pattern. In other words, just use the Click event handlers and from the listeners simply call the ViewModel methods.

For completeness of the topic, the code excerpts are given below:

<shell:applicationbariconbutton click="appbar_button1_Click" iconuri="/Images/appbar_button1.png" text="Download" x:name="appbar_button1"></shell:applicationbariconbutton>

to set the event handler and the actual handler code is given below:

private void appbar_button1_Click(object sender, EventArgs e)
{
ViewModelLocator.MyViewModel.MyCommand.Execute(null)
}

Not very neat but this is the best option that was have so far.

Fixing: Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

It's almost 2:00 AM and I am happily working on a piece of ASP.NET code. Suddenly and from nowhere I get a horrible exception:

[System.Threading.ThreadAbortException] = {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}

Not good, noot good at all. The code has just started working fine and at the final stage of testing boom and this exception. But, Google is here (ummm sorry, it's Bing. I've been using Bing recently but hey old habits are difficult to break). Looks like this sort of sh**t happens not only in ASP.NET applications but in other areas of .NET. Digging further and deeper within the search results. Here is a million dollar tip. Can't find something fast? No worries. The answer is right there somewhere, well in MSDN for sure.

Look, sometimes it's better to look at your code rather than surf from page to page desparately looking for a solution. When something odd happens, it means that you're doing something odd in your code. Wait a minute, just ask yourself: what's so strange about this code? Nothing particular. Clean code (hmm you thought anything else?), a try-catch block here, a couple of lines there, raising an event from that try-catch block and here it is. In the event handler we have... yeah Server.Redirect. It turns out that this little pest is breaking the whole stuff. This reminds me a similar situation that has occured to me quite a while ago and guess what - it was Server.Transfer within a try-catch block. This is not too difficult to refactor. Keep the processing within the try-catch block and use some sort of Boolean based on which I can refactor redirect out of the try-catch block. Don't like extra typing (who does)? No problem. There is a neat workaroung.

You have probably never noticed that the Response.Redirect method accepts the second argument of Boolean type. So that does the magic. Simply, call like this:

Response.Redirect("http://www.gotohell.com", false);

You see, this was quite easy and how horrible did it look in the beginning.

No More ChevronWP7 Tokens?

If you have been thinking about unlocking your Windows Phone 7 with ChevronWP7 unlocking tool, you'd better do that fast. According to the ChevronWP7 Team, they have almost reached the 10,000 sold tokens mark. You see, their agreement with Microsoft was allowing them to sell 10,000 tokens only.

To admit, I was not expecting the ChevronWP7 to become so popular. The 10,000 figure is quite impressive though. This means that there are 10,000 developers already willing to join the platform. Most likely there are more and this shall put enough pressure on Microsoft to allow the ChevronWP7 Team sell more tokens. Or maybe start direct licensing.

The outlook is that before the ChevronWP7 team negotiates a new deal with Microsoft, there may be a temporary shortage of the tokens. However, I think 10,000 developers is not a figure that Microsoft can easily neglect. Undoubtedly, Windows Phone 7 is the best platform at the moment. But the problem with Windows Phone 7 is that the market does not thinks so. At the moment, the market thinks that Android is the best platform. A lion's share in Android's tremendous success lies in the fact that Google has managed to create a strong and large development community. I remember how Google started forming the community quite long before the first device would hit the market.

Microsoft shall take this lesson into consideration when planning the developer strategy. The bottom line is that the platform is as good as the choice and quality of applications that it gives. In this respect Android is still in the lead. Let's see if this picture changes in 2012.

Happy New Year by the way!

How to Add Existing Folder to Visual Studio

Visual Studio has a nice feature to add existing files to a project and the process if simple and straightforward. What about adding an existing folder to a project? This is especially useful if you accidentally remove a folder from a project. A typical action done by developers in this case is to create a new folder in the project, add existing files there, delete the existing folder and then rename the new folder.

Visual Studio has functionality to easily add existing folders to the project. However, this functionality is not visible. In other words, there is no "Add Existing Folder..." menu item neither in the main menu, nor in the project's shortcut menu.

To add an existing folder to Visual Studio project first click the Show All Files button in Solution Explorer. This will show all files and folder even if they are excluded from the project. Now just right click a particular folder and select the Include In Project menu item.

For your convenience, please have a look at the screen shot. We have circled in red the Show All Files button and the folder that we would like to include.

Generating Random Strings in PHP

Generating random strings is a frequently used programming technique. Random string are practically everywhere. For example, you may need to generate a random password, e-mail activation code, various keys and so on. Strangely enough, most of the programming languages and development platforms don't have such functionality built-in. Today we'll look how to develop this in PHP. To have a clear target, our goal is to create a function that generates random strings or arbitrary lengths from a predefined character set. We will present you with two different techniques. The first one is simpler to implement and maintain but can be slightly, just slightly slower then the second version.
However, when it comes to a compromise between simplicity, clarity and performance we choose simplicity and clarity. (This does not mean that we ignore performance, however you should not look at performance as is. Rather, you shall view the application as a whole. What do you prefer, a lightning fast payroll application cutting one 0 from your salary from time to time or a slower application printing your salary correctly all the time. This is a topic who may well make a whole book and we promise to publish several posts on code and application quality).

function randomString($length)
{
   // we have a habit to name return value variables as result
   $result = "";

   // predefined character set
   $charset = "abcdefghijklmnopqrstuvwxyz0123456789";

   $i = 0;

   while ($i < $length)
   {
      // pick a random character from the charset
      $char = substr($charset, mt_rand(0, strlen($charset)-1), 1);

      // we generate random string with no repeated characters
      // that's why we reject a character if it's already in the $result
      if (!strstr($result, $char))
      {
         $result .= $char;
         $i++;
      }
    }
   return $result;
}


The second version is almost the same but instead of picking up the characters from a predefined charset string, we get it from a function which takes a random number and returns a character.


function getRandomChar($num)
{
    switch($num)
    {
       case "1":
          return "a";
          break;
       case "2":
          return "b";
          break;
       case "3":
          return "c";
          break;
       case "4":
          return "d";
          break;
       ... // so on for all chars
    }
}



function randomString($length)
{
   $result="";
   if($length>0)
   {
      for($i=1; $i<=$length; $i++)

      {
         $num = mt_rand(1,36);
         $result .= getRandomChar($num);
      } 
   }
   return $result;
}

The second version is slightly faster however it is more complex and less flexible. For example, if you wanted to change the charset (e.g. include new chars like .,# and so on), in the first version you would just add them to the $charset variable. However, with the second version you would have to update the switch construct in the getRandomChar function. So, our preference goes to version one.

Fixing Cyclic Relationships Between the Parent-Child Relation in Entity Framework and WCF

It has been quite a while since I last wrote a post on this blog (due to lack of time as you may guess). Nevertheless, the blog has been getting more and more readers. I have decided to continue writing new posts and keep the blog alive :) So, here we go again.
I have started a lot of WCF and Entity Framework programming recently. IMHO, for now Entity Framework is powerful enough to be used in serious projects and WCF and Entity Framework make a great duo for implementing solutions based on a service-oriented architecture.

I must admit that adoption of Entity Framework has not been very smooth. Due to the nature of my projects, code-first is the only viable option for me. As you are well aware only recently has Entity Framework started supporting code-first approach.

So far all has been going well. I have quickly designed my domain model, configured entities, put in flexibility and so on. To be short, it has been a real rock 'n roll until I got this horrible situation.

The underlying connection was closed: The connection was closed unexpectedly. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly.


The worst thing was that the application worked for certain type of entities yet breaking for others. Then I carefully looked at my entities, looked more and more then noticed that only those entities that had parent-child relationship, they would give this problem. Something had to do with the relationship. I knew that I was missing something and something serious. In situations like this (and not only this), MSDN is your best friend. I started with the attributes and naturally the DataContract attribute was the first one. property has attracted my attention

public bool IsReference { get; set; }

Putting this property to true has quickly solved the problem.

As it turns out, when you have a relationship between two entities and they reference each other, this cyclic reference causes a stack overflow in the WCF serializer. It is pity that .NET does not give any informative exception. Rather, it just closes the connection.

Thus, if you run into a similar situation, make sure your entities are decorated by the DataContract attribute as shown below.

[DataContract(IsReference = true)]
Codingware.com