Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

Assign Contact to Account based on Mail Domain Name

Posted on by 230

Hi Guys, 

I added a custom field to my account entity that contains different mail domain names that are owned by the account holder.

then i wrote a plugin so when a new contact is created it looks up if a domain name matches email adress and auto assigns it to the account.

however it does not work. 

i am very new to plugin dev. and don't quite understand how to apply my "_contact" variable to the CRM... i know my query works and all but i must be missing a details. can anybody help me with this?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Crm.Sdk.Messages;
using System.ServiceModel;

namespace Assigncontacttoaccount
{
    
        public class AssignAccount : IPlugin
        {
           
            public void Execute(IServiceProvider serviceProvider)
            {

                // Obtain the execution context from the service provider. (same as other plugin-written diff)
                Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));
                IOrganizationServiceFactory wod_serviceFactory = null; // why is this null and in the other plugin it pulls stuff...
                IOrganizationService wod_CrmService = null;
                wod_serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                wod_CrmService = wod_serviceFactory.CreateOrganizationService(context.UserId);

                if ((context.MessageName == "Create") && (context.PrimaryEntityName == "contact") && (context.InputParameters.Contains("Target")) && (context.InputParameters["Target"] is Entity))
                {
                    Entity _contact = (Entity)context.InputParameters["Target"];
                    //Make sure there is an email address on the contact and it's not already being tied to an Account
                    if ((_contact.Contains("emailaddress1")) && (!_contact.Contains("parentcustomerid")))
                    {                    
                        string _email = (string)_contact["emailaddress1"];
                        string[] _domain = _email.Split('@');
                        if (_domain.Length == 2)
                        {                            
                            QueryExpression _query = new QueryExpression();
                            _query.NoLock = true;
                            _query.EntityName = "account";
                            _query.ColumnSet = new ColumnSet();
                            _query.ColumnSet.Columns.Add("name");
                            _query.Distinct = true;
                            _query.Criteria = new FilterExpression();
                            _query.Criteria.FilterOperator = LogicalOperator.And;                           
                            _query.Criteria.AddCondition("new_linkeddomain", ConditionOperator.Like, "%"+ _domain[1].ToString()+ "%");
                            EntityCollection _accounts = (EntityCollection)wod_CrmService.RetrieveMultiple(_query);
                            if ((_accounts != null) && (_accounts.Entities.Count > 0))
                            {
                                _contact.Attributes.Add("Jobtitle", _accounts.Entities[0].Attributes["name"].ToString());
                                _contact.Attributes.Add("parentcustomerid", new EntityReference(_accounts.Entities[0].LogicalName, _accounts.Entities[0].Id));
                                context.InputParameters["Target"] = _contact;                               
                            }
                        }
                    }
                }
            }
        }
    }


*This post is locked for comments

  • Anthony A Profile Picture
    Anthony A 230 on at
    RE: Assign Contact to Account based on Mail Domain Name

    Great, that did the job! it works now.

    I wish i could have found some easy documentation about query expression, i had to use different information from different source to build it :(

    here is the final code (for anyone else trying to to this)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Client;
    using Microsoft.Xrm.Sdk.Query;
    using Microsoft.Xrm.Sdk.Discovery;
    using Microsoft.Crm.Sdk.Messages;
    using System.ServiceModel;
    
    namespace Assigncontacttoaccount
    {
        
            public class AssignAccount : IPlugin
            {
               
                public void Execute(IServiceProvider serviceProvider)
                {
    
                    // Obtain the execution context from the service provider. (same as other plugin-written diff)
                    Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));
                    IOrganizationServiceFactory wod_serviceFactory = null; // why is this null and in the other plugin it pulls stuff...
                    IOrganizationService wod_CrmService = null;
                    wod_serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    wod_CrmService = wod_serviceFactory.CreateOrganizationService(context.UserId);
    
                    if ((context.MessageName == "Create") && (context.PrimaryEntityName == "contact") && (context.InputParameters.Contains("Target")) && (context.InputParameters["Target"] is Entity))
                    {
                        Entity _contact = (Entity)context.InputParameters["Target"];
                        //Make sure there is an email address on the contact and it's not already being tied to an Account
                        if ((_contact.Contains("emailaddress1")) && (!_contact.Contains("parentcustomerid")))
                        {                                                                       
                            string _email = _contact.GetAttributeValue<string>("emailaddress1");
                            string[] _domain = _email.Split('@');
                            if (_domain.Length == 2)
                            {                                                        
                                QueryExpression _query = new QueryExpression("account");
                                _query.ColumnSet = new ColumnSet("accountid", "name");
                                _query.Distinct = true;
                                _query.Criteria = new FilterExpression(LogicalOperator.And);
                                _query.Criteria.AddCondition("new_linkeddomain", ConditionOperator.Like, "%" + _domain[1].ToString() + "%");
                                EntityCollection _accounts = (EntityCollection)wod_CrmService.RetrieveMultiple(_query);                            
                                if ((_accounts != null) && (_accounts.Entities.Count > 0))
                                {
                                    Entity firstAccount = _accounts.Entities[0];
                                    //_contact.Attributes.Add("jobtitle", firstAccount["name"].ToString());
                                    _contact.Attributes.Add("parentcustomerid", new EntityReference(firstAccount.LogicalName, firstAccount.Id));
                                    context.InputParameters["Target"] = _contact;                               
                                }
                                
                            } 
                        }
                    }
                }
            }
        }


  • Aric Levin Profile Picture
    Aric Levin 30,188 on at
    RE: Assign Contact to Account based on Mail Domain Name

    Have you made changes to the queryexpression retrieving your accounts? can you post it.

    It should have come through, but can you add the accountid column to the ColumnSet:

    _query.ColumnSet = new ColumnSet ("accountid", "name");

    Your code above (in your recent post), seems to also be retrieving account info from a lookup control and not from an entity.

    Your code should be something like this:

    QueryExpression _query = new QueryExpression("account");

    _query.ColumnSet = new ColumnSet("accountid", "name");

    _query.Distinct = true;

    _query.Criteria = new FilterExpression(LogicalOperator.And);                          

    _query.Criteria.AddCondition("new_linkeddomain", ConditionOperator.Like, "%"+ _domain[1].ToString()+ "%");

    EntityCollection _accounts = (EntityCollection)wod_CrmService.RetrieveMultiple(_query);

    if ((_accounts != null) && (_accounts.Entities.Count > 0))

    {

      // Just for clean readability

      Entity firstAccount = _accounts.Entities[0];

      _contact.Attributes.Add("Jobtitle", firstAccount["name"].ToString());

      _contact.Attributes.Add("parentcustomerid", new EntityReference(firstAccount.LogicalName, firstAccount.Id));

     context.InputParameters["Target"] = _contact;

    }

  • Anthony A Profile Picture
    Anthony A 230 on at
    RE: Assign Contact to Account based on Mail Domain Name

    So i did a bit more  debugging.

    My problem is the GUID. when i read it, using "...id.tostring()" i get a bunch of 0000...

    so:

    _accounts.Entities[0].Id = 00000000-0000-0000-0000-000000000000

    _accounts.Entities[0].LogicalName = "account"

    _accounts.Entities[0].Attributes["name"]  =the name of the account that i need the guid...

    how do i read the GUID of the account i fetched using the query?

  • Anthony A Profile Picture
    Anthony A 230 on at
    RE: Assign Contact to Account based on Mail Domain Name

    Ok... I had to put the plugin in syncronous/pre-operation mode (didnt know that)

    Now the jobtitle fields gets populated with the proper "account" info.  but only if i comment out the reference line:

    so my only issue now is this line... i will try your code...   (and i know that _accounts.Entities[0].LogicalName, _accounts.Entities[0].Id is ok since i am testing it with my jobtitle field...)

    _contact.Attributes.Add("parentcustomerid", new EntityReference(_accounts.Entities[0].LogicalName, _accounts.Entities[0].Id));  

  • TNS Profile Picture
    TNS 1,195 on at
    RE: Assign Contact to Account based on Mail Domain Name

    Inside this loop :   if ((_accounts != null) && (_accounts.Entities.Count > 0))  paste below code .... hoping your query is correct and you are getting records... also change above line also which I have said ....

    Entity co = new Entity("contact");

    for (int i=0;i< _accounts.Entities.Count ;i++)

    {

     co.Attributes["contactid"] = _contact.Id;

     co.Attributes["Jobtitle"] = _accounts[i].Attributes["name"];

     co.Attributes["parentcustomerid"] = new EntityReference("account", _accounts[i].Id);

     servcie.Update(co);

    }

    and still not work.. debug your plugin and check where you are not getting record..

  • Anthony A Profile Picture
    Anthony A 230 on at
    RE: Assign Contact to Account based on Mail Domain Name

    for testing purposes i used this code and was able to debug plugin to see that everything worked.

    but I couldn't get the entity reference to update using this method.

    ....

    Entity ContEnty = wod_CrmService.Retrieve(_contact.LogicalName, _contact.Id, attributes);

    ContEnty.Attributes["jobtitle"] = _accounts.Entities[0].Attributes["name"].ToString());

    wod_CrmService.Update(ContEnty);

    ...

  • Anthony A Profile Picture
    Anthony A 230 on at
    RE: Assign Contact to Account based on Mail Domain Name

    same result.

    Plug in executes with no errors but nothing appears in "jobtitle" or "parentcustomerid" ?

  • TNS Profile Picture
    TNS 1,195 on at
    RE: Assign Contact to Account based on Mail Domain Name

    Hi,

    Please change your line and try ...

    string _email = (string)_contact["emailaddress1"];  to

    string _email = _contact.GetAttributeValue<string>("emailaddress1");

    Thanks!

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,235 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans