Monday, October 31, 2011

.Select(p => p.Id);

Make a list of POCOs into a list of the Guids for the POCOs painlessly like so:

var bar = foo.Select(p => p.Id);

Friday, October 28, 2011

Farewell to Mark Reynolds

Today's the last at AMD for Mark Reynolds. Mark, it was very good working with you. Gina Bendel takes over from him in running testing.

This is belated, but while I'm thinking about it: Welcome to our team and AMD to Rafael Torres, Emma Arce, and Bhavani Akole!

Thursday, October 27, 2011

loop through collections within a collection in a Lambda

var foo = bars.Where(b => b.bazes.Any(bz => quxIds.Contains(bz.Id)));

use .Distinct when using .Concat to get rid of the duplicates

var ids = foo.Concat(bar).Concat(baz).Concat(qux).Distinct().ToList();

AOP and advice

We are using AOP in our app for cross-cutting OOP concerns as http://www.developerfusion.com/article/5307/aspect-oriented-programming-using-net/ suggests such as saving a record to a history table whenever another object is updated.

Wednesday, October 26, 2011

Another TFS quirk: Resolve versus Associate

When checking in code in Team Foundation Server and associating the check-in with a task, when you click on the checkbox for a task for an association, take the time to change the dropdown that appears to Associate instead of Resolve or you will set the task's state to Code Complete.

css3pie.com

css3pie.com is a tool for accommodating CSS3 features in IE8, IE7, and yes, IE6. I have not tried it yet.

Tuesday, October 25, 2011

OnActionExecuting and OnAuthorization

When an attribute colors an action like so, what is it doing?

[MyActionAttribute("this","that")]

public ActionResult Index()

{

 
 

Let's take a look. We can hand in variables, mess with them, and then hand them back to the action by way of the ViewBag! Using OnActionExecuting and OnAuthorization to do the same thing here is likely overkill. You'd probably just pick one or the other. This touches on these some.

namespace MyApp.Web.UI.ActionFilters

{

   public class MyActionAttribute : ActionFilterAttribute, IAuthorizationFilter

   {

      private List<string> _stuff;

      

      public MyActionAttribute(params string[] stringBits)

      {

         this._stuff = new List<string>();

         for (int i = 0; i < stringBits.Length; i++)

         {

            _stuff.Add(stringBits[i].ToUpper());

         }

         _stuff.Add("I'm always here.");

      }

      

      public override void OnActionExecuting(ActionExecutingContext filterContext)

      {

         Authorize(filterContext);

      }

      

      public void OnAuthorization(AuthorizationContext filterContext)

      {

         Authorize(filterContext);

      }

      

      public void Authorize(ControllerContext filterContext)

      {

         if (filterContext.HttpContext.Session == null)

         {

            throw new NullReferenceException("You're session is null.");

         }

         filterContext.Controller.ViewBag.Whatever = _stuff;

      }

   }

}

Wouldn't it be awesome...

...if this would work with NHibernate!?

IQueryable<Foo> bar = queryOne.AsQueryable().Concat(queryTwo.AsQueryable()));

 
 

It won't.

.Contains Pitfall! Beware!

var foo = GetAll().Where(f => bar.Contains(f.Id));

 
 

...is going to crash if bar has no items. It's not enough for the collection to be not null. A collection with zero records causes an error.

While I am thinking about LinqSpecs

While I am thinking about it, Kar-khan wrote the following extension for LinqSpecs:

using LinqSpecs;

namespace AMD.Avalanche.Core.Utils

{

   public class SpecificationBuilder<T>

   {

      private Specification<T> _spec;

      public SpecificationBuilder() { }

      

      public void AddAnd(Specification<T> specification)

      {

         if (_spec == null)

            _spec = specification;

         else

            _spec = new AndSpecification<T>(_spec, specification);

      }

      

      public void AddOr(Specification<T> specification)

      {

         if (_spec == null)

            _spec = specification;

         else

            _spec = new OrSpecification<T>(_spec, specification);

      }

      

      public Specification<T> ToSpecification()

      {

         return _spec;

      }

   }

}

 
 

Use it like so...

var specBuilder = new SpecificationBuilderlt;Foogt;();

specBuilder.AddAnd(MySpecs.NameCriteria(whatever));

LinqSpecs pain!

LinqSpecs is proving tough to use. There is probably a good reason too. Jorge has noticed that it is in alpha and Craig has noticed that it hasn't been updated in over a year. Boo. We struggled to find a way to append a spec to an existing IQueryable and the class below does allow for that, however, when the query concerns get complicated enough NHibernate fails. Perhaps it is crafting HQL it cannot execute???

public class FooLinqSpecHelper : Specification<Foo>

{

   private readonly Foo Foo;

   

   public IQueryable<Foo> ConcatenateQuery(IQueryable<Foo> existingQuery,

            Specification<Foo> specification)

   {

      IQueryable<Foo> concatenatedQuery =

            existingQuery.Where(specification.IsSatisfiedBy());

      return concatenatedQuery;

   }

   

   public IQueryable<Guid> ConcatenateQueryThenReturnOnlyIds(IQueryable<Foo>

            existingQuery, Specification<Foo> specification)

   {

      IQueryable<Guid> concatenatedQuery =

            existingQuery.Where(specification.IsSatisfiedBy()).Select(p => p.Id);

      return concatenatedQuery;

   }

   

   public override Expression<Func<Foo, bool>> IsSatisfiedBy()

   {

      return c => c == Foo;

   }

}

Sunday, October 23, 2011

testing Dictionary sorting and using .AddRange in a Lambda

No sooner did I write a blog posting on how to Sort a Dictionary than I found this suggesting that you cannot Sort a Dictionary. I disagree however. The means mentioned earlier works. One may move "half" of a dictionary out to a list to inspect the order within it.

foreach (KeyValuePair<Guid,string> pair in foo)

{

   myList.Add(pair.Value);

}

 
 

Here is the same thing in the shape of a Lambda utilizing .AddRange:

myList.AddRange(foo.Select(pair => pair.Value));

 
 

Verify the sorting with testing by pulling the "half" of the Dictionary you want out to a list and looking at the order of the list:

Assert.AreEqual(3, foo.Count);

Assert.AreEqual("a", myList[0]);

Assert.AreEqual("b", myList[1]);

Assert.AreEqual("c", myList[2]);

Saturday, October 22, 2011

Sort a Dictionary

This shows how to sort a Dictionary like so:

var sortedDict = (from entry in myDict orderby entry.Value ascending select entry).ToDictionary(pair => pair.Key, pair => pair.Value);

how to make links in html email communications NOT the default blue across numerous email clients including gmail

Put this at the top of the document.

<style>

span a {color:#7BC243;}

span a:hover {color:#7BC243;}

.stylegreen a {color:#7BC243;}

.stylegreen a:hover {color:#7BC243;}

</style>

 
 

Links look like this:

<span><a class="stylegreen" style="color:#7BC243; a {color:#7BC243;} a:hover {color:#7BC243;}" href="http://www.example.com/" target="_blank">Touch Me&raquo;</a></span>

 
 

The a and a:hover stuff above might be unneeded. I haven't troubleshot that yet.

Friday, October 21, 2011

ghost of patterns past

The jay-sea-em-es pattern may be revisited. Namely:
  • Controllers reach out to repositories, get domain objects, and flatten then to DTOs (with Automapper) which are handed to Views.
  • Views have forms which bind back to models that are handed to a "Command Processor" which:
    1. generically takes models
    2. uses reflection to get the "name" of the model type
    3. goes fishing by way of IoC for a handler class for the name which will perform an action
      • the handler will perform a CRUD action based on the model
      • create and edit typically have the same model and the whether-or-not of the Id matching any existing record denotes create vs. edit or the other way around
      • a delete model has just an Id

I'm fascinated by Linq to NHibernate's Expand()

something to research

IQueryable can be an antipattern

IQueryable is proving a little bit dangerous. If someone casts it off to a list before it is appropriate the query may not be as "filtered" as it might otherwise be and might bring back too many records causing a performance problem. Example: One pulls all of the records of foo via an IQueryable, then makes the IQueryable jump through some hoops, filtering down the record set, and finally casts the subset of all of the records of foo off to a list. That is fine, however, the door is open for another developer to find reason to cast the IQueryable off to a list "further upstream" (such as at the point where we are getting all of the foo records) thus negating any efficiency in using IQueryable. It's also hard to safeguard against this. Craig suggested that perhaps the boundaries of repository interfaces should denote where an IQueryable is cast off to a list and that all of the progressive spooling up of an IQueryable should be done in the repository itself.

Wednesday, October 19, 2011

Add a new task in TFS

Let's add a story first. Under your project in the "Team Explorer" there will be a container for queries that will be called “Work Items” and here one should right click and pick New Work Item > User Story. When creating a story, pick the proper Iteration. Go to the "All Links" tab and click on New to add a new task.

an apology

this post should have shown this

foreach (Program program in programs) foreach (ProgramPlan programPlan in program.ProgramPlans) programPlans.Add(programPlan);

 
 

refactored to this

programPlans.AddRange(programs.SelectMany(program => program.ProgramPlans));

 
 

it's a good thing I practice TDD

remove the duplicates in a list of T

programPlans = programPlans.Distinct().ToList();

I'm still not great at lambdas.

I'm still not great at lambdas. I don't find them intuitive. Resharper found that I could refine this...

foreach(Program program in programs) foreach(ProgramPlan programPlan in programPlans) programPlans.Add(programPlan);

 
 

...to this...

foreach (ProgramPlan programPlan in programs.SelectMany(program => programPlans)) programPlans.Add(programPlan);

 
 

...but I wouldn't have seen it by myself. I'm also frustrated by var and having to reverse engineer what a variable really is. I guess I'm trapped in 2005. :(

Monday, October 17, 2011

.Intersect

var controllerRoles = _roles.Intersect(roles); is an example of using .Intersect

a better explanation on mocking

Here are some notes to explain what I was attempting here.

 
 

[TestClass]

public class MyTest

{

   A FooBuilder will return a Qux when its Build method is called.

   A FooBuilder will have getsetters for BarRepository and BazService like so:

      public IBarRepository BarRepository { get; set; }

      public IBazService BazService { get; set; }

   The getsetters will host external dependencies

   private FooBuilder fooBuilder;

   

   [TestInitialize]

   public void Setup()

   {

      Joel Holder wrote SessionObjectCache which wraps Session and when

      used in test merely stores things in a Dictionary allowing Session to be mocked.

      SessionObjectCache.Remove(CachedEntries.USER_CONTEXT);

      MocksRegistry will have getsetters like so...

         public Mock<IBarRepository> BarRepositoryMock { get; set; }

         public Mock<IBazService> BazServiceMock { get; set; }

      ...that will be populated with dummy repositories and services

      var registry = new MocksRegistry();

      The next two lines mock methods calls that will be encountered when

      the Build method on FooBuilder runs. Instead of actually running the

      methods when the test runs, the methods will be monkey-patched to

      return specifications based on the these two lines of code.

      registry.BarRepositoryMock.Setup(repo =>

            repo.GetAll()).Returns(new List<Bar>().AsQueryable());

      registry.BazServiceMock.Setup(repo =>

            repo.DoesMatchAnyBazForBars(It.IsAny<List<Bar>>()));

      Let's instantiate our FooBuilder while telling it how to conditional

      behave so as not to really need external dependencies.

      fooBuilder = new FooBuilder

      {

         BarRepository = registry.BarRepositoryMock.Object,

         BazService = registry.BazServiceMock.Object

      };

      var testServices = new Dictionary<string, object>();

      testServices[AppCtxIds.FOO_BUILDER] = fooBuilder;

      Here we are monkey-patching ServiceLocator so that when an IoC

      attempt to wire up IBarRepository to an BarRepository occurs the

      true ServiceLocator will be sidestepped in favor of our fake one.

      ServiceLocator.LookupSource = () => testServices;

      }

   

   In our test we will test the Qux of a UserContext. In the name of

   making a Qux will must deal with two calls to external dependencies.

   We are dealing with the dependencies by way of mocking.

   [TestMethod]

   public void LetsTest()

   {

      var qux = BuildQux("Tom");

      var userContext = SessionObjectCache.LazyGet<UserContext>

            (CachedEntries.USER_CONTEXT,

            new Func<UserContext>(() =>

            {

               return new UserContext { Qux = qux };

            }));

      Assert.IsTrue(SessionObjectCache.Exists(CachedEntries.USER_CONTEXT));

      Assert.AreEqual("Tom", SessionObjectCache.Get<UserContext>

            (CachedEntries.USER_CONTEXT).Qux.Name);

   }

   

   private Qux BuildQux(string whatever)

   {

      return fooBuilder.Build(whatever);

   }

   

   private class TestController : Controller

   {

   

   }

}

merging in TFS demystified

When merging changes with Team Foundation Server's default merge tool one will see three windows, two small windows (for the code one currently has and the code one is trying to merge in) and one large window (for the ultimate concoction of the two). The two small windows will sit side by side and conflicts will be denoted by a thick black line running across the two windows. One may click on areas near the black lines to add the content from one of the two small windows to the concoction. Areas still highlighted in light blue have not yet been resolved.

Friday, October 14, 2011

TFS: how to associate a bug to an iteration and how to associate a check-in with a bug or task

When viewing a bug in Team Foundation Server, at the same Details pane where one may log hours there is an Iteration drop down where one may associate the bug with a particular iteration. When performing a check-in you will notice four icons for Source Files, Work Items, Check-in Notes, and Policy Warnings at the left of the dialog box that manages the check-in. Click on Work Items to associate the check-in with a task or bug. The query drop down that will appear at the top of the dialog box will allow you to select different categorizations of tasks and bugs to browse from.

Thursday, October 13, 2011

using LESS variables

@amd-green: #009944;

   

.foo

{

   color: @amd-green;

   font-size: 12px;

}

Set up Chirpy

  1. get Chirpy by going here and clicking the big green "Download" button
  2. open Chirpy.vsi which should bring up an installation wizard
  3. after completing the wizard, install Google Closure from here
  4. assuming you are using Windows 7, move compiler.jar (in compiler.zip) to C:\Users\\Documents\Visual Studio 2010\Addins
  5. download and install the Java SE Development Kit 7
  6. right-click on the "My Computer" at your desktop and then select Properties
  7. when the Properties dialog box appears, first navigate to the Advanced tab and then click the "Environment Variables..." button
  8. at Environment Variables:

       create a variable for JAVA_HOME with
       C:\Program Files\Java\jre7 as the value

       open the Path variable and splice
       ;C:\Program Files\Java\jre7\bin onto the end of the string

       
       

further prep steps at Visual Studio

  1. at Tools > Options > Chirpy > Javascript (js) ...uncheck "run JS Hint" and change .chirp.js to .full.js
  2. at Tools > Options > Chirpy > Google Closure Compiler ...check "Use Offline Compression"
  3. CSS Is Less in another Visual Studio Add-in to install

use the "go online" icon to reassociate with TFS

Ff you have detached from the TFS server, use the "go online" icon to reassociate with Team Foundation Server. It is at the top of the Solution Explorer. It should be one of a handful of icons.

Tuesday, October 11, 2011

another mocking example

[TestClass]

public class MyTest

{

   private FooBuilder fooBuilder;

   

   [TestInitialize]

   public void Setup()

   {

      SessionObjectCache.Remove(CachedEntries.USER_CONTEXT);

      var registry = new MocksRegistry();

      registry.BarRepositoryMock.Setup(repo =>

            repo.GetAll()).Returns(new List<Bar>().AsQueryable());

      registry.BazServiceMock.Setup(repo =>

            repo.DoesMatchAnyBazForBars(It.IsAny<List<Bar>>()));

      fooBuilder = new FooBuilder

      {

         BarRepository = registry.BarRepositoryMock.Object,

         BazService = registry.BazServiceMock.Object

      };

      var testServices = new Dictionary<string, object>();

      testServices[AppCtxIds.FOO_BUILDER] = fooBuilder;

      ServiceLocator.LookupSource = () => testServices;

      }

   

   [TestMethod]

   public void LetsTest()

   {

      var qux = BuildQux("Tom");

      var userContext = SessionObjectCache.LazyGet<UserContext>

            (CachedEntries.USER_CONTEXT,

            new Func<UserContext>(() =>

            {

               return new UserContext { Qux = qux };

            }));

      Assert.IsTrue(SessionObjectCache.Exists(CachedEntries.USER_CONTEXT));

      Assert.AreEqual("Tom", SessionObjectCache.Get<UserContext>

            (CachedEntries.USER_CONTEXT).Qux.Name);

   }

   

   private Qux BuildQux(string whatever)

   {

      return fooBuilder.Build(whatever);

   }

   

   private class TestController : Controller

   {

   

   }

}

Sunday, October 9, 2011

Model Bind to a Collection

I'm trying to do something like this in this post in the name of figuring out how to model bind collections. My approach is more ghetto. I have three objects:

using System.Collections.Generic;

namespace MvcApplication.Models

{

   public class Foo

   {

      public string Whatever { get; set; }

      public List<Bar> SomeCollection { get; set; }

   }

}

 
 

namespace MvcApplication.Models

{

   public class Bar

   {

      public int Number { get; set; }

   }

}

 
 

namespace MvcApplication.Models

{

   public class Baz

   {

   public string Question { get; set; }

   }

}

 
 

Alright, here is a view that uses a list of Baz as a its model and will bind to a Foo:

@using MvcApplication.Models

@model List<Baz>

@{

ViewBag.Title = "Home Page";

Int32 counter = 0;

}

<h2>@ViewBag.Message</h2>

<form method="post" action="/home/about/">

<input type="test" name="Whatever" />

@foreach(Baz baz in Model)

{

   <br/>

   <br/>

   @baz.Question

   <table>

      <tr>

         <td>0</td>

         <td>1</td>

         <td>2</td>

         <td>3</td>

         <td>4</td>

         <td>5</td>

         <td>6</td>

      </tr>

      <tr>

         <td>

            <input type="radio" name="SomeCollection[@counter].Number" value="0" />

         </td>

         <td>

            <input type="radio" name="SomeCollection[@counter].Number" value="1" />

         </td>

         <td>

            <input type="radio" name="SomeCollection[@counter].Number" value="2" />

         </td>

         <td>

            <input type="radio" name="SomeCollection[@counter].Number" value="3" />

         </td>

         <td>

            <input type="radio" name="SomeCollection[@counter].Number" value="4" />

         </td>

         <td>

            <input type="radio" name="SomeCollection[@counter].Number" value="5" />

         </td>

         <td>

            <input type="radio" name="SomeCollection[@counter].Number" value="6" />

         </td>

      </tr>

   </table>

   counter++;

}

<input type="submit" value="submit" />

</form>

Wednesday, October 5, 2011

Tuesday, October 4, 2011

what is an n+1 problem?

I often heard talk of n+1 problems when I worked at Headspring. Today was the day I finally asked someone (Rafael Torres) what an n+1 problem is.
  1. If one has an object and the object has a collection of children...
  2. And, if one queries the number of children...
  3. And if one then runs a while (myCounter < numberOfChildren) loop, querying a child object for each of the passes through the loop...
  4. One will have n number of queries for n number of children...
  5. +1 query for the query to get the count (or is it the query to get the object to begin with? –I’m fuzzy on this.)
This is a lot of queries. It is going to get "heavy" in some situations. This is the way NHibernate works unless one uses Eager Fetching to get children with a parent upon pulling a parent from a database.

our two ways of mocking methods

We have two ways of mocking with MOQ for the two different approaches to inversion of control. For Dependency Injection:

IQueryable<Foo> foos = TestObjects.BuildFooCollection().AsQueryable();

mockFooRepository = new Mock<IFooRepository>();

mockFooRepository.Setup(repo => repo.GetAll()).Returns(foos);

fakeFooRepo = mockFooRepository.Object;

 
 

In the situation above, fakeFooRepo would be handed to a FooRepository getsetter on a controller in lieu allowing dependency inject to put a real FooRepository there. Alternatively... For Service Locator:

registry = new MocksRegistry();

ServiceLocator.LookupSource = () =>

{

   return registry;

};

IQueryable<Bar> bars = TestObjects.BuildFooCollection().AsQueryable();

registry.BarRepositoryMock.Setup(repo => repo.GetAll()).Returns(bars);

Sunday, October 2, 2011

noob question: why should I care about delegates?

I just had a good conversation about delegates and I think I am beginning to understand why I should care a little bit better. It was not clear to me why I should want to use a pointer to a method instead of just calling the method. On the other side of the before mentioned discussion I understand:
  1. In the art of functional programming, one can hand an anonymous delegate, as wrapped in a Func perhaps, to data (I envision a Func being handed to a method on a repository) in lieu of the usual thing in which an object is handed into a method. In the functional programming approach, the receiving method needs only know that it is to run a function of a certain <object,object> shape and nothing more. The functionality that the method fires is thus not shaped by the method itself and is instead shaped by what is handed in. Yay!
  2. The line of code that calls a method and the method itself are loosely coupled by way of a Func. You could put another Func "in front" of a Func too to chain them sequentially and then later detach the first Func as a something run by the second Func if you desire.
  3. One may spool up delegates and ultimately execute spools of delegates.
  4. Closures allow one to encapsulate some behavior and then pass it around like any other object. What is more, apparently state may be retained in closures! This is next for me to research.