locked
CRM 2011: Plugin that retrieves the related records Name attribute in a N:N relation RRS feed

  • Question

  • Hi

    This is maybe over my head:) But I have following scenario:

    I have a N:N Relation between Account and IT-Service(Custom entity)

    I need to make a plugin that triggers on the associate message.

    I know by now that this plugin will be triggered every time anything is associated in CRM, and therefor I have this:

     if (!context.InputParameters.Contains("<strong>Relationship</strong>")) { return; }
                Relationship relationship = (Relationship)context.InputParameters["Relationship"];
                if (relationship.SchemaName != "df_account_df_itservice") { return; }
                if (!context.InputParameters.Contains("<strong>Target</strong>")) { return; }
                EntityReference target = (EntityReference)context.InputParameters["Target"];
                if (!context.InputParameters.Contains("<strong>RelatedEntities</strong>")) { return; }
                EntityReferenceCollection related = (EntityReferenceCollection)context.InputParameters["RelatedEntities"];

    But now i'm pretty stuck. I dont know which way to go.

    I have a EntityReferenceCollection with my related records (I think!!) and I have the Target (Normally the Account record)

    But how can I iterate thorugh the EntityReferenceCollection? Or is this totally wrong and should I instead try somethin like this:

     QueryExpression query = new QueryExpression()
                        {
                        EntityName = "df_itservice",
                        ColumnSet = new ColumnSet(true),
                        LinkEntities =
                        {
                        new LinkEntity(){
                        Columns = new ColumnSet(true),
                        LinkFromEntityName = "account",
                        LinkFromAttributeName = "accountid",
                        LinkToEntityName = "df_account_df_itservice",
                        LinkToAttributeName = "accountid",
                        LinkCriteria = new FilterExpression
                        {
                            FilterOperator = LogicalOperator.And,
                            Conditions =
                            {
                                new ConditionExpression
                                {
                                    AttributeName = ..........
                                            }
                        }
                        };

    If yes how should my queryexpression look like?

    After the queryexpression I could do something like this (found in the SDK):

     // Obtain results from the query expression.
                        EntityCollection ec = _serviceProxy.RetrieveMultiple(query);
                        // Display results.
                        for (int i = 0; i < ec.Entities.Count; i++)
                        {
                            Console.WriteLine("Query Expression Retrieved: {0}", ((Role)ec.Entities[i]).Name);
                        }

    Would it be possible for me to retrieve the names(I need to retrieve data from this attribute: "df_itservices") of the related records?

    As you can see Im totally lost to which way to get, so please HELP

    Tuesday, March 6, 2012 9:45 AM

Answers

All replies

  • I have this now:

    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Text;
    using Microsoft.Crm.Sdk;
    using Microsoft.Xrm.Sdk;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk.Messages;
    using Microsoft.Xrm.Sdk.Metadata;
    using Microsoft.Xrm.Sdk.Query;
    using Microsoft.Xrm.Sdk.Client;
    namespace InsertRelatedRecordsNamespace
    {
        public class InsertRelatedRecordsName : IPlugin
        {
            public void Execute(IServiceProvider serviceProvider)
            {
                // Obtain the execution context from the service provider.
                IPluginExecutionContext context = (IPluginExecutionContext)
                serviceProvider.GetService(typeof(IPluginExecutionContext));
                if (!context.InputParameters.Contains("<strong>Relationship</strong>")) { return; }
                Relationship relationship = (Relationship)context.InputParameters["Relationship"];
                if (relationship.SchemaName != "df_account_df_itservice") { return; }
                if (!context.InputParameters.Contains("<strong>Target</strong>")) { return; }
                EntityReference target = (EntityReference)context.InputParameters["Target"];
                if (!context.InputParameters.Contains("<strong>RelatedEntities</strong>")) { return; }
                EntityReferenceCollection related = (EntityReferenceCollection)context.InputParameters["RelatedEntities"];
                // Obtain the organization service reference.
                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
                //Extract the tracing service 
                ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
                    if (tracingService == null) 
                    throw new InvalidPluginExecutionException("Failed to retrieve the tracing service.");
                    try
                    {
                        tracingService.Trace("Plugin has started..");
                        Guid accId = (Guid)target.Id;
                        tracingService.Trace(accId.ToString());
                        QueryExpression query = new QueryExpression()
                        {
                        EntityName = "df_itservice",
                        ColumnSet = new ColumnSet(true),
                        LinkEntities =
                        {
                        new LinkEntity
                        {
                        Columns = new ColumnSet(true),
                        LinkFromEntityName = "account",
                        LinkFromAttributeName = "accountid",
                        LinkToEntityName = "AccountItService",
                        LinkToAttributeName = "accountid",
                        LinkCriteria = new FilterExpression
                                                {
                                                    FilterOperator = LogicalOperator.And,
                                                    Conditions = 
                                                    {
                                                        new ConditionExpression
                                                        {
                                                            AttributeName = "accountid",
                                                            Operator = ConditionOperator.Equal,
                                                            Values = { accId }
                                                        }
                                                    }
                                                }
                                            }
                        }
                        };
            //Call Crm Service
            EntityCollection interSectionValues = service.RetrieveMultiple(query);
            if (interSectionValues != null && interSectionValues.Entities.Count > 0)
            {
                 
                for (int i = 0; i < interSectionValues.Entities.Count; i++)
                {
                    Console.WriteLine("Query Expression Retrieved: {0}", (interSectionValues.Entities[i]).Attributes["df_serviceid"]);
                }
            }
                                        }
                    catch (FaultException<OrganizationServiceFault> ex) 
                    { 
                    throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex); 
                    } 
    }
    }
    }

    But Im really unsure if this is the right way.

    I think I need to get the related GUIDS from the intersect table first(What Im trying with this code), and then I need to make a query to get the attributes of the records with the retrieved GUIDs. Im a on my way to the mental here?

    Tuesday, March 6, 2012 10:49 AM
  • I created a solution to the issue: Look at my blog to see the way I solved it.

    Caspers CRM dream blog

    • Marked as answer by Casper Schau Wednesday, March 7, 2012 8:29 AM
    Wednesday, March 7, 2012 8:28 AM