public void Execute_correct_pairs()
        {
            var service = Substitute.For <IOrganizationService>();

            service.Execute(Arg.Any <OrganizationRequest>()).Returns((OrganizationResponse)null);

            QualifyLeadResponse qualifyLeadResponse = service.Send(new QualifyLeadRequest());
            WhoAmIResponse      whoAmIResponse      = service.Send(new WhoAmIRequest());
        }
        public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx)
        {
            var req = request as QualifyLeadRequest;

            var orgService = ctx.GetOrganizationService();

            if (req.LeadId == null)
            {
                throw new Exception("Lead Id must be set in request.");
            }

            var leads = (from l in ctx.CreateQuery("lead")
                         where l.Id == req.LeadId.Id
                         select l);

            var leadsCount = leads.Count();

            if (leadsCount != 1)
            {
                throw new Exception(string.Format("Number of Leads by given LeadId should be 1. Instead it is {0}.", leadsCount));
            }

            // Made here to get access to CreatedEntities collection
            var response = new QualifyLeadResponse();

            response["CreatedEntities"] = new EntityReferenceCollection();

            // Create Account
            if (req.CreateAccount) // ParentAccount
            {
                var account = new Entity("account")
                {
                    Id = Guid.NewGuid()
                };
                account.Attributes["originatingleadid"] = req.LeadId;
                orgService.Create(account);
                response.CreatedEntities.Add(account.ToEntityReference());
            }

            // Create Contact
            if (req.CreateContact)
            {
                var contact = new Entity("contact")
                {
                    Id = Guid.NewGuid()
                };
                contact.Attributes["originatingleadid"] = req.LeadId;
                orgService.Create(contact);
                response.CreatedEntities.Add(contact.ToEntityReference());
            }

            // Create Opportunity
            if (req.CreateOpportunity)
            {
                var opportunity = new Entity("opportunity")
                {
                    Id = Guid.NewGuid()
                };

                // Set OpportunityCurrencyId if given
                // MSDN link:
                // https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.qualifyleadrequest.opportunitycurrencyid.aspx
                if (req.OpportunityCurrencyId != null)
                {
                    opportunity.Attributes["transactioncurrencyid"] = req.OpportunityCurrencyId;
                }

                // Associate Account or Contact with Opportunity
                // MSDN link:
                // https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.qualifyleadrequest.opportunitycustomerid.aspx
                if (req.OpportunityCustomerId != null)
                {
                    var logicalName = req.OpportunityCustomerId.LogicalName;

                    // Associate Account or Contact
                    if (logicalName.Equals("account") || logicalName.Equals("contact"))
                    {
                        opportunity.Attributes["customerid"] = req.OpportunityCustomerId;
                    }
                    // Wrong Entity was given as parameter
                    else
                    {
                        throw new Exception(string.Format("Opportunity Customer Id should be connected with Account or Contact. Instead OpportunityCustomerId was given with Entity.LogicalName = {0}", logicalName));
                    }
                }

                opportunity.Attributes["originatingleadid"] = req.LeadId;
                orgService.Create(opportunity);
                response.CreatedEntities.Add(opportunity.ToEntityReference());
            }

            // Actual Lead
            var lead = leads.First();

            lead.Attributes["statuscode"] = new OptionSetValue(req.Status.Value);
            orgService.Update(lead);

            return(response);
        }
Example #3
0
        protected override void Execute(PluginContext context)
        {
            context.TracingService.Trace("enter qualifylead 1.0.0 version");

            string leadId    = context.GetInputParameter <string>("leadid");
            string contactId = context.GetInputParameter <string>("contactid");
            string userId    = context.GetInputParameter <string>("userid");

            context.TracingService.Trace("qualifylead leadId='{0}',contactId='{1}',userId='{2}'", leadId, contactId, userId);

            Lead lead         = GetLead(new Guid(leadId), context.OrganizationService);
            bool needToUpdate = false;

            Lead proxyLead = new Lead
            {
                Id = lead.Id
            };

            context.TracingService.Trace("get lead data");

            if (lead.ParentContact == null && string.IsNullOrEmpty(contactId))
            {
                context.TracingService.Trace("set new contact data");
                Contact contact = new Contact
                {
                    FirstName                       = lead.FirstName
                    , LastName                      = lead.LastName
                    , MiddleName                    = lead.MiddleName
                    , MobilePhone                   = lead.MobilePhone
                    , EmailAddress1                 = lead.EmailAddress1
                    , CustomerType                  = lead.CustomerType ?? Contact.CustomerTypeEnum.Individual
                    , GenderCode                    = lead.GenderCode ?? Contact.GenderEnum.Unknown
                    , Store                         = lead.Store
                    , CommunicationConsent          = lead.CommunicationConsent
                    , PersonalDataProcessingConsent = lead.PersonalDataProcessingConsent
                };

                context.TracingService.Trace("create new contact");
                contact.Id              = context.OrganizationService.Create(contact);
                lead.ParentContact      = contact.ToEntityReference();
                proxyLead.ParentContact = contact.ToEntityReference();
                needToUpdate            = true;
            }
            else
            {
                if (!string.IsNullOrEmpty(contactId))
                {
                    if (lead.Contact == null)
                    {
                        context.TracingService.Trace("set contact data");
                        proxyLead.ParentContact = new EntityReference(Contact.EntityLogicalName, new Guid(contactId));
                        lead.ParentContact      = new EntityReference(Contact.EntityLogicalName, new Guid(contactId));
                        needToUpdate            = true;
                    }
                }
            }

            if (needToUpdate)
            {
                context.TracingService.Trace("update contact on lead");
                context.OrganizationService.Update(proxyLead);
            }

            QualifyLeadRequest qualifyLeadRequest = new QualifyLeadRequest
            {
                CreateAccount         = false,
                CreateContact         = false,
                CreateOpportunity     = true,
                LeadId                = lead.ToEntityReference(),
                OpportunityCustomerId = lead.ParentContact,
                Status                = new OptionSetValue((int)Lead.LeadStatusCode.Qualified)
            };

            context.TracingService.Trace("call request");
            QualifyLeadResponse qualifyLeadResponse = (QualifyLeadResponse)context.OrganizationService.Execute(qualifyLeadRequest);

            context.TracingService.Trace("get response");

            context.TracingService.Trace("get response {0} items", qualifyLeadResponse.CreatedEntities.Count());

            foreach (var data in qualifyLeadResponse.CreatedEntities)
            {
                context.TracingService.Trace(data.LogicalName);

                if (data.LogicalName == Opportunity.EntityLogicalName)
                {
                    context.TracingService.Trace("set outputparameter opportunityid {0}", data.Id);
                    context.SetOutputParameter("opportunityid", data.Id.ToString());
                    context.SetOutputParameter("Error", string.Empty);

                    Team team = GetTeam(new Guid(userId), context.OrganizationService, context.TracingService);

                    EntityReference projectTypeId = null;
                    if (team != null)
                    {
                        context.TracingService.Trace("team '{0}', {1}", team.Name, team.Id);
                        projectTypeId = team.ProjectTypeId ?? null;

                        if (projectTypeId != null)
                        {
                            context.TracingService.Trace("project '{0}'", projectTypeId.Name);
                        }
                    }

                    Opportunity opportunity = new Opportunity
                    {
                        Id            = data.Id
                        , Description = lead.Comment
                        , Store       = lead.Store ?? null
                        , ProjectType = projectTypeId ?? null
                    };
                    context.OrganizationService.Update(opportunity);
                    context.TracingService.Trace("update opportunity");
                }
            }
        }
Example #4
0
        /// <summary>
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Creates required records for this sample.
                    CreateRequiredRecords();

                    // Qualify a lead to create an opportunity
                    QualifyLeadRequest qualifyRequest = new QualifyLeadRequest
                    {
                        LeadId            = new EntityReference(Lead.EntityLogicalName, _leadId),
                        Status            = new OptionSetValue((int)lead_statuscode.Qualified),
                        CreateOpportunity = true
                    };
                    QualifyLeadResponse qualifyResponse = (QualifyLeadResponse)_serviceProxy.Execute(qualifyRequest);
                    _opportunityId = qualifyResponse.CreatedEntities[0].Id;
                    if (_opportunityId != Guid.Empty)
                    {
                        Console.WriteLine("\nQualified Lead to create an Opportunity record.");
                    }

                    // Verify the curently active BPF instance for the qualified Opportunity record
                    RetrieveProcessInstancesRequest procOpp1Req = new RetrieveProcessInstancesRequest
                    {
                        EntityId          = _opportunityId,
                        EntityLogicalName = Opportunity.EntityLogicalName
                    };
                    RetrieveProcessInstancesResponse procOpp1Resp = (RetrieveProcessInstancesResponse)_serviceProxy.Execute(procOpp1Req);

                    // Declare variables to store values returned in response
                    Entity activeProcessInstance = null;

                    if (procOpp1Resp.Processes.Entities.Count > 0)
                    {
                        activeProcessInstance = procOpp1Resp.Processes.Entities[0]; // First record is the active process instance
                        _processOpp1Id        = activeProcessInstance.Id;           // Id of the active process instance, which will be used
                                                                                    // later to retrieve the active path of the process instance

                        Console.WriteLine("Current active process instance for the Opportunity record: '{0}'", activeProcessInstance["name"].ToString());
                        _procInstanceLogicalName = activeProcessInstance["name"].ToString().Replace(" ", string.Empty).ToLower();
                    }
                    else
                    {
                        Console.WriteLine("No process instances found for the opportunity record; aborting the sample.");
                        Environment.Exit(1);
                    }

                    // Retrieve the active stage ID of the active process instance
                    _activeStageId = new Guid(activeProcessInstance.Attributes["processstageid"].ToString());

                    // Retrieve the process stages in the active path of the current process instance
                    RetrieveActivePathRequest pathReq = new RetrieveActivePathRequest
                    {
                        ProcessInstanceId = _processOpp1Id
                    };
                    RetrieveActivePathResponse pathResp = (RetrieveActivePathResponse)_serviceProxy.Execute(pathReq);
                    Console.WriteLine("\nRetrieved stages in the active path of the process instance:");
                    for (int i = 0; i < pathResp.ProcessStages.Entities.Count; i++)
                    {
                        Console.WriteLine("\tStage {0}: {1} (StageId: {2})", i + 1,
                                          pathResp.ProcessStages.Entities[i].Attributes["stagename"], pathResp.ProcessStages.Entities[i].Attributes["processstageid"]);


                        // Retrieve the active stage name and active stage position based on the activeStageId for the process instance
                        if (pathResp.ProcessStages.Entities[i].Attributes["processstageid"].ToString() == _activeStageId.ToString())
                        {
                            _activeStageName     = pathResp.ProcessStages.Entities[i].Attributes["stagename"].ToString();
                            _activeStagePosition = i;
                        }
                    }

                    // Display the active stage name and Id
                    Console.WriteLine("\nActive stage for the process instance: '{0}' (StageID: {1})", _activeStageName, _activeStageId);

                    // Prompt the user to move to the next stage. If user choses to do so:
                    // Set the next stage (_activeStagePosition + 1) as the active stage for the process instance
                    bool moveToNextStage = true;
                    Console.WriteLine("\nDo you want to move to the next stage (y/n):");
                    String answer = Console.ReadLine();
                    moveToNextStage = (answer.StartsWith("y") || answer.StartsWith("Y"));
                    if (moveToNextStage)
                    {
                        // Retrieve the stage ID of the next stage that you want to set as active
                        _activeStageId = (Guid)pathResp.ProcessStages.Entities[_activeStagePosition + 1].Attributes["processstageid"];

                        // Retrieve the process instance record to update its active stage
                        ColumnSet cols1 = new ColumnSet();
                        cols1.AddColumn("activestageid");
                        Entity retrievedProcessInstance = _serviceProxy.Retrieve(_procInstanceLogicalName, _processOpp1Id, cols1);

                        // Update the active stage to the next stage
                        retrievedProcessInstance["activestageid"] = new EntityReference(ProcessStage.EntityLogicalName, _activeStageId);
                        _serviceProxy.Update(retrievedProcessInstance);


                        // Retrieve the process instance record again to verify its active stage information
                        ColumnSet cols2 = new ColumnSet();
                        cols2.AddColumn("activestageid");
                        Entity retrievedProcessInstance1 = _serviceProxy.Retrieve(_procInstanceLogicalName, _processOpp1Id, cols2);

                        EntityReference activeStageInfo = retrievedProcessInstance1["activestageid"] as EntityReference;
                        if (activeStageInfo.Id == _activeStageId)
                        {
                            Console.WriteLine("\nChanged active stage for the process instance to: '{0}' (StageID: {1})",
                                              activeStageInfo.Name, activeStageInfo.Id);
                        }
                    }

                    // Prompts to delete the required records
                    DeleteRequiredRecords(promptForDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics 365 throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }