Author: nrogoff

2011 in review

The WordPress.com stats helper monkeys prepared a 2011 annual report for this blog.

Here’s an excerpt:

The concert hall at the Syndey Opera House holds 2,700 people. This blog was viewed about 9,000 times in 2011. If it were a concert at Sydney Opera House, it would take about 3 sold-out performances for that many people to see it.

Click here to see the complete report.

Interactive demo app of Windows Phone 7 for Android and iPhone

Microsoft have rather cleverly created a little demo web app that lets an android or iPhone user get some idea of how the WP7 phone works.

Check it out at http://m.microsoft.com/windowsphone/en-us/demo/

Start showing people how much better WP7 clearly is as a phone OS.

A bit bizarre, but it does not work in my IE9 browser!!

Understanding CA2214 code analysis warnings using ViewModels

If like me you didn’t understand the the rest of the message and it’s implications here is a simple explanation and answer.

When an object that implements an inherited class (e.g. a ViewModel that inherits from ViewModelBase) is constructed, the constructors in the base class or classes are executed first.

However as the base classes execute methods or events, if these implemented methods or events are overridden, by a more derived class, then the base could call these and not it’s intended base methods. This could cause some unexpected behaviour.

If you make calls to potentially override-able methods yourself (e.g. RaisePropertyChanged) , you probably intended to and know full well what the consequences are. So why the annoying message?

Well, CA2214 is warning you that this may become a problem if anyone decides to inherit from your class (e.g. your ViewModel). As this is probably not something that you want or intend in your project, you can eliminate this warning by simply sealing your class!

    public sealed class MainViewModel : ViewModelBase

This will ensure that your class cannot be inherited from. This should make the warning go away.

If you are writing your own base class or a class that is to be inherited from, then don’t call override-able methods in your constructors!

Hope that helps! hhhmmmmm

How to easily add open source libraries to .NET projects using NuGet

I have just come across one of the best Visual Studio extensions called NuGet (http://nuget.org/).

It makes it incredibly easy to add available libraries, including such things as JavaScript libraries like jQuery. Not only that, but it will work out any dependencies, download those and then warn you if any get updated.

The easiest way to get going is to add it to Visual Studio using the ‘Extension Manager’ which you will find under the ‘Tools’ menu. It’s called ‘NuGet Package Manager’.

Once installed, it is simplicity itself to add a reference and download the binaries, dependencies and code for a useful library (such as MVVM Light or jQuery).

  1. Right-click on the references folder in your solution.
  2. Select ‘Manage NuGet Packages…’image
  3. and voila…search for new libraries or check for updates. If NuGet finds any updates then you will get an alert when VS2010 starts.

SNAGHTML198fc1

Potential TFS connection Problem TF30063

There is one fly in this ointment that took me a little time to resolve. A bug in NuGet can force the connection to your TFS server to be dropped. The only way out is to restart Visual Studio.  the solution to this turns out to be extremely trivial.

All you need to do is add your TFS server URL to the Intranet security group in Internet Explorer!

The credit for resolving this must go to the very brilliant effort by Miha Markic. See his blog about it at http://blog.rthand.com/post/2011/08/26/Fixing-combination-of-NuGet-and-Team-Foundation-in-workgroup-configuration-401-Unauthorized.aspx

Testing an SMTP Service using telnet

Here’s a quick way to manually test your SMTP service.

The best plan is to run this test on the server first (ensure that localhost or 127.0.0.1 is allowed to access the service) and then from a remote client next.

Follow these steps

(the response examples are those returned against a Windows 2008 R2 Server SMTP Service):

  1. Type Telnet <server name or IP> 25 at a command prompt, and then press ENTER.

    The output should look something like:
    220
    CP5-15164 Microsoft ESMTP MAIL Service, Version: 7.5.7600.16601 ready at  Fr
    i, 16 Sep 2011 11:23:30 +0100

  2. Type ehlo, and then press ENTER.

    The output resembles the following: 
    250-CP5-15164 Hello [127.0.0.1]
    250-TURN
    250-SIZE 2097152
    250-ETRN
    250-PIPELINING
    250-DSN
    250-ENHANCEDSTATUSCODES
    250-8bitmime
    250-BINARYMIME
    250-CHUNKING
    250-VRFY
    250 OK

  3. Type mail from:email@domain.com, and then press ENTER.

    The output resembles the following:
    250 2.1.0 email@domain.com….Sender OK

  4. Type rcpt to:youremail@domain.com, and then press ENTER.

    The output resembles the following:
    250 2.1.5 youremail@domain.com

  5. Type Data, and then press ENTER.

    The output resembles the following:
    354 Start mail input; end with <CRLF>.<CRLF>

  6. Type Subject:Test # subject, and then press ENTER two times.
  7. Type Test # body, and then press ENTER.
  8. Press ENTER, type a period (.), and then press ENTER.

    The output resembles the following:
    250 2.6.0 <CP5-151641XvpFVjCRG00000007@CP5-15164> Queued mail for delivery

  9. Type quit, and then press ENTER.

    The output resembles the following:
    221 2.0.0 CP5-15164 Service closing transmission channel

Creating an easy Grouped ObservableCollection for the LongListSelector

The LongListSelector is great for long lists in Windows Phone 7, but getting your data into the right format can be tricky and confusing (certainly took me a while to work out what to do!). Especially if you want to use ‘pure’ binding to an ObservableCollection.

The answer that I found easiest to understand and follow was to use ‘nested Observable collections’. This also ensure that things are kept up-to-date in the UI without additional coding.

To help me understand what was need I broke it down into some simple stages. I am sure it can be done with a single LINQ statement.

Let say you have a list of contacts that you would like to display with the typical A-Z short cuts as shown here. This includes showing group titles that contain no child records too!

 

Create the basic object – Contacts

We’ll start with the simple Contact class that has two 3 properties. One is derived to create the key value. This can be any value, but here it’s the first letter of the Name value in lower case. If your data is changing then you should implement the INotifyPropertyChanged interface. I have left it out here for simplicity.

namespace PhoneTester1.Model
{
    public class Contact
    {
        public string Name { get; set; }
        public string JobTitle { get; set; }

        private string _NameKey;
        /// <summary>
        /// First letter of the Name. Used for grouping in the long list selector
        /// </summary>
        public string NameKey
        {
            get
            {
                //If not set then
                if (_NameKey == null)
                {
                    //get the first letter of the Name
                    char key = char.ToLower(this.Name[0]);
                    if (key < 'a' || key > 'z')
                    {
                        key = '#';
                    }
                    _NameKey = key.ToString();
                }
                return _NameKey;
            }
        }
    }
}

 

Create the Group Observable Collection

Then we’ll create a Group class. I have called it GroupOC for Grouping Observable Collections.

using System.Collections.ObjectModel;

namespace PhoneTester1.Model
{
    public class GroupedOC<T>:ObservableCollection<T>
    {
        /// <summary>
        /// The Group Title
        /// </summary>
        public string Title
        {
            get;
            set;
        }

        /// <summary>
        /// Constructor ensure that a Group Title is included
        /// </summary>
        /// <param name="name">string to be used as the Group Title</param>
        public GroupedOC(string name)
        {
            this.Title = name;
        }

        /// <summary>
        /// Returns true if the group has a count more than zero
        /// </summary>
        public bool HasItems
        {
            get
            {
                return (Count != 0);
            }
            private set
            {
            }
        }
    }
}

 

Create the Helper method to Group the Contacts

I created a static method  called CreateGroupedOC in a static Collection Helper class called CollectionHelper. This can then be called on to group everything up.

using System.Collections.ObjectModel;
using System.Linq;
using PhoneTester1.Model;

namespace PhoneTester1.Functions
{
    public static class CollectionHelpers
    {
        /// <summary>
        /// Groups a passed Contacts ObservableCollection
        /// </summary>
        /// <param name="InitialContactsList">Unordered collection of Contacts</param>
        /// <returns>Grouped Observable Collection of Contacts suitable for the LongListSelector</returns>
        public static ObservableCollection<GroupedOC<Contact>> CreateGroupedOC(ObservableCollection<Contact> InitialContactsList)
        {

            //Initialise the Grouped OC to populate and return
            ObservableCollection<GroupedOC<Contact>> GroupedContacts = new ObservableCollection<GroupedOC<Contact>>();

            //first sort our contacts collection into a temp List using LINQ
            var SortedList = (from con in InitialContactsList
                              orderby con.Name
                              select con).ToList();

            //Now enumerate throw the alphabet creating empty groups objects
            //This ensure that the whole alphabet exists even if we never populate them
            string Alpha = "#abcdefghijklmnopqrstuvwxyz";
            foreach (char c in Alpha)
            {
                //Create GroupedOC for given letter
                GroupedOC<Contact> thisGOC = new GroupedOC<Contact>(c.ToString());

                //Create a temp list with the appropriate Contacts that have this NameKey
                var SubsetOfCons = (from con in SortedList
                                    where con.NameKey == c.ToString()
                                    select con).ToList<Contact>();

                //Populate the GroupedOC
                foreach (Contact csm in SubsetOfCons)
                {
                    thisGOC.Add(csm);
                }

                //Add this GroupedOC to the observable collection that is being returned 
                // and the LongListSelector can be bound to.
                GroupedContacts.Add(thisGOC);
            }
            return GroupedContacts;
        }
    }
}

 

Tie it together in your ViewModel

In my projects I am usually populating a collection of objects either from a database or web service. Here we’ll start with a collection of Contacts that is populated in a random order. This ObservableCollection we would pass to the method shown above (CreateGroupedOC ) to group it and return a grouped ObservableCollection.. This can then be referenced in your ViewModel and bound to the LongListSelector control.

I also use the very handy MVVM Light Toolkit produced by the very excellent Laurent Bugnion of GalaSoft. This you can find at http://mvvmlight.codeplex.com/ and some info about it at http://www.galasoft.ch/mvvm/getstarted/. I strongly recommend using it.

I have included my whole ViewModel below. Hopefully the comments make it self explanatory!

using System;
using System.Collections.ObjectModel;
using System.Text;
using GalaSoft.MvvmLight;
using PhoneTester1.Functions;
using PhoneTester1.Model;

namespace PhoneTester1.ViewModel
{
    /// <summary>
    /// This class contains properties that the main View can data bind to.
    /// You can also use Blend to data bind with the tool's support.
    /// This code is provided as is by Hard Medium Soft Ltd.
    /// see us at http://www.hardmediumsoft.com
    /// </summary>
    public class MainViewModel : ViewModelBase
    {
        public string ApplicationTitle
        {
            get
            {
                return "Nicholas Rogoff for Hard Medium Soft Ltd.";
            }
        }

        public string PageName
        {
            get
            {
                return "Tester App";
            }
        }

        /// <summary>
        /// The <see cref="GroupedContacts" /> property's name.
        /// </summary>
        public const string GroupedContactsPropertyName = "GroupedContacts";

        private ObservableCollection<GroupedOC<Contact>> _GroupedContacts = new ObservableCollection<GroupedOC<Contact>>();

        /// <summary>
        /// Gets the GroupedContacts property.
        /// 
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public ObservableCollection<GroupedOC<Contact>> GroupedContacts
        {
            get
            {
                return _GroupedContacts;
            }
            set
            {
                if (_GroupedContacts == value)
                {
                    return;
                }
                var oldValue = _GroupedContacts;
                _GroupedContacts = value;
                // Update bindings, no broadcast
                RaisePropertyChanged(GroupedContactsPropertyName);
            }
        }

        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            //Populate some Contacts with random strings
            ObservableCollection<Contact> tempContactsOC = new ObservableCollection<Contact>();
            for (int i = 0; i < 50; i++)
            {
                Contact tempContact=new Contact(){Name = RandomString(12,false,i) + " - " + i, JobTitle=RandomString(18,false,i)};
                tempContactsOC.Add(tempContact);
            }
            //Create our Nested ObservableCollection
            GroupedContacts = CollectionHelpers.CreateGroupedOC(tempContactsOC);
        }

        #region Random String generator

        /// <summary>
        /// Generates a random string with the given length
        /// </summary>
        /// <param name="size">Size of the string</param>
        /// <param name="lowerCase">If true, generate lowercase string</param>
        /// <returns>Random string</returns>
        private string RandomString(int size, bool lowerCase, int seed)
        {
            StringBuilder builder = new StringBuilder();
            Random random = new Random((int)DateTime.Now.Ticks * seed);
            char ch;
            for (int i = 0; i < size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }
            if (lowerCase)
                return builder.ToString().ToLower();
            return builder.ToString();
        }
    
        #endregion

    }
}

 

If you think you can make this simpler or better please let me know. Thanks.