.NET 4.0 Dynamic

There is a built in type now in .NET 4.0 called “dynamic.”  Just as its name implied its a lose type, it has an infinite amount of properties and methods…(reminds me of python)  This should not be confused with “var” which is a strongly typed lazy-man’s variable. 


Dynamic is whatever you want it to be quick example… 


The below code illustrates the use of dynamics.   I have declared a simple class that has two properties (Name and Description) and one method PrintUsingReflection…


using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Reflection;

namespace BlogTests
    public class Test
        public string Name { get; set; }
        public string Description { get; set; }

        public void PrintUsingReflection(object test)
            string name = test.GetType().GetProperty("Name")
			    .GetValue(test, null) as string;
            string Description = test.GetType()
			   .GetValue(test, null) as string;

            Console.WriteLine("Hello there " 
			    + name + " description"
				+ Description);

    public class DynamicExample
        public void ThisIsATest()
            object test = new Test()
                Name = "Nick",
                Description = "Nicks Dynamic Variable!"


        private void PrintUsingDynamics(object test)
            dynamic dynamicTest = test;
            Console.WriteLine("Hello there " + 
			   dynamicTest.Name + " description" +


Lets start with the test method called ThisIsATest()..

I am going to start by initializing a class called Test and then cast it to an object…

object test = new Test()
    Name = "Nick",
    Description = "Nicks Dynamic Variable!"

I then pass the object to PrintUsingDynamics() within the method you will see:

dynamic dynamicTest = test;
Console.WriteLine("Hello there " + dynamicTest.Name + " description" + dynamicTest.Description);

I take the provided object(which is really a “Test” class) and assign it to the “dynamicTest” variable.  At this point it is now a lose type…

In case you don’t believe me.. lets see what intellisense has to say about “dynamicTest.”




Inside my Console.WriteLine i then attempt to access the Name and Description properties… then the black magic of dynamics takes over.  Volia! 

“Hello there Nick Nicks Dynamic Variable”.. displays. 


Back in the day we would have had to have done some really code heavy reflection:

private void PrintUsingReflection(object test)
    string name =  
		 .GetValue(test, null) as string;
    string Description =    
		 .GetValue(test, null) as string;

   Console.WriteLine("Hello there " + name  + 
                    " description" + Description);

Now if you look at the line after we print out "Hello there..” you will see dynamicTest.PrintUsingReflection(test);

dynamic dynamicTest = test;
Console.WriteLine("Hello there " + dynamicTest.Name + " description" + dynamicTest.Description);

Which is an example of accessing a “method” on a dynamic type.  At runtime the compiler crosses its fingers, and then calls the method PrintUsingReflection and hopes that the method exists… and volia!  Once again

“Hello there Nick Nicks Dynamic Variable”.. displays. 


This has been around for a while… but its incredibly useful!


Which one is easier (correct answer is dynamics)….?  The basic premise is whatever you type has to exist.. the compiler basically skips compile time checking.. and at runtime will resolve any property/method calls so be careful!


This comes in handy when doing things with “DataItems” that are anonymous types… avoids you having to create some type of “internal” type just so you can get to the data you need..

Tagged with: , , , , ,
Posted in C#, General, LinkedIn, Microsoft, Programming


Reached the end of the internet?  This site will help StumbleUpon.


I feel like this is a paid advertisement, I assure you it is not, but this is a pretty neat site that is basically a “pandora” for web sites.  You enter in the types of stuff you want to see…


Then click “Save Preferences..” then click  Stumble!


It will then randomly choose a site for you for me it was (http://www.stumbleupon.com/stumbleupon.com/video.php?v=27aOpc)


This time, it chose an amazingly funny video… notice the appearance of a toolbar there which gives you various options. 

Lets stumble one more time


This time it took me to a site in the  “Health” category…


A little about the usage of the site.. first its free!  All you have to do is register.



1. Stumble (click it and it will take you to a new website)

2. I like it, basically says show me more like this.

3. Thumbs down, didn’t like this one… try not to show anything like this.

4.  Share options these allow you to post to facebook, twitter or email (icon or share button)

5. The drop down list that says All topics allows you to toggle between your categories.  So in stead of looking through everything maybe you want to see “News”

6.  Lastly is Conversational icon and that takes you to a site which shows you what users thought of whatever you were viewing.


On the far right side of the toolbar:


You will see some additional icons. 

1. “’0 Favorites” takes you to your favorites page which is anything that you have given a “thumbs up”

2.  You have a home icon that takes you to stumbleupon.com

3.  Lastly the x is how you close the icon bar.


One final note is the globe SU icon above the house is the google chrome extension that will bring up the toolbar whenever you want.  Its useful if you want it you can install it here:



I have found it useful, esp. when i reached the end of the internet….

Tagged with:
Posted in Entertainment, General, Web Sites, World Wide Web


StackOverflow.com is a community based Question and Answer site that is free and reliable. When people are having those completely random, inexplicable issues, while developing code and there is no solution in site this site is your savior. Unless you are coding in Cobalt or some other really rare environment you post a question, and within seconds will get some type of feedback. It’s been along for so long why am I blogging about it? Well recently, they finally released an api that allows for you to share your reputation as an image. For years they have allowed this, but it was javascript/iframe based which did not allow for embedding in public forums(most strip out the html markup).


Today I am happy to announce to you that this is no longer a limitation.


They now have an url friendly way to share your rep!


So why is this important to share with people?  Well SO is a reputation based site, so as you help other people you gain reputation.  Here is how the reputation works:

    answer is voted up:  +10

    question is voted up:  +5

    answer is accepted: +15 (+2 to acceptor)

    post is voted down: -2 (-1 to voter)


Reputation is not easy to come by, there are a lot of bored developers out there trolling the site just waiting for a question they can answer,and the community is not shy about down voting bad answers.  As a result the reputation you earned is well respected among software developers.



I recommend you getting involved in the site on both sides.  If you are having issues, ask questions.  If you are looking for some feedback on a design idea?  ask the question.  If you are doing something you aren’t quite sure is industry standard?  ask the question.


And when you don’t have any questions to answer, spend a couple minutes a day helping out others.  I guarantee the process of helping outers will increase the breadth and depth of your knowledge.



The creators of SO recently have expanded their sites to other areas most can be seen here ( http://stackexchange.com/) these sites range Administration (server issues),  Programming,  Food, Music, Gamming, so if software isn’t your thing.. maybe one of the other sites might make for a good hobby…

Tagged with: , , , ,
Posted in C#, General, Java, Linux, Microsoft, OS, Programming, Web Sites, Windows, World Wide Web

Nutrition Labels

I want to propose a revolutionary idea, but first some background. When it comes to food, the majority of American’s are either stupid, lazy, or poor;  or at least that is what they claim when it comes to eating habits.

Quotes from almost-real people:

I eat bad because I don’t have the money to buy good food. ~Rob aka “Poor”(Mercedes owner)

Good food never keeps as well as cheap food and I don’t have the time to go to the super market every week. –Beth aka “Lazy” (Stay at home mom)

I’m on heart meds and vitamins, so I don’t have to worry about Nutrition. ~John “Stupid” (Heart-Attack Victim)

Back to reality.  Lets do a quick case study Trader Joes, Joe-Joe’s aka “healthy, addictive Oreos.”  If you were to look on the side of a box of Joe Joes you would see this:

Nutrition Facts
Serving Size: 2 Cookies
Servings Per Container 21
Amount Per Serving
Calories 130 Calories from Fat 50
% Daily Value *
Total Fat 6g 9%
Saturated Fat 2g 10%
Monounsaturated Fat 3g
Polyunsaturated Fat 1g
Trans Fat 0g
Cholesterol 0g 0%
Sodium 80mg 3%
Total Carbohydrate 19g 6%
Dietary Fiber 0g
Sugars 11g
Protein 1g
Vitamin A 0%
Vitamin C 0%
Calcium 0%
Iron 6%
* The Percent Daily Values are based on a 2,000 calorie diet, so your values may change depending on your calorie needs. The values here may not be 100% accurate because the recipes have not been professionally evaluated nor have they been evaluated by the U.S. FDA.

Now quick survey.  How many people in America eat 2 Oreo’s?  Exactly.

Here is what the Nutrition Label should read:

Nutrition Facts
Serving Size: 1/2 Box
Servings Per Container 2
Amount Per Serving
Calories 1300 Calories from Fat 500
% Daily Value *
Total Fat 60g 90%
Saturated Fat 20g 100%
Contains bad Fats Yes
Cholesterol 0g 0%
Sodium 800mg 30%
Total Carbohydrate 190g 60%
Dietary Fiber 0g
Sugars 110g
Protein 10g
Vitamin A 0%
Vitamin C 0%
Calcium 0%
Iron 60%
* The Percent Daily Values are based on a 2,000 calorie diet, so your values may change depending on your calorie needs. You should only eat 2 cookies. The values here may not be 100% accurate because they were calculated by Nick.

Here comes the revolution…  Standardize the labels to either be the entire package, or half the package.  By allowing companies to control the serving sizes it allows for the marketers to massage them into healthier foods.   It would also be nice to make companies highlight in red the things that are bad, and in green the things that are better for you because I am going to guess most people couldn’t tell you what Saturated, Monounsaturated, and Polyunsaturated fats are…

Okay, now that my rant is over, time to finish the rest of my serving of Joe-Joe’s.

Tagged with: , , ,
Posted in General, Life, Thoughts

Clearing Unwanted Chrome History Entries.

I will say this article is not for the faint of heart, or useful to 99% of the people out there but for me it was a major pain in the arse.  Anytime you find your self hacking around with files that you have no clue what they do, you know you are in an extreme situation.

So here is how it went down.  As all American men know its Football season, and that means its Fantasy Football Season.  I know we don’t visit the Fantasy Football League home page that often, wink wink and using a bookmarking to the page is tooo slow for me.

I just want to type  in the chrome address games enter and voila!   For those familiar with ESPN Fantasy Football the league address is something like:


Unfortunately as most non-Americans know this was a World Cup year, and as a result some of us might have done some WC Bracket entries. This poses an issue for me because the URL for the ESPN bracket entry is some what similar


As a result I type in “games”…


Just got a nervous tick thinking about it… When I type games the bracket predictor shows up first (because of alphabetical sorting of URL), as result I can’t type “games” enter, I have to type games down down  down enter.  Completely unacceptable when you are theoretically doing this 20 times a day.

Now the simplest solution is to clear all history.  I don’t want to do this because I like the history, and ease of going to sites I visit frequently.

Tools you will need:

1.  Utility to browse SQL Lite files.  Simple easy one:  http://sourceforge.net/projects/sqlitebrowser/

2.  SQL Knowledge.

Step 1 Close Chrome.  That might prove challenging if you are reading this… 😉

Step 2. Open up “SQLite Database Browser” and then navigate top the History file located:

– C:\Users\<Your user name>\AppData\Local\Google\Chrome\User Data\Default\History

Note history is actually the file name not the directory name.

Once you have opened the file you should see:


Click the Execute SQL Tab and enter

select count(1) from urls where url like '%bpredictor%'

In my case I had 27 entries.  The like condition in my scenario was bpredictor, you can change this to be whatever you want.  Now the magical part that will allow me to sleep well tonight.

delete from urls where url like '%bpredictor%'  ;
delete from segments where name like '%bpredictor%' ;

If you were to run your SQL Count command again you will now see 0.

Now you are done, go to File->Save Database.


Open up chrome type in “games”… wohooo! Now hit enter!


Notice my shameless plug for StackOverflow.com  if you don’t know what it is, and you are a developer you should!

I am finding some pretty cool things in these SQL Lite DBs.. if i find anything else useful.. you know I will share it.

Tagged with: , , , , , ,
Posted in General, Google, LinkedIn, Programming, Web Sites

Entity Framework Trigger Like Auditing


Our stack consisted of a status Quo SOA suite combining mostly Microsoft technologies, ASP.NET, WCF, and Entity Framework.  The primary purpose of the application was a custom content management suite; the users were performing basic CRUD with a dash of business logic.

Architects decided that the enterprise needed a more scalable, generic, and "complex" security pattern, notice the lack of any adjectives relating to "security" .  The resulting configuration was the user logs into the UI using windows authentication, and then request a  SAML token from a security service.  Once the SAML was obtained, it was then passed around for all service calls.  The damaging side effect was that all of our WCF Business services ran anonymously so all auditing information could not be DB triggered, and was handled programmatically.

Data Model Overview:

Entity Framework 3.5 SP1 is more than an ORM so we created a conceptual model of our database.  Pretty much all of our tables were similar to the below,  some type of data, and then some auditing fields.

EF_Example_DataModel EF_Example_EF_Model 


















Example of existing Auditing Logic:

Then there was the Update case, which was completely protected from user error….

static internal ComponentCreate(ComponentVO source, EFContext context)
  ComponentTypecpntType = ComponentTypeDAO.GetC(source.BusinessKey.ComponentType);
  Componenttarget = new Component()
    Code = source.BusinessKey.Code,
    Description = source.Description,
    Name = source.Name,
    ComponentType= cpntType,
    PackageIndicator = false,
    InsertedBy = source.InsertedBy,
    InsertedOn = DateTime.Now,
    UpdatedBy = source.UpdatedBy,
    UpdatedOn = DateTime.Now,


Ironically enough the code sample I stole this from was setting the Insert during an update case….

Developing the new Solution

I was reading online about text templeting, and decided that this was potentially a convenient way to generate our code triggers. Three great resources are:




All we needed to do was standardize our conceptual model, and make sure all tables with auditable fields were mapped to the same 4 property names. Once we had this, T4 gave us the ability to generate our own custom EF entities.

How it was done…

Inside the EF model we mapped all of the table audit fields to a standard set of properties. E.G. the INSRT_DT field in the database became an InsertedOn property in the EF model.

By standardizing all of the audit information it allowed us to be able to identify any entity that was “auditable.” Once we found this pattern we turned to T4 templates. Visual Studio built in support for T4 templates is coming in 2010, but I actually found out that you can still use them in 2008 SP1. With that being said let’s start.

The first thing we did was extract an IAuditable interface.

namespace Audit
  public interface IAuditable
    voidSetInsertedOn(DateTime date);
    voidSetInsertedBy(string user);
    voidSetUpdatedOn(DateTime date);
    voidSetUpdatedBy(string user);


Next we then detached our EF model from the built in code generation. We did this by going into the solution explorer, finding our EF model and then going to properties. There is a property on the model called “Custom Tool” and an associated value of EntityModelCodeGenerator. Simply just remove this value. In an uber high level the custom tool iterates over your entitymodel and generats the EFModel.Designer file. We are going to replace this process with a t4 template.

I obtained my based template from the following site:


Download the template and add it to the solution. Once it’s added navigate the file and once again go to the Custom Tool property and set the value to “TextTemplatingFileGenerator.”

Now onto the messy stuff, I am actually going to show you in reverse, because the T4 stuff is absolutley hiddeous (unless you love perl, and if you love perl you have issues).

The first step in our process is to register an event handler to slightly modify the entity before saving to the databse. Think of it as a code trigger. We do this in the constructor of our Entity Framrwork Model. My model was called “EFContext” so the resulting constructor is below.

public EFContext() : base("name=EFContext", "EFContext")
  this.SavingChanges += new EventHandler(UpdateAuditInformation);

The next piece to the puzzle is to attach and implement the IAuditable interface to any entity that contains all 4 of our auditing fields. Also note we inserted an implementation that sets our fields.

Example is below:

public partial class ComponentType : EntityObject, IAuditable


  #region IAuditable Members

   public void SetInsertedOn(DateTimedate)
     this.InsertedOn = date;

   public void SetInsertedBy(stringuser)
       this.InsertedBy = user;

    public void SetUpdatedOn(DateTimedate)
       this.UpdatedOn = date;
    public void SetUpdatedBy(stringuser)
        this.UpdatedBy = user;


And the final piece is the code trigger. The following code basically says, iterate through everything that has changed, if the entity is IAuditable update the trigger fields.

// SavingChanges event handler. 

private void UpdateAuditInformation(objectsender, EventArgs e)
    //Update create
    foreach (ObjectStateEntry entry in this.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified))

    if(entry.Entity is IAuditable){
    //Start pseudo code.. 

    IAuditabletemp = entry.Entity as IAuditable;
    if(entry.State == EntityState.Added ){
     if(entry.State == EntityState.Added || entry.State == EntityState.Modified){

Onto the stuff that gives me nightmares. The modified T4 Template…

The first thing I did was go down to the block of using statements and add at statement to pull in our interface… not too repulsive..

using System;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Data.EntityClient;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Data;
using EntityFramework.Audit; 


If you scroll down in the T4 template to the “#region Contexts” this is where we added the “Code Trigger” to all of the constructors. Additionally, right beneath the constructors I actually also paste the code to handle the auditing…

#region Constructor

public <#=className#>() : base("name=<#=className#>", "<#=className#>")
   this.SavingChanges += new EventHandler(UpdateAuditInformation);

// SavingChanges event handler.
private void UpdateAuditInformation(object sender, EventArgs e)
   foreach (ObjectStateEntry entry in

Now for the promised nasty piece:

The only hard part of this process was to generate the “IAuditable“interface .The magical line, line 242 , is down in the #region Entities section. There is a section in the T4 template that iterates through each EntityType in your conceptual model and generates a class file to represent it. So I simplied added a section that calls a method to see if its IUpdateable, and if so it adds the interface.

public <#=entity.Abstract ? "abstract " : "" #>partial class <#=entity.Name#> : <#=entity.BaseType == null ? "EntityObject" : entity.BaseType.Name#> <#=ContainsIUpdateable(entity.Members.OfType<EdmProperty>().ToList()) ? ", IAuditable" : ""#>

If you look in the “Convenience methods” section in the T4 template you will see a method called ContainsIUpdateable that actually uses Linq to search through the properties of the conceptual entity for each one of the requried fields.


public bool ContainsIUpdateable(IEnumerable<EdmProperty> edmProperties){
//check to make sure it contains...

   if (
      (edmProperties.Where(x => x.Name == "InsertedOn").FirstOrDefault()) != null &&
      (edmProperties.Where(x => x.Name == "InsertedBy").FirstOrDefault()) != null &&
      (edmProperties.Where(x => x.Name == "UpdatedBy").FirstOrDefault()) != null &&
      (edmProperties.Where(x => x.Name == "UpdatedOn").FirstOrDefault()) != null
      return true;
    return false;

The last and final step is the generation of the implementation of IAuditable inside the entity. This is done right before the Navigational Properties secion (line 349).

We insert a conditional code block that says, if ContainsIUpdateable generate this code:

<#if(ContainsIUpdateable(entity.Members.OfType<EdmProperty>().ToList())) {#>

#region IAuditable Members
public void SetInsertedOn(DateTime date)
    this.InsertedOn = date;

public void SetInsertedBy(string user)
    this.InsertedBy = user;

public void SetUpdatedOn(DateTime date)
   this.UpdatedOn = date;

public void SetUpdatedBy(string user)
   this.UpdatedBy = user;

And voila! Simple huh? T4 templates are actually very useful if you are using .NET 3.5. EF 4.0 is much more powerful, but unfortunately you need 2010 to develop in it. We actually also used the same T4 template to do some lazy loading. So if someone navigates to a link that was not loaded, it automagically loads it for them. This feature actually is coming out in EF 4, so its only useful for 3.5 or earlier.

Tagged with:
Posted in C#, LinkedIn, Microsoft

I show up every morning for a Rugby Match, but Football is on…

Agile is a sore subject for me.  SCRUM is a team concept, but why do I always attend morning huddles where the quarterback is barking orders from upper management? ?


Imagine what would happen you altered the rules around SCRUM and injecting a SCRUM Master that directs your every move?









I don’t think it would be very pretty or productive.  Some possible outcomes:

The game would start:

  1. But never progress because of a side conversation between the master and the ref.
  2. No one else would understand what is going on so no one would ever advance the ball
  3. Huddle would collapse because only 2 people really understand what is going on
  4. The game will constantly stop because the scrum master wants to change the play

The game would never start:

  1. Because the scrum master is more concerned about whether Joe is in the right position.
  2. The scrum master never showed up.


Horrible parallels aside, daily SCRUMs are designed to be more than a project management meeting.  The generic painful format is

1.  What did you do yesterday?

2.  What are you doing today?

3.  Besides this meeting, what else is standing in your way? 


Remember anyone with money can get SCRUM Master certified, the process reminds me of school these days, everyone passes, as long as you finish the test! A result of this is a lot of bad scum implementations.


What shouldn’t happen in the SCRUM? 

1.  Solving the issues that individuals have.

2.  People are talking to show how important they are a.k.a.  Conversations that the fiefs don’t understand.  I spoke in metaphors so let me elaborate, I like to think of this one as .  A random tangent has arisen and you find yourself observing 2 or 3 people conversing in a foreign language.   You hear the words coming out of their mouth but no one really understands what is going on.

3.  Last longer than 15 minutes.

4.  People shouldn’t sit down.


SCRUM has become painful for me because I keep seeing the same things happen.  First as schedules tighten, SCRUM slowly devolves into a daily project planning meeting.  The format is basically a daily update on tasks, the SCRUM master uses the meeting as a forum to make sure the project plan is up to date. 


Another common issue is referred to as the “Gorilla in the Room,” where one person dominates conversation and people look to them for opinions.  I have seen two scenarios of this, first was when the Gorilla was the SCRUM Master, as a result the meeting only happens with the Scrum master can attend.  When that person is out of office, or at another meeting the daily SCRUM turns into a high school class.  Teacher doesn’t show up, and 5 minutes later the students are roaming the hallways.  The team doesn’t buy into the meetings and their values.   The second “Gorilla in the Room” scenario is when people are afraid to speak because of a dominant team member that is never kept in check, as a result ideas/issues don’t flourish because of fear to speak, the resulting consequence is the absence of a team, and belief in the decisions that are made.


The last, and most prominent issue, I encounter in large scrum meetings is going into asinine conversations about issues.  The vast majority of the team isn’t involved, doesn’t care, or understand what the elite upper class is talking about so they tune out.    Keep the meeting focused on who is in attendance, and turn side conversations into follow up meetings, invite anyone who can contribute positively, and those that can’t but are still interested invite them as silent spectators. 


When SCRUM goes bad it turns into a daily impediment.  People see the meeting as invaluable and as an interruption in their day.   The SCRUM meeting should be the opposite, team members should be able to inform others what they are doing, voice impediments and know that shortly after the meeting their issues will be addressed. As a result the collaboration, keeps the team informed and interested, and as a result future issues have a higher possibility of being found.


It’s a lot easier to ignore an email, than it is to ignore a publicly voiced concern in front of a team.  These are the reasons I support daily SCRUM; it keeps people informed on who is doing what, and also gives people a forum to voice need for help.

Tagged with:
Posted in General, LinkedIn, Programming