- Create a new public class called EmailDataAccessLayerQueryExpression in the DataAccessLayer folder that inherits from BaseDataAccessLayer and implements IEmailDataAccessLayer:
public class EmailDataAccessLayerQueryExpression : BaseDataAccessLayer, IEmailDataAccessLayer
- Add the following using statements to the default ones:
using Microsoft.Xrm.Sdk;
using Packt.Xrm.Entities;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;
- Create a constructor that takes IOrganizationService and calls the base constructor:
public EmailDataAccessLayerQueryExpression(IOrganizationService organizationService) : base(organizationService)
- Override the UpdateEntity method to use OrganizationService:
public override void UpdateEntity(Entity entity)
{
OrganizationService.Update(entity);
}
- Override the Commit method to have no implementation:
public override void Commit()
{
}
- Implement the CloseEmailAsCancelled method to use OrganizationService:
public void CloseEmailAsCancelled(Email email)
{
email.StateCode = EmailState.Canceled;
var setStateRequest = new SetStateRequest()
{
Status = new OptionSetValue((int)email_statuscode.Canceled),
State = new OptionSetValue((int)EmailState.Canceled),
EntityMoniker = new EntityReference(Email.EntityLogicalName,
email.Id)
};
OrganizationService.Execute(setStateRequest);
}
- Implement the GetEmails method to use QueryExpression:
public IEnumerable<Email> GetEmails(Guid parentEntityId)
{
var queryExpression = new QueryExpression()
{
EntityName = Email.EntityLogicalName,
ColumnSet = new ColumnSet( "subject"),
Criteria =
{
Filters =
{
new FilterExpression
{
FilterOperator = LogicalOperator.And,
Conditions =
{
new ConditionExpression("regardingobjectid", ConditionOperator.Equal, parentEntityId),
new ConditionExpression("statecode", ConditionOperator.Equal, (int)EmailState.Open)
},
}
}
}
};
var entityCollection = OrganizationService.RetrieveMultiple(queryExpression);
return entityCollection.Entities.Select(e => e.ToEntity<Email>()).ToList();
}
- Update the GetEmailDataAccessLayer method in DataAccessLayerFactory to return an instance of the newly created EmailDataAccessLayerQueryExpression object:
public IEmailDataAccessLayer GetEmailDataAccessLayer()
{
if (_emailDataAccessLayer == null)
_emailDataAccessLayer = new EmailDataAccessLayerQueryExpression(_organisationService);
return _emailDataAccessLayer;
}