-1
  1. List item

1.>I have created new plugin(fired on creation and update of any custom entity(suppose:ce1))

2.>Registered in online version.

3.>That plugin Creating Workflows(System xaml workflow using c# code) and also activating that WF.

4.>That WF creating F9..:)

5.>Problem is...:(

6.>Using a different C# App That WF is only created not activated in online version(i.e that WF is in draft mode)

7.>But it is working f9 in on premise version.

8.>It is working f9 in online also but using CRM interface.

9.>using C# application it is throwing an Error at the line where that WF is Going to be activate...Error is:Can not publish Workflows when Impersonating.

Any kind of help is appreciated...please help me...

Thanks.

Anish
  • 588
  • 6
  • 21

2 Answers2

0

Posting your plugin code would be helpful. But if you're getting the IOrganizationService using the plugin context, it might be using impersonation, and if that's the case, I'd try creating a new OrganizationServiceProxy with the correct owner and seeing if that resolves the issue.

I don't have access to an online version so this is a stab in the dark.

Daryl
  • 18,592
  • 9
  • 78
  • 145
  • Hi Daryl, That is true..but all workflows are creating and activating inside a plugin..and that plugin executes under a ofcourse single user's context and even same user's context...i.e context of that single user in plugin is same as the context of single user for Workflows... Can u ellaborate more..pls.. Thanks. – Anish Jun 27 '12 at 06:06
  • That is happening in crm online.and there is single user.AND say that user(u1)under which plugin triggered.in the same context that workflow is creating AND under same cotext that workflow is also activating... if this would be problem.. then I changed ownerid of recently created workflow with context.userid(also hardcoded id of administrator..i.e..that single user u1).. but then also not working.. giving the same error... Is there any trick behind activating workflow from plugin.Is there any kind of run time change of user..but then why it is working using CRM interface?Please help. Thanks. – Anish Jun 27 '12 at 10:09
  • @AnishwithCRM Why do you have to activate the workflow through a plugin? Normally you'd activate the workflow when you add it to CRM and not deactivate it unless it is no longer needed... – Daryl Jun 27 '12 at 12:35
  • @DarylThat is not happening here...If i will not write code to activate that created WF(recently created by PLUGIN) Then it will be just created in crm's Process but in draft mode...:( – Anish Jun 27 '12 at 13:14
  • @AnishwithCRM Your question is extremely confusing so let me be sure I understand you... You have a plugin, that creates a workflow, then activates it. It works on premise but not online, and you're trying to get it to work online? – Daryl Jun 27 '12 at 14:14
0
//Getting Service as happens in PLUGIN
IOrganizationServiceFactory serviceFactory =          (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
  IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

//Configuring xaml to create workflow    

 string xamlWfPrefix = @"<?xml version=""1.0"" encoding=""utf-16""?>
<Activity x:Class=""XrmWorkflow"" 
xmlns=""http://schemas.microsoft.com/netfx/2009/xaml/activities"" 
xmlns:mva=""clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35""
xmlns:mxs=""clr-namespace:Microsoft.Xrm.Sdk;assembly=Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" 
xmlns:mxswa=""clr-namespace:Microsoft.Xrm.Sdk.Workflow.Activities;assembly=Microsoft.Xrm.Sdk.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35""
xmlns:s=""clr-namespace:System;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" 
xmlns:scg=""clr-namespace:System.Collections.Generic;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" 
xmlns:srs=""clr-namespace:System.Runtime.Serialization;assembly=System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089""
xmlns:this=""clr-namespace:"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
  <x:Members>
    <x:Property Name=""InputEntities"" Type=""InArgument(scg:IDictionary(x:String, mxs:Entity))"" />
    <x:Property Name=""CreatedEntities"" Type=""InArgument(scg:IDictionary(x:String, mxs:Entity))"" />
  </x:Members>
  <this:XrmWorkflow.InputEntities>
    <InArgument x:TypeArguments=""scg:IDictionary(x:String, mxs:Entity)"" />
  </this:XrmWorkflow.InputEntities>
  <this:XrmWorkflow.CreatedEntities>
    <InArgument x:TypeArguments=""scg:IDictionary(x:String, mxs:Entity)"" />
  </this:XrmWorkflow.CreatedEntities>
  <mva:VisualBasic.Settings>Assembly references and imported namespaces for internal implementation</mva:VisualBasic.Settings>
  <mxswa:Workflow>
    <Sequence DisplayName=""CreateStep1"">
      <Sequence.Variables>
        <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_1"" />
        <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_2"" />
      </Sequence.Variables>
      <Assign x:TypeArguments=""mxs:Entity"" To=""[CreatedEntities(&quot;CreateStep1_localParameter#Temp&quot;)]"" Value=""[New Entity(&quot;new_crm_new_sfeed&quot;)]"" />
      <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression"">
        <mxswa:ActivityReference.Arguments>
          <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">CreateCrmType</InArgument>
          <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { Microsoft.Xrm.Sdk.Workflow.WorkflowPropertyType.String, """;

                    xamlWfPrefix += displayname + @""", ""String"" }]</InArgument>
          <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType"">
            <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" />
          </InArgument>
          <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_1]</OutArgument>
        </mxswa:ActivityReference.Arguments>
      </mxswa:ActivityReference>
      <mxswa:SetEntityProperty Attribute=""new_name"" Entity=""[CreatedEntities(&quot;CreateStep1_localParameter#Temp&quot;)]"" EntityName=""new_crm_new_sfeed"" Value=""[CreateStep1_1]"">
        <mxswa:SetEntityProperty.TargetType>
          <InArgument x:TypeArguments=""s:Type"">
            <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" />
          </InArgument>
        </mxswa:SetEntityProperty.TargetType>
      </mxswa:SetEntityProperty>
      <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression"">
        <mxswa:ActivityReference.Arguments>
          <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">CreateCrmType</InArgument>
          <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { Microsoft.Xrm.Sdk.Workflow.WorkflowPropertyType.String, """;

                    xamlWfPrefix += displayname;

                    string xamlWfSuffix = @", ""String"" }]</InArgument>
          <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType"">
            <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" />
          </InArgument>
          <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_2]</OutArgument>
        </mxswa:ActivityReference.Arguments>
      </mxswa:ActivityReference>
      <mxswa:SetEntityProperty Attribute=""new_description"" Entity=""[CreatedEntities(&quot;CreateStep1_localParameter#Temp&quot;)]"" EntityName=""new_crm_new_sfeed"" Value=""[CreateStep1_2]"">
        <mxswa:SetEntityProperty.TargetType>
          <InArgument x:TypeArguments=""s:Type"">
            <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" />
          </InArgument>
        </mxswa:SetEntityProperty.TargetType>
      </mxswa:SetEntityProperty>
      <mxswa:CreateEntity EntityId=""{x:Null}"" DisplayName=""CreateStep1"" Entity=""[CreatedEntities(&quot;CreateStep1_localParameter#Temp&quot;)]"" EntityName=""new_crm_new_sfeed"" />
      <Assign x:TypeArguments=""mxs:Entity"" To=""[CreatedEntities(&quot;CreateStep1_localParameter&quot;)]"" Value=""[CreatedEntities(&quot;CreateStep1_localParameter#Temp&quot;)]"" />
      <Persist />
    </Sequence>
  </mxswa:Workflow>
</Activity>";

       //Calling method to create total xaml code that requires to create workflow
       string xamlWf = BuildWorkflowXaml(xamlWfPrefix, xamlWfSuffix, recordCreated);
        //Initiating workflow to be create
        Workflow wfOnCreate = new Workflow()
              {
                Name = "CRM_DNNWorkflow_OnCreate",
                Type = new OptionSetValue(1),
                Category = new OptionSetValue(0),
                Scope = new OptionSetValue(2),
                LanguageCode = 1033, // U.S. English
                TriggerOnCreate = true,
                OnDemand = false,
                PrimaryEntity = logicalname, //Name of entity on which WF will be fired
                Description = @"Tracks Creation",
                Xaml = xamlWf
                    };


                    xamlWf = BuildWorkflowXaml(xamlWfPrefix, xamlWfSuffix, recordDeleted);
                   //Another WF
                    Workflow wfOnDelete = new Workflow()
                    {
                        Name = "CRM_DNNWorkflow_OnDelete",
                        Type = new OptionSetValue(1),
                        Category = new OptionSetValue(0),
                        Scope = new OptionSetValue(2),
                        LanguageCode = 1033, // U.S. English
                        TriggerOnDelete = true,
                        OnDemand = false,
                        PrimaryEntity = logicalname,
                        Description = @"Tracks Deletion",
                        Xaml = xamlWf
                    };


                    xamlWf = BuildWorkflowXaml(xamlWfPrefix, xamlWfSuffix, recordModified);
                    //Another WF
                    Workflow wfOnModify = new Workflow()
                    {
                        Name = "CRM_DNNWorkflow_OnModify",
                        Type = new OptionSetValue(1),
                        Category = new OptionSetValue(0),
                        Scope = new OptionSetValue(2),
                        LanguageCode = 1033, // U.S. English
                        TriggerOnUpdateAttributeList = attributeList,
                        OnDemand = false,
                        PrimaryEntity = logicalname,
                        Description = @"Tracks Modification",
                        Xaml = xamlWf
                    };


                    workflowOnCreateId = service.Create(wfOnCreate);
                    workflowOnDeleteId = service.Create(wfOnDelete);
                    workflowOnModifyId = service.Create(wfOnModify);           

                    //activate workflow (OnCreate)
                    ActivateWorkflow(workflowOnCreateId, service, serviceProvider);

                    //activate workflow (OnDelete)
                    ActivateWorkflow(workflowOnDeleteId, service, serviceProvider);

                    //activate workflow (OnModify)
                    ActivateWorkflow(workflowOnModifyId, service, serviceProvider);
                }
            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                tracingService.Trace("Exception: {0}", ex.ToString());
                throw;
                //throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);
            }
        }



        /// <summary>
        /// Builds the Xaml to define the function of a Workflow.
        /// </summary>
        /// <param name="prefix">Prefix to Xaml code</param>
        /// <param name="suffix">Suffix to Xaml code</param>
        /// <param name="status">Sets the description field of the new_crm_new_sfeed Entity</param>
        /// <returns></returns>
        private string BuildWorkflowXaml(string prefix,string suffix,string status)
        {
            return prefix + status + suffix;
        }



        /// <summary>
        /// Activates a Workflow.
        /// </summary>
        /// <param name="workflowId">Guid of the workflow to be created.</param>
        /// <param name="service">IOrganizationService Object.</param>
        private void ActivateWorkflow(Guid workflowId,IOrganizationService service,IServiceProvider serviceProvider) 
        {
            //Extract the tracing service for use in plug-in debugging.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            try
            {
                SetStateRequest activateRequest = new SetStateRequest
                {
                    EntityMoniker = new EntityReference(Workflow.EntityLogicalName, workflowId),
                    State = new OptionSetValue((int)WorkflowState.Activated),
                    Status = new OptionSetValue(2)
                };
                //**Error Occurs Here**
                OrganizationResponse respActivation = service.Execute(activateRequest);
                tracingService.Trace("ActivateResponse", respActivation);
                workflowGUIDs.Add(workflowId);
            }
            catch (InvalidPluginExecutionException exe)
            {
                tracingService.Trace("Exception: {0}", exe.ToString());
                throw;
            }            
        }





**FROM MY C# APPLICATION**



// Form the RetrieveOrganization Request.
   RetrieveOrganizationRequest request = new RetrieveOrganizationRequest();
   request.UniqueName = organizationUniqueName;
   RetrieveOrganizationResponse response = (RetrieveOrganizationResponse)discoveryServiceProxy.Execute(request);

// Form the URL.
   Uri uri = new Uri(response.Detail.Endpoints[EndpointType.OrganizationService]);

 //Form the OrganizationServiceProxy Object.
   orgServiceProxy = new OrganizationServiceProxy(uri, null, discoveryServiceProxy.ClientCredentials, discoveryServiceProxy.DeviceCredentials);


Entity Dnn_selectedEntity = new Entity("new_dnn_selected_entity");
Dnn_selectedEntity["new_name"] = entityMetadataId.Value.ToString();
Dnn_selectedEntity["new_trackedentity"] = entityMetadataId.Key;
orgServiceProxy.Create(Dnn_selectedEntity);
//After Creting this record That Plugin fires....



Thanks.
Anish
  • 588
  • 6
  • 21