I used this method to Get a contact id from email "From" field. This method can be customized and you can get any entity you need from this field.
public Guid? GetContactIdInFromField(IEnumerable<ActivityParty> party)
{
var fromItems = party.Select(c => c.ToEntity<ActivityParty>()).ToArray();
var fromContacts = from c in fromItems
where c.PartyId.LogicalName == Contact.EntityLogicalName
select c;
var contactRef = fromContacts.FirstOrDefault();
if (contactRef == null)
return null;
return contactRef.PartyId.Id;
}
Call function:
var contactFromId = GetContactIdInFromField(emailEntity.From);
Hope this helps.
Showing posts with label Plug-ins. Show all posts
Showing posts with label Plug-ins. Show all posts
Tuesday, March 26, 2013
Plugin Utils Interface CRM 2011 in C#
For my plugins I usually use this "utils".
I have an Plugin Utils folder where I add these 3 classes:
EntityPlugin.cs
namespace Plugins
{
public abstract class EntityPlugin<T> where T : Entity
{
private static bool LogInit = false;
public void Execute(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new ArgumentNullException("serviceProvider");
}
var utils = new PluginUtils(serviceProvider);
var entity = utils.PluginContext.InputParameters["Target"] as Entity;
if (entity == null)
{
//if Post Delete dont take entity entityReference
if (utils.PluginContext.MessageName.ToLower() != "delete" || utils.PluginContext.Stage != 40)
{
var entityReference = utils.PluginContext.InputParameters["Target"] as EntityReference;
entity = utils.Service.Retrieve(entityReference.LogicalName, entityReference.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
T target = entity.ToEntity<T>();
Execute(utils, target);
}
//in case of Post Delete
else
{
T target = null;
Execute(utils, target);
}
}
else
{
T target = entity.ToEntity<T>();
Execute(utils, target);
}
}
protected abstract void Execute(IPluginUtils utils, T target);
}
}
IPluginUtils.cs
namespace Plugins.Interfaces
{
public interface IPluginUtils
{
CrmDataContext CrmDataContext { get; }
IPluginExecutionContext PluginContext { get; }
IOrganizationService Service { get; }
}
}
PluginUtils .cs
namespace Plugins
{
public class PluginUtils : IPluginUtils
{
public PluginUtils(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new ArgumentNullException("serviceProvider");
}
PluginContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
Service = serviceFactory.CreateOrganizationService(PluginContext.UserId);
CrmDataContext = new CrmDataContext(Service);
}
public IPluginExecutionContext PluginContext { get; private set; }
public IOrganizationService Service { get; private set; }
public CrmDataContext CrmDataContext { get; private set; }
}
}
In my plugins the code will look something like this:
namespace Plugins.Account
{
public class PostCreate_AccountDoSomething : EntityPlugin<EntityMappings.Account>, IPlugin
{
protected override void Execute(Interfaces.IPluginUtils utils, EntityMappings.Account target)
{
//do code
utils.Service.Execute(somerequest);
}
}
}
I have an Plugin Utils folder where I add these 3 classes:
EntityPlugin.cs
namespace Plugins
{
public abstract class EntityPlugin<T> where T : Entity
{
private static bool LogInit = false;
public void Execute(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new ArgumentNullException("serviceProvider");
}
var utils = new PluginUtils(serviceProvider);
var entity = utils.PluginContext.InputParameters["Target"] as Entity;
if (entity == null)
{
//if Post Delete dont take entity entityReference
if (utils.PluginContext.MessageName.ToLower() != "delete" || utils.PluginContext.Stage != 40)
{
var entityReference = utils.PluginContext.InputParameters["Target"] as EntityReference;
entity = utils.Service.Retrieve(entityReference.LogicalName, entityReference.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
T target = entity.ToEntity<T>();
Execute(utils, target);
}
//in case of Post Delete
else
{
T target = null;
Execute(utils, target);
}
}
else
{
T target = entity.ToEntity<T>();
Execute(utils, target);
}
}
protected abstract void Execute(IPluginUtils utils, T target);
}
}
IPluginUtils.cs
namespace Plugins.Interfaces
{
public interface IPluginUtils
{
CrmDataContext CrmDataContext { get; }
IPluginExecutionContext PluginContext { get; }
IOrganizationService Service { get; }
}
}
PluginUtils .cs
namespace Plugins
{
public class PluginUtils : IPluginUtils
{
public PluginUtils(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new ArgumentNullException("serviceProvider");
}
PluginContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
Service = serviceFactory.CreateOrganizationService(PluginContext.UserId);
CrmDataContext = new CrmDataContext(Service);
}
public IPluginExecutionContext PluginContext { get; private set; }
public IOrganizationService Service { get; private set; }
public CrmDataContext CrmDataContext { get; private set; }
}
}
In my plugins the code will look something like this:
namespace Plugins.Account
{
public class PostCreate_AccountDoSomething : EntityPlugin<EntityMappings.Account>, IPlugin
{
protected override void Execute(Interfaces.IPluginUtils utils, EntityMappings.Account target)
{
//do code
utils.Service.Execute(somerequest);
}
}
}
CRM 2011: Associate/Disassociate entities from a relation C#
In my exact requirement I had a N:N relation between 2 entities and I had to associate/disassociate entities that are connected with this N:N relation.
Here are two methods for this.
public static void DisassociateEntitiesToTarget(EntityReference target, EntityReferenceCollection relatedEntities, string relationName, IOrganizationService service)
{
// Add the relationship schema name
Relationship relationship = new Relationship(relationName);
// Disassociate the entities records to target
service.Disassociate(target.LogicalName, target.Id, relationship, relatedEntities);
}
Call the method
DisassociateEntitiesToTarget(targetEntity.ToEntityReference(), relatedEntities, "relationName", utils.Service);
public static void AssociateEntitiesToTarget(EntityReference target, EntityReferenceCollection relatedEntities, string relationName, IOrganizationService service)
{
// Add the relationship schema name
Relationship relationship = new Relationship(relationName);
// Associate the entities to target
service.Associate(target.LogicalName, target.Id, relationship, relatedEntities);
}
Call the method:
AssociateEntitiesToTarget(targetEntity.ToEntityReference(), entitiesToAssociate, "relationName", utils.Service);
Here are two methods for this.
public static void DisassociateEntitiesToTarget(EntityReference target, EntityReferenceCollection relatedEntities, string relationName, IOrganizationService service)
{
// Add the relationship schema name
Relationship relationship = new Relationship(relationName);
// Disassociate the entities records to target
service.Disassociate(target.LogicalName, target.Id, relationship, relatedEntities);
}
Call the method
DisassociateEntitiesToTarget(targetEntity.ToEntityReference(), relatedEntities, "relationName", utils.Service);
public static void AssociateEntitiesToTarget(EntityReference target, EntityReferenceCollection relatedEntities, string relationName, IOrganizationService service)
{
// Add the relationship schema name
Relationship relationship = new Relationship(relationName);
// Associate the entities to target
service.Associate(target.LogicalName, target.Id, relationship, relatedEntities);
}
Call the method:
AssociateEntitiesToTarget(targetEntity.ToEntityReference(), entitiesToAssociate, "relationName", utils.Service);
Get related entities from Many to many relation CRM 2011
I had a request to obtain all related entities from N:N relation for a specific entity in this relation. There might be other ways to achieve this but this method I used and it worked for me, so I thought to share it with you in case somebody else will need it.
This is the function that returns the a collection of entities for a specific entity from this relation.
/// <summary>
/// get entities from many to many relation
/// </summary>
/// <param name="entityToRetrieve">the entity name that we want to retrieve</param>
/// <param name="relationName">relation name</param>
/// <param name="targetEntity">entity name</param>
/// <param name="service"></param>
/// <returns>collection of entities</returns>
public static DataCollection<Entity> GetRelatedEntitDataFromManyToManyRelation(string entityToRetrieve, string[] columnsToRetieve, string relationName, EntityReference targetEntity, IOrganizationService service)
{
DataCollection<Entity> result = null;
QueryExpression query = new QueryExpression();
query.EntityName = entityToRetrieve;
query.ColumnSet = new ColumnSet(columnsToRetieve);
Relationship relationship = new Relationship();
relationship.SchemaName = relationName;
RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();
relatedEntity.Add(relationship, query);
RetrieveRequest request = new RetrieveRequest();
request.RelatedEntitiesQuery = relatedEntity;
request.ColumnSet = new ColumnSet(targetEntity.LogicalName + "id");
request.Target = targetEntity;
RetrieveResponse response = (RetrieveResponse)service.Execute(request);
if (((DataCollection<Relationship, EntityCollection>)(((RelatedEntityCollection)(response.Entity.RelatedEntities)))).Contains(new Relationship(relationName)) && ((DataCollection<Relationship, EntityCollection>)(((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Relationship(relationName)].Entities.Count > 0)
{
result = ((DataCollection<Relationship, EntityCollection>)(((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Relationship(relationName)].Entities;
}
return result;
}
You can call this function is like this:
var relatedAccountsForTarget = GetRelatedEntitDataFromManyToManyRelation("account", new string[]{ "accountid" }, "Type here relationName", targetEntity.ToEntityReference(), utils.Service);
This is the function that returns the a collection of entities for a specific entity from this relation.
/// <summary>
/// get entities from many to many relation
/// </summary>
/// <param name="entityToRetrieve">the entity name that we want to retrieve</param>
/// <param name="relationName">relation name</param>
/// <param name="targetEntity">entity name</param>
/// <param name="service"></param>
/// <returns>collection of entities</returns>
public static DataCollection<Entity> GetRelatedEntitDataFromManyToManyRelation(string entityToRetrieve, string[] columnsToRetieve, string relationName, EntityReference targetEntity, IOrganizationService service)
{
DataCollection<Entity> result = null;
QueryExpression query = new QueryExpression();
query.EntityName = entityToRetrieve;
query.ColumnSet = new ColumnSet(columnsToRetieve);
Relationship relationship = new Relationship();
relationship.SchemaName = relationName;
RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();
relatedEntity.Add(relationship, query);
RetrieveRequest request = new RetrieveRequest();
request.RelatedEntitiesQuery = relatedEntity;
request.ColumnSet = new ColumnSet(targetEntity.LogicalName + "id");
request.Target = targetEntity;
RetrieveResponse response = (RetrieveResponse)service.Execute(request);
if (((DataCollection<Relationship, EntityCollection>)(((RelatedEntityCollection)(response.Entity.RelatedEntities)))).Contains(new Relationship(relationName)) && ((DataCollection<Relationship, EntityCollection>)(((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Relationship(relationName)].Entities.Count > 0)
{
result = ((DataCollection<Relationship, EntityCollection>)(((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Relationship(relationName)].Entities;
}
return result;
}
You can call this function is like this:
var relatedAccountsForTarget = GetRelatedEntitDataFromManyToManyRelation("account", new string[]{ "accountid" }, "Type here relationName", targetEntity.ToEntityReference(), utils.Service);
Retrieve option set text in CRM 2011 server side
This method was taken from Guru Prasad's Blog. Here we can find several methods based on your needs that you can use to achieve the needed result. Thank you Guru!
I'll share one of the methods that I used in my code using metadata service:
public static string GetoptionsetText(string entityName, string attributeName, int optionSetValue, IOrganizationService service)
{
string AttributeName = attributeName;
string EntityLogicalName = entityName;
RetrieveEntityRequest retrieveDetails = new RetrieveEntityRequest
{
EntityFilters = EntityFilters.Attributes,
LogicalName = EntityLogicalName
};
RetrieveEntityResponse retrieveEntityResponseObj = (RetrieveEntityResponse)service.Execute(retrieveDetails);
Microsoft.Xrm.Sdk.Metadata.EntityMetadata metadata = retrieveEntityResponseObj.EntityMetadata;
Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata picklistMetadata = metadata.Attributes.FirstOrDefault(attribute => String.Equals
(attribute.LogicalName, attributeName, StringComparison.OrdinalIgnoreCase)) as Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata;
Microsoft.Xrm.Sdk.Metadata.OptionSetMetadata options = picklistMetadata.OptionSet;
IList<OptionMetadata> OptionsList = (from o in options.Options
where o.Value.Value == optionSetValue
select o).ToList();
string optionsetLabel = (OptionsList.First()).Label.UserLocalizedLabel.Label;
return optionsetLabel;
}
I'll share one of the methods that I used in my code using metadata service:
public static string GetoptionsetText(string entityName, string attributeName, int optionSetValue, IOrganizationService service)
{
string AttributeName = attributeName;
string EntityLogicalName = entityName;
RetrieveEntityRequest retrieveDetails = new RetrieveEntityRequest
{
EntityFilters = EntityFilters.Attributes,
LogicalName = EntityLogicalName
};
RetrieveEntityResponse retrieveEntityResponseObj = (RetrieveEntityResponse)service.Execute(retrieveDetails);
Microsoft.Xrm.Sdk.Metadata.EntityMetadata metadata = retrieveEntityResponseObj.EntityMetadata;
Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata picklistMetadata = metadata.Attributes.FirstOrDefault(attribute => String.Equals
(attribute.LogicalName, attributeName, StringComparison.OrdinalIgnoreCase)) as Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata;
Microsoft.Xrm.Sdk.Metadata.OptionSetMetadata options = picklistMetadata.OptionSet;
IList<OptionMetadata> OptionsList = (from o in options.Options
where o.Value.Value == optionSetValue
select o).ToList();
string optionsetLabel = (OptionsList.First()).Label.UserLocalizedLabel.Label;
return optionsetLabel;
}
Subscribe to:
Posts (Atom)