Hi All,
I am getting object reference not set to an instance of an object from below code :
Below error message :
Unhandled Exception: Microsoft.Crm.CrmException: Unexpected exception from plug-in (Execute): BMS_InternalCRM.WorkflowActivities.User.GetUserBySecurityRole: System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Crm.Sandbox.SandboxCodeUnit.Execute(IExecutionContext context)
at Microsoft.Crm.Workflow.Services.ProxyCustomActivity.Execute(CodeActivityContext executionContext)
Whats wrong in the below code any idea ?
public sealed class GetUserBySecurityRole : CodeActivity
{
[Input("Security Role")]
public InArgument<string> SecurityRole { get; set; }
[Output("User")]
[ReferenceTarget("systemuser")]
public OutArgument<EntityReference> User { get; set; }
IOrganizationService service = null;
OrganizationServiceContext organizationServiceContext = null;
protected override void Execute(CodeActivityContext executionContext)
{
//Create the tracing service
ITracingService tracingService = executionContext.GetExtension<ITracingService>();
//Create the context
IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
service = serviceFactory.CreateOrganizationService(context.UserId);
//create the organization service context that gives the ability of querying
organizationServiceContext = new OrganizationServiceContext(service);
string securityRole = SecurityRole.Get<string>(executionContext);
//get the first user id from the security role
EntityReference userId = GetUserFromRoleName(securityRole);
if (userId == null)
throw new Exception("No user with security role " + securityRole + " was found.");
//set the user as the output parameter
this.User.Set(executionContext, userId);
}
private EntityReference GetUserFromRoleName(string rolename)
{
var user = (from u in organizationServiceContext.CreateQuery("systemuser")
join ur in organizationServiceContext.CreateQuery("systemuserroles") on (Guid)u["systemuserid"] equals (Guid)ur["systemuserid"]
join r in organizationServiceContext.CreateQuery("role") on (Guid)ur["roleid"] equals (Guid)r["roleid"]
where ((string)r["name"]) == rolename
select new
{
Id = u.Contains("systemuserid") ? (Guid)u["systemuserid"] : Guid.Empty,
}).FirstOrDefault();
EntityReference userRecord = new EntityReference("systemuser", user.Id);
return userRecord;
}
}
Please let me know if any one knows :
Thanks,
Jharana