Example #1
0
        public static async Task <EntityReference> PromptInitialQuestion(Activity context, ConnectorClient connector, IOrganizationService service, Microsoft.Xrm.Sdk.Entity cxConversation, Microsoft.Xrm.Sdk.Entity cxCurrentStep)
        {
            Microsoft.Xrm.Sdk.Entity cxStep = cxCurrentStep;

            //update conversation to reflect the current step and initiate any workflow triggers
            Microsoft.Xrm.Sdk.Entity upsConversation1 = new Microsoft.Xrm.Sdk.Entity("aspect_cxconversation", "aspect_conversationid", context.Conversation.Id);
            upsConversation1["aspect_currentcxstepid"] = new EntityReference(cxCurrentStep.LogicalName, cxCurrentStep.Id);
            upsConversation1["aspect_nextcxstepid"]    = null;
            service.Execute(new UpsertRequest()
            {
                Target = upsConversation1
            });

            string responseText = ReplaceOutputText(service, new EntityReference(cxConversation.LogicalName, cxConversation.Id), (string)cxStep["aspect_message"]);


            //Create a conversation message with the text sent to the user
            Microsoft.Xrm.Sdk.Entity conversationClient = new Microsoft.Xrm.Sdk.Entity("aspect_cxconversationmessage");
            conversationClient["aspect_cxconversationid"] = new EntityReference("aspect_cxconversation", cxConversation.Id);
            conversationClient["aspect_cxstepid"]         = new EntityReference(cxCurrentStep.LogicalName, cxCurrentStep.Id);
            conversationClient["aspect_direction"]        = true;
            conversationClient["aspect_name"]             = cxConversation.Id.ToString();
            conversationClient["aspect_message"]          = responseText;
            service.Create(conversationClient);


            //send reply
            var responseMessage = context.CreateReply();

            responseMessage.Text      = responseText;
            responseMessage.Speak     = responseText;
            responseMessage.InputHint = Dynamics.CXGetAnswers(service, cxStep);
            responseMessage.Value     = JsonConvert.SerializeObject(new Dynamics.CXInformation()
            {
                //CXBotId = ((Guid)(((AliasedValue)["aspect_cxbot.aspect_cxbotid"]).Value)).ToString(),
                CXBotName          = (string)(((AliasedValue)cxCurrentStep["aspect_cxbot.aspect_name"]).Value),
                AudioDirectory     = cxCurrentStep.Contains("aspect_cxbot.aspect_audiodirectory") ? (string)(((AliasedValue)cxCurrentStep["aspect_cxbot.aspect_audiodirectory"]).Value) : string.Empty,
                RecordingDirectory = cxCurrentStep.Contains("aspect_cxbot.aspect_recordingdirectory") ? (string)(((AliasedValue)cxCurrentStep["aspect_cxbot.aspect_recordingdirectory"]).Value) : string.Empty,
                CXStepId           = cxStep.Id.ToString(),
                CXStepAudio        = cxStep.Contains("aspect_audio") ? (string)cxStep["aspect_audio"] : string.Empty,
                CXText             = responseText,
                CXAnswers          = CXGetAnswers(service, cxStep),
                CXType             = Dynamics.CXGetType((OptionSetValue)cxStep["aspect_type"])
            });
            ResourceResponse msgResponse = connector.Conversations.ReplyToActivity(responseMessage);

            //update conversation to reflect the current step and initiate any workflow triggers
            Microsoft.Xrm.Sdk.Entity upsConversation2 = new Microsoft.Xrm.Sdk.Entity("aspect_cxconversation", "aspect_conversationid", context.Conversation.Id);
            upsConversation2["aspect_currentcxstepid"] = new EntityReference(cxCurrentStep.LogicalName, cxCurrentStep.Id);
            upsConversation2["aspect_nextcxstepid"]    = cxStep.Contains("aspect_nextcxstepid") ? (EntityReference)cxStep["aspect_nextcxstepid"] : null;
            service.Execute(new UpsertRequest()
            {
                Target = upsConversation2
            });

            return(cxStep.Contains("aspect_nextcxstepid") ? (EntityReference)cxStep["aspect_nextcxstepid"] : null);
        }
Example #2
0
        public static async Task <Microsoft.Xrm.Sdk.Entity> PromptNextQuestion(IDialogContext context, IOrganizationService service, Microsoft.Xrm.Sdk.Entity cxCurrentStep, Microsoft.Xrm.Sdk.Entity cxNextStep, IMessageActivity message)
        {
            Microsoft.Xrm.Sdk.Entity cxStep = service.Retrieve(cxNextStep.LogicalName, cxNextStep.Id, new ColumnSet(true));

            //update conversation to initiate any workflow triggers
            Microsoft.Xrm.Sdk.Entity upsConversation = new Microsoft.Xrm.Sdk.Entity("aspect_cxconversation", "aspect_conversationid", message.Conversation.Id);
            upsConversation["aspect_nextcxstepid"] = new EntityReference(cxNextStep.LogicalName, cxNextStep.Id);
            UpsertResponse upsResponse = (UpsertResponse)service.Execute(new UpsertRequest()
            {
                Target = upsConversation
            });

            string responseText = ReplaceOutputText(service, (EntityReference)upsResponse["Target"], (string)cxStep["aspect_message"]);

            //Create a conversation message with outbound message
            Microsoft.Xrm.Sdk.Entity conversationMessageOutbound = new Microsoft.Xrm.Sdk.Entity("aspect_cxconversationmessage");
            conversationMessageOutbound["aspect_cxconversationid"] = new EntityReference("aspect_cxconversation", "aspect_conversationid", message.Conversation.Id);
            conversationMessageOutbound["aspect_cxstepid"]         = new EntityReference(cxNextStep.LogicalName, cxNextStep.Id);
            conversationMessageOutbound["aspect_direction"]        = true;
            conversationMessageOutbound["aspect_name"]             = message.Id;
            conversationMessageOutbound["aspect_message"]          = responseText;
            service.Create(conversationMessageOutbound);

            //Update conversation to reflect the current step
            Microsoft.Xrm.Sdk.Entity upsConversation2 = new Microsoft.Xrm.Sdk.Entity("aspect_cxconversation", "aspect_conversationid", message.Conversation.Id);
            upsConversation2["aspect_currentcxstepid"] = new EntityReference(cxNextStep.LogicalName, cxNextStep.Id);
            upsConversation2["aspect_lastanswer"]      = message.Text;
            upsConversation2["aspect_nextcxstepid"]    = null;
            service.Execute(new UpsertRequest()
            {
                Target = upsConversation2
            });

            //send outbound message
            IMessageActivity responseMessage = context.MakeMessage();

            responseMessage.Text      = responseText;
            responseMessage.Speak     = responseText;
            responseMessage.InputHint = Dynamics.CXGetAnswers(service, cxStep);
            responseMessage.Value     = JsonConvert.SerializeObject(new Dynamics.CXInformation()
            {
                //CXBotId = ((Guid)(((AliasedValue)["aspect_cxbot.aspect_cxbotid"]).Value)).ToString(),
                CXBotName          = (string)(((AliasedValue)cxCurrentStep["aspect_cxbot.aspect_name"]).Value),
                AudioDirectory     = cxCurrentStep.Contains("aspect_cxbot.aspect_audiodirectory") ? (string)(((AliasedValue)cxCurrentStep["aspect_cxbot.aspect_audiodirectory"]).Value) : string.Empty,
                RecordingDirectory = cxCurrentStep.Contains("aspect_cxbot.aspect_recordingdirectory") ? (string)(((AliasedValue)cxCurrentStep["aspect_cxbot.aspect_recordingdirectory"]).Value) : string.Empty,
                CXStepId           = cxStep.Id.ToString(),
                CXStepAudio        = cxStep.Contains("aspect_audio") ? (string)cxStep["aspect_audio"] : string.Empty,
                CXText             = responseText,
                CXAnswers          = CXGetAnswers(service, cxStep),
                CXType             = Dynamics.CXGetType((OptionSetValue)cxStep["aspect_type"])
            });
            await context.PostAsync(responseMessage);

            return(cxNextStep);
        }
        public static void UpdateIfCRMValueIsDifferent_EntityReference(Microsoft.Xrm.Sdk.Entity oSourceCIFEntity,
                                                       Microsoft.Xrm.Sdk.Entity oTargetCIFEntity,
                                                       string attributeName, object objSourceVal,
                                                       string logicalName, bool allowNull = true) {
            bool isEmpty = (objSourceVal == null) || (objSourceVal == DBNull.Value);
            bool isDifferent = true;

            // get the CRM current value - if one is available to compare - if none assume different
            if (oSourceCIFEntity != null) {
                EntityReference existingValue = null;

                // get the existing value
                if (oSourceCIFEntity.Attributes.Contains(attributeName))
                    existingValue = (EntityReference)oSourceCIFEntity[attributeName];

                // check if the values are different
                if (((existingValue == null) && !isEmpty) || ((existingValue != null) && isEmpty)) {
                    isDifferent = true;
                } else {
                    if ((existingValue == null) && isEmpty)
                        isDifferent = false;
                    else
                        if (!existingValue.Id.Equals((Guid)objSourceVal))
                        isDifferent = true;
                    else
                        isDifferent = false;
                }
            }

            // get the new string value if the objects are different
            if (isDifferent) {
                if (isEmpty) {
                    if (allowNull) {
                        if (oTargetCIFEntity.Contains(attributeName)) {
                            oTargetCIFEntity[attributeName] = null;
                        } else {
                            oTargetCIFEntity.Attributes.Add(attributeName, null);
                        }
                    }
                } else {
                    if (oTargetCIFEntity.Contains(attributeName)) {
                        oTargetCIFEntity[attributeName] = new EntityReference(logicalName, (Guid)objSourceVal);
                    } else {
                        oTargetCIFEntity.Attributes.Add(attributeName, new EntityReference(logicalName, (Guid)objSourceVal));
                    }
                }
            }
        }
Example #4
0
        public static Guid GetAliasedId(CRM.Entity entity, string fieldName)
        {
            if (entity == null || string.IsNullOrEmpty(fieldName))
            {
                return(Guid.Empty);
            }

            if (!entity.Contains(fieldName))
            {
                return(Guid.Empty);
            }

            CRM.AliasedValue alias = (CRM.AliasedValue)entity[fieldName];

            switch (alias.Value.GetType().ToString())
            {
            case "Microsoft.Xrm.Sdk.EntityReference":
                return(((CRM.EntityReference)alias.Value).Id);

            case "System.Guid":
                return(new Guid(alias.Value.ToString()));
            }

            return(Guid.Empty);
        }
Example #5
0
        public static string GetAliasedValue(CRM.Entity entity, string fieldName)
        {
            if (entity == null || string.IsNullOrEmpty(fieldName))
            {
                return(string.Empty);
            }

            if (!entity.Contains(fieldName))
            {
                return(string.Empty);
            }

            CRM.AliasedValue alias = (CRM.AliasedValue)entity[fieldName];

            if (alias.Value.GetType().ToString() == "System.Guid" || alias.Value.GetType().ToString() == "System.String" || alias.Value.GetType().ToString() == "System.Boolean" || alias.Value.GetType().ToString() == "System.Int32")
            {
                return(alias.Value.ToString());
            }

            if (alias.Value.GetType().ToString() == "System.Double")
            {
                return(Convert.ToDouble(alias.Value, CultureInfo.GetCultureInfo("en-us")).ToString("###0.000000", CultureInfo.GetCultureInfo("en-us")).Replace(',', '.'));
            }

            CRM.EntityReference referencia = (CRM.EntityReference)alias.Value;

            return(referencia.Name);
        }
Example #6
0
        public static Guid GetReferenceId(CRM.Entity entity, string fieldName)
        {
            if (entity == null || string.IsNullOrEmpty(fieldName))
            {
                return(Guid.Empty);
            }

            if (!entity.Contains(fieldName))
            {
                return(Guid.Empty);
            }

            return(((CRM.EntityReference)entity[fieldName]).Id);
        }
Example #7
0
        public static string GetReferenceValue(CRM.Entity entity, string fieldName)
        {
            if (entity == null || string.IsNullOrEmpty(fieldName))
            {
                return(string.Empty);
            }

            if (!entity.Contains(fieldName))
            {
                return(string.Empty);
            }

            return(((CRM.EntityReference)entity[fieldName]).Name);
        }
Example #8
0
        public static string GetStringValue(CRM.Entity entity, string fieldName)
        {
            if (entity == null || string.IsNullOrEmpty(fieldName))
            {
                return(string.Empty);
            }

            if (!entity.Contains(fieldName))
            {
                return(string.Empty);
            }

            return(entity[fieldName].ToString());
        }
Example #9
0
        public static decimal GetMoneyValue(CRM.Entity entity, string fieldName)
        {
            if (entity == null || string.IsNullOrEmpty(fieldName))
            {
                return(0);
            }

            if (!entity.Contains(fieldName))
            {
                return(0);
            }

            CRM.Money data = (CRM.Money)entity[fieldName];
            return(Convert.ToDecimal(data.Value));
        }
Example #10
0
        public static string GetOptionValue(CRM.Entity entity, string fieldName)
        {
            if (entity == null || string.IsNullOrEmpty(fieldName))
            {
                return(string.Empty);
            }

            if (!entity.Contains(fieldName))
            {
                return(string.Empty);
            }

            CRM.OptionSetValue option = (CRM.OptionSetValue)entity[fieldName];

            return(option.Value.ToString(CultureInfo.InvariantCulture));
        }
Example #11
0
        public static string CXGetAnswers(IOrganizationService service, Microsoft.Xrm.Sdk.Entity cxStep)
        {
            switch (((OptionSetValue)cxStep["aspect_type"]).Value)
            {
            case 126460000:     //MESSAGE
                return(string.Empty);

                break;

            case 126460001:     //QUESTION
                return(cxStep.Contains("aspect_answers") ? (string)cxStep["aspect_answers"] : string.Empty);

                break;

            case 126460002:     //MENU
                EntityCollection cxStepAnswers = service.RetrieveMultiple(new FetchExpression(string.Format(@"<fetch mapping='logical' version='1.0' distinct='false' output-format='xml-platform' no-lock='true'>
                                                      <entity name='aspect_cxstepanswer'>
                                                        <all-attributes />
                                                        <order descending='false' attribute='aspect_name' />
                                                        <filter type='and'>
                                                          <condition value='{0}' attribute='aspect_cxstepid' operator='eq' />
                                                        </filter>
                                                      </entity>
                                                    </fetch>", cxStep.Id)));

                List <string> allAnswers = new List <string>();
                foreach (Microsoft.Xrm.Sdk.Entity e in cxStepAnswers.Entities)
                {
                    allAnswers.AddRange(((string)e["aspect_answers"]).Split(','));
                }
                return(string.Join(",", (from a in allAnswers where !string.IsNullOrEmpty(a) && !string.IsNullOrWhiteSpace(a) select a.Trim())));

                break;

            case 126460003:     //TRANSFER
                return(string.Empty);

                break;

            default:
                return(string.Empty);
            }
        }
Example #12
0
 public static void FireWorkflow(IOrganizationService service, Microsoft.Xrm.Sdk.Entity cxStep, bool entryWorkflow)
 {
     try
     {
         string workflowProperty = entryWorkflow ? "aspect_entryworkflowid" : "aspect_answerworkflowid";
         if (cxStep.Contains(workflowProperty))
         {
             ExecuteWorkflowRequest request = new ExecuteWorkflowRequest()
             {
                 WorkflowId = ((EntityReference)cxStep[workflowProperty]).Id,
                 EntityId   = (Guid)(((AliasedValue)cxStep["aspect_cxconversation.aspect_cxconversationid"]).Value)
             };
             // Execute the workflow.
             ExecuteWorkflowResponse response = (ExecuteWorkflowResponse)service.Execute(request);
         }
     }
     catch (Exception ex)
     {
         //user defined workflow errored
     }
 }
 public static object GetValue(this Entity entity, string fieldName)
 {
     return(entity.Contains(fieldName) && entity[fieldName] != null ? entity[fieldName] : null);
 }
        public static string ProcessDynamicContent(Microsoft.Xrm.Sdk.Entity record, string jsonTemplate)
        {
            try
            {
                JObject jobject = JObject.Parse(jsonTemplate);

                JArray a        = JArray.Parse(jobject["body"].ToString());
                JArray newArray = new JArray();

                foreach (JObject o in a.Children <JObject>())
                {
                    bool   dynamicContent = false;
                    string schemaName     = string.Empty;

                    foreach (JProperty p in o.Properties())
                    {
                        if (p.Name.Equals("dynamicContent"))
                        {
                            dynamicContent = true;
                        }
                        if (p.Name.Equals("text"))
                        {
                            // extract schema name between { } ex. {description}
                            // schemaName = description
                            schemaName = (string)o["text"];

                            if (!string.IsNullOrEmpty(schemaName))
                            {
                                schemaName = schemaName.Substring(1, schemaName.Length - 2);
                            }
                        }
                    }

                    // placeholder json for new textbox element
                    string jsonElement = @"{
                         ""type"": ""TextBlock"",
                         ""text"": """",
                         ""wrap"": true,
                         }";

                    if (!String.IsNullOrEmpty(schemaName))
                    {
                        // get value by schema name from Record
                        if (record.Contains(schemaName))
                        {
                            string fieldValue = (string)record[schemaName];

                            // remove html and perform string split
                            fieldValue = ConvertHTMLToText(fieldValue);

                            if (record.LogicalName == "email")
                            {
                                // remove any emails after the first detected email in the chain
                                int stringPosition = fieldValue.IndexOf("From:");

                                if (stringPosition != -1)
                                {
                                    fieldValue = fieldValue.Substring(0, stringPosition);
                                }

                                // attempt to remove signature by mapping from name
                                Microsoft.Xrm.Sdk.EntityCollection collection = (Microsoft.Xrm.Sdk.EntityCollection)record["from"];
                                string fromValue = collection.ToCommaSeparatedString();
                                stringPosition = fieldValue.IndexOf(fromValue);

                                if (stringPosition != -1)
                                {
                                    fieldValue = fieldValue.Substring(0, stringPosition);
                                }
                            }

                            // dodge - replace multiple line break characters with a unique break string
                            fieldValue = Regex.Replace(fieldValue, "[\r\n\f]", "/crmcs/", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                            string[] fieldValues = fieldValue.Split(new string[] { "/crmcs/" }, StringSplitOptions.None);

                            for (int i = 0; i < fieldValues.Length; i++)
                            {
                                string value = fieldValues[i];

                                if (!string.IsNullOrEmpty(value))
                                {
                                    JObject newElement = null;

                                    if (i == 0)
                                    {
                                        // first value to replace current element
                                        newElement = o;
                                    }
                                    else
                                    {
                                        // next value set as new textbox element
                                        newElement = JObject.Parse(jsonElement);
                                    }
                                    newElement["text"] = value;
                                    newArray.Add(newElement);
                                }
                            }
                        }
                        else
                        {
                            // do nothing
                        }
                    }
                    else
                    {
                        newArray.Add(o);
                    }
                }

                jobject["body"] = newArray;

                // return formatted JSON Template as string to keep things consistent
                return(jobject.ToString());
            }
            catch (Exception ex)
            {
                throw new Exception("ProcessDynamicContent :: " + ex.Message);
            }
        }