Dynamics CRM 2011 getting entity has not been modified in post update - dynamics-crm-2011

I want to get the not modified entity when PostUpdate event triggered.
I try to use
context.PreEntityImages
but it is null.
How to I get this entity in PostUpdate event?

First, you need to register a pre-entityimage for the post-update step.
You can then acquire the entityimage using the following code snippet:
public void Execute(IServiceProvider serviceProvider)
{
var context = (IPluginExecutionContext) serviceProvider.GetService(typeof (IPluginExecutionContext));
Entity preImage = context.PreEntityImages.First().Value;
}

Related

Using context.InputParameters["Target"]

I am creating a plugin for Dynamics CRM 2011 to be executed when Qualifying a lead. I use this code
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory.CreateOrganizationService(null);
Entity curEntity = (Entity)context.InputParameters["Target"];
but when I get the context.InputParameters["Target"] it says that key not found. How can I get the lead entity when qualifying a Lead?
If your plugin is executed on QualifyLead message (Lead as primary entity) you can get the reference to the lead in this way:
public void Execute(IServiceProvider serviceProvider)
{
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
if (context.InputParameters.Contains("LeadId") && context.InputParameters["LeadId"] is EntityReference)
{
EntityReference leadReference = (EntityReference)context.InputParameters["LeadId"];
Guid leadId = leadReference.Id;
// rest of your code
basically this message doesn't contain Target parameter, instead it contains LeadId parameter.
I needed the name of the entity precisely because my same custom workflow was getting triggered on workflow for two different entities. Thus identifying the Target was necessary until i found "PrimaryEntityName".
context.PrimaryEntityName could be used in case someone is looking to identify which target entity the workflow was triggered on

CRM 2011 Update System User when New account created

I am trying to populate a field in the system user entity whenever a user creates an account. I keep getting errors when trying to retrieve the system user entity so that I can populate its attributes. My code is as follows:
public void Execute(IServiceProvider serviceProvider)
{
ITracingService tracingservice = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory.CreateOrganizationService(context.InitiatingUserId);
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
try
{
//Get entity that fired plugin
Entity entMain = (Entity)context.InputParameters["Target"];
//Make a String for the last activity entity
String strLastEntity = "";
//Make the entity for the user entity
Entity entUser = (Entity)service.Retrieve("systemuser", context.InitiatingUserId, new ColumnSet(new String[] { "new_lastactivityentity" }));
//Get the entity type that fired the plugin and set it to the right field for the user entity
if (entMain.LogicalName.Equals("account"))
{
strLastEntity = entMain.LogicalName;
entUser["new_lastactivityentity"] = strLastEntity;
}
}
catch (Exception ex)
{
tracingservice.Trace("FollowupPlugin: {0}", ex.ToString());
throw;
}
}
}
The error is:
Could not load file or assembly 'PluginRegistration, Version=2.1.0.1, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
Can someone explain how to get the system user so I can update its attributes?
It is because you have an assembly reference that isn't installed on the server, in particular that is PluginRegistration.
You could place that dll in the GAC on the server, however this won't work for CRM Online (or in a Sandbox registration I believe).
Is PluginRegistration a reference to the Microsoft assembly used in the plugin registration tool? Generally speaking you don't need a reference to that in your project, so you could try removing the reference.

Setting OwnerId of a custom activity

I have created a custom CRM activity that I'm using in a workflow.
I'm using this activity as an InArgument to a custom workflow activity.
In the Execute() method I'm trying to set the OwnerId of the custom CRM activity instance to a system user and calling UpdateObject(entity) on the context object that I have generated using CrmSvcUtil.
[Input("Some name")]
[ReferenceEntity("mycustomactivity")]
[Required]
public InArgument<EntityReference> MyCustomActivity{get;set;}
void Execute(CodeActivityContext context)
{
IOrganizationService svc = context.GetExtension<IOrganizationService>();
var customActivityReference = MyCustomActivity.GetValue(MyCustomActivity);
//MyServiceContext is an OrganizationServiceContext generated using CrmSvcUtil
MyServiceContext servicecontext = new MyServiceContext(svc);
//GetCutomActivityInstance uses the Id to get an instance of the custom activity)
MyCustomCRMActivity activityInstance = GetCutomActivityInstance (servicecontext,customActivityReference.Id);
activityInstance.OwnerId = new EntityReference("systemuser",<SomeGUID>);
context.UpdateObject(activityInstance);
context.SaveChanges();
}
The above does not work, the activity owner is defaulting to my crm user account and is not updated to reflect the owner I'm setting in activityInstance.OwnerId
Any help would be much appreciated.
The owner can't be changed by update. You have to use the AssignRequest (or the built-in Assign-step, see screenshot)
See this answer https://stackoverflow.com/a/7746205/315862

sharepoint object model itemadding eventreceiver

I am trying to add a event receiver on a list for itemadding. I have a field called EmployeeName people picker from which i need to get userprofile of that particular employee on item adding and trying to get EmployeeNo auto updated from userprofile.
I using as below: but not working
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
UserProfileManager profileManager = new UserProfileManager(context);
UserProfile myProfile = profileManager.GetUserProfile(item["EmployeeName"].ToString());
if (myProfile["EmployeeNo"].Value != null)
{
properties.AfterProperties["EmployeeNo"] = (myProfile["EmployeeNo"]).ToString();
}
item.Update();
}
Please help me on this.
Check if you use the correct internal column names.
Where do you get "item" from? Try using properties.ListItem instead.
Don't call properties.ListItem.update() (or item.update() in your code).

SPWorkflowActivationProperties.Item is NULL in Simple SharePoint Workflow

I have generated a C# SharePoint Sequential Workflow project using the very handy STSDEV tool (it got me around the requirement to have access to a 32-bit SharePoint installation which is required for other tools such as VSeWSS 1.3).
I've added a simple 'modify the title' action to test my basic setup:
public sealed partial class CopyWorkflow : SharePointSequentialWorkflowActivity
{
public CopyWorkflow()
{
InitializeComponent();
workflowProperties = new SPWorkflowActivationProperties();
}
public SPWorkflowActivationProperties workflowProperties;
private void onWorkflowActivated1_Invoked_1(object sender, ExternalDataEventArgs e)
{
workflowProperties.Item["Title"] = workflowProperties.Item["Title"].ToString() + ": Processed by Workflow";
workflowProperties.Item.Update();
}
}
Whoever, after installing my workflow via WSP into an installation of WSS 3.0, activating the feature, and configuring the workflow to start whenever a new item is created for a particular list, I get my breakpoint in onWorkflowActivated1_Invoked_1 hit, but the workflowProperties.Item is always NULL instead of an SPListItem representing the item that was just added.
What do I need to do to get the Item to be filled when this callback is called?
Update: I've noticed that the thread executing the workflow is running anonymously rather than as the logged in user or the system user, and therefore won't have access to the list data. Furthermore, the SharePoint log file show the following exception:
Unexpected System.ArgumentNullException: Value cannot be null. Parameter name: uriString at System.Uri..ctor(String uriString) at Microsoft.SharePoint.SPSite..ctor(String requestUrl) at Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties.<get_Site>b__0() at Microsoft.SharePoint.SPSecurity.CodeToRunElevatedWrapper(Object state) at Microsoft.SharePoint.SPSecurity.<>c__DisplayClass4.<RunWithElevatedPrivileges>b__2() at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode) at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(WaitCallback secureCode, Object param) at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(CodeToRunElevated secureCode) at Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties....
and
Unexpected ...get_Site() at Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties.get_Web() at Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties.get_Item() at BechtelWorkflow.CopyWorkflow.onWorkflowActivated1_Invoked_1(Object sender, ExternalDataEventArgs e) at System.Workflow.ComponentModel.Activity.RaiseGenericEvent[T](DependencyProperty dependencyEvent, Object sender, T e) at System.Workflow.Activities.HandleExternalEventActivity.RaiseEvent(Object[] args) at System.Workflow.Activities.HandleExternalEventActivity.Execute(ActivityExecutionContext executionContext) at System.Workflow.ComponentModel.ActivityExecutor'1.Execute(T activity, ActivityExecutionContext executionContext) at System.Workflow.ComponentModel.ActivityExecutor'1.Execute(Activity activi...
Have you bound WorkflowActivationProperties with Workflow designer?
WorkflowActivationProperties http://img718.imageshack.us/img718/9703/ss20100305091353.png
This issue occurs if the the InitialStateName of the designer in the workflow properties is not equal to "Initial state" or is pointed to other stage abruptly.
Once a state wherein we have the workflowProperties ,etc like the above image. Things start working as required.

Resources