/// <summary> /// Executes the plug-in. /// </summary> /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the /// <see cref="IPluginExecutionContext"/>, /// <see cref="IOrganizationService"/> /// and <see cref="ITracingService"/> /// </param> /// <remarks> /// For improved performance, Microsoft Dynamics CRM caches plug-in instances. /// The plug-in's Execute method should be written to be stateless as the constructor /// is not called for every invocatio /// n of the plug-in. Also, multiple system threads /// could execute the plug-in at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in plug-ins. /// </remarks> protected void ExecutePostOpportunityUpdate(LocalPluginContext localContext) { try { string OppsBugestAmount = string.Empty; string PreviousOppsBugestAmount = string.Empty; string smsMessage = string.Empty; bool sendMessageCond = false; string oppsCreatedByID = string.Empty; string OppsCreatedBy = string.Empty; string OppsAccountName = string.Empty; string OppsBugestAmountValue = string.Empty; string OppCurrency = string.Empty; string OppCurrencySymbol = string.Empty; string OppTitle = string.Empty; if (localContext == null) { throw new ArgumentNullException("localContext"); } SmsSender s = new SmsSender(); //Organization Service IOrganizationService service = localContext.OrganizationService; IPluginExecutionContext context = localContext.PluginExecutionContext; //Tracing Service ITracingService trace = (ITracingService)localContext.TracingService; Entity preImageEntity = (context.PreEntityImages != null && context.PreEntityImages.Contains(this.preImageAlias)) ? context.PreEntityImages[this.preImageAlias] : null; Entity postImageEntity = (context.PostEntityImages != null && context.PostEntityImages.Contains(this.postImageAlias)) ? context.PostEntityImages[this.postImageAlias] : null; if (EnableSMS == "false") { return; } trace.Trace("Nemxo API Key " + NexmoApiKey); trace.Trace("Nemxo API secret " + NexmoApiSecret); trace.Trace("Threshold " + Threshold.ToString()); trace.Trace("Opp ID: " + postImageEntity.Id.ToString()); //get from user number string UserNumber = s.GetAccountNumber(NexmoApiKey, NexmoApiSecret); trace.Trace("UserNumber" + UserNumber.ToString()); if (postImageEntity.Attributes.Contains("budgetamount")) { OppsBugestAmount = ((Microsoft.Xrm.Sdk.Money)postImageEntity.Attributes["budgetamount"]).Value.ToString(); } if (preImageEntity.Attributes.Contains("budgetamount")) { PreviousOppsBugestAmount = ((Microsoft.Xrm.Sdk.Money)preImageEntity.Attributes["budgetamount"]).Value.ToString(); } trace.Trace("PreviousOppsBugestAmount" + PreviousOppsBugestAmount.ToString()); if (string.IsNullOrEmpty(PreviousOppsBugestAmount)) { PreviousOppsBugestAmount = "0"; sendMessageCond = true; } else if (string.Compare(OppsBugestAmount, PreviousOppsBugestAmount) != 0) { sendMessageCond = true; } if (sendMessageCond == false) { return; } trace.Trace("OppsBugestAmount" + OppsBugestAmount.ToString()); OppTitle = postImageEntity.Attributes["name"].ToString(); Entity CreatedOpp = service.Retrieve("opportunity", new Guid(postImageEntity.Id.ToString()), new ColumnSet(true)); if (CreatedOpp.Attributes.Contains("customerid")) { trace.Trace("customerid found"); trace.Trace("customerid:" + CreatedOpp.Attributes["customerid"]); string accountID = ((Microsoft.Xrm.Sdk.EntityReference)(CreatedOpp.Attributes["customerid"])).Id.ToString(); string fetchxmlAccount = @"<fetch mapping='logical'> <entity name='account'><all-attributes/> <filter type='and'> <condition attribute='accountid' operator='eq' uitype='account' value='{" + accountID + "}' />" + "</filter></entity></fetch>"; EntityCollection AccountDetails = service.RetrieveMultiple(new FetchExpression(fetchxmlAccount)); if (AccountDetails != null) { if (AccountDetails.Entities.Count > 0) { trace.Trace("account found"); OppsAccountName = AccountDetails.Entities[0].Attributes["name"].ToString(); } else { trace.Trace("AccountDetails rows count equals 0"); } } else { trace.Trace("AccountDetails is null"); } } else { trace.Trace("customerid not found"); } trace.Trace("OppsAccountName" + OppsAccountName); OppTitle = CreatedOpp.Attributes["name"].ToString(); trace.Trace("OppTitle: " + OppTitle); if (postImageEntity.Attributes.Contains("budgetamount")) { OppCurrency = ((Microsoft.Xrm.Sdk.EntityReference)(CreatedOpp.Attributes["transactioncurrencyid"])).Id.ToString(); OppsBugestAmount = Convert.ToDouble(OppsBugestAmount).ToString("0.00"); PreviousOppsBugestAmount = Convert.ToDouble(OppsBugestAmount).ToString("0.00"); Entity Currency = service.Retrieve("transactioncurrency", new Guid(OppCurrency), new ColumnSet(true)); string currencySymbol = Currency.Attributes["currencysymbol"].ToString(); OppsBugestAmountValue = OppsBugestAmount; OppsBugestAmount = currencySymbol + OppsBugestAmount; PreviousOppsBugestAmount = currencySymbol + PreviousOppsBugestAmount; trace.Trace("OppsBugestAmount: " + OppsBugestAmount); trace.Trace("PreviousOppsBugestAmount: " + PreviousOppsBugestAmount); } OppsCreatedBy = ((Microsoft.Xrm.Sdk.EntityReference)(CreatedOpp.Attributes["createdby"])).Name.ToString(); trace.Trace("OppsCreatedBy: " + OppsCreatedBy); oppsCreatedByID = ((Microsoft.Xrm.Sdk.EntityReference)(CreatedOpp.Attributes["createdby"])).Id.ToString(); trace.Trace("oppsCreatedByID: " + oppsCreatedByID); string fetchxmluser = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" + "<entity name='systemuser'>" + "<attribute name='fullname' />" + "<attribute name='businessunitid' />" + "<attribute name='title' /> " + "<attribute name='address1_telephone1'/>" + "<attribute name='positionid' /> " + "<attribute name='systemuserid' /> " + "<attribute name='mobilephone' />" + "<attribute name='parentsystemuserid' />" + "<attribute name='firstname' />" + "<order attribute='fullname' descending= 'false' />" + "</entity>" + "</fetch>"; EntityCollection entitiesUsers = service.RetrieveMultiple(new FetchExpression(fetchxmluser)); trace.Trace("entitiesUsers: " + entitiesUsers.Entities.Count); Entity e = null; Entity eManager = null; string managerUID = string.Empty; //Get manager ID for current user for (int count = 0; count < entitiesUsers.Entities.Count; count++) { e = null; e = entitiesUsers.Entities[count]; if (e.Id.ToString() == oppsCreatedByID && e.Attributes.Contains("parentsystemuserid")) { managerUID = ((Microsoft.Xrm.Sdk.EntityReference)(e.Attributes["parentsystemuserid"])).Id.ToString(); break; } } trace.Trace("managerUID: " + managerUID); //Get Manager Entity if (!string.IsNullOrEmpty(managerUID)) { for (int count = 0; count < entitiesUsers.Entities.Count; count++) { eManager = null; if (entitiesUsers.Entities[count].Id.ToString() == managerUID) { eManager = entitiesUsers.Entities[count]; break; } } //Get Manager Phone number string ToNumber = string.Empty; string message = "An opportunity {0} for {1} has been updated with probable value {2}"; if (eManager != null) { trace.Trace("Manager Name: " + eManager.Attributes["fullname"].ToString()); if (eManager.Attributes.Contains("mobilephone")) { ToNumber = eManager.Attributes["mobilephone"].ToString(); trace.Trace("ToNumber: " + ToNumber); if (string.IsNullOrEmpty(OppsAccountName)) { message = "An opportunity '{0}' has been updated with probable value {1}"; smsMessage = string.Format(message, OppTitle, OppsBugestAmount); } else { message = "An opportunity '{0}' for {1} has been updated with probable value {2}"; smsMessage = string.Format(message, OppTitle, OppsAccountName, OppsBugestAmount); } } } //update the message detail if (!string.IsNullOrEmpty(OppsBugestAmountValue) && !string.IsNullOrEmpty(ToNumber)) { if (Convert.ToDouble(OppsBugestAmountValue) > Threshold) { smsMessage = HTMLEncodeSpecialChars(smsMessage); s.SendSMS(ToNumber, UserNumber, NexmoApiKey, NexmoApiSecret, Uri.EscapeDataString(smsMessage)); //throw new InvalidPluginExecutionException(string.Format("SMS send message {0}", smsMessage)); } else { //throw new InvalidPluginExecutionException(string.Format("SMS Will not send message {0}", smsMessage)); } } } } catch (Exception ex) { throw new InvalidPluginExecutionException(string.Format("Exception {0}", ex.Message)); } }
/// <summary> /// Executes the plug-in. /// </summary> /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the /// <see cref="IPluginExecutionContext"/>, /// <see cref="IOrganizationService"/> /// and <see cref="ITracingService"/> /// </param> /// <remarks> /// For improved performance, Microsoft Dynamics CRM caches plug-in instances. /// The plug-in's Execute method should be written to be stateless as the constructor /// is not called for every invocatio /// n of the plug-in. Also, multiple system threads /// could execute the plug-in at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in plug-ins. /// </remarks> protected void ExecutePostOpportunityUpdate(LocalPluginContext localContext) { try { string OppsBugestAmount = string.Empty; string PreviousOppsBugestAmount = string.Empty; string smsMessage = string.Empty; bool sendMessageCond = false; string oppsCreatedByID = string.Empty; string OppsCreatedBy = string.Empty; string OppsAccountName = string.Empty; string OppsBugestAmountValue = string.Empty; string OppCurrency = string.Empty; string OppCurrencySymbol = string.Empty; string OppTitle = string.Empty; if (localContext == null) { throw new ArgumentNullException("localContext"); } SmsSender s = new SmsSender(); //Organization Service IOrganizationService service = localContext.OrganizationService; IPluginExecutionContext context = localContext.PluginExecutionContext; //Tracing Service ITracingService trace = (ITracingService)localContext.TracingService; Entity preImageEntity = (context.PreEntityImages != null && context.PreEntityImages.Contains(this.preImageAlias)) ? context.PreEntityImages[this.preImageAlias] : null; Entity postImageEntity = (context.PostEntityImages != null && context.PostEntityImages.Contains(this.postImageAlias)) ? context.PostEntityImages[this.postImageAlias] : null; if (EnableSMS == "false") return; trace.Trace("Nemxo API Key " + NexmoApiKey); trace.Trace("Nemxo API secret " + NexmoApiSecret); trace.Trace("Threshold " + Threshold.ToString()); trace.Trace("Opp ID: " + postImageEntity.Id.ToString()); //get from user number string UserNumber = s.GetAccountNumber(NexmoApiKey, NexmoApiSecret); trace.Trace("UserNumber" + UserNumber.ToString()); if (postImageEntity.Attributes.Contains("budgetamount")) { OppsBugestAmount = ((Microsoft.Xrm.Sdk.Money)postImageEntity.Attributes["budgetamount"]).Value.ToString(); } if (preImageEntity.Attributes.Contains("budgetamount")) { PreviousOppsBugestAmount = ((Microsoft.Xrm.Sdk.Money)preImageEntity.Attributes["budgetamount"]).Value.ToString(); } trace.Trace("PreviousOppsBugestAmount" + PreviousOppsBugestAmount.ToString()); if (string.IsNullOrEmpty(PreviousOppsBugestAmount)) { PreviousOppsBugestAmount = "0"; sendMessageCond = true; } else if (string.Compare(OppsBugestAmount, PreviousOppsBugestAmount) != 0) { sendMessageCond = true; } if (sendMessageCond == false) return; trace.Trace("OppsBugestAmount" + OppsBugestAmount.ToString()); OppTitle = postImageEntity.Attributes["name"].ToString(); Entity CreatedOpp = service.Retrieve("opportunity", new Guid(postImageEntity.Id.ToString()), new ColumnSet(true)); if (CreatedOpp.Attributes.Contains("customerid")) { trace.Trace("customerid found"); trace.Trace("customerid:" + CreatedOpp.Attributes["customerid"]); string accountID = ((Microsoft.Xrm.Sdk.EntityReference)(CreatedOpp.Attributes["customerid"])).Id.ToString(); string fetchxmlAccount = @"<fetch mapping='logical'> <entity name='account'><all-attributes/> <filter type='and'> <condition attribute='accountid' operator='eq' uitype='account' value='{" + accountID + "}' />" + "</filter></entity></fetch>"; EntityCollection AccountDetails = service.RetrieveMultiple(new FetchExpression(fetchxmlAccount)); if (AccountDetails != null) { if (AccountDetails.Entities.Count > 0) { trace.Trace("account found"); OppsAccountName = AccountDetails.Entities[0].Attributes["name"].ToString(); } else { trace.Trace("AccountDetails rows count equals 0"); } } else { trace.Trace("AccountDetails is null"); } } else { trace.Trace("customerid not found"); } trace.Trace("OppsAccountName" + OppsAccountName); OppTitle = CreatedOpp.Attributes["name"].ToString(); trace.Trace("OppTitle: " + OppTitle); if (postImageEntity.Attributes.Contains("budgetamount")) { OppCurrency = ((Microsoft.Xrm.Sdk.EntityReference)(CreatedOpp.Attributes["transactioncurrencyid"])).Id.ToString(); OppsBugestAmount = Convert.ToDouble(OppsBugestAmount).ToString("0.00"); PreviousOppsBugestAmount = Convert.ToDouble(OppsBugestAmount).ToString("0.00"); Entity Currency = service.Retrieve("transactioncurrency", new Guid(OppCurrency), new ColumnSet(true)); string currencySymbol = Currency.Attributes["currencysymbol"].ToString(); OppsBugestAmountValue = OppsBugestAmount; OppsBugestAmount = currencySymbol + OppsBugestAmount; PreviousOppsBugestAmount = currencySymbol + PreviousOppsBugestAmount; trace.Trace("OppsBugestAmount: " + OppsBugestAmount); trace.Trace("PreviousOppsBugestAmount: " + PreviousOppsBugestAmount); } OppsCreatedBy = ((Microsoft.Xrm.Sdk.EntityReference)(CreatedOpp.Attributes["createdby"])).Name.ToString(); trace.Trace("OppsCreatedBy: " + OppsCreatedBy); oppsCreatedByID = ((Microsoft.Xrm.Sdk.EntityReference)(CreatedOpp.Attributes["createdby"])).Id.ToString(); trace.Trace("oppsCreatedByID: " + oppsCreatedByID); string fetchxmluser = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" + "<entity name='systemuser'>" + "<attribute name='fullname' />" + "<attribute name='businessunitid' />" + "<attribute name='title' /> " + "<attribute name='address1_telephone1'/>" + "<attribute name='positionid' /> " + "<attribute name='systemuserid' /> " + "<attribute name='mobilephone' />" + "<attribute name='parentsystemuserid' />" + "<attribute name='firstname' />" + "<order attribute='fullname' descending= 'false' />" + "</entity>" + "</fetch>"; EntityCollection entitiesUsers = service.RetrieveMultiple(new FetchExpression(fetchxmluser)); trace.Trace("entitiesUsers: " + entitiesUsers.Entities.Count); Entity e = null; Entity eManager = null; string managerUID = string.Empty; //Get manager ID for current user for (int count = 0; count < entitiesUsers.Entities.Count; count++) { e = null; e = entitiesUsers.Entities[count]; if (e.Id.ToString() == oppsCreatedByID && e.Attributes.Contains("parentsystemuserid")) { managerUID = ((Microsoft.Xrm.Sdk.EntityReference)(e.Attributes["parentsystemuserid"])).Id.ToString(); break; } } trace.Trace("managerUID: " + managerUID); //Get Manager Entity if (!string.IsNullOrEmpty(managerUID)) { for (int count = 0; count < entitiesUsers.Entities.Count; count++) { eManager = null; if (entitiesUsers.Entities[count].Id.ToString() == managerUID) { eManager = entitiesUsers.Entities[count]; break; } } //Get Manager Phone number string ToNumber = string.Empty; string message = "An opportunity {0} for {1} has been updated with probable value {2}"; if (eManager != null) { trace.Trace("Manager Name: " + eManager.Attributes["fullname"].ToString()); if (eManager.Attributes.Contains("mobilephone")) { ToNumber = eManager.Attributes["mobilephone"].ToString(); trace.Trace("ToNumber: " + ToNumber); if (string.IsNullOrEmpty(OppsAccountName)) { message = "An opportunity '{0}' has been updated with probable value {1}"; smsMessage = string.Format(message, OppTitle, OppsBugestAmount); } else { message = "An opportunity '{0}' for {1} has been updated with probable value {2}"; smsMessage = string.Format(message, OppTitle, OppsAccountName, OppsBugestAmount); } } } //update the message detail if (!string.IsNullOrEmpty(OppsBugestAmountValue) && !string.IsNullOrEmpty(ToNumber)) { if (Convert.ToDouble(OppsBugestAmountValue) > Threshold) { smsMessage = HTMLEncodeSpecialChars(smsMessage); s.SendSMS(ToNumber, UserNumber, NexmoApiKey, NexmoApiSecret, Uri.EscapeDataString(smsMessage)); //throw new InvalidPluginExecutionException(string.Format("SMS send message {0}", smsMessage)); } else { //throw new InvalidPluginExecutionException(string.Format("SMS Will not send message {0}", smsMessage)); } } } } catch (Exception ex) { throw new InvalidPluginExecutionException(string.Format("Exception {0}", ex.Message)); } }