Esempio n. 1
0
        public override CallFlow BuildCallFlow()
        {
            CallFlow flow = new CallFlow();

            flow.AddState(ViewStateBuilder.Build("greeting", "myMenu", new Say("greeting", "Welcome to the dynamic menu example.")), true);
            //This is a fake service that mimics getting meta-data for the menus from a web service or database
            DynamicMenuService service     = new DynamicMenuService();
            VoiceMenu          myMenu      = service.GetMenu("myMenu");
            Prompt             menuOptions = new Prompt();

            //Build the prompts for the menu options form the meta-data
            foreach (MenuOption option in myMenu.Options)
            {
                menuOptions.audios.Add(new TtsMessage(option.PromptMsg + service.GetSelectionPrompt(option.Number)));
            }
            //Create the initial state and view model without any transitions
            State myMenuState = ViewStateBuilder.Build("myMenu", new Ask("myMenu", menuOptions,
                                                                         new Grammar(new BuiltinGrammar(BuiltinGrammar.GrammarType.digits, 1, 1))));

            //Add the transitions to the state
            foreach (MenuOption option in myMenu.Options)
            {
                myMenuState.AddTransition("continue", option.TransitionTarget, new Condition("result == '" + option.Number.ToString() + "'"));
            }
            //Add the state to the call flow
            flow.AddState(myMenuState);
            flow.AddState(ViewStateBuilder.Build("doThis", new Exit("doThis", "You selected to do this. Goodbye.")));
            flow.AddState(ViewStateBuilder.Build("doThat", new Exit("doThat", "You selected to do that. Goodbye.")));
            flow.AddState(ViewStateBuilder.Build("doWhatever", new Exit("doWhatever", "You selected to do whatever. Goodbye.")));
            flow.AddState(ViewStateBuilder.Build("invalidSelect", new Exit("invalidSelect", "That was an invalid selection. Goodbye.")));
            return(flow);
        }
Esempio n. 2
0
        public override CallFlow BuildCallFlow()
        {
            CallFlow flow = new CallFlow();

            //Use the Exit object instead of the Say object
            //because this just plays a prompt and exits.  The
            //Say object expects a transition to another state
            //or object.
            flow.AddState(ViewStateBuilder.Build("greeting", new Exit("greeting", "Hello World")), true);
            return(flow);
        }
        // Creating
        public VoiceResponse <CallFlow> CreateCallFlow(CallFlow request)
        {
            ParameterValidator.IsNotNullOrWhiteSpace(request.Title, "title");
            ParameterValidator.IsNotNull(request.Steps, "steps");

            var callFlows = new CallFlows(new CallFlow {
                Title = request.Title, Steps = request.Steps, Record = request.Record
            });
            var result = restClient.Create(callFlows);

            return((VoiceResponse <CallFlow>)result.Object);
        }
        // Updating
        public VoiceResponse <CallFlow> UpdateCallFlow(string id, CallFlow callFlow)
        {
            ParameterValidator.IsNotNullOrWhiteSpace(callFlow.Title, "title");
            ParameterValidator.IsNotNull(callFlow.Steps, "steps");

            var callFlows = new CallFlows(new CallFlow {
                Id = id, Title = callFlow.Title, Steps = callFlow.Steps, Record = callFlow.Record
            });
            var result = restClient.Update(callFlows);

            return((VoiceResponse <CallFlow>)result.Object);
        }
Esempio n. 5
0
        public override CallFlow BuildCallFlow()
        {
            CallFlow            flow          = new CallFlow();
            List <VxmlProperty> appProperties = new List <VxmlProperty>();

            appProperties.Add(new VxmlProperty("inputmode", "dtmf"));
            flow.AddState(ViewStateBuilder.Build("greeting", "getStartDate",
                                                 new Say("greeting", new Prompt("Welcome to the Reusable Dialog Component Example.")
            {
                bargein = false
            })
            {
                properties = appProperties
            }), true);

            //This tells the state machine to use the state machine in the reusable component.
            flow.AddState(new State("getStartDate", "getFinishDate")
                          .AddNestedCallFlow(new GetDateDtmfRDC(new Prompt("Enter the start date as a six digit number.")))
                          .AddOnExitAction(delegate(CallFlow cf, State state, Event e)
                                           { cf.Ctx.SetGlobal <GetDateDtmfOutput>("StartDate", ((GetDateDtmfRDC)state.NestedCF).GetResults()); }));

            //We will reuse the component again for the finish date.
            flow.AddState(new State("getFinishDate", "calcDifference")
                          .AddNestedCallFlow(new GetDateDtmfRDC(new Prompt("Enter the finish date as a six digit number.")))
                          .AddOnExitAction(delegate(CallFlow cf, State state, Event e)
                                           { cf.Ctx.SetGlobal <GetDateDtmfOutput>("FinishDate", ((GetDateDtmfRDC)state.NestedCF).GetResults()); }));

            //Calculate the difference in days
            flow.AddState(new State("calcDifference", "differenceInDays")
                          .AddOnEntryAction(delegate(CallFlow cf, State state, Event e)
            {
                var startDate   = cf.Ctx.GetGlobalAs <GetDateDtmfOutput>("StartDate");
                var finishDate  = cf.Ctx.GetGlobalAs <GetDateDtmfOutput>("FinishDate");
                string daysDiff = finishDate.Date.Subtract(startDate.Date).Days.ToString();
                var d           = new { daysDiff = daysDiff };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string json = serializer.Serialize(d);
                cf.FireEvent("continue", json);
            }));

            Prompt sayDiff = new Prompt();

            sayDiff.audios.Add(new TtsMessage("The difference between the start and finish dates is "));
            sayDiff.audios.Add(new TtsVariable("d.daysDiff"));
            sayDiff.audios.Add(new TtsMessage(" days."));
            sayDiff.bargein = false;
            flow.AddState(ViewStateBuilder.Build("differenceInDays", "goodbye", new Say("differenceInDays", sayDiff)));
            flow.AddState(ViewStateBuilder.Build("goodbye", new Exit("goodbye", "Goodbye.")));
            return(flow);
        }
Esempio n. 6
0
        public override CallFlow BuildCallFlow()
        {
            CallFlow flow = new CallFlow();

            flow.AddState(ViewStateBuilder.Build("mainMenu", new Ask("mainMenu", "Press one for option one. Press two for option two.",
                                                                     new Grammar(new BuiltinGrammar(BuiltinGrammar.GrammarType.digits, 1, 1))))
                          .AddTransition("continue", "optionOne", new Condition("result == '1'"))
                          .AddTransition("continue", "optionTwo", new Condition("result == '2'"))
                          .AddTransition("continue", "invalidSelect", new Condition("result != '1' && result != '2'")), true);
            flow.AddState(ViewStateBuilder.Build("optionOne", new Exit("optionOne", "You selected option one. Goodbye.")));
            flow.AddState(ViewStateBuilder.Build("optionTwo", new Exit("optionTwo", "You selected option two. Goodbye.")));
            flow.AddState(ViewStateBuilder.Build("invalidSelect", new Exit("invalidSelect", "That was an invalid selection. Goodbye.")));
            return(flow);
        }
Esempio n. 7
0
        public void Create()
        {
            var restClient = MockRestClient
                             .ThatExpects("{  \"title\": \"Forward call to 31612345678\",  \"record\": true,  \"steps\": [    {      \"options\": {        \"destination\": \"31612345678\"      },      \"action\": \"transfer\"    }  ]}")
                             .AndReturns("{  \"data\": [    {      \"id\": \"de3ed163-d5fc-45f4-b8c4-7eea7458c635\",      \"title\": \"Forward call to 31612345678\",      \"record\": true,      \"steps\": [        {          \"id\": \"2fa1383e-6f21-4e6f-8c36-0920c3d0730b\",          \"action\": \"transfer\",          \"options\": {            \"destination\": \"31612345678\"          }        }      ],      \"createdAt\": \"2017-03-06T14:52:22Z\",      \"updatedAt\": \"2017-03-06T14:52:22Z\"    }  ],  \"_links\": {    \"self\": \"/call-flows/de3ed163-d5fc-45f4-b8c4-7eea7458c635\"  }}")
                             .FromEndpoint("POST", "call-flows", baseUrl)
                             .Get();

            var client = Client.Create(restClient.Object);

            var newCallFlow = new CallFlow
            {
                Title  = "Forward call to 31612345678",
                Record = true,
                Steps  = new List <Step> {
                    new Step {
                        Action = "transfer", Options = new Options {
                            Destination = "31612345678"
                        }
                    }
                }
            };

            var callFlowResponse = client.CreateCallFlow(newCallFlow);

            restClient.Verify();

            Assert.IsNotNull(callFlowResponse.Data);
            Assert.IsNotNull(callFlowResponse.Links);

            var links = callFlowResponse.Links;

            Assert.AreEqual("/call-flows/de3ed163-d5fc-45f4-b8c4-7eea7458c635", links.GetValueOrDefault("self"));

            var callFlow = callFlowResponse.Data.FirstOrDefault();

            Assert.AreEqual("de3ed163-d5fc-45f4-b8c4-7eea7458c635", callFlow.Id);
            Assert.AreEqual("Forward call to 31612345678", callFlow.Title);
            Assert.AreEqual(true, callFlow.Record);
            Assert.IsNotNull(callFlow.CreatedAt);
            Assert.IsNotNull(callFlow.UpdatedAt);
            Assert.IsNotNull(callFlow.Steps);

            var step = callFlow.Steps.FirstOrDefault();

            Assert.AreEqual("2fa1383e-6f21-4e6f-8c36-0920c3d0730b", step.Id);
            Assert.AreEqual("transfer", step.Action);
            Assert.AreEqual("31612345678", step.Options.Destination);
        }
Esempio n. 8
0
        const string YourAccessKey = "YOUR_ACCESS_KEY"; // your access key here.

        internal static void Main(string[] args)
        {
            var client      = Client.CreateDefault(YourAccessKey);
            var newCallFlow = new CallFlow
            {
                Title  = "Forward call to 31612345678",
                Record = true,
                Steps  = new List <Step> {
                    new Step {
                        Action = "transfer", Options = new Options {
                            Destination = "31612345678"
                        }
                    }
                }
            };

            var newCall = new Call
            {
                source      = "31644556677",
                destination = "33766723144",
                callFlow    = newCallFlow
            };

            try
            {
                var callResponse = client.CreateCall(newCall);
                var call         = callResponse.Data.FirstOrDefault();
                Console.WriteLine("The Call Flow Created with Id = {0}", call.Id);
            }
            catch (ErrorException e)
            {
                // Either the request fails with error descriptions from the endpoint.
                if (e.HasErrors)
                {
                    foreach (var error in e.Errors)
                    {
                        Console.WriteLine("code: {0} description: '{1}' parameter: '{2}'", error.Code, error.Description, error.Parameter);
                    }
                }
                // or fails without error information from the endpoint, in which case the reason contains a 'best effort' description.
                if (e.HasReason)
                {
                    Console.WriteLine(e.Reason);
                }
            }
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
Esempio n. 9
0
        public void Update()
        {
            var restClient = MockRestClient
                             .ThatExpects("{\"id\":\"de3ed163-d5fc-45f4-b8c4-7eea7458c635\",\"title\":\"Updated call flow\",\"steps\":[{\"action\":\"transfer\",\"options\":{\"destination\":\"31611223344\"}}]}")
                             .AndReturns(filename: "CallFlowUpdate.json")
                             .FromEndpoint("PUT", "call-flows/de3ed163-d5fc-45f4-b8c4-7eea7458c635", baseUrl)
                             .Get();

            var client = Client.Create(restClient.Object);

            var callFlow = new CallFlow
            {
                Title = "Updated call flow",
                Steps = new List <Step> {
                    new Step {
                        Action = "transfer", Options = new Options {
                            Destination = "31611223344"
                        }
                    }
                }
            };

            var callFlowResponse = client.UpdateCallFlow("de3ed163-d5fc-45f4-b8c4-7eea7458c635", callFlow);

            restClient.Verify();

            Assert.IsNotNull(callFlowResponse.Data);
            Assert.IsNotNull(callFlowResponse.Links);

            var links = callFlowResponse.Links;

            Assert.AreEqual("/call-flows/de3ed163-d5fc-45f4-b8c4-7eea7458c635", links.GetValueOrDefault("self"));

            var updatedCallFlow = callFlowResponse.Data.FirstOrDefault();

            Assert.AreEqual("de3ed163-d5fc-45f4-b8c4-7eea7458c635", updatedCallFlow.Id);
            Assert.AreEqual("Updated call flow", updatedCallFlow.Title);
            Assert.AreEqual(false, updatedCallFlow.Record);
            Assert.IsNotNull(updatedCallFlow.CreatedAt);
            Assert.IsNotNull(updatedCallFlow.UpdatedAt);
            Assert.IsNotNull(updatedCallFlow.Steps);

            var step = updatedCallFlow.Steps.FirstOrDefault();

            Assert.AreEqual("3538a6b8-5a2e-4537-8745-f72def6bd393", step.Id);
            Assert.AreEqual("transfer", step.Action);
            Assert.AreEqual("31611223344", step.Options.Destination);
        }
Esempio n. 10
0
        public override CallFlow BuildCallFlow()
        {
            CallFlow flow = new CallFlow();
            //Get the transfer number from the web.confg
            string xferNum  = ConfigurationManager.AppSettings["xferNum"];
            string xferFrom = ConfigurationManager.AppSettings["xferFrom"];

            flow.AddState(ViewStateBuilder.Build("xfer", "xferComplete",
                                                 new VoiceModel.Transfer("xfer", xferNum, xferFrom,
                                                                         new Prompt("Please hold while you are transfered to the next available agent.")))
                          .AddTransition("busy", "xferBusy", null)
                          .AddTransition("noanswer", "xferNoAnswer", null)
                          .AddTransition("error", "xferError", null), true);
            flow.AddState(ViewStateBuilder.Build("xferBusy", new Exit("xferBusy", "That line is busy.")));
            flow.AddState(ViewStateBuilder.Build("xferNoAnswer", new Exit("xferNoAnswer", "Sorry, no one answered the phone.")));
            flow.AddState(ViewStateBuilder.Build("xferError", new Exit("xferError", "There was an error placing that call.")));
            flow.AddState(ViewStateBuilder.Build("xferComplete", new Exit("xferComplete", "The transfer has been completed.")));
            return(flow);
        }
Esempio n. 11
0
        public override CallFlow BuildCallFlow()
        {
            CallFlow flow = new CallFlow();

            flow.AddState(ViewStateBuilder.Build("greeting", "getZip", new Say("greeting", "Welcome to Weather Voice.")), true);
            flow.AddState(ViewStateBuilder.Build("getZip", "getWeather", new Ask("getZip", "Enter the five digit zip code for the area where you would like the weather report on.",
                                                                                 new Grammar(new BuiltinGrammar(BuiltinGrammar.GrammarType.digits, 5)))));
            State GetWeatherState = new State("getWeather", "voiceWeather");

            GetWeatherState.OnEntry.Add(delegate(CallFlow cf, State state, Event e)
            {
                //This is a mockup weather service that can be used for testing
                // DAL.IWeatherService service = new DAL.WeatherServiceMockup();

                //This is an implementation of the Google weather service
                //This was an unofficial API and service has been stopped by Google
                //DAL.IWeatherService service = new DAL.GoogleWeatherService();

                //This implementation uses the MSN weather service
                DAL.IWeatherService service     = new DAL.MsnWeatherService();
                Weather currWeather             = service.getWeather(state.jsonArgs);
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string jsonWeather = serializer.Serialize(currWeather);
                cf.FireEvent("continue", jsonWeather);
            });
            flow.AddState(GetWeatherState);

            Prompt weatherPrompt = new Prompt();

            weatherPrompt.audios.Add(new TtsMessage("The temperature today is "));
            weatherPrompt.audios.Add(new TtsVariable("d.temp"));
            weatherPrompt.audios.Add(new Silence(1000));
            weatherPrompt.audios.Add(new TtsMessage("The conditions are "));
            weatherPrompt.audios.Add(new TtsVariable("d.conditions"));

            flow.AddState(ViewStateBuilder.Build("voiceWeather", "goodbye", new Say("voiceWeather", weatherPrompt)));
            flow.AddState(ViewStateBuilder.Build("goodbye", new Exit("goodbye", "Thank you for using Weather Voice. Goodbye.")));
            return(flow);
        }
Esempio n. 12
0
        /// <summary>
        /// This request updates a call flow resource. The single parameter is the unique ID that was returned upon creation.<br/>
        /// If successful, this request will return an object with a data property, which is an array that has a single call flow object. If the request failed, an error object will be returned.
        /// </summary>
        /// <param name="id">The unique ID which was returned upon creation of a call flow.</param>
        /// <param name="callFlow"></param>
        /// <returns></returns>
        public VoiceResponse <CallFlow> UpdateCallFlow(string id, CallFlow callFlow)
        {
            CallFlows callFlows;

            ParameterValidator.IsNotNull(callFlow.Steps, "steps");

            if (callFlow.Title != null || callFlow.Title != "")
            {
                callFlows = new CallFlows(new CallFlow {
                    Id = id, Title = callFlow.Title, Steps = callFlow.Steps, Record = callFlow.Record
                });
            }
            else
            {
                callFlows = new CallFlows(new CallFlow {
                    Id = id, Steps = callFlow.Steps, Record = callFlow.Record
                });
            }
            var result = restClient.Update(callFlows);

            return((VoiceResponse <CallFlow>)result.Object);
        }
Esempio n. 13
0
        public void Create()
        {
            var restClient = MockRestClient
                             .ThatExpects("{\"source\":\"31644556677\",\"destination\":\"33766723144\",\"callFlow\":{\"title\":\"Forward call to 31612345678\",\"record\":true,\"steps\":[{\"action\":\"transfer\",\"options\":{\"destination\":\"31612345678\"}}]},\"duration\":0}")
                             .AndReturns(filename: "CallCreate.json")
                             .FromEndpoint("POST", "calls", baseUrl)
                             .Get();

            var client = Client.Create(restClient.Object);

            var newCallFlow = new CallFlow
            {
                Title  = "Forward call to 31612345678",
                Record = true,
                Steps  = new List <Step> {
                    new Step {
                        Action = "transfer", Options = new Options {
                            Destination = "31612345678"
                        }
                    }
                }
            };
            var newCall = new Call
            {
                Source      = "31644556677",
                Destination = "33766723144",
                CallFlow    = newCallFlow
            };
            var callResponse = client.CreateCall(newCall);

            restClient.Verify();

            Assert.IsNotNull(callResponse.Data);

            var call = callResponse.Data.FirstOrDefault();

            Assert.AreEqual("cac63a43-ff05-4cc3-b8e3-fca82e97975c", call.Id);
        }
Esempio n. 14
0
        /// <summary>
        /// Creating a call flow
        /// </summary>
        /// <param name="request"></param>
        /// <returns>If successful, this request will return an object with a data property, which is an array that has a single call flow object. If the request failed, an error object will be returned.</returns>
        public VoiceResponse <CallFlow> CreateCallFlow(CallFlow request)
        {
            CallFlows callFlows;

            ParameterValidator.IsNotNull(request.Steps, "steps");

            if (request.Title != null || request.Title != "")
            {
                callFlows = new CallFlows(new CallFlow {
                    Title = request.Title, Steps = request.Steps, Record = request.Record
                });
            }
            else
            {
                callFlows = new CallFlows(new CallFlow {
                    Steps = request.Steps, Record = request.Record
                });
            }
            var result = restClient.Create(callFlows);


            return((VoiceResponse <CallFlow>)result.Object);
        }
Esempio n. 15
0
        public override CallFlow BuildCallFlow()
        {
            CallFlow flow = new CallFlow();

            flow.AddState(ViewStateBuilder.Build("greeting", "assist",
                                                 new Say("greeting", new Prompt("Hello. This is Mayhem.")
            {
                bargein = false
            })), true);
            string apiUrl = ConfigurationManager.AppSettings["commandMgrUrl"];

            CommandMgr.Sdk.CommandMgr commService  = new CommandMgr.Sdk.CommandMgr(apiUrl);
            List <Command>            commands     = commService.ListCommands();
            List <string>             commandNames = new List <string>();

            foreach (Command c in commands)
            {
                commandNames.Add(c.Name);
            }
            Prompt assistNoinput = new Prompt("I could not hear you. Please let me know what you want me to do.")
            {
                bargein = false
            };
            List <Prompt> assistNoinputs = new List <Prompt>();

            assistNoinputs.Add(assistNoinput);
            assistNoinputs.Add(assistNoinput);
            Prompt assistNomatch = new Prompt("I could not understand you. Please let me know what you want me to do.")
            {
                bargein = false
            };
            List <Prompt> assistNomatches = new List <Prompt>();

            assistNomatches.Add(assistNomatch);
            assistNomatches.Add(assistNomatch);
            flow.AddState(ViewStateBuilder.Build("assist", "queueCommand",
                                                 new Ask("assist", new Prompt("How may I assist you?")
            {
                bargein = false
            }, new Grammar("commands", commandNames))
            {
                noinputPrompts = assistNoinputs,
                nomatchPrompts = assistNomatches
            })
                          .AddTransition("nomatch", "didNotUnderstand", null)
                          .AddTransition("noinput", "didNotUnderstand", null));

            flow.AddState(ViewStateBuilder.Build("didNotUnderstand", "goodbye",
                                                 new Say("didNotUnderstand", "I did not understand your request.")));

            flow.AddState(new State("queueCommand", "commandSent")
                          .AddTransition("error", "errSendingCommand", null)
                          .AddOnEntryAction(delegate(CallFlow cf, State state, Event e)
            {
                try
                {
                    string url = ConfigurationManager.AppSettings["commandMgrUrl"];
                    CommandMgr.Sdk.CommandMgr service = new CommandMgr.Sdk.CommandMgr(url);
                    service.Queue(state.jsonArgs);
                    cf.FireEvent("continue", "");
                }
                catch
                {
                    cf.FireEvent("error", "");
                }
            }));
            flow.AddState(ViewStateBuilder.Build("commandSent", "doMore", new Say("commandSent", new Prompt("Your request has been sent.")
            {
                bargein = false
            })));
            flow.AddState(ViewStateBuilder.Build("errSendingCommand", "doMore", new Say("errSendingCommand", "There was an error sending your request.")));

            Prompt doMoreNoinput = new Prompt("I could not hear you. Let me know if I can assist with anything else by saying yes or no.")
            {
                bargein = false
            };
            List <Prompt> doMoreNoinputs = new List <Prompt>();

            doMoreNoinputs.Add(assistNoinput);
            doMoreNoinputs.Add(assistNoinput);
            Prompt doMoreNomatch = new Prompt("I could not understand you. Let me know if I can assist with anything else by saying yes or no.")
            {
                bargein = false
            };
            List <Prompt> doMoreNomatches = new List <Prompt>();

            doMoreNomatches.Add(doMoreNomatch);
            doMoreNomatches.Add(doMoreNomatch);
            List <string> doMoreOptions = new List <string>();

            doMoreOptions.Add("yes");
            doMoreOptions.Add("no");
            flow.AddState(ViewStateBuilder.Build("doMore",
                                                 new Ask("doMore", new Prompt("May I assist you with anything else?")
            {
                bargein = false
            }, new Grammar("assistOptions", doMoreOptions))
            {
                noinputPrompts = doMoreNoinputs,
                nomatchPrompts = doMoreNomatches
            })
                          .AddTransition("continue", "goodbye", new Condition("result == 'no'"))
                          .AddTransition("continue", "assist", new Condition("result == 'yes'"))
                          .AddTransition("nomatch", "goodbye", null)
                          .AddTransition("noinput", "goodbye", null));


            flow.AddState(ViewStateBuilder.Build("goodbye", new Exit("goodbye", "Thank you for using Mayhem. Goodbye")));
            return(flow);
        }
Esempio n. 16
0
        public override CallFlow BuildCallFlow()
        {
            CallFlow flow = new CallFlow();
            //Create Service/Domain Layer for accessing survey information
            SurveyService service = new SurveyService();

            //Get a survey named MySurvey
            Service.DTO.Survey survey = service.GetSurvey("MySurvey");
            //If we did not get a survey back there is an error. Tell the caller.
            if (survey == null)
            {
                flow.AddState(new VoiceState("noSurvey", new Exit("noSurvey", "Error finding survey in database. Goodbye.")), true);
                return(flow);
            }

            //If we got here then we have a survey from the database.
            //Create a greeting and on the exit action from this state
            //get the user we seeded from the database.  In a real survey
            //application we would prompt the user for their id and pin
            //to identify them.
            State greeting = new VoiceState("greeting", new Say("greeting", "Please take our short survey"))
                             .AddOnExitAction(delegate(CallFlow cf, State state, Event e)
            {
                SurveyService sservice = new SurveyService();
                User user = sservice.GetUserByUserId("001");
                int uid   = 0;
                if (user != null)
                {
                    uid = user.Id;
                }
                cf.Ctx.SetGlobal <int>("userId", uid);
            });

            flow.AddState(greeting, true);
            State prevState     = greeting;
            int   questionNum   = 0;
            int   questionCount = survey.Questions.Count;

            //Iterate through the survey questions and add them to our callflow.
            foreach (Question question in survey.Questions)
            {
                questionNum++;
                string questionId   = question.Id.ToString();
                bool   lastQuestion = questionNum == questionCount;
                prevState.AddTransition("continue", questionId, null);
                Ask askQuestion = new Ask(questionId);
                askQuestion.initialPrompt.Add(new Prompt(question.Text));
                if (question.AnswerType == AnswerTypes.boolean)
                {
                    askQuestion.grammar = new Grammar(new BuiltinGrammar(BuiltinGrammar.GrammarType.boolean));
                }
                else
                {
                    askQuestion.grammar = new Grammar("possibleAnswers", question.PossibleAnswers.Select(p => p.Answer).ToList());
                }
                State questionState = ViewStateBuilder.Build(questionId, askQuestion);
                questionState.AddOnExitAction(delegate(CallFlow cf, State state, Event e)
                {
                    SurveyService sservice = new SurveyService();
                    string response        = state.jsonArgs;
                    int userId             = cf.Ctx.GetGlobalAs <int>("userId");
                    int qId = Int32.Parse(state.Id);
                    sservice.InsertResponse(response, qId, userId);
                });
                flow.AddState(questionState);
                prevState = questionState;
            }
            //Take the last question in the survey and add a transition to the application exit.
            prevState.AddTransition("continue", "goodbye", null);
            //Tell the caller goodbye and hangup
            flow.AddState(new VoiceState("goodbye", new Exit("goodbye", "Thank you for taking our survey. Goodbye.")));

            return(flow);
        }
Esempio n. 17
0
 public ValidateDate(CallFlow cf, State state)
 {
     _cf    = cf;
     _state = state;
 }
Esempio n. 18
0
        public override CallFlow BuildCallFlow()
        {
            CallFlow flow = new CallFlow();

            //Make the first recording and playback
            flow.AddState(ViewStateBuilder.Build("getRecording", "playback",
                                                 new Record("getRecording", "Please record your information after the beep.  Press the pound key when you are finished."))
                          .AddOnExitAction(delegate(CallFlow cf, State state, Event e)
            {
                VoiceModel.Logger.ILoggerService logger = VoiceModel.Logger.LoggerFactory.GetInstance();
                try
                {
                    //Copy last recording to another location
                    string recordingPhysicalPath = Server.MapPath(RecordingPath);
                    string recordingFileName     = recordingPhysicalPath + "//" + cf.SessionId + ".wav";
                    logger.Debug("Copying recording " + recordingFileName);
                    System.IO.File.Copy(recordingFileName, "c://tmp//" + cf.SessionId + "_first.wav");
                }
                catch (Exception ex)
                {
                    logger.Error("Error copying recording: " + ex.Message);
                }
            }), true);
            Prompt playbackPrompt = new Prompt("You recorded ");

            playbackPrompt.audios.Add(new Audio(new ResourceLocation(new Var(flow, "recordingUri")),
                                                new Var(flow, "recordingName"), "Error finding recording"));
            State playbackState = ViewStateBuilder.Build("playback", "getRecording2", new Say("playback", playbackPrompt));

            playbackState.AddOnEntryAction(delegate(CallFlow cf, State state, Event e)
            {
                cf["recordingUri"]  = cf.RecordedAudioUri;
                cf["recordingName"] = cf.SessionId + ".wav";
            });
            flow.AddState(playbackState);

            //Make the second recording and playback
            flow.AddState(ViewStateBuilder.Build("getRecording2", "playback2",
                                                 new Record("getRecording2", "Please record your information after the beep.  Press the pound key when you are finished."))
                          .AddOnExitAction(delegate(CallFlow cf, State state, Event e)
            {
                VoiceModel.Logger.ILoggerService logger = VoiceModel.Logger.LoggerFactory.GetInstance();
                try
                {
                    //Copy last recording to another location
                    string recordingPhysicalPath = Server.MapPath(RecordingPath);
                    string recordingFileName     = recordingPhysicalPath + "//" + cf.SessionId + ".wav";
                    logger.Debug("Copying recording " + recordingFileName);
                    System.IO.File.Copy(recordingFileName, "c://tmp//" + cf.SessionId + "_second.wav");
                }
                catch (Exception ex)
                {
                    logger.Error("Error copying recording: " + ex.Message);
                }
            }));
            State playbackState2 = ViewStateBuilder.Build("playback2", "goodbye", new Say("playback2", playbackPrompt));

            playbackState.AddOnEntryAction(delegate(CallFlow cf, State state, Event e)
            {
                cf["recordingUri"]  = cf.RecordedAudioUri;
                cf["recordingName"] = cf.SessionId + ".wav";
            });
            flow.AddState(playbackState2);

            //Say goodbye and exit
            flow.AddState(ViewStateBuilder.Build("goodbye", new Exit("goodbye", "Your message has been saved. Goodbye.")));
            return(flow);
        }