# Sunday, August 30, 2009

Normally, I don't have enough time to really dig into the bleeding edge technologies, but I am trying to rectify that. The question is always "When is it too early.."

For now, I have been looking at some of .Net 4.0's newer features, and one really cool thing for environments which have years of legacy software is called "Multi-targeting". Essentially, it allows you set the target environment for an application in the same IDE (but later target new versions).

As an example, let's say you are currently using ASP.Net 2.0, and you have to because of client concerns. No problem, you'll be able to set the VS IDE to target the 2.0 framework. However, when you decide to upgrade, you can just change the target framework version. The neat thing is that the IDE willl hide and show Intellisense based on the target framework as well.

Scott Guthie is writing a series on it I plan on following closely. This time, I may just have to be more bleeding edge than I have been in the past.

Sunday, August 30, 2009 4:31:31 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Saturday, August 29, 2009

The following code snippets make retrieving values from DataRows safely, and properly casts them to the desired values.

 

        /// <summary>

        /// Gets the int value from data row.

        /// </summary>

        /// <param name="fieldName">Name of the field.</param>

        /// <param name="dr">The dr.</param>

        /// <returns></returns>

        public static int GetIntValueFromDataRow(string fieldName, DataRow dr)

        {

            return (dr[fieldName] == DBNull.Value ? 0 : Convert.ToInt32(dr[fieldName].ToString()));

        }

 

        /// <summary>

        /// Gets the int value from data row.

        /// </summary>

        /// <param name="fieldName">Name of the field.</param>

        /// <param name="dr">The dr.</param>

        /// <param name="defaultValue">The default value.</param>

        /// <returns></returns>

        public static int GetIntValueFromDataRow(string fieldName, DataRow dr, int defaultValue)

        {

            return (dr[fieldName] == DBNull.Value ? defaultValue : Convert.ToInt32(dr[fieldName].ToString()));

        }

 

        /// <summary>

        /// Gets the string value from data row.

        /// </summary>

        /// <param name="fieldName">Name of the field.</param>

        /// <param name="dr">The dr.</param>

        /// <returns></returns>

        public static string GetStringValueFromDataRow(string fieldName, DataRow dr)

        {

            return (dr[fieldName] == DBNull.Value ? String.Empty : dr[fieldName].ToString());

        }

 

        /// <summary>

        /// Gets the string value from data row.

        /// </summary>

        /// <param name="fieldName">Name of the field.</param>

        /// <param name="dr">The dr.</param>

        /// <param name="defaultValue">The default value.</param>

        /// <returns></returns>

        public static string GetStringValueFromDataRow(string fieldName, DataRow dr, string defaultValue)

        {

            return (dr[fieldName] == DBNull.Value ? defaultValue : dr[fieldName].ToString());

        }

 

        /// <summary>

        /// Gets the bool value from data row.

        /// </summary>

        /// <param name="fieldName">Name of the field.</param>

        /// <param name="dr">The dr.</param>

        /// <returns></returns>

        public static bool GetBoolValueFromDataRow(string fieldName, DataRow dr)

        {

            return (dr[fieldName] == DBNull.Value ? false : Convert.ToBoolean(dr[fieldName].ToString()));

        }

 

        /// <summary>

        /// Gets the decimal value from data row.

        /// </summary>

        /// <param name="fieldName">Name of the field.</param>

        /// <param name="dr">The dr.</param>

        /// <returns></returns>

        public static decimal GetDecimalValueFromDataRow(string fieldName, DataRow dr)

        {

            return (dr[fieldName] == DBNull.Value ? 0 : Convert.ToDecimal(dr[fieldName].ToString()));

        }

Saturday, August 29, 2009 7:32:59 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Friday, August 28, 2009

I am a huge fan of CodeSmith. If you are not familiar with it, and you do any amount of coding at all, you owe it to yourself to check it out.

Below is some template code which loads the foreign keys of a table into a Dictionary object. It stores the name of the table and foreign key field name. As you can see, it generates a notice when it comes across a recursive relationship.

 

public Dictionary<string,string> GetForeignKeyTables()
{
    Dictionary<string,string> dic = new Dictionary<string,string>( );

 for (int idx = 0; idx < SourceTable.ForeignKeys.Count; idx ++)
 {
        string primaryTable = String.Empty;
        string primaryKey = String.Empty;

  // To get the foreign key columns
  ColumnSchema col1 = SourceTable.ForeignKeys[idx].ForeignKeyMemberColumns[0];
        primaryKey = col1.Name.Trim();

  // To get the foreign key tables
        primaryTable = SourceTable.ForeignKeys[idx].PrimaryKeyTable.ToString().Replace("dbo.",String.Empty).Trim();
        if (!dic.ContainsKey(primaryKey))
            dic.Add(primaryKey, primaryTable);
        else
            MessageBox.Show("This table may contain recursive relationships. You must set those relationships up manually.");
    }

    return dic;
}

 

Friday, August 28, 2009 10:48:39 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, August 27, 2009
Interview question -- non-technical about how I handle release problems.
Thursday, August 27, 2009 12:01:11 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, August 25, 2009
An example of reflection in coding!
Tuesday, August 25, 2009 6:12:16 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

Today has been an insanely busy day, but I have so much I want to blog about, and this one won't wait. A few days ago, as I was using some code I found on the net, I commented here about the over-use of the var keyword.

Seems I am not the only one who has an opinion on the matter. I subscribe to the CodeProject newsletter, and each issue features a survey. This week, the survey relates to the opinion of the var type in C#. You can see the survey results here. Make sure you click through to the "optional text answers" for some funny comments (and a few relevant ones as well).

The interesting thing to note from the survey is that the answers tend to skew towards the "never use that scenario" range. The two areas where it is most prevalent is with LINQ, and with anonymous types, which makes total sense.

All Things | C# | CSharp | Design | General
Tuesday, August 25, 2009 5:28:04 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Monday, August 24, 2009

Question: What's reflection, and how have you used it to solve a problem?

Answer: Reflection is a way to look at assembly metadata and look in and see what is contained. It also allows you to use late binding and call methods within those assembles.

For the second part, a simple explanation is all you need to show that you understand how it is used.

So what if you've enver used reflection? First, shame on you (kidding!). It DOES serve a very important purpose and allows for some great solutions, especially at an architectural level. If you've never used it, I recommend immediately trying it out, and you'll find many, many uses. Here's a tutorial I found that looks decent. That way, when asked this question (and I get this one a lot) you can answer how you *might* really use it. Honestly, you've probably used it and didn't realize it if you've added certain attributes to your code.

I have used reflection for everything from identifying certain classes and functions. For example, for a coding sample, I used LINQ for Reflection and attributes to identify classes which supported certain calculations. By doing this, I could add more functions dynamically and the UI would pick it without changing code. Since LINQ for Reflection is not discussed much, I'll post some about that later.

There are some costs associated with Reflection though. Speed! Late Binding is slower by it's nature, as well as all the processing looking for methods, so plan and use wisely!

Monday, August 24, 2009 3:27:02 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Sunday, August 23, 2009

As a full time developer, I search the web... a lot. If you are writing a lot of new code without at least searching to see what exists, you're either getting paid by the hour (or line of code), stubborn or a glutton for punishment. Even if I don't use it, I can get some guidance on what someone else tried, and how it worked out before I start coding. Granted, it usually requires a lot of refactoring the code to my standards or needs, but it's a great start.

As I was thinking of things I wanted to put on my site, I realized it would be nice to share my "favorites"...sort of. If I found something useful, I wanted to be able to show what it was, how I found it useful and where someone else can find it. In a way, I am also helping to promote someone else's hard work and improving their search engine visibility to return the favor of their sharing their work.

Out of this, I came up with an idea for a "Useful Links" section. I wanted to be able to add links and commentary, and also add it to my Activity Aggregator to show help show the content of the site has changed. Later, as I was using Bing, I got the idea to add some webthumbs to enhance the page graphically, so the reader would know what the site looked like before going there. I also needed to add an admin page for creating the useful links (and ultimately maintaining them -- which is on my TODO list). I'll also leave out the icon creation part, although I really need to farm out for a new cool looking icon, which is also on my list of things to do.

I'll skip the admin section, as it's just data entry fields. The process for creating the entries does change a bit, as I needed to do a few extra steps.

  1. Save the UsefulLink class
  2. Default the webthumb image to a default "safety" image in case we can't get a webthumb
  3. Make a request to get a webthumb image of the target site
  4. Once the image is retrieved, update the UsefulLink record to point to the new webthumb
  5. Update the Activity Aggregator to show we have a new useful link.

Step 3 is where things get tricky. How in all getout do we get webthumb images? There are controls out there you can get, and they are reasonably priced as well. But I decided to keep searching so I could write this one on my own, as it seems like an interesting challenge.

My next thought was to create my own service to do this. There's plenty of code out there, but the easiest way to do this would require some WinForms programming. Don't get me wrong, I LOVE programming WinForms. The problem is I don't want to have to install it everywhere I am at, as I need a service. I could possibly create a Web and Windows service to do this as well, but that seemed overly complex. So I did a search, and I found this, which is a service which does it for you. What's even nicer is that they expose a nice API to use. As of now, the first 100 images a month are free, and after that, the fees are very reasonable. Even though I doubt I will go over 100 images per month, I am so impressed I may pay just to keep the service going.

I was also able to find some c# code to make learning the API fast. I did end up changing it some, but in general it worked very well. You can find it here.

So when the service returns with my image (I used the medium size), I save it to a thumbs directory (had to add write permissions to the directory, or I got an obscure GDI+ error), and call a method on my UsefulLink class to update the record with the thumbnail image. I name the image with the current date and time so that the names will be unique as well.

Finally, once I have downloaded the image and updated the UsefulLink record, I add a call to my Activity class which creates an entry for the Activity Aggregator. As I add more items to throw into the Activity Aggregator, I am considering refactoring things to do some delegate multicasting for all the updates, or perhaps creating a factory where you provide class (should be easy since my business objects share the same base class) or interface, and it knows how to create the activity record instead of making individual calls. That's on my list down the road. :)

Here's what the Activity Aggrgator looks like, with a special Useful Link icon():

 

And here's what the Useful Link section (which has the webthumbs) looks like. I will only be showing 10 at a time to save web page real estate. But I also don't want to lose older links off the page. I am debating now whether to use paging, or just have a smaller hyperlink-only section below the most recent links. I am leaning towards paging, as I have a very neat service I want to implement which makes paging and sorting incredibly fast and easy (more on that someday.. I need to upgrade it to user .Net 3.5 functionality before I post it).

 

All Things | ASP.Net | C# | CSharp | Design | General
Sunday, August 23, 2009 5:28:00 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
Usage of the "var" variable declaration and readability.
All Things | C# | CSharp | Design | General
Sunday, August 23, 2009 7:09:25 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Friday, August 21, 2009
Another interview question of the day -- Access Modifiers
Friday, August 21, 2009 5:06:04 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Wednesday, August 19, 2009
Another interview question du jour!
Wednesday, August 19, 2009 8:34:53 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, August 18, 2009

I've been doing technical interviews for about 5 years now for .Net, and hired a lot of developers in that time. As a result, I have become proficient at quickly assessing a level of technical expertise as well as how a developer may fit within an organization. I will blog another time about what characteristics I look for in a candidate, but for now, I will go through some of the technical questions I ask, answer them, and explain why I ask the question.

Question: What's the difference between an abstract class and an interface

Answer: They have some similarities in that they both define abstract members which have to be implemented. An interface is really just a contract where you are stating "if I implement this interface, I will implement these methods". However, an abstract class can have an implementation, where an interface cannot. An abstract class can also have constructors and field data.

One advantage of an interface is that you can implement more than one interface per class, but you can only inherit from one class.

Note there's a lot more you could talk about with them both (and you don't want to overtalk any question), but the above will demonstrate you have a good knowledge of OOP design, which is what I was looking for. It's surprising how many developers cannot get this question right.

To learn more, here's a good article which discusses them in more detail (more than you'd need to answer the question for sure, but good knowledge to have!)

Tuesday, August 18, 2009 4:02:10 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Monday, August 17, 2009
I highly recommend the Application Architecture guide from CodePlex.
Monday, August 17, 2009 1:21:50 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Sunday, August 16, 2009

Decided to look at my web stats, and when I was looking at the search criteria people were using to find my site, I had to laugh at this one: hate llblgen

I wonder if someone else was at the point of frustration I was. All I can say is this -- don't blog about it!! :) I really ought to categorize this as a "Trick or Tip".

Sunday, August 16, 2009 6:19:47 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Saturday, August 15, 2009

I needed to use LINQ to XML to grab some RSS feed information into a BusinessObject I created to save to a database. Here's what I needed:

var activityList = from e in doc.Descendants("item")

                                       select new RubiconPortal.BusinessObjects.Activity

                                       {

                                           ActivityTypeID = ActivityTypes.Blog.Code,

                                           ActivityDate = e.Element("pubDate").Value.RSSDateTime().ToShortDateString() + " " + e.Element("pubDate").Value.RSSDateTime().ToShortDateString(),

                                           ActivitySummary = HttpUtility.HtmlDecode(e.Element("title").Value),

                                           ActivityDetailsURL = e.Element("link").Value

                                       };

 

Since the pubDate comes across in a format which is different than I wanted, I decided to write an extension method called RSSDateTime() to convert to a DateTime, from which I can format any way I want or work with. Here's the method:

 

public static DateTime RSSDateTime(this string date)

        {

            DateTime d;

            if (DateTime.TryParse(date, out d))

            {

                return Convert.ToDateTime(date);

            }

 

            return DateTime.Now;

 

        }

Saturday, August 15, 2009 9:18:49 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

I have to get some landscape rock put out before my home owner's association has a cow, but I decided to do some more work on my activity aggregator. Today, I decided to integrate my blog feed into it, so when I post here, it will automatically update this activity on my home page (and soon to be in my developer's area).

Here's what the end result looks (for now).

Doing it was fairly easy with the design I implemented in my last post. My BlogFeed class inherits the BaseFeed class, which means I need to implement the ParseFeed() method. Since the RSS feed from my blog is XML, I was easily able to adapt the same code from my TwitterFeed class to work for this RSS feed (which should actually work for any RSS feed I pass in).

I also created another Extension method (for practice) to convert the RSS feed date time to a C# DateTime object. I will post that code as "Tip of the Day" but I have to give Dan Wahlin credit for it, as I adapted some sample code he provided.

Here's how the RSS feed (aka BlogFeed) uses LINQ to XML for creating my activity object.

    internal class BlogFeed : BaseFeed

    {

 

        public override int ParseFeed(XDocument doc)

        {

            try

            {

                ReturnCode code = ReturnCode.Success;

                if (doc != null)

                {

                    var activityList = from e in doc.Descendants("item")

                                       select new RubiconPortal.BusinessObjects.Activity

                                       {

                                           ActivityTypeID = ActivityTypes.Blog.Code,

                                           ActivityDate = e.Element("pubDate").Value.RSSDateTime().ToShortDateString() + " " + e.Element("pubDate").Value.RSSDateTime().ToShortDateString(),

                                           ActivitySummary = HttpUtility.HtmlDecode(e.Element("title").Value),

                                           ActivityDetailsURL = e.Element("link").Value

                                       };

 

                    foreach (Activity item in activityList)

                    {

                        //We need to check and see if the item exists

                        if (!Activity.CheckEntryExists(item.ActivityTypeID, item.ActivityDetailsURL))

                        {

                            int results = item.Save();

                            if (results != ReturnCode.Success.Code)

                                code = ReturnCode.Failure;

                        }

                        else

                            return code.Code;   //we can break once we hit one we've already logged (for performance reasons

 

 

                    }

 

 

                }

                return code.Code;

            }

            catch (Exception ex)

            {

                ErrorHandler(ex, "An unexpected error occurred in TwitterFeed.ParseFeed() - " + ex.Message);

                return ReturnCode.Failure.Code;

            }

        }

    }

 

My next step will be to integrate some AJAX so when the user hovers over the link, they can see things like the date, more of the topic, etc. I also need to integrate my "Useful Links" dicussion as well.

All Things | ASP.Net | C# | CSharp | Design | General
Saturday, August 15, 2009 9:13:22 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Friday, August 14, 2009

Tonight was a very enjoyable night of coding. I created the first phase of my "activity aggregator". I actually had a more clever name for it, but being tired, it slips my mind right now.

Currently, I post several places.. short updates for on Twitter. Longer discussions end up on here, my blog. I have some other sources I plan on integrating over time, such as links I found useful (similar to Digg, but also where I can place why I found it useful). That means growth, and when it comes to design, it's best to design change into it up front.

The first thing I needed to do was create my table and business object to collect these activities. In my table, I store ActivityDate, what type of activity it was (foreign key to another table -- ActivityType), a brief summary of the activity text, and finally the url someone interested could click on to get more information. The internal members of my activity class look like this:

   15         #region Private Members

   16 

   17         private int activityID;

   18         private int activityTypeID;

   19         private string activityDate;

   20         private string activitySummary;

   21         private string activityDetailsURL;

   22 

   23         #endregion

 

Each private member has a publically exposed property.

 

Most of my activities will have XML feeds, such as the RSS feed of my blog, and the Twitter API. Therefore, I enforce a similar implementation by creating an abstract base class, called BaseFeed, which looks like this:

    1 using System.Xml.Linq;

    2 using RubiconPortal.Common;

    3 

    4 namespace RubiconPortal.BusinessObjects

    5 {

    6     internal abstract class BaseFeed : BaseClass

    7     {

    8 

    9         public abstract int ParseFeed(XDocument doc);

   10 

   11     }

   12 }

 

So now I have a "contract" that I need to use to have a similar method for any activity I want to log. I could have used an interface for this, since there's no true implentation here, and I may refactor it later to do so, but I do have some ideas where I may want to provide some implementation, so that's why I chose an abstract class.

 

So the first item I wanted to do was implement capturing my Twitter posts in this activity, since I currently don't have a way to capture and post them on my site. I will add the rest of the activities later. In a previous post, I described how I took the Yedda Twitter API and modified it to return XDocuments, and here's another chance to take advantage of that change with LINQ.

 

When I post to my Twitter feed, I want to make sure my home page automatically reflects this activity. So I implement a TwitterFeed object, which implements the BaseFeed method ParseFeed. Using LINQ to XML, I pull out the pieces of the response I want, and populate the public properties of my Activities class, then save my activity. Here's what my TwitterFeed class looks like:

 

    1 using System;

    2 using System.Linq;

    3 using System.Web;

    4 using System.Xml.Linq;

    5 using Rubicon.Common;

    6 using RubiconPortal.Common;

    7 

    8 namespace RubiconPortal.BusinessObjects

    9 {

   10     internal class TwitterFeed : BaseFeed

   11     {

   12         public override int ParseFeed(XDocument doc)

   13         {

   14             try

   15             {

   16                 if (doc != null)

   17                 {

   18                     var activityList = from e in doc.Descendants("status")

   19                                        select new RubiconPortal.BusinessObjects.Activity

   20                                        {

   21                                            ActivityTypeID = ActivityTypes.Twitter.Code,

   22                                            ActivityDate = (e.Element("created_at").Value.ParseDateTime()).ToShortDateString() + " " + (e.Element("created_at").Value.ParseDateTime()).ToShortTimeString(),

   23                                            ActivitySummary = HttpUtility.HtmlDecode(e.Element("text").Value),

   24                                            ActivityDetailsURL = "http://twitter.com/" + e.Element("user").Element("screen_name").Value

   25                                        };

   26 

   27                     foreach (RubiconPortal.BusinessObjects.Activity item in activityList)

   28                     {

   29                         item.Save();

   30                     }

   31                 }

   32 

   33                 return ReturnCode.Success.Code;

   34             }

   35             catch (Exception ex)

   36             {

   37                 ErrorHandler(ex, "An unexpected error occurred in TwitterFeed.ParseFeed() - " + ex.Message);

   38                 return ReturnCode.Failure.Code;

   39             }

   40         }

   41 

   42     }

   43 

   44 }

 

Within the ParseFeed method I am using LINQ to XML to populate my business object calling the save() method to write it to the database. As you can see, using LINQ to XML can be a lot simpler than using XML/XPath. Once in the database, I can query it in my user control, and display it on my home page here.

 

Now, when I make my Twitter post, all I need to do is take the XDocument the Twitter API returns, and pass it into the ParseFeed method, which looks like this...

   35                     //Post my tweet to Twitter

   36                     TwitterAPI twit = new TwitterAPI();

   37                     XDocument doc = twit.UpdateAsXML(Settings.TwitterUserName(), Settings.TwitterPassword(), txtPost.Text);

   38 

   39                     //Save it to the activity table for displaying the activity

   40                     TwitterFeed feed = new TwitterFeed();

   41                     feed.ParseFeed(doc);

 

Simple and neat! Now when I implement it for my blog, it will be just as quick and easy!

 

Props go out to this post I snagged an extension method for formatting the Twitter posting date to something a human can use (and my C# class can use to manipulate and save!)

 

 

 

Friday, August 14, 2009 7:40:31 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Wednesday, August 12, 2009
Some tools I downloaded today which appear VERY useful, and touching on the ORM topic.
Wednesday, August 12, 2009 6:31:11 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  |