Random Musings

June 19, 2009

Reflection in C#

Filed under: Dynamics CRM — haditeo @ 10:00 pm
Tags: , ,

These are the code before it’s refactored

         private Opportunity ToOpportunity(DynamicEntity de)
         {
             try
             {
                 Opportunity opportunity = new Opportunity();

                 foreach (string attribute in opportunity.AttributesList)
                 {
                     if (!de.Properties.Contains("opportunityid"))
                         throw new PropertiesNotExistException("The Dynamic Entity type Opportunity does not have id property");

                     opportunity.Id = new KeyProperty("opportunityid", ((Key)de["opportunityid"]));

                     switch (attribute)
                     {
                         case "customerid":
                             if (de.Properties.Contains(attribute))
                                 opportunity.SetPotentialClient(((Customer)de[attribute]).Value);
                             break;
                         case "new_contactpersonid":
                             if (de.Properties.Contains(attribute))
                                 opportunity.SetContactPerson(((Lookup)de[attribute]).Value);
                             break;
                         case "new_clientcategory":
                             if (de.Properties.Contains(attribute))
                                 opportunity.SetClientCategory(((Picklist)de[attribute]).Value);
                             break;
                         case "name":
                             if (de.Properties.Contains(attribute))
                                 opportunity.SetPotentialProjectTitle(de[attribute].ToString());
                             break;
                         case "new_potentialprojecttitlechinese":
                             if (de.Properties.Contains(attribute))
                                 opportunity.SetPotentialProjectTitleInChinese(de[attribute].ToString());
                             break;
                         case "new_accountmanager":
                             if (de.Properties.Contains(attribute))
                                 opportunity.SetAccountManager(de[attribute].ToString());
                             break;
                         case "new_kba":
                             if (de.Properties.Contains(attribute))
                                 opportunity.SetKba(((Picklist)de[attribute]).Value);
                             break;
                         case "new_servicetype":
                             if (de.Properties.Contains(attribute))
                                 opportunity.SetServiceType(((Picklist)de[attribute]).Value);
                             break;
                         case "new_developmenttype":
                             if (de.Properties.Contains(attribute))
                                 opportunity.SetProjectDevelopmentType(((Picklist)de[attribute]).Value);
                             break;
                         case "new_regionopportunityid":
                             if (de.Properties.Contains(attribute))
                                 opportunity.SetRegion(((Lookup)de[attribute]).Value);
                             break;
                         case "new_location":
                             if (de.Properties.Contains(attribute))
                                 opportunity.SetLocation(de[attribute].ToString());
                             break;
                         case "new_countryopportunityid":
                             if (de.Properties.Contains(attribute))
                                 opportunity.SetCountry(((Lookup)de[attribute]).Value);
                             break;
                         case "description":
                             if (de.Properties.Contains(attribute))
                                 opportunity.SetDescription(de[attribute].ToString());
                             break;
                         case "new_source":
                             if (de.Properties.Contains(attribute))
                                 opportunity.SetSource(((Picklist)de[attribute]).Value);
                             break;
                         case "new_estimatedprojectcost":
                             if (de.Properties.Contains(attribute))
                                 opportunity.SetEstimatedProjectCost(((CrmMoney)de[attribute]).Value);
                             break;
                         case "estimatedvalue":
                             if (de.Properties.Contains(attribute))
                                 opportunity.SetEstimatedProjectFees(((CrmMoney)de[attribute]).Value);
                             break;
                         case "new_estimatedfeespercentage":
                             if (de.Properties.Contains(attribute))
                                 opportunity.SetEstimatedFeesPercentage(((CrmDecimal)de[attribute]).Value);
                             break;
                         case "new_estimatedprojectstartdate":
                             if (de.Properties.Contains(attribute))
                                 opportunity.SetEstimatedProjectStartDate(((CrmDateTime)de[attribute]).UserTime);
                             break;
                         case "new_estimatedprojectenddate":
                             if (de.Properties.Contains(attribute))
                                 opportunity.SetEstimatedProjectEndDate(((CrmDateTime)de[attribute]).UserTime);
                             break;
                     }
                 }
                 return opportunity;
             }
             catch (SoapException soapExc)
             {
                 throw soapExc;
             }
             catch (Exception exc)
             {
                 throw exc;
             }

         }

and these are the code after it’s refactored

        public Opportunity ToOpportunity(DynamicEntity de)
        {
            try
            {
                Assembly sdkDll = Assembly.LoadFrom("microsoft.crm.sdk.dll");

                Opportunity newOpportunity = new Opportunity();

                foreach(PropertyInfo pi in  typeof(Opportunity).GetProperties())
                {
                    string crmFieldMapping = ((CrmFieldMapping)(pi.GetCustomAttributes(typeof(CrmFieldMapping), false))[0]).GetCrmFieldMapping();
                    string crmTypeProperty = ((CrmTypeProperty)(pi.GetCustomAttributes(typeof(CrmTypeProperty), false))[0]).GetCrmTypeProperty();

                    if (de.Properties.Contains(crmFieldMapping))
                    {
                        Type currentCrmTypeProperty = sdkDll.GetType("Microsoft.Crm.Sdk." + crmTypeProperty);

                        object obj = Activator.CreateInstance(currentCrmTypeProperty, crmFieldMapping, de[crmFieldMapping]);

                        pi.SetValue(newOpportunity, obj, null);
                    }
                }

                return newOpportunity;
            }
            catch (SoapException soapExc)
            {
                throw soapExc;
            }
            catch (Exception exc)
            {
                throw exc;
            }

        }

Currently i’m closely applying Domain Driven Development by creating domain objects first. The previous source code is created without using reflection. Yesterday, i was wondering and got the idea of decorating the domain object with custom attributes as metadata, so that i can easily refer to it when reflecting the object at runtime.

These are the sample of the custom attribute :

    public class Opportunity
    {
        private KeyProperty opportunityId;
        [CrmTypeProperty("KeyProperty")]
        [CrmFieldMapping("opportunityid")]
        public KeyProperty Id
        {
            get { return opportunityId; }
            set { opportunityId = value; }
        }

        private StringProperty _projectTitle;
        [CrmTypeProperty("StringProperty")]
        [CrmFieldMapping("name")]
        public StringProperty PotentialProjectTitle
        {
            get { return _projectTitle; }
            set { _projectTitle = value; }
        }
   }

What are the advantages of using reflection ? Now, let’s say i am adding another property at the domain object, i just need to update the domain object and i don’t need to change the code at the data layer.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: