Hi, i want to get the fetchxml result and with help of loop share contact record (the number of record is in a field) to just one user in a field with help of plugin.
I'm new to CRM and plugin any help is appreciated.
this is my code
for example number of contact to share field = 3
to whom want to share field = john smith
namespace Saedi
{
public class DistributionNumber : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory.CreateOrganizationService(context.UserId);
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity contact = (Entity)context.InputParameters["Target"];
try
{
//if (contact.Attributes.Contains("new_sharecontactnumber"))
//{
string fetchXml =
@"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""false"">
<entity name=""contact"">
<attribute name=""fullname"" />
<attribute name=""telephone1"" />
<attribute name=""contactid"" />
<order attribute=""fullname"" descending=""false"" />
<filter type=""and"">
<condition attribute=""ownerid"" operator=""eq-userid"" />
<condition attribute=""modifiedon"" operator=""today"" />
</filter>
</entity>
</fetch>";
fetchXml = string.Format(fetchXml, contact.Id);
var qe = new FetchExpression(fetchXml);
var result = service.RetrieveMultiple(qe);
if (fetchXml != null && result.Entities.Count > 0)
{
string totalcount = result.Entities.Count.ToString();
int new_sharecontactnumber = Convert.ToInt32(contact.Attributes["new_sharecontactnumber"]);
//for (int i = 0; i == result.Entities.Count; i++)
//{
for (int j = 0; j <= new_sharecontactnumber; j++)
{
//throw new InvalidPluginExecutionException("the number of records is: " + totalcount)
//Entity item = result.Entities[i];
Guid userlookupid = ((EntityReference)contact.Attributes["new_useruser"]).Id;
var UserRef = new EntityReference(((EntityReference)contact.Attributes["new_useruser"]).LogicalName, userlookupid);
GrantAccessRequest request = new GrantAccessRequest
{
PrincipalAccess = new PrincipalAccess
{
AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess,
Principal = UserRef
},
Target = new EntityReference(result[j].LogicalName, result[j].Id)
};
service.Execute(request);
}
//}
}
else
{
throw new InvalidPluginExecutionException("no record has been found");
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message);
}
}
}
}
}