Monday, September 9, 2013

Pet Peeve #1

Calling ToString() on an object that is already typed as a String.  I see this in all sorts of situations, but this morning it was when accessing a configuration value:

AppSettings is a NameValueCollection.  When accessing its this[string name] or this[int index] properties, it returns a String.  Don’t give future developers more code that they have to read and subsequently ignore, that doesn’t add to readability.

Tuesday, July 16, 2013

Snippet to Create “C# Like” Collapsible Regions in VS2012 Javascript Files

Ever wanted to create a collapsible region within Javascript? If you have the Web Essentials Extension for VS 2012 you already have that feature:
But, the one thing that they are missing in the Web Essentials Extension is a snippet to allow you to automatically insert the region syntax.  Just save this text to “C:\Users\$UserName$\Documents\Visual Studio 2012\Code Snippets\JavaScript\My Code Snippets\regions.snippet” on your local computer, and viola!
<CodeSnippet Format="1.1.0" xmlns="">
    <Author>Daryl LaBar</Author>
    <Description>Code snippet for region in javascript Using Web Essentials 2012</Description>
        <ToolTip>Region name</ToolTip>
    <Code Language="JavaScript">
      <![CDATA[//#region $name$
//#endregion $name$]]>

Wednesday, July 3, 2013

Making FetchXml in Javascript Less SOAPy and XMLy

Whenever I have to request data from CRM within Javascript, my first attempt is always to use an OData call.  The request urls aren’t too difficult to create (On a side note, there are multiple custom tools for this purpose. I prefer LinqPad.) and the data transferred in the request and the response is extremely tiny.  But… it has some limitations, especially within CRM.  So what do you do when you’ve hit one of the limitations?
  1. Search the internet for “CRM FetchXML from JavaScript
  2. Copy and paste some hard coded SOAP XML from a random post somewhere
  3. Shoehorn your FetchXML into it.
  4. Spend an hour parsing the returned XML with the XML Parser, trying to figure out how many .childNode[i] and .firstChild properties you need to string together to get your actual data.
  5. Feel sorry for the next developer that has to tweak your “ParseResults” code.
Need to do it again 3 months later?  Repeat the process form the top.  It’s one of those processes that makes you amazed there isn’t an easier way.  Well… now there is.

CRM FetchXML Soap Library

In the spirit of “All problems in computer science being solvable by another level of abstraction,” I’ve create a small JavaScript library to abstract away all of the SOAPy, XMLy, uglyness.  Here is an example of it’s use:
// Fetch Xml Call to get all opportunities for TX, with their estimated values
var fetchXml = '<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">' +
'  <entity name="opportunity">' +
'    <attribute name="estimatedvalue" />' +
'    <order attribute="name" descending="false" />' +
'    <link-entity name="account" from="accountid" to="customerid" alias="ae">' +
'      <filter type="and">' +
'        <condition attribute="address1_stateorprovince" operator="eq" value="TX" />' +
'      </filter>' +
'    </link-entity>' +
'    <link-entity name="account" from="accountid" to="parentaccountid" visible="false" link-type="outer" alias="Account">' +
'      <attribute name="address1_stateorprovince" />' +
'    </link-entity>' +
'  </entity>' +

var response = Allegient.Core.SoapLib.executeFetchXmlRequest(fetchXml);

Just give the Library FetchXml, and it’ll give you back a collection of javascript objects that are parsed from the result. Here is what the result looks like in the IE debugger:

IE Debugger Window

Here are a couple things to take note of:
  1. The response returned is just an array of entities.
  2. Each entity has a property that maps to a property of the entity returned.  This allows working with the entities in a way that is much easier than XML parsing.  ie to get the first entity’s name: “response[0].name” or to get the the 2nd entity’s currency’s name: “response[1].transactioncurrencyid.Name”.

The Implementation

There is a lot going on under the covers, so we’ll start at the top with executeFetchXmlRequest and work our way down:

executeFetchXmlRequest: function (fetchXml, onSuccess, onError, async) {

     if (async == null) {
         async = false;
    var request = '<request i:type="b:RetrieveMultipleRequest" xmlns:b="" xmlns:i="">'
         + '    <b:Parameters xmlns:c="">'
         + '        <b:KeyValuePairOfstringanyType>'
         + '            <c:key>Query</c:key>'
         + '            <c:value i:type="b:FetchExpression">'
         + '                <b:Query>' + CrmEncodeDecode.CrmXmlEncode(fetchXml)
         + '                </b:Query>'
         + '            </c:value>'
         + '        </b:KeyValuePairOfstringanyType>'
         + '    </b:Parameters>'
         + '    <b:RequestId i:nil="true"/>'
         + '    <b:RequestName>RetrieveMultiple</b:RequestName>'
         + '</request>';
     var response = null;
     var internalOnSuccess;
     if (onSuccess == null) {
         internalOnSuccess = function (r) { response = Allegient.Core.SoapLib._onFetchXmlSuccess(r); };
     } else {
         internalOnSuccess = function (r) {
             var temp = Allegient.Core.SoapLib._onFetchXmlSuccess(r);
             response = onSuccess(temp);
             if (response == null) {
                 response = temp;
    Allegient.Core.SoapLib.executeRequest(request, internalOnSuccess, onError, async);
     return response;

executeFetchXmlRequest just wraps the FetchXml with the RetrieveMultipleRequest request xml, encoding the FetchXml as well.  Then it sets up some default response handlers, allowing for the request to be made asynchronously.  The next step is the executeRequest:

executeRequest: function (requestXml, onSuccess, onError, async) {

     if (async == null) {
         async = false;
    var soapEnvelope = ""
    + "<s:Envelope xmlns:s=\"\">"
    + "<s:Body>"
    + "   <Execute xmlns=\"\" xmlns:i=\"\">"
    + requestXml
    + "    </Execute>"
    + "  </s:Body>"
    + "</s:Envelope>";
     var req = Allegient.Core.SoapLib.getXMLHttpRequest();"POST", Allegient.Core.SoapLib._getServerUrl(), async)
     // Responses will return XML. It isn't possible to return JSON.
     req.setRequestHeader("Accept", "application/xml, text/xml, */*");
     req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
     req.setRequestHeader("SOAPAction", "");
     req.onreadystatechange = function () { Allegient.Core.SoapLib.ExecuteSOAPResponse(req, onSuccess, onError); };

It’s primary purpose is to wrap the CRM Request Xml in a Soap Envelope.  It can be used to wrap any SOAP calls to CRM to help keep them DRY (Included in the library is an ExecuteWorkflowRequest to illustrate how another request type would utilize executeRequest).

It utilizes three helper functions.
  1. getXMLHttpRequest - returns an XMLHttpRequestObject in a browser specific safe manner.
  2. _getServerUrl – returns the URL for the SOAP endpoint using the context information available in the form or HTML Web Resource.
  3. ExecuteSOAPResponse – Handles the callback from the request, determining based on the readyState and status if it executed successfully or with an error, calling the appropriate call back.

The default error callback just displays the error in an alert().  The default success callback as defined by executeFetchXmlRequest is _onFetchXmlSuccess:

_onFetchXmlSuccess: function (response) {
     response = Allegient.Core.SoapLib._replaceAll(response, "<ExecuteResponse ", "<a:ExecuteResponse ");
     response = Allegient.Core.SoapLib._replaceAll(response, "<ExecuteResult ", "<a:ExecuteResult ");
     response = response.replace(/<(\/?)([^:>]*:)?([^>]+)>/g, "<$1$3>");
     var doc = Allegient.Core.SoapLib._parseXmlString(response);
     if (Allegient.Core.SoapLib._getElementText(doc.getElementsByTagName("ResponseName")[0]) == "RetrieveMultiple") {
         var elements = doc.getElementsByTagName("Entity");
         var entities = new Array();
         for (var i = 0; i < elements.length; i++) {
             entities[i] = Allegient.Core.SoapLib.XML2jsobj(elements[i]);
        return entities;
     } else {
         return doc.getElementsByTagName("Results")[0];

There is some RegEx magic to remove the namespace prefixes from the XML so XML2jsobj returns valid property names.  Small side note here, the ExecuteResponse and ExecuteResult are the only xml elements in the response that don’t have a namesapce and my current regex doesn’t handle them correctly, hence the manual addition of the namespace prefix to the tag.  _parseXmlString returns a valid XMLDomParser that has loaded the xml passed in.  A quick walk of the XML Dom to see if this is a RetrieveMultiple Response, and if so, each entity is parsed one at a time by XML2jobj.  If it’s not a RetrieveMultiple response, the DOM results from the response are returned.  XML2jobj is based off of a version by Craig Buckler, but specifically modified for reading CRM attribute data:

XML2jsobj: function (node) {
     var data = {};
     var isNull = true;
     // append a value
     function Add(name, value) {
         isNull = false;
         if (data[name]) {
             if (data[name].constructor != Array) {
                 data[name] = [data[name]];
            data[name][data[name].length] = value;
        else {
             data[name] = value;
    function AddAttributes(entity, node) {
         for (var i = 0; i < node.childNodes.length; i++) {
             isNull = false;
             var valuePair = node.childNodes[i];
             var key = Allegient.Core.SoapLib._getElementText(valuePair.firstChild);
             var value = valuePair.childNodes[1].childNodes;
             if (value.length == 1 && value[0].tagName == "Value") {
                 data[key] = Allegient.Core.SoapLib._getElementText(value[0]);
             } else if (value.length == 1 && value[0].nodeType == 3) {
                 data[key] = value[0].nodeValue;
             } else {
                 data[key] = Allegient.Core.SoapLib.XML2jsobj(valuePair.childNodes[1]);
     var c, cn;

     // child elements
     for (c = 0; cn = node.childNodes[c]; c++) {
         if (cn.nodeType == 1) {
             if (cn.childNodes.length == 1 && cn.firstChild.nodeType == 3) {
                 // text value
                 Add(cn.nodeName, cn.firstChild.nodeValue);
            else if (cn.nodeName == "Attributes") {
                 AddAttributes(data, cn)
             } else {
                 // sub-object
                 Add(cn.nodeName, Allegient.Core.SoapLib.XML2jsobj(cn));
    if (isNull) {
         data = null;
    return data;

It loops through the XML DOM, creating a new js object for each node in the xml, with special processing for the attributes collection, resulting in the response looking like the screen shot above. 


The CRM FetchXML SOAP Library is extremely helpful, allowing for just the FetchXML to be passed in (no need to worry about SOAP headers or the wrapping Request XML itself) and a collection of entity JavaScript objects returned.  It should now change your javascript FetchXML steps from what is listed at the top of this article, to this:
  1. Search the internet for “CRM FetchXML from JavaScript”
  2. Download this library
  3. Never repeat steps 1-2 again
  4. Use your FetchXML as is, calling executeFetchXmlRequest
  5. Easily access the data you need in the response
  6. Go home early, and sleep better at night*

*Step 6 is not required but highly likely ;)

Click here to download the source code.

Thursday, April 18, 2013

Programmatically Generating Properties for OptionSet Enums

Generating early bound entity classes for CRM Entities is fairly simple.  Generating the Enums for the OptionSets is fairly simple as well.  Generating the OptionSet Enum properties for entities that are typed to the correct Enum is not so simple, and not currently supported by the CrmSrvUtil.exe.  If you want to be able to use the enums for populating the option set values, you have to continually write code that looks like this:
contact.Address1_AddressTypeCode = new OptionSetValue((int)contact_address1_addresstypecode.Home);

Which I don’t like for three reasons:

No Compile Time Error Checking to Ensure the Correct Enum Type is Used
For my current customer, they have some OptionSets that were created in CRM 4.0, before they had global OptionSets.  Once they upgraded to CRM 2011, they added global versions of these OptionSets as well, so if you’re not paying attention, you could easily be populating a local OptionSetValue on an entity, with the int value of a global OptionSetEnum (which have different int values).

Extra “Boiler Plate” Code Requires More KeyStrokes, and is Less Readable
Any time there is extra code that really isn’t needed, it makes it harder on the human brain to determine exactly what the code is doing because it in essence, has to ignore part of the information.

Just as 
(((x)*2)+1) = 13 
is harder to read than 
x*2+1 = 13 
so is

contact.Address1_AddressTypeCode = new OptionSetValue((int)contact_address1_addresstypecode.Home);

harder to read than

contact.Address1_AddressTypeCodeEnum = contact_address1_addresstypecode.Home;

25% of the text has been eliminated, which results in code that requires less typing, and is more readable.

Inconsistent Mapping of Attribute/Property Name to Enum Type
Determining the correct Enum for a given entity’s OptionSet property is usually pretty straight forward, but sometimes it’s not. i.e. The Enum for FieldPermission.CanCreate is field_security_permission_type and the Enum for Metric.AmountDataType is metric_goaltype.  The only intellisense that’s provided is that it’s an OptionSet, and it is up to the developer to find and choose the correct one.

The Entity OptionSet Enum Mapper Utility to the Rescue!
I have created an EntityOptionSetEnumMapper utility to generate a property for each OptionSetValue with the correct Enum.  For example, it generates these additional properties for the Contact class (CrmEntities is the namespace):

public partial class Contact
  public CrmEntities.contact_accountrolecode? AccountRoleCodeEnum { ... }
  public CrmEntities.contact_address1_addresstypecode? Address1_AddressTypeCodeEnum { ... }
  public CrmEntities.contact_address1_freighttermscode? Address1_FreightTermsCodeEnum { ... }
  public CrmEntities.contact_address1_shippingmethodcode? Address1_ShippingMethodCodeEnum { ... }
  public CrmEntities.contact_address2_addresstypecode? Address2_AddressTypeCodeEnum { ... }
  public CrmEntities.contact_address2_freighttermscode? Address2_FreightTermsCodeEnum { ... }
  public CrmEntities.contact_address2_shippingmethodcode? Address2_ShippingMethodCodeEnum { ... }
  public CrmEntities.contact_customersizecode? CustomerSizeCodeEnum { ... }
  public CrmEntities.contact_customertypecode? CustomerTypeCodeEnum { ... }
  public CrmEntities.contact_educationcode? EducationCodeEnum { ... }
  public CrmEntities.contact_familystatuscode? FamilyStatusCodeEnum { ... }
  public CrmEntities.contact_gendercode? GenderCodeEnum { ... }
  public CrmEntities.contact_haschildrencode? HasChildrenCodeEnum { ... }
  public CrmEntities.contact_leadsourcecode? LeadSourceCodeEnum { ... }
  public CrmEntities.contact_paymenttermscode? PaymentTermsCodeEnum { ... }
  public CrmEntities.contact_preferredappointmentdaycode? PreferredAppointmentDayCodeEnum { ... }
  public CrmEntities.contact_preferredappointmenttimecode? PreferredAppointmentTimeCodeEnum { ... }
  public CrmEntities.contact_preferredcontactmethodcode? PreferredContactMethodCodeEnum { ... }
  public CrmEntities.contact_shippingmethodcode? ShippingMethodCodeEnum { ... }
  public CrmEntities.contact_statuscode? StatusCodeEnum { ... }
  public CrmEntities.contact_territorycode? TerritoryCodeEnum { ... }

This is a partial class, and so will be combined at compile time with the existing Contact Class.  All of the existing OptionSetValue properties will still exist, but now there will be new ones (appended with “Enum”) that are typed to the correct Enum type.

Each property still uses the OptionSetValue property to store and retrieve the data, so when Address1_AddressTypeCodeEnum is updated, it will also update Address1_AddressTypeCode and visa versa, since they use the Entity.Attributes collection and share the same key.  Here is the Address1_AddressTypeCodeEnum property that is generated:

public CrmEntities.contact_address1_addresstypecode? Address1_AddressTypeCodeEnum
         return (CrmEntities.contact_address1_addresstypecode?)EntityOptionSetEnum.GetEnum(this, "address1_addresstypecode");
         Address1_AddressTypeCode = value.HasValue ? new Microsoft.Xrm.Sdk.OptionSetValue((int)value) : null;

It makes use of an internal static class that is also in the output file, that retrieves the OptionSet from the Attributes collection as a nullable int:

internal static class EntityOptionSetEnum
    public static int? GetEnum(Microsoft.Xrm.Sdk.Entity entity, string attributeLogicalName)
            return entity.GetAttributeValue<Microsoft.Xrm.Sdk.OptionSetValue>(attributeLogicalName).Value;
            return null;

The nullable int is then cast to the correct enum type which is then returned. 

Using the Entity OptionSet Enum Mapper Executable
The only thing that the Entity OptionSet Enum Mapper requires is the dll that contains the early bound Entities and Enums created via the CrmSrvcUtil.  It requires no interaction with the CRM server itself.  This creates a standard “which came first, the chicken or the egg” problem.  The Entity and Enum dll must be built first before the utility can be ran, but it must run before the dll is built in order for the generated code to be included in the dll.  This is fixed by adding a pre-build event to the Entities and Enums dll project to build a temporary version of the dll, and then invoking the utility to run and generated the code.      

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe" /target:library /reference:"C:\PathOfSdk\microsoft.xrm.sdk.dll" "$(ProjectDir)Entities.cs" "$(ProjectDir)OptionSets.cs"

This basically says, compile the Entities and OptionSet files, referencing the Microsoft.Xrm.Sdk.  By default this will get compiled to the bin directory of the project, with the name Entities.dll.  A second pre-build event will be needed to call the utility and generate the EntityOptionSetEnum.cs file (which will need to be manually added to the project file the first time).

"C:\PathOfExe\EntityOptionSetEnumMapper.exe" "$(TargetDir)Entities.dll" "$(ProjectDir)EntityOptionSetEnums.cs"

This will run the utility, passing in the path to the Entities.dll to use to generate the EntityOptionSetEnum.cs file, and the path and name of the file to generate.

Both these steps happen before the dll itself get’s built, generating the EntityOptionSetEnum.cs file, which will then be compiled with the actual dll.

Below are separate downloads for the Executable, and the Source Code.  Enjoy!

Entity OptionSet Enum Mapper Executable
Entity OptionSet Enum Mapper Source

Wednesday, March 20, 2013

Make Websites Startup Faster When Debugging

Currently I’m working on an website that caches data during the Application_Start event of the Global.asax.cs.  Generally this is a great idea for a website, especially when deploying a website in a load balanced environment, because the penalty of loading cached data can be spent in one page load.  Take the server out of the load balancer, deploy your changes, hit the first page, verify that no errors occurred, and put the server back in the balancer.  This ensures that a user hitting the site, won’t have to pay the penalty of loading the cache data.

But, this is not so much fun when developing/debugging.  90% of the time a developer works on a single page at a time, and if the page uses only a small fraction of the cache, or none at all, they get to pay the cache load penalty each time they restart the website.  Having to wait even 20 seconds each time the website is restarted in Visual Studio is real productivity killer.

Some developers may opt to comment out the cache loading portion of the Application_Start.  But if they accidently commit the change into source control, production could be affected the next time it’s deployed.  And the next time they get latest from source control, they’ll loose their local commented out Application_Start.   So how does one ensure that production will always cache the data on Application_Start, without forcing developers to pay the cache load penalty?

System.Diagnostics.Debugger.IsAttached to the Rescue!

protected void Application_Start(object sender, EventArgs e)
     if (System.Diagnostics.Debugger.IsAttached)
         // Speed up the first page load for debugging by not loading all of the Cache
Debugger.IsAttached will check to see if a debugger is currently attached.  Since this will always be the case when developing the website locally, and never be the case in production (assuming there isn’t some catastrophic production event), developers can enjoy the productivity improvements when developing the website, without risking any performance issues in production.

Friday, March 8, 2013

Simplifying Retrieval of Aliased Values in CRM 2011

Aliased values have always annoyed me when performing a QueryExpression, or FetchXML Query.  It requires a lot of boiler plate code each time you attempt to retrieve an aliased value (checking for it to exist, including the entity logical name, casting the aliased value’s value to the correct type, etc).  Due to being a lazy developer who believes if I do something twice, that’s once too many, I created some extension methods to simplify the process.  I’m posting them here today for the world to enjoy.
First the code:  There are 5 methods. 
  1. GetAliasedValue<T> – This is the main method.  It’s an extension method on Entity, so it can be used on any entity, early bound or late.  It accepts the an attributeName which is the name of the aliased attribute.  As long as you don’t have duplicate aliased names (i.e. linking/joining on two different entities, and returning the same attribute name from both),  you don’t have to preappend the the logical name of the entity of the aliased value.  It is also generic, so that it will cast the value of the aliased value to the generic type.
  2. SplitAliasedAttributeEntityName – This helper method splits the attribute name passed in, by a period to determine if an entity logical name has been passed in, or only an attribute name.
  3. IsAttributeAliasedValue – This method determines if a particular aliased value is the aliased value requested by the user
  4. GetAliasedValueOrDefault<T> – By default GetAliasedValue<> will throw an exception if the aliased value wasn’t found, along with a list of the attributes contained in the collection.  This checks to see if the aliased value exists, and gets the default value for the generic type if isn’t doesn’t exist.
  5. HasAliasedAttribute – Used by GetAliasedValueOrDefault<T>.  Also helpful if you want to do some other logic besides getting the default value if it isn’t found
         /// <summary>
         /// Returns the Aliased Value for a column specified in a Linked entity
         /// </summary>
         /// <typeparam name="T">The type of the aliased attribute form the linked entity</typeparam>
         /// <param name="entity"></param>
         /// <param name="attributeName">The aliased attribute from the linked entity.  Can be preappeneded with the
         /// linked entities logical name and a period. ie "Contact.LastName"</param>
         /// <returns></returns>
         public static T GetAliasedValue<T>(this Entity entity, string attributeName)
             string aliasedEntityName = SplitAliasedAttributeEntityName(ref attributeName);
             AliasedValue aliased;
             foreach (var attribute in entity.Attributes.Values)
                 aliased = attribute as AliasedValue;
                 if(entity.IsAttributeAliasedValue(attributeName, aliasedEntityName, aliased))
                         return (T)aliased.Value;
                     catch (InvalidCastException)
                         throw new InvalidCastException(
                             String.Format("Unable to cast attribute {0}.{1} from type {2} to type {3}",
                                     aliased.EntityLogicalName, aliased.AttributeLogicalName,
                                     typeof(T).Name, aliased.Value.GetType().Name));
             throw new Exception("Aliased value with attribute " + attributeName +
                 " was not found!  Only these attributes were found: " + String.Join(", ", entity.Attributes.Keys));

         /// <summary>
         /// Handles spliting the attributeName if it is formated as "EntityAliasedName.AttributeName",
         /// updating the attribute name and returning the aliased EntityName
         /// </summary>
         /// <param name="attributeName"></param>
         /// <param name="aliasedEntityName"></param>
         private static string SplitAliasedAttributeEntityName(ref string attributeName)
             string aliasedEntityName = null;
             if (attributeName.Contains('.'))
                 var split = attributeName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
                 if (split.Length != 2)
                     throw new Exception("Attribute Name was specified for an Alaised Value with " + split.Length +
                     " split parts, and two were expected.  Attribute Name = " + attributeName);
                 aliasedEntityName = split[0];
                 attributeName = split[1];
             return aliasedEntityName;

        private static bool IsAttributeAliasedValue(this Entity entity, string attributeName, string aliasedEntityName, AliasedValue aliased)
             bool value =
            (aliased != null &&
                 (aliasedEntityName == null || aliasedEntityName == aliased.EntityLogicalName) &&
                 aliased.AttributeLogicalName == attributeName);

             /// I believe there is a bug in CRM 2011 when dealing with aggregate values of a linked entity in FetchXML.
             /// Even though it is marked with an alias, the AliasedValue in the Attribute collection will use the 
             /// actual CRM name, rather than the aliased one, even though the AttributeCollection's key will correctly
             /// use the aliased name.  So if the aliased Attribute Logical Name doesn't match the assumed attribute name
             /// value, check to see if the entity contains an AliasedValue with that key whose attribute logical name 
             /// doesn't match the key (the assumed bug), and mark it as being the aliased attribute
             if (!value && aliased != null && entity.Contains(attributeName))
                 var aliasedByKey = entity[attributeName] as AliasedValue;
                 if (aliasedByKey != null && aliasedByKey.AttributeLogicalName != attributeName &&
                      Object.ReferenceEquals(aliased, aliasedByKey))
                     value = true;
             return value;

         /// <summary>
         /// Returns the Aliased Value for a column specified in a Linked entity, returning the default value for 
         /// the type if it wasn't found
         /// </summary>
         /// <typeparam name="T">The type of the aliased attribute form the linked entity</typeparam>
         /// <param name="entity"></param>
         /// <param name="attributeName">The aliased attribute from the linked entity.  Can be preappeneded with the
         /// linked entities logical name and a period. ie "Contact.LastName"</param>
         /// <returns></returns>
         public static T GetAliasedValueOrDefault<T>(this Entity entity, string attributeName)
             T value;
             if (entity.HasAliasedAttribute(attributeName))
                 value = entity.GetAliasedValue<T>(attributeName);
                 value = default(T);
             return value;

         /// <summary>
         /// Returns the Aliased Value for a column specified in a Linked entity
         /// </summary>
         /// <typeparam name="T">The type of the aliased attribute form the linked entity</typeparam>
         /// <param name="entity"></param>
         /// <param name="attributeName">The aliased attribute from the linked entity.  Can be preappeneded with the
         /// linked entities logical name and a period. ie "Contact.LastName"</param>
         /// <returns></returns>
         public static bool HasAliasedAttribute(this Entity entity, string attributeName)
             string aliasedEntityName = SplitAliasedAttributeEntityName(ref attributeName);
             return entity.Attributes.Values.Any(a =>
                 entity.IsAttributeAliasedValue(attributeName, aliasedEntityName, a as AliasedValue));

Just add these methods to an Extension class and ease the burden aliased values incur:

        public Guid GetBusinessUnit(IOrganizationService service, Guid buildingId)
             var qe = new QueryExpression("new_building");
             qe.ColumnSet.AddColumns("new_buildingid", "new_name");
             qe.Criteria.AddCondition("new_buildingid", ConditionOperator.Equal, buildingId);
             var location = qe.AddLink("new_location", "new_locationid", "new_locationid");
             location.Columns.AddColumn("new businessunitid");
             return service.RetrieveMultiple(qe).Entities.FirstOrDefault().GetAliasedValue<EntityReference>("new_businessunitid").Id;