public void Check_if_Opportunity_was_created_after_sending_request() { var context = new XrmFakedContext(); context.ProxyTypesAssembly = Assembly.GetExecutingAssembly(); var service = context.GetFakedOrganizationService(); var lead = new Lead() { Id = Guid.NewGuid() }; context.Initialize(new[] { lead }); var request = new QualifyLeadRequest() { CreateAccount = false, CreateContact = false, CreateOpportunity = true, LeadId = lead.ToEntityReference(), Status = new OptionSetValue((int)LeadState.Qualified) }; service.Execute(request); var opportunity = (from opp in context.CreateQuery <Opportunity>() where opp.OriginatingLeadId.Id == lead.Id select opp).First(); Assert.NotNull(opportunity); }
public void Status_of_qualified_Lead_should_be_qualified() { var context = new XrmFakedContext(); var service = context.GetOrganizationService(); var lead = new Lead() { Id = Guid.NewGuid() }; context.Initialize(new List <Entity>() { lead }); var request = new QualifyLeadRequest() { CreateAccount = false, CreateContact = false, CreateOpportunity = false, LeadId = lead.ToEntityReference(), Status = new OptionSetValue((int)LeadState.Qualified) }; service.Execute(request); var qualifiedLead = (from l in context.CreateQuery <Lead>() where l.Id == lead.Id select l).Single(); Assert.Equal((int)LeadState.Qualified, qualifiedLead.StatusCode.Value); }
public QualifyLeadResponse QualifyLead(EntityReference entityReference, bool createAccount, bool createContact, bool createOpportunity, EntityReference opportunityCurrencyId, EntityReference opportunityCustomerId) { var portal = PortalCrmConfigurationManager.CreatePortalContext(); var context = portal.ServiceContext; if (opportunityCurrencyId == null) { var currency = context.CreateQuery("transactioncurrency").FirstOrDefault( c => c.GetAttributeValue <string>("currencyname") == "US Dollar") ?? context.CreateQuery("transactioncurrency").FirstOrDefault(); if (currency != null) { opportunityCurrencyId = currency.ToEntityReference(); } } //start with the case of creating contact, account, AND opportunity var qualifyLeadReq = new QualifyLeadRequest { CreateAccount = true, CreateContact = true, CreateOpportunity = true, LeadId = entityReference, OpportunityCurrencyId = opportunityCurrencyId, Status = new OptionSetValue((int)LeadStatusCode.Qualified) }; var qualifyLeadResponse = (QualifyLeadResponse)context.Execute(qualifyLeadReq); return(qualifyLeadResponse); }
public async Task <List <Entity> > QualifyLeadAsync(QualifyLeadRequest action) { string fullUrl = $"{ApiUrl}/leads({action.LeadId:P})/Microsoft.Dynamics.CRM.QualifyLead"; JObject jObject = action.GetRequestObject(); var request = new HttpRequestMessage(new HttpMethod("POST"), fullUrl) { Content = new StringContent(JsonConvert.SerializeObject(jObject), Encoding.UTF8, "application/json") }; HttpResponseMessage response = await Authorization.GetHttpClient().SendAsync(request); ResponseValidator.EnsureSuccessStatusCode(response); string responseContent = await response.Content.ReadAsStringAsync(); var data = JsonConvert.DeserializeObject <JObject>(responseContent); List <Entity> entities = QualifyLeadResponseFormatter.GetCreatedEntities(data); foreach (Entity entity in entities) { EntityDefinition entityDefinition = WebApiMetadata.GetEntityDefinition(entity.LogicalName); string primaryKey = entityDefinition?.PrimaryIdAttribute; if (entity.Contains(primaryKey)) { entity.Id = Guid.Parse(entity.GetAttributeValue <string>(primaryKey)); } } return(entities); }
public override EntityReferenceCollection Execute() { EntityReference aliasRef = _crmContext.RecordCache[_alias]; var lead = new Lead(GlobalTestingContext.ConnectionManager.CurrentConnection.Retrieve(aliasRef, new ColumnSet(Lead.Fields.TransactionCurrencyId, Lead.Fields.CustomerId, Lead.Fields.CampaignId))); Logger.WriteLine($"Qualifying Lead {lead.Id}"); QualifyLeadRequest req = lead.CreateQualifyLeadRequest(_createAccount, _createContact, _createOpportunity); return(GlobalTestingContext.ConnectionManager.CurrentConnection.Execute <QualifyLeadResponse>(req).CreatedEntities); }
protected override void Execute(CodeActivityContext executionContext) { #region "Load CRM Service from context" Common objCommon = new Common(executionContext); objCommon.tracingService.Trace("Load CRM Service from context --- OK"); #endregion #region "Read Parameters" EntityReference lead = this.Lead.Get(executionContext); if (lead == null) { return; } bool createAccount = this.CreateAccount.Get(executionContext); bool createContact = this.CreateContact.Get(executionContext); bool createOpportunity = this.CreateOpportunity.Get(executionContext); EntityReference existingAccount = this.ExistingAccount.Get(executionContext); int leadStatus = this.LeadStatus.Get(executionContext); objCommon.tracingService.Trace("LeadID=" + lead.Id); #endregion #region "QualifyLead Execution" var query = new QueryExpression("organization"); query.ColumnSet = new ColumnSet("basecurrencyid"); var result = objCommon.service.RetrieveMultiple(query); var currencyId = (EntityReference)result.Entities[0]["basecurrencyid"]; var qualifyIntoOpportunityReq = new QualifyLeadRequest(); qualifyIntoOpportunityReq.CreateOpportunity = createOpportunity; qualifyIntoOpportunityReq.CreateAccount = createAccount; qualifyIntoOpportunityReq.CreateContact = createContact; qualifyIntoOpportunityReq.OpportunityCurrencyId = currencyId; if (existingAccount != null) { qualifyIntoOpportunityReq.OpportunityCustomerId = new EntityReference( "account", existingAccount.Id); } qualifyIntoOpportunityReq.Status = new OptionSetValue(leadStatus); qualifyIntoOpportunityReq.LeadId = new EntityReference("lead", lead.Id); var qualifyIntoOpportunityRes = (QualifyLeadResponse)objCommon.service.Execute(qualifyIntoOpportunityReq); Console.WriteLine(" Executed OK."); #endregion }
/// <summary> /// <c>Qualify</c> a <c>Lead</c> and create an account, contact, or opportunity records that are linked to the originating lead. /// <para> /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.qualifyleadrequest(v=crm.8).aspx /// </para> /// </summary> /// <param name="id"><c>Lead</c> Id</param> /// <param name="qualifyTo">Lead qualified to entity type</param> /// <param name="existingRecordType">Existing record entity type</param> /// <param name="existingRecordId">If you qualify with existing record (account or contact) set record Id</param> /// <param name="currencyId"> /// If you want create an <c>Opportunity</c> set <c>TransactionCurrency Id</c>, otherwise leave NULL. /// <para> /// If you want create an <c>Opportunity</c> and do not know / sure <c>TransactionCurrency Id</c> leave NULL, this method will find <c>TransactionCurrency Id</c> /// </para> /// </param> /// <param name="campaignId"></param> /// <param name="status"><see cref="LeadQualifiedStatusCode"/> status code</param> /// <param name="customStatusCode">If you're using your custom statuscodes set this, otherwise you can set "0 (zero)" or null</param> /// <returns>Resturns created entities after qualification in <see cref="QualifyLeadResponse.CreatedEntities"/> property.</returns> public QualifyLeadResponse Qualify(Guid id, QualifyLeadTo qualifyTo, ExistingEntityType?existingRecordType, Guid?existingRecordId, Guid?currencyId, Guid?campaignId, LeadQualifiedStatusCode status = LeadQualifiedStatusCode.Qualified, int customStatusCode = 0) { ExceptionThrow.IfGuidEmpty(id, "id"); ExceptionThrow.IfNegative((int)qualifyTo, "qualifyTo"); int statusCode = (int)status; if (status == LeadQualifiedStatusCode.CustomStatusCode) { ExceptionThrow.IfNegative(customStatusCode, "customStatusCode"); statusCode = customStatusCode; } bool isAccount = (qualifyTo.HasFlag(QualifyLeadTo.Account) || qualifyTo.HasFlag(QualifyLeadTo.AccountAndContact) || qualifyTo.HasFlag(QualifyLeadTo.OpportunityWithAccountAndContact)) && !qualifyTo.HasFlag(QualifyLeadTo.None); bool isContact = (qualifyTo.HasFlag(QualifyLeadTo.Contact) || qualifyTo.HasFlag(QualifyLeadTo.AccountAndContact) || qualifyTo.HasFlag(QualifyLeadTo.OpportunityWithContact) || qualifyTo.HasFlag(QualifyLeadTo.OpportunityWithAccountAndContact)) && !qualifyTo.HasFlag(QualifyLeadTo.None); bool isOpportunity = (qualifyTo.HasFlag(QualifyLeadTo.OpportunityWithContact) || qualifyTo.HasFlag(QualifyLeadTo.OpportunityWithAccountAndContact) || qualifyTo.HasFlag(QualifyLeadTo.OpportunityWithExistingRecord)) && !qualifyTo.HasFlag(QualifyLeadTo.None); QualifyLeadRequest request = new QualifyLeadRequest() { LeadId = new EntityReference(this.EntityName.ToLower(), id), CreateAccount = isAccount, CreateContact = isContact, CreateOpportunity = isOpportunity, Status = new OptionSetValue(statusCode) }; if (campaignId.HasValue) { ExceptionThrow.IfGuid(campaignId.Value, "campaignId"); request.SourceCampaignId = new EntityReference("campaign", campaignId.Value); } if (isOpportunity) { var currencyEntityReference = currencyId.HasValue && !currencyId.Value.IsGuidEmpty() ? new EntityReference("transactioncurrency", currencyId.Value) : GetTransactionCurrency("lead", id); ExceptionThrow.IfNull(currencyEntityReference, "OpportunityCurrency"); ExceptionThrow.IfGuidEmpty(currencyEntityReference.Id, "OpportunityCurrency.Id"); request.OpportunityCurrencyId = currencyEntityReference; if (qualifyTo.HasFlag(QualifyLeadTo.OpportunityWithExistingRecord)) { ExceptionThrow.IfNull(existingRecordType, "existingRecordType"); ExceptionThrow.IfGuidEmpty(existingRecordId.Value, "existingRecordId"); request.OpportunityCustomerId = new EntityReference(existingRecordType.Description(), existingRecordId.Value); } } return((QualifyLeadResponse)this.OrganizationService.Execute(request)); }
public QualifyLeadRequest CreateQualifyLeadRequest(bool createAccount, bool createContact, bool createOpportunity) { var req = new QualifyLeadRequest() { CreateAccount = createAccount, CreateContact = createContact, CreateOpportunity = createOpportunity, LeadId = _lead.ToEntityReference(), OpportunityCurrencyId = Currency, OpportunityCustomerId = Customer, SourceCampaignId = Campaign, Status = new OptionSetValue((int)Lead_StatusCode.Qualified) }; req.Parameters.Add("SuppressDuplicateDetection", true); return(req); }
public void PerformTestSetup() { MessageName = "QualifyLead"; var accountEntity = EntityFactory.CreateAccount(); var campaignEntity = EntityFactory.CreateCampaign(); var leadEntity = EntityFactory.CreateLead(); QualifyLeadRequest = new QualifyLeadRequest { CreateAccount = true, CreateContact = true, CreateOpportunity = true, LeadId = leadEntity.ToEntityReference(), OpportunityCurrencyId = CrmReader.GetCurrencyId(), OpportunityCustomerId = accountEntity.ToEntityReference(), SourceCampaignId = campaignEntity.ToEntityReference(), Status = new OptionSetValue(3) }; }
protected override void ExecuteWorkflowLogic() { var qualifyLeadRequest = new QualifyLeadRequest() { CreateAccount = IsCreateAccont.Get(Context.ExecutionContext), CreateContact = IsCreateContact.Get(Context.ExecutionContext), CreateOpportunity = IsCreateOpportunity.Get(Context.ExecutionContext), LeadId = Lead.Get(Context.ExecutionContext), Status = LeadStatus.Get(Context.ExecutionContext), OpportunityCurrencyId = Currency.Get(Context.ExecutionContext) }; if (OpportunityCustomerAccount.Get(Context.ExecutionContext) != null) { qualifyLeadRequest.OpportunityCustomerId = OpportunityCustomerAccount.Get(Context.ExecutionContext); } else if (OpportunityCustomerContact.Get(Context.ExecutionContext) != null) { qualifyLeadRequest.OpportunityCustomerId = OpportunityCustomerContact.Get(Context.ExecutionContext); } var qualifyLeadResponse = (QualifyLeadResponse)Context.UserService.Execute(qualifyLeadRequest); foreach (var createdEntity in qualifyLeadResponse.CreatedEntities) { switch (createdEntity.LogicalName) { case "account": Account.Set(Context.ExecutionContext, createdEntity); break; case "contact": Contact.Set(Context.ExecutionContext, createdEntity); break; case "opportunity": Opportunity.Set(Context.ExecutionContext, createdEntity); break; } } }
public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); Console.WriteLine("=== Creating and Qualifying Leads ==="); // Create two leads. var lead1 = new Lead { CompanyName = "A. Datum Corporation", FirstName = "Henriette", LastName = "Andersen", Subject = "Sample Lead 1" }; _lead1Id = _serviceProxy.Create(lead1); NotifyEntityCreated(Lead.EntityLogicalName, _lead1Id); var lead2 = new Lead { CompanyName = "Adventure Works", FirstName = "Michael", LastName = "Sullivan", Subject = "Sample Lead 2" }; _lead2Id = _serviceProxy.Create(lead2); NotifyEntityCreated(Lead.EntityLogicalName, _lead2Id); //<snippetWorkingWithLeads1> // Qualify the first lead, creating an account and a contact from it, but // not creating an opportunity. var qualifyIntoAccountContactReq = new QualifyLeadRequest { CreateAccount = true, CreateContact = true, LeadId = new EntityReference(Lead.EntityLogicalName, _lead1Id), Status = new OptionSetValue((int)lead_statuscode.Qualified) }; var qualifyIntoAccountContactRes = (QualifyLeadResponse)_serviceProxy.Execute(qualifyIntoAccountContactReq); Console.WriteLine(" The first lead was qualified."); //</snippetWorkingWithLeads1> foreach (var entity in qualifyIntoAccountContactRes.CreatedEntities) { NotifyEntityCreated(entity.LogicalName, entity.Id); if (entity.LogicalName == Account.EntityLogicalName) { _leadAccountId = entity.Id; } else if (entity.LogicalName == Contact.EntityLogicalName) { _contactId = entity.Id; } } // Retrieve the organization's base currency ID for setting the // transaction currency of the opportunity. var query = new QueryExpression("organization"); query.ColumnSet = new ColumnSet("basecurrencyid"); var result = _serviceProxy.RetrieveMultiple(query); var currencyId = (EntityReference)result.Entities[0]["basecurrencyid"]; // Qualify the second lead, creating an opportunity from it, and not // creating an account or a contact. We use an existing account for the // opportunity customer instead. var qualifyIntoOpportunityReq = new QualifyLeadRequest { CreateOpportunity = true, OpportunityCurrencyId = currencyId, OpportunityCustomerId = new EntityReference( Account.EntityLogicalName, _accountId), Status = new OptionSetValue((int)lead_statuscode.Qualified), LeadId = new EntityReference(Lead.EntityLogicalName, _lead2Id) }; var qualifyIntoOpportunityRes = (QualifyLeadResponse)_serviceProxy.Execute(qualifyIntoOpportunityReq); Console.WriteLine(" The second lead was qualified."); foreach (var entity in qualifyIntoOpportunityRes.CreatedEntities) { NotifyEntityCreated(entity.LogicalName, entity.Id); if (entity.LogicalName == Opportunity.EntityLogicalName) { _opportunityId = entity.Id; } } DeleteRecords(promptforDelete); } }
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"); } } }
private void PostToRecordWalls() { Console.WriteLine("\r\n== Working with Record Walls =="); // Create the leads. CreateRequiredRecords(); // Follow each of the leads. _follow1 = new PostFollow { RegardingObjectId = _lead1.ToEntityReference() }; _serviceContext.AddObject(_follow1); _follow2 = new PostFollow { RegardingObjectId = _lead2.ToEntityReference() }; _serviceContext.AddObject(_follow2); _follow3 = new PostFollow { RegardingObjectId = _lead3.ToEntityReference() }; _serviceContext.AddObject(_follow3); _serviceContext.SaveChanges(); Console.WriteLine(" The 3 leads are now followed."); // Create posts, mentions, and comments related to the leads. // Create a post related to lead 1 with a mention and a comment. _leadPost1 = new Post { RegardingObjectId = _lead1.ToEntityReference(), Source = new OptionSetValue((int)PostSource.AutoPost), // Include a mention in the post text. Text = String.Format("This lead is similar to @[{0},{1},\"{2}\"]", Lead.EntityTypeCode, _lead2.Id, _lead2.FullName) }; _serviceContext.AddObject(_leadPost1); _serviceContext.SaveChanges(); Console.WriteLine(" Post 1 has been created."); // It isn't necessary to keep track of the comment because the comment will // be deleted when its parent post is deleted. var comment1 = new PostComment { PostId = _leadPost1.ToEntityReference(), Text = "Sample comment 1" }; _serviceContext.AddObject(comment1); _serviceContext.SaveChanges(); Console.WriteLine(" Comment 1 has been created."); // Create a post related to lead 2 with three comments. var post2 = new Post { RegardingObjectId = _lead2.ToEntityReference(), Source = new OptionSetValue((int)PostSource.ManualPost), Text = "This lead was created for a sample." }; _serviceContext.AddObject(post2); _serviceContext.SaveChanges(); Console.WriteLine(" Post 2 has been created."); var comment2 = new PostComment { PostId = post2.ToEntityReference(), Text = "Sample comment 2" }; var comment3 = new PostComment { PostId = post2.ToEntityReference(), Text = "Sample comment 3" }; var comment4 = new PostComment { PostId = post2.ToEntityReference(), Text = "Sample comment 4" }; _serviceContext.AddObject(comment2); _serviceContext.AddObject(comment3); _serviceContext.AddObject(comment4); _serviceContext.SaveChanges(); Console.WriteLine(" Comments 2, 3, and 4 have been created."); // Qualify some leads. Since there is an active post rule config for // qualification of a lead, this should generate an auto post to the record // wall of each lead that is qualified. // Qualify lead 2. var qualifyLead2Request = new QualifyLeadRequest { CreateAccount = true, LeadId = _lead2.ToEntityReference(), Status = new OptionSetValue((int)lead_statuscode.Qualified) }; var qualifyLead2Response = (QualifyLeadResponse)_serviceProxy.Execute( qualifyLead2Request); // Store the generated Account to delete it later. foreach (var entityRef in qualifyLead2Response.CreatedEntities) { _generatedEntities.Add(entityRef); } Console.WriteLine(" Lead 2 was qualified."); // Qualify lead 3. var qualifyLead3Request = new QualifyLeadRequest { CreateAccount = true, LeadId = _lead3.ToEntityReference(), Status = new OptionSetValue((int)lead_statuscode.Qualified) }; var qualifyLead3Response = (QualifyLeadResponse)_serviceProxy.Execute( qualifyLead3Request); foreach (var entityRef in qualifyLead3Response.CreatedEntities) { _generatedEntities.Add(entityRef); } Console.WriteLine(" Lead 3 was qualified."); }
/// <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; } }
[STAThread] // Required to support the interactive login experience static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { // Create any entity records that the demonstration code requires SetUpSample(service); #region Demonstrate /// <summary> /// Function to set up the sample. /// </summary> /// <param name="service">Specifies the service to connect to.</param> /// Console.WriteLine("=== Creating and Qualifying Leads ==="); // Create two leads. var lead1 = new Lead { CompanyName = "A. Datum Corporation", FirstName = "Henriette", LastName = "Andersen", Subject = "Sample Lead 1" }; _lead1Id = service.Create(lead1); NotifyEntityCreated(Lead.EntityLogicalName, _lead1Id); var lead2 = new Lead { CompanyName = "Adventure Works", FirstName = "Michael", LastName = "Sullivan", Subject = "Sample Lead 2" }; _lead2Id = service.Create(lead2); NotifyEntityCreated(Lead.EntityLogicalName, _lead2Id); // Qualify the first lead, creating an account and a contact from it, but // not creating an opportunity. var qualifyIntoAccountContactReq = new QualifyLeadRequest { CreateAccount = true, CreateContact = true, LeadId = new EntityReference(Lead.EntityLogicalName, _lead1Id), Status = new OptionSetValue((int)lead_statuscode.Qualified) }; var qualifyIntoAccountContactRes = (QualifyLeadResponse)service.Execute(qualifyIntoAccountContactReq); Console.WriteLine(" The first lead was qualified."); foreach (var entity in qualifyIntoAccountContactRes.CreatedEntities) { NotifyEntityCreated(entity.LogicalName, entity.Id); if (entity.LogicalName == Account.EntityLogicalName) { _leadAccountId = entity.Id; } else if (entity.LogicalName == Contact.EntityLogicalName) { _contactId = entity.Id; } } // Retrieve the organization's base currency ID for setting the // transaction currency of the opportunity. var query = new QueryExpression("organization"); query.ColumnSet = new ColumnSet("basecurrencyid"); var result = service.RetrieveMultiple(query); var currencyId = (EntityReference)result.Entities[0]["basecurrencyid"]; // Qualify the second lead, creating an opportunity from it, and not // creating an account or a contact. We use an existing account for the // opportunity customer instead. var qualifyIntoOpportunityReq = new QualifyLeadRequest { CreateOpportunity = true, OpportunityCurrencyId = currencyId, OpportunityCustomerId = new EntityReference( Account.EntityLogicalName, _accountId), Status = new OptionSetValue((int)lead_statuscode.Qualified), LeadId = new EntityReference(Lead.EntityLogicalName, _lead2Id) }; var qualifyIntoOpportunityRes = (QualifyLeadResponse)service.Execute(qualifyIntoOpportunityReq); Console.WriteLine(" The second lead was qualified."); foreach (var entity in qualifyIntoOpportunityRes.CreatedEntities) { NotifyEntityCreated(entity.LogicalName, entity.Id); if (entity.LogicalName == Opportunity.EntityLogicalName) { _opportunityId = entity.Id; } } DeleteRequiredRecords(service, prompt); } #endregion else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
public void QualifyLead(QualifyLeadRequest action) { QualifyLeadAsync(action).GetAwaiter().GetResult(); }
public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); Console.WriteLine("=== Creating and Qualifying Leads ==="); // Create two leads. var lead1 = new Lead { CompanyName = "A. Datum Corporation", FirstName = "Henriette", LastName = "Andersen", Subject = "Sample Lead 1" }; _lead1Id = _serviceProxy.Create(lead1); NotifyEntityCreated(Lead.EntityLogicalName, _lead1Id); var lead2 = new Lead { CompanyName = "Adventure Works", FirstName = "Michael", LastName = "Sullivan", Subject = "Sample Lead 2" }; _lead2Id = _serviceProxy.Create(lead2); NotifyEntityCreated(Lead.EntityLogicalName, _lead2Id); //<snippetWorkingWithLeads1> // Qualify the first lead, creating an account and a contact from it, but // not creating an opportunity. var qualifyIntoAccountContactReq = new QualifyLeadRequest { CreateAccount = true, CreateContact = true, LeadId = new EntityReference(Lead.EntityLogicalName, _lead1Id), Status = new OptionSetValue((int)lead_statuscode.Qualified) }; var qualifyIntoAccountContactRes = (QualifyLeadResponse)_serviceProxy.Execute(qualifyIntoAccountContactReq); Console.WriteLine(" The first lead was qualified."); //</snippetWorkingWithLeads1> foreach (var entity in qualifyIntoAccountContactRes.CreatedEntities) { NotifyEntityCreated(entity.LogicalName, entity.Id); if (entity.LogicalName == Account.EntityLogicalName) { _leadAccountId = entity.Id; } else if (entity.LogicalName == Contact.EntityLogicalName) { _contactId = entity.Id; } } // Retrieve the organization's base currency ID for setting the // transaction currency of the opportunity. var query = new QueryExpression("organization"); query.ColumnSet = new ColumnSet("basecurrencyid"); var result = _serviceProxy.RetrieveMultiple(query); var currencyId = (EntityReference)result.Entities[0]["basecurrencyid"]; // Qualify the second lead, creating an opportunity from it, and not // creating an account or a contact. We use an existing account for the // opportunity customer instead. var qualifyIntoOpportunityReq = new QualifyLeadRequest { CreateOpportunity = true, OpportunityCurrencyId = currencyId, OpportunityCustomerId = new EntityReference( Account.EntityLogicalName, _accountId), Status = new OptionSetValue((int)lead_statuscode.Qualified), LeadId = new EntityReference(Lead.EntityLogicalName, _lead2Id) }; var qualifyIntoOpportunityRes = (QualifyLeadResponse)_serviceProxy.Execute(qualifyIntoOpportunityReq); Console.WriteLine(" The second lead was qualified."); foreach (var entity in qualifyIntoOpportunityRes.CreatedEntities) { NotifyEntityCreated(entity.LogicalName, entity.Id); if (entity.LogicalName == Opportunity.EntityLogicalName) { _opportunityId = entity.Id; } } DeleteRecords(promptforDelete); } }