Saturday, September 17, 2011

Get all Account and Contact Entity Activities in MS CRM 4.0 through QueryExpression, LinkEntity and FilterExpression

Database Query: "SELECT * FROM ActivityPointerBase INNER JOIN ActivityPartyBase ON ActivityPartyBase.activityId = ActivityPointerBase.activityid WHERE ActivityPartyBase.partyobjecttypecode in (1,2)"
-- 1 for Account Entity and 2 for Contact Entity

static void GetAllContactandAccountActivities()
        {
            CRMHelper objCRMHelper = new CRMHelper();
            CrmService service = objCRMHelper.GetCRMService();

            AllColumns activityPointerBaseColumns = new AllColumns();

            QueryExpression query = new QueryExpression();
            query.ColumnSet = activityPointerBaseColumns;
            query.EntityName = EntityName.activitypointer.ToString();

            LinkEntity objLinkEntity = new LinkEntity();
            objLinkEntity.LinkFromEntityName = EntityName.activitypointer.ToString();
            objLinkEntity.LinkFromAttributeName = "activityid";
            objLinkEntity.LinkToEntityName = EntityName.activityparty.ToString();
            objLinkEntity.LinkToAttributeName = "activityid";

            //WHERE CONDITION
            FilterExpression activityFilter = new FilterExpression();
            ConditionExpression activityCondition = new ConditionExpression();
            activityCondition.AttributeName = "partyobjecttypecode";
            activityCondition.Operator = ConditionOperator.In;
            activityCondition.Values = new object[] { 1, 2 };
            activityFilter.Conditions = new ConditionExpression[] { activityCondition };
            objLinkEntity.LinkCriteria = activityFilter;

            // Link from ActivityPointer to ActivityPartyBase
            query.LinkEntities = new LinkEntity[] { objLinkEntity };

            BusinessEntityCollection result = service.RetrieveMultiple(query);
            if (result.BusinessEntities.Length > 0)
            {
                foreach (BusinessEntity objBE in result.BusinessEntities)
                {
                }
            }
        }