Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Customer experience | Sales, Customer Insights,...
Answered

assign the ownership of the contact to the team of the user who is creating the contact using plugin

(0) ShareShare
ReportReport
Posted on by 34

Hi i have the following requirement. i am new to plugins. 

"When a new contact is created from CRM, automatically assign the ownership of the contact to the team of the user who is creating the contact"

I am not sure how to find the team using the owner field and set the team to the contact. could you please advise me? thank you, Siva

public class updateOwnership : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

var entity = context.InputParameters["Target"] as Entity;

if (entity.LogicalName != "contact")
return;
var owner = entity.GetAttributeValue<String>("ownerid");
}
}

These are few sample teams. 

pastedimage1622077323729v1.png

  • SivaR Profile Picture
    34 on at
    RE: assign the ownership of the contact to the team of the user who is creating the contact using plugin

    The following code helped me to fix the error. Thank you for the suggestion. 

    Guid teamid = result.Entities[0].GetAttributeValue<Guid>("teamid");
    EntityReference team = new EntityReference
    {
    Id = teamid,
    LogicalName = "team"
    };
    var tempContact = new Entity("contact", entity.Id);
    tempContact["ownerid"] = team;
    service.Update(tempContact);

  • Community Member Profile Picture
    on at
    RE: assign the ownership of the contact to the team of the user who is creating the contact using plugin

    Hi, Thank you for the response.

    I am running the following code and getting this error:

    Exception Message: An exception System.FormatException was thrown while trying to convert input value ' + ownerid + ' to attribute 'teammembership.systemuserid'. Expected type of attribute value: System.Guid. Exception raised: Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).

    I am not sure how to pass the ownerid. i tried the way you have suggested. i got the similar error. so i tried to pass the ownerid into the fetchxml as + ownerid +. Still getting errors. Any suggestion on how to pass the owner id into fetchXML.

    public class OwnershipUpdateToTeam : IPlugin

    {

    // When a new contact is created from CRM, automatically assign the ownership of the contact to the team of the user who is creating the contact

    public void Execute(IServiceProvider serviceProvider)

    {

    var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

    var entity  = context.InputParameters["Target"] as Entity;

    if (entity.LogicalName != "contact" || !entity.Contains("ownerid"))

    return;

    //serivice

    IOrganizationServiceFactory serviceFactory =

                           (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

    IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

    //EntityReference owner = entity.GetAttributeValue<EntityReference>("ownerid");

    Guid ownerid = entity.GetAttributeValue<EntityReference>("ownerid").Id;

    //Get user's team

    var fetchXml = $@"

    <fetch >

     <entity name='team'>

    <attribute name='teamid' />

    <attribute name='teamtype' />

      <order attribute='createdon' descending='false' />

    <filter type='and'>

     <condition attribute='teamtype' operator='eq' value='0' />

    </filter>

    <link-entity name='teammembership' from='teamid' to='teamid' visible='false' intersect='true'>  

    <filter >

          <condition attribute='systemuserid' operator='eq' value=' + ownerid + '/>

        </filter>

    </link-entity>

     </entity>

    </fetch>";

    EntityCollection result = service.RetrieveMultiple(new FetchExpression(fetchXml));

    if (result.Entities.Count > 0 )

    {

    //get the team and assign the team to owner field

    foreach (var c in result.Entities)

    {

    var team = c.Attributes["teamid"];

    var tempContact = new Entity("contact", entity.Id);

    tempContact["ownerid"] = team;

    service.Update(tempContact);

    break;

    }

    }

    }

    }

  • Verified answer
    PabloCRP Profile Picture
    1,088 on at
    RE: assign the ownership of the contact to the team of the user who is creating the contact using plugin

    Hi, I would do the next steps

    1.- retrieve the Team's users (I'll assume that the first coincidence, a user can be in multiples teams)

    2.- update current recort  if not null step one (you can update in plugin in stage 40 Post-Operation , I remember doing this in stage 20(pre-operation) trows a security error)

    using System;
    using System.Linq;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;
    
    public void Execute(IServiceProvider serviceProvider)
    {
    	var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
    	var entity = context.InputParameters["Target"] as Entity;
    	if (entity.LogicalName != "contact"|| !entity.Contains("ownerid"))
    	return;
        //serivice
        IOrganizationServiceFactory serviceFactory =
            (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
        IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
    	EntityReference owner = entity.GetAttributeValue("ownerid");
    	//Get user's team
    	var fetchXml = $@"
    	
    	  
    		
    		
    		  
    		
    	  
    	";
    	EntityCollection result = service.RetrieveMultiple(new FetchExpression(fetchXml));
    	if(result.Entities.Any()){
    		var team = result.Entities.FirstOrDefault().GetAttributeValue("teamid");
    		var tempContact = new Entity("contact",entity.Id);
    		tempContact["ownerid"] = team;
    		service.Update(tempContact);
    	}
    	
    }

    Hope it helps.

    regards

     if it was helpful please consider mark it as an answer 

  • Verified answer
    PabloCRP Profile Picture
    1,088 on at
    RE: assign the ownership of the contact to the team of the user who is creating the contact using plugin

    Hi, I would do the next steps

    1.- retrieve the Team's users (I'll assume that the first coincidence, a user can be in multiples teams)

    2.- update current recort  if not null step one (you canupdate in plugin in stage 40 Post-Operation , I remember doing this in stage 20(pre-operation) trows a security error)

    using System;
    using System.Linq;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;
    
    public void Execute(IServiceProvider serviceProvider)
    {
    	var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
    	var entity = context.InputParameters["Target"] as Entity;
    	if (entity.LogicalName != "contact"|| !entity.Contains("ownerid"))
    	return;
        //serivice
        IOrganizationServiceFactory serviceFactory =
            (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
        IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
    	EntityReference owner = entity.GetAttributeValue("ownerid");
    	//Get user's team
    	var fetchXml = $@"
    	
    	  
    		
    		
    		  
    		
    	  
    	";
    	EntityCollection result = service.RetrieveMultiple(new FetchExpression(fetchXml));
    	if(result.Entities.Any()){
    		var team = result.Entities.FirstOrDefault().GetAttributeValue("teamid");
    		var tempContact = new Entity("contact",entity.Id);
    		tempContact["ownerid"] = team;
    		service.Update(tempContact);
    	}
    	
    }

    Hope it helps.

    regards

    if it was helpful please consider mark it as an answer

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

Daivat Vartak – Community Spotlight

We are honored to recognize Daivat Vartak as our March 2025 Community…

Announcing Our 2025 Season 1 Super Users!

A new season of Super Users has arrived, and we are so grateful for the daily…

Kudos to the February Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 293,027 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 231,852 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156 Moderator

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans