Tuesday, March 26, 2013

CRM 2011 Get the right server url in javascript

I used the method found on Daniel Cai's Blog and it worked for me, hopefully it will for for others too.

My function is a little modified (I removed some checks) but uses the same idea from Daniel's blog. Also the idea with prependOrgName that Andrii Butenko suggested worked for me.

My function looks like this:


function GetServerUrl () {

    var context = Xrm.Page.context;

    if (context.isOutlookClient() && !context.isOutlookOnline()) {
        crmServerUrl = window.location.protocol + "//" + window.location.host;
    } else {
        crmServerUrl = context.getServerUrl();
        crmServerUrl = crmServerUrl.replace(/^(http|https):\/\/([_a-zA-Z0-9\-\.]+)(:([0-9]{1,5}))?/, window.location.protocol + "//" + window.location.host);
        crmServerUrl = crmServerUrl.replace(/\/$/, ""); // remove trailing slash if any
    }
    return crmServerUrl;
}

Update: With the Rollup 12 we can use getClientUrl that will solve all our problems. See bellow description taken from msdn


getClientUrl

Returns the base URL that was used to access the application.
This method is new in Microsoft Dynamics CRM 2011 Update Rollup 12 and the Microsoft Dynamics CRM December 2012 Service Update.
The values returned will resemble those listed in the following table.

 

ClientValue
Microsoft Dynamics CRM (on-premises)
http(s)://server/org
Microsoft Dynamics CRM Online
https://org.crm.dynamics.com
Microsoft Dynamics CRM for Outlook with Offline Access when offline
http://localhost:2525
Return Value
Type: String

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);
        }
    }
}



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);

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);

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;
        }