Skip to content

Refactoring in reusing code, and getting the latest DateTime record from the Database

Today had been a fairly busy day yet again, and I will discuss reusing old code in more detail from the previous post, in that refactoring is a good thing. You can observe certain bits of code that are repeated in the lists of code you write, and it may be a good idea for future maintenance to get that bit of repeated code and place this in a method.
For example, the inner bit of code inside this method had been repeated, so I placed this outside into a method called getSessionCount which returns a long integer (Int64) which can then be reused over and over again, in particular for my toggle switch method which is discussed on another post: –

private long getSessionCount()
long sessionCount = 0;

if (Request.QueryString[“subscriber”] != null && Request.QueryString[“date”] != null)
sessionCount = PortalStats.GetAllSessionsCountByDateBySubscriberID(Request.QueryString[“date”].ToString(), Convert.ToInt64(Subscriber.FindSubscriberByUsername(Request.QueryString[“subscriber”]).SubscriberID));
else if (Request.QueryString[“date”] != null)
sessionCount = PortalStats.GetAllSessionsCountByDate(Request.QueryString[“date”].ToString());
sessionCount = PortalStats.GetAllSessionsCount();

return sessionCount;

This saves looking at these bits of code that may be a bit long and repeated, if you change one part of the repeated code, the rest has to be changed which may take longer than necessary when rewriting code. So this saves a lot of time!

Another thing about why refactoring is good is that having done this, it saves me time when maintaining pages of code, I have reused the whole .aspx code in other pages that generate these reports, so its a good foundation to code!

One last thing I would like to talk in detail is the generating very dynamic reporting based on dates for PDFs, see my previous post on generating PDFs earlier this year. The problem that I had found out is that if you have old records of stats that you need the last two weeks of, you need to get the last record of the table holding the stats if you don’t rely on dates. So far I hard coded DateTime.Today which checks today’s date then used DateTime.AddDays(-14) which may not get any data if your database table holds records two months back. You may think that this wouldn’t worry you but it may happen if your database is under maintenance and no stats are stored for days on end.

Here is code which may help you counter this: –

long sessionCount = getSessionCount();

DataTable dtAllSessions;

dtAllSessions = CreateDataForSessions(Convert.ToInt32(sessionCount) – 1);

string latestDateString = dtAllSessions.Rows[0][“Month”].ToString() + “/” + dtAllSessions.Rows[0][“Day”].ToString() + “/” + dtAllSessions.Rows[0][“Year”].ToString();

System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
provider = new System.Globalization.CultureInfo(“en-US”);

DateTime value;
DateTime latestDate;
if (DateTime.TryParseExact(latestDateString, “M/d/yyyy”, CultureInfo.InvariantCulture, DateTimeStyles.None, out value))
latestDate = Convert.ToDateTime(latestDateString, provider);

Response.Redirect(“../reports/SessionsStatsReport.aspx?format=pdf&date=” + latestDate.AddDays(-days + 1).ToShortDateString());

Not wondering too much about the method CreateDataForSessions() which basically stores data into the DataTable, you can see the code is dynamic in checking that the very last record of the table based on the method CreateDataForSessions() and stores into the dtAllSessions which is a datatable.

string latestDateString = dtAllSessions.Rows[0][“Month”].ToString() + “/” + dtAllSessions.Rows[0][“Day”].ToString() + “/” + dtAllSessions.Rows[0][“Year”].ToString(); gets the month, day and year column of that last row, and does a parse of the date using TryParseExact. If you seen this before, its quite handling parsing dates on strings, and makes sure to use M/d/yyyy for the Regular Expression as MM/dd/yyyy is very strict in that you need 0’s in front of single values which is a pain!

Last but not least, you can add this:-

if (DateTime.TryParseExact(latestDateString, “M/d/yyyy”, CultureInfo.InvariantCulture, DateTimeStyles.None, out value))
latestDate = Convert.ToDateTime(latestDateString, provider);
latestDate = DateTime.Today;

if (days == 0)
Response.Redirect(“../reports/SessionsStatsReport.aspx?format=pdf&date=” + latestDate.AddDays(-days + 1).ToShortDateString());

This makes it flexible in that if the parsing fails you always can refer to the latest date! So it can always get a date!
Then you can use a days variable used for toggling between the set days to view, days is:-

private static int days = 0;

I realized that having a static integer for holding the days would be easier than relying on a value in the dropdown list which based on my code was not what I wanted. And when days = 0, you see all the records!!

Hope for any of you who wants to get the latest record and switch between the number of records stored in the DataTable can find it useful!


National Hack The Government Day 2012 #nhtg12

National Hack The Government Day 2012 has come and gone, and boy it was a blast!! Organised by Rewired State (Emma McQueeny and Adam McGreggor) and hosted by Government Digital Service (GDS), it is basically a hack day event on as they say there coding for a better country. It makes use of taking government data and creating prototypes of tools, services, applications or even websites on the 21st April 2012 hence gicving pretty much free reign on what you can do.

Still recovering from the events, I managed to build a working application just before time was up (which I was quite happy about) called FarmAllot.The application FarmALlot is suppose to find your nearest allotment for farming vegetables agreed by DEFRA, and organised by the community to purchase a plot together agreed by DEFRA, and through social communciation. It bypasses the restrictions of going through council and its long waiting lists! It was my idea before the event, and I wanted to stick away from the House Saving API offered by DECC, so I stuck with trying to match the criteria of DEFRA. As it seems the API’s which I wanted to grab from DEFRA where very hard to come by, having spent 1.5 days looking for any data from DEFRA was hard to come by, I tried to look at the Geological Society and Countryside Survey to get soil data of any kind on pollutants but to no prevail, and felt that time was wasted on looking for the API.

Instead my earlier coding attempts seem too have prevailed as I built a map which finds local farms and farmers markets around the UK, and adopted it further to find suitable places for allotments, I then used the uk land directory data via RSS feeds to gather all the locations based on counties, and stick the points on a bing map based on the selected plot of interest. Then finally quickly mocked up a sample message to send to the owner of the plot. I wanted to get some DEFRA data to stick at the end of the plot information to see if it met DEFRA critique but ran out of time! The application won the special award for best application most likely to annoy Government! (which was funny in a way, as I was kind of building it for the people not the Government!).

Notable applications worth mentioning from the Show and Tell were Green Games by John Lyons on an application that awards families rewarded tree points for each green thing they do in the house. It allows different initiatives have different points, based on a green thing they do accumulation of points can get some real life reward, like a trip to the zoo, or to the cinema. Wheres My New House by Tim McGinely and Kevin Daniells which showcased how many house that the council can allow to build within your area, and calculates how much land a potential supermaket can be occupying that piece of land that could be used for housing like Tescos. I particular liked the hack on the google map interfact changing the colour scheme completed to black, yellow, blue and green. See .

FInally the application I love the most which ironically won Best In Show award was Loftify by @stef, which was an application that is a service for families to collectively pay for home energy efficiency for older relatives with a little help from the Government. It allows cost savings information such as Get loft insulation and huge efficiency savings. It shows a visualsation with an image of a grandmother figure getting warmer as the cuts of energy were made. It certainly was genuis and comical as well as informative and certainly deserved the award!

I enjoyed the event, met some familiar faces aswell as new ones, and had free beer and pizza, it was particular well organised including the social drinking afterwards, well worth going for next year!!

A Quick Tip – On Binding Enums to a DropdownList

Here’s a really handy tip for binding an enum to a DropDownList component in ASP.NET, all you need to do is to write a HashTable with your enumerated type, and convert the value, and key of that enumeration to the Hashtable object and set it as the datasource of the DropdownbList. Here’s how: –

protected void Page_Load(object sender, EventArgs e)
Hashtable ht = GetEnumForBind(typeof(YourEnum));
DropDownList1.DataSource = ht;
DropDownList1.DataTextField = “value”;
DropDownList1.DataValueField = “key”;



public Hashtable GetEnumForBind(Type enumeration)
string[] names = Enum.GetNames(enumeration);
Array values = Enum.GetValues(enumeration);
Hashtable ht = new Hashtable();
for (int i = 0; i < names.Length; i++)
ht.Add(Convert.ToInt32(values.GetValue(i)).ToString(), names[i]);
return ht;

A Quick Tip on SortCommand in DataGrid Tables

Here is a quick tip that I only realised now when using the SortCommand in DataGrid Tables, this is to don’t use the conventional sorting in the DataGrid Table, it doesn’t sort the columns properly at all, just link to the database source directly and store it into the DataTable as specified: –

protected void dgSessions_Sort(object source, DataGridSortCommandEventArgs e)
// Store the Sort Expression Direction

string sortExpressionDirection = “asc”;
if (SortExpressionDirection == null)
SortExpressionDirection = sortExpressionDirection;

//Retrieve the table from the session object.
DataTable dt = Session[“SessionTable”] as DataTable;
////dt.DefaultView.Sort = e.SortExpression + ” ” + SortOrder(SortExpressionDirection);

// Store the Sort Expression into session object.
Session[“SessionSortExpression”] = e.SortExpression;
Session[“SessionSortDirection”] = sortExpressionDirection;

tbl.DataSource = dt;

In the datatable code as specified: –

tbl.AllowSorting = true;
tbl.SortCommand += new DataGridSortCommandEventHandler(this.dgSessions_Sort);

You can see I commented out the dt.DefaultViewSort, simply store the ordered data in the Session[“SessionTable”] and it should work!

Free WP7 icons for developers

Here is another set of free icons for WP& developers I had just found at

It has 126 different icons and some newer ones for WP7 Mango.

EF Mapping with POCO Errors

If you ever receive the following error messaging containing this wording “Mapping and metadata information could not be found for EntityType”, it is a rather anonymous message saying that in the Model folder of the EF mappings in the .edmx file, something has gone wrong in the mappings of the XML somewhere.

For anyone else dealing with the error,  it’s clearly stating the likely scenarios which I’ve found that cause this (extremely unhelpful) error:

  • Misspelled properties (case-sensitive!) This is the most likely problem, if somewhere in your model fields/attributes are missing to the conceptual model of your database, Visual Studio will complain like nobody’s business, make sure all fields/attributes/variables right down to the types match correctly. E.g.

    <EntityType Name=”test”>
        <PropertyRef Name=”testID” />
        <PropertyRef Name=”secondtestID” />
      <Property Type=”String” Name=”test” Nullable=”false” MaxLength=”16″ FixedLength=”true” Unicode=”false” />
      <Property Type=”Int32″ Name=”secondtestID” Nullable=”false” />
      <Property Type=”String” Name=”CLI” MaxLength=”25″ FixedLength=”true” Unicode=”false” />
      <Property Type=”DateTime” Name=”ReceivedTime” />
      <Property Type=”String” Name=”testparam” MaxLength=”100″ FixedLength=”true” Unicode=”false” />
      <Property Type=”Boolean” Name=”testbool” />

    This has got to match with the variables in the model class of your web service.

  • Properties missing in the POCO class. (You need to write everything down correctly!) This also includes things lime Nullable=”false” for keys, you need to include this otherwise it won’t work.
  • Type mismatches between the POCO and entity-type (e.g., int 32 instead of long)
  • Enums in the POCO (EF doesn’t support enums right now, so don’t include them)

DataBinding in WP7–The Quick and Easy Way

Here is something I found for those who wish to perform databinding on a  List Box using ItemsSource using static data the quick and easy way!

I started by added a static reference to the MainViewModel in the App class of App.xaml.cs

 private static MainViewModel viewModel = null;

 public static MainViewModel ViewModel
  // Delay creation of the view model until necessary
  if (viewModel == null)
   viewModel = new MainViewModel();
  return viewModel;

My two lists in the MainViewModel class of MainViewModel.cs looked like this:

 public MainViewModel()
  // Insert code required on object creation below this point
  Items1 = new ObservableCollection<ItemViewModel>() {
  new ItemViewModel() { LineOne = "runtime one", LineTwo = "Maecenas praesent accumsan bibendum", LineThree = "Facilisi faucibus habitant inceptos interdum lobortis nascetur pharetra placerat pulvinar sagittis senectus sociosqu", },
  new ItemViewModel() { LineOne = "runtime two", LineTwo = "Dictumst eleifend facilisi faucibus", LineThree = "Suscipit torquent ultrices vehicula volutpat maecenas praesent accumsan bibendum dictumst eleifend facilisi faucibus", },
  new ItemViewModel() { LineOne = "runtime three", LineTwo = "Habitant inceptos interdum lobortis", LineThree = "Habitant inceptos interdum lobortis nascetur pharetra placerat pulvinar sagittis senectus sociosqu suscipit torquent", },

  Items2 = new ObservableCollection<ItemViewModel>() {
  new ItemViewModel() { LineOne = "runtime one", LineTwo = "Maecenas praesent accumsan bibendum", LineThree = "Facilisi faucibus habitant inceptos interdum lobortis nascetur pharetra placerat pulvinar sagittis senectus sociosqu", },
  new ItemViewModel() { LineOne = "runtime two", LineTwo = "Dictumst eleifend facilisi faucibus", LineThree = "Suscipit torquent ultrices vehicula volutpat maecenas praesent accumsan bibendum dictumst eleifend facilisi faucibus", },


 public ObservableCollection<ItemViewModel> Items1 { get; private set; }

 public ObservableCollection<ItemViewModel> Items2 { get; private set; }

Now I changed the initialisation of DataContext in MainPage.xaml.cs to reference the static object

  if (DataContext == null)
  DataContext = App.ViewModel;

Removed the direct reference to the Items1 list in MainPage.xaml so it only had the binding

  <ListBox x:Name="ListBoxOne" ItemsSource="{Binding}" MouseLeftButtonUp="ListBoxOne_MouseLeftButtonUp" Style="{StaticResource PhoneListBox}">

And now I can use my conditions check to set the ItemsSource using the following code in MainPage.xaml.cs

  ListBoxOne.ItemsSource = App.ViewModel.Items2;