private async Task HandleChangeWallpaper(VoiceCommandServiceConnection connection, VoiceCommandUserMessage user_message)
        {
            //copy images to appdata
            var local_folder = ApplicationData.Current.LocalFolder;
            var install_path = Package.Current.InstalledLocation;
            var media_path   = await install_path.GetFolderAsync("media\\images");

            var images = await media_path.GetFilesAsync();

            foreach (var image in images)
            {
                try
                {
                    await local_folder.GetFileAsync(image.Name);

                    continue;
                }
                catch { }
                await image.CopyAsync(local_folder, image.Name, ReplaceExisting);
            }

            //change wallpaper and prepare response back to user

            var result = await UserSettings.ChangeWallpaperAsync();

            user_message.SpokenMessage = "Your wallpaper was modified, do you want me to change the lock screen as well?";

            var backup_message = new VoiceCommandUserMessage
            {
                SpokenMessage = "Change your lock screen",
            };

            var response       = VoiceCommandResponse.CreateResponseForPrompt(user_message, backup_message);
            var confirm_result = await connection.RequestConfirmationAsync(response);

            if (confirm_result.Confirmed)
            {
                await UserSettings.ChangeLockScreenAsync();

                user_message.SpokenMessage = "Your lock screen was also modified.";
                response = VoiceCommandResponse.CreateResponse(user_message);
                await connection.ReportSuccessAsync(response);
            }
            else
            {
                user_message.SpokenMessage = "okay, you're all set then";
                response = VoiceCommandResponse.CreateResponse(user_message);
                await connection.ReportSuccessAsync(response);
            }
        }
Ejemplo n.º 2
0
        private async Task CortanaResponseShowSong(SongResult info)
        {
            if (info == null)
            {
                await CompleteMessage("Right now... Nothing is playing");
            }
            else if (info.Loved)
            {
                var message = $"Now is playing: {info.Song}, from artist {info.Artist}, on album {info.Album}. You liked this song.";
                await CompleteMessage(message);
            }
            else
            {
                var message = $"Now is playing: {info.Song}, from artist {info.Artist}, on album {info.Album}. Do you like this song?";

                var userPrompt = new VoiceCommandUserMessage();
                userPrompt.DisplayMessage = userPrompt.SpokenMessage = message;

                var userReprompt = new VoiceCommandUserMessage();
                var prompt       = "Do you like this song?";
                userReprompt.DisplayMessage = userReprompt.SpokenMessage = prompt;

                var response = VoiceCommandResponse.CreateResponseForPrompt(userPrompt, userReprompt);
                var voiceCommandConfirmation = await voiceServiceConnection.RequestConfirmationAsync(response);

                if (voiceCommandConfirmation == null)
                {
                    response = VoiceCommandResponse.CreateResponse(userPrompt);
                    await voiceServiceConnection.ReportSuccessAsync(response);
                }
                else if (voiceCommandConfirmation.Confirmed)
                {
                    var service = new SmartHouseService();
                    var result  = await service.LoveSong();

                    await CompleteMessage(result?.Message);
                }
                else
                {
                    await CompleteMessage("");
                }
            }
        }
Ejemplo n.º 3
0
        private async void ShowHaveOtherBusConfirm()
        {
            List <VoiceCommandContentTile> vcTiles = new List <VoiceCommandContentTile>();

            vcTiles.Add(new VoiceCommandContentTile
            {
                Title           = "目前已经没有公车了,是否继续查询?",
                ContentTileType = VoiceCommandContentTileType.TitleWithText,
                Image           = await StorageFile.GetFileFromApplicationUriAsync(
                    new Uri("ms-appx:///BusSearchVCService/Images/GreyTile.png"))
            });

            // Create a VoiceCommandUserMessage for the initial question.
            VoiceCommandUserMessage userMsg = new VoiceCommandUserMessage();

            userMsg.DisplayMessage = userMsg.SpokenMessage = "请选择";
            // Create a VoiceCommandUserMessage for the second question,
            // in case Cortana needs to reprompt.
            VoiceCommandUserMessage repeatMsg = new VoiceCommandUserMessage();

            repeatMsg.DisplayMessage = repeatMsg.SpokenMessage = "请重新选择";

            VoiceCommandResponse response = VoiceCommandResponse.CreateResponseForPrompt(userMsg, repeatMsg, vcTiles);

            var vcConfirm = await vcConnection.RequestConfirmationAsync(response);

            if (vcConfirm != null)
            {
                if (vcConfirm.Confirmed)
                {
                    await HandleSearchWhereBusList();
                }
                else
                {
                    VoiceCommandUserMessage cancelMsg = new VoiceCommandUserMessage();
                    cancelMsg.DisplayMessage = repeatMsg.SpokenMessage = "非常抱歉";
                    VoiceCommandResponse response1 = VoiceCommandResponse.CreateResponse(cancelMsg);
                    vcConnection.ReportFailureAsync(response1);
                }
            }
        }
Ejemplo n.º 4
0
        private async Task SendCompletionMessageForBookCheapestFromXtoY(string mSource, string mDest)
        {
            string slat, slng, dlat, dlng, token, mDisplay;

            slat = slng = dlng = dlat = null;
            var mUserMessage = new VoiceCommandUserMessage();
            var mUserPrompt = new VoiceCommandUserMessage();
            VoiceCommandResponse    mResponseError, mResponseSuccess, mResponseUserPrompt;
            VoiceCommandContentTile mCabTile = new VoiceCommandContentTile();
            CabsAPI                        mCabsApi = new CabsAPI();
            GeoResponse                    mGeoResp;
            Geolocator                     mLocator;
            ReverseGeoResposne             mRevGeoResp;
            PriceEstimateResponse          mPriceEstResp;
            BookingDetailsResponse         mBookingDetailsResp;
            CabEstimate                    mCabToDisplay;
            List <CabEstimate>             mCabEstimate;
            List <VoiceCommandContentTile> mCabTiles = new List <VoiceCommandContentTile>();

            token = Windows.Storage.ApplicationData.Current.LocalSettings.Values["Token"].ToString();
            if (mDest.Equals(""))
            {
                await ShowProgressScreen("Insufficient Info");

                mDisplay = "Sorry no destination provided Please enter a valid destination";
                mUserMessage.DisplayMessage = mUserMessage.SpokenMessage = mDisplay;
                mResponseError = VoiceCommandResponse.CreateResponse(mUserMessage);
            }
            else
            {
                mGeoResp = await mCabsApi.GeoCodingResult(token, mDest);

                if (mGeoResp.Code == ResponseCode.SUCCESS)
                {
                    dlat = mGeoResp.Position.Latitude;
                    dlng = mGeoResp.Position.Longitude;
                }
                else
                {
                    mDisplay = "Plese enter proper Destination";
                    mUserMessage.DisplayMessage = mUserMessage.SpokenMessage = mDisplay;
                    mResponseError = VoiceCommandResponse.CreateResponse(mUserMessage);
                    await voiceServiceConnection.ReportFailureAsync(mResponseError);
                }
            }
            if (mSource.Equals(""))
            {
                mLocator = new Geolocator();
                mLocator.DesiredAccuracyInMeters = 50;
                var mPosition = await mLocator.GetGeopositionAsync();

                slat        = mPosition.Coordinate.Point.Position.Latitude.ToString();
                slng        = mPosition.Coordinate.Point.Position.Longitude.ToString();
                mRevGeoResp = await mCabsApi.GetReverseCodingResultlatlng(token, slat + "," + slng);

                if (mRevGeoResp.Code == ResponseCode.SUCCESS)
                {
                    try
                    {
                        mSource = mRevGeoResp.FormattedAddress.Substring(0, mRevGeoResp.FormattedAddress.IndexOf(", Hyderabad"));
                    }
                    catch
                    {
                        mSource = mRevGeoResp.FormattedAddress;
                    }
                }
                else
                {
                    mDisplay = "Source not found with current location";
                    mUserMessage.DisplayMessage = mUserMessage.SpokenMessage = mDisplay;
                    mResponseError = VoiceCommandResponse.CreateResponse(mUserMessage);
                    await voiceServiceConnection.ReportFailureAsync(mResponseError);
                }
            }
            else
            {
                mGeoResp = await mCabsApi.GeoCodingResult(token, mSource);

                if (mGeoResp.Code == ResponseCode.SUCCESS)
                {
                    slat = mGeoResp.Position.Latitude;
                    slng = mGeoResp.Position.Longitude;
                }
                else
                {
                    mDisplay = "Source not found";
                    mUserMessage.DisplayMessage = mUserMessage.SpokenMessage = mDisplay;
                    mResponseError = VoiceCommandResponse.CreateResponse(mUserMessage);
                    await voiceServiceConnection.ReportFailureAsync(mResponseError);
                }
            }
            if (slat != "" && slng != "" && dlat != "" && dlng != "")
            {
                mDisplay = "Looking for best cab providers from " + mSource.ToUpperInvariant() + " to " + mDest.ToUpperInvariant();
                await ShowProgressScreen(mDisplay);

                mDisplay = "Booking cheapest cab from " + mSource.ToUpperInvariant() + " to " + mDest.ToUpperInvariant();
                await ShowProgressScreen(mDisplay);

                mPriceEstResp = await mCabsApi.GetEstimate(token, slat, slng, dlat, dlng);

                if (mPriceEstResp.Code == ResponseCode.SUCCESS)
                {
                    mCabEstimate = mPriceEstResp.Estimates;
                    if (mCabEstimate.Count != 0)
                    {
                        string mDisplay1 = "Ok I have found the cheapest cab for you. Shall i book it?";
                        mUserPrompt.DisplayMessage = mUserPrompt.SpokenMessage = mDisplay1;
                        mDisplay = "Shall i book it";
                        mUserMessage.DisplayMessage = mUserMessage.SpokenMessage = mDisplay;
                        mCabTile.ContentTileType    = VoiceCommandContentTileType.TitleWith68x68IconAndText;

                        mCabToDisplay = mCabEstimate[0];
                        if (mCabToDisplay.Provider.Equals("UBER"))
                        {
                            mCabTile.Image = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///ContosoCabs.VoiceCommandService/img/uber.png"));
                        }
                        else
                        {
                            mCabTile.Image = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///ContosoCabs.VoiceCommandService/img/ola.png"));
                        }

                        mCabTile.Title     = mCabToDisplay.Provider;
                        mCabTile.TextLine1 = "Type : " + mCabToDisplay.Type;
                        mCabTile.TextLine2 = "ETA : " + mCabToDisplay.Eta;
                        mCabTile.TextLine3 = "Estimated Fare : " + mCabToDisplay.CurrentEstimate.LowRange + "-" + mCabToDisplay.CurrentEstimate.HighRange;
                        mCabTiles.Add(mCabTile);
                        mResponseUserPrompt = VoiceCommandResponse.CreateResponseForPrompt(mUserPrompt, mUserMessage, mCabTiles);
                        var voiceCommandConfirmation = await voiceServiceConnection.RequestConfirmationAsync(mResponseUserPrompt);

                        if (voiceCommandConfirmation.Confirmed)
                        {
                            mBookingDetailsResp = await mCabsApi.BookCab(token, slat, slng);

                            mDisplay = "Successfully booked." + mCabToDisplay.Type + " Your cab driver " + mBookingDetailsResp.BookingData.DriverDetails.Name + " will be arriving in " + mCabToDisplay.Eta;
                            mUserMessage.DisplayMessage = mUserMessage.SpokenMessage = mDisplay;
                            mResponseSuccess            = VoiceCommandResponse.CreateResponse(mUserMessage, mCabTiles);
                            await voiceServiceConnection.ReportSuccessAsync(mResponseSuccess);
                        }
                        else
                        {
                            var    userMessage             = new VoiceCommandUserMessage();
                            string BookingCabToDestination = "Cancelling cab request...";
                            await ShowProgressScreen(BookingCabToDestination);

                            string keepingTripToDestination = "Cancelled.";
                            userMessage.DisplayMessage = userMessage.SpokenMessage = keepingTripToDestination;
                            var response1 = VoiceCommandResponse.CreateResponse(userMessage);
                            await voiceServiceConnection.ReportSuccessAsync(response1);
                        }
                    }
                    else
                    {
                        mDisplay = "Sorry there are no cabs available right now";
                        mUserMessage.DisplayMessage = mUserMessage.SpokenMessage = mDisplay;
                        mResponseError = VoiceCommandResponse.CreateResponse(mUserMessage);
                        await voiceServiceConnection.ReportFailureAsync(mResponseError);
                    }
                }
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Search for, and change state of lights in room
        /// </summary>
        private async Task SendCompletionMessageChangingState(string room, bool state)
        {
            // Begin loading data to search for the target store. If this operation is going to take a long time,
            // for instance, requiring a response from a remote web service, consider inserting a progress screen
            // here, in order to prevent Cortana from timing out.
            string progressScreenString = string.Format(
                cortanaResourceMap.GetValue("ProgressLookingForLightInRoom", cortanaContext).ValueAsString,
                room);

            await ShowProgressScreen(progressScreenString);

            Model.LightStore store = new Model.LightStore();
            await store.LoadLights();

            // We might have multiple trips to the destination. For now, we just pick the first.
            IEnumerable <Model.Light> lights = store.Lights.Where(p => p.Room == room);

            Model.Light light = null;
            if (lights.Count() > 1)
            {
                // If there is more than one trip, provide a disambiguation screen rather than just picking one
                // however, more advanced logic here might be ideal (ie, if there's a significant number of items,
                // you may want to just fall back to a link to your app where you can provide a deeper search experience.
                string disambiguatioRoomString = string.Format(
                    cortanaResourceMap.GetValue("DisambiguationWhichRoom", cortanaContext).ValueAsString, room, state);
                string disambiguationRepeatString = cortanaResourceMap.GetValue("DisambiguationRepeat", cortanaContext).ValueAsString;
                light = await DisambiguateLights(lights, disambiguatioRoomString, disambiguationRepeatString);
            }
            else
            {
                // One or no trips exist with that destination, so retrieve it, or return null.
                light = lights.FirstOrDefault();
            }

            var userPrompt = new VoiceCommandUserMessage();

            VoiceCommandResponse response;

            if (light == null)
            {
                var userMessage = new VoiceCommandUserMessage();
                // In this scenario, perhaps someone has modified data on your service outside of this
                // apps control. If you're accessing a remote service, having a background task that
                // periodically refreshes the phrase list so it's likely to be in sync is ideal.
                // This is unlikely to occur for this sample app, however.
                string NoSuchLightInRoom = string.Format(
                    cortanaResourceMap.GetValue("NoSuchLightInRoom", cortanaContext).ValueAsString,
                    room);
                userMessage.DisplayMessage = userMessage.SpokenMessage = NoSuchLightInRoom;

                response = VoiceCommandResponse.CreateResponse(userMessage);
                await voiceServiceConnection.ReportSuccessAsync(response);
            }
            else
            {
                string stateString = state ? "on" : "off";
                // Prompt the user for confirmation that we've selected the correct trip to cancel.
                string changeLightStateInRoom = string.Format(
                    cortanaResourceMap.GetValue("ChangeLightStateInRoom", cortanaContext).ValueAsString,
                    room, stateString);
                userPrompt.DisplayMessage = userPrompt.SpokenMessage = changeLightStateInRoom;

                var    userReprompt = new VoiceCommandUserMessage();
                string confirmChangeLightStateInRoom = string.Format(
                    cortanaResourceMap.GetValue("ConfirmChangeLightStateInRoom", cortanaContext).ValueAsString,
                    room, stateString);
                userReprompt.DisplayMessage = userReprompt.SpokenMessage = confirmChangeLightStateInRoom;

                response = VoiceCommandResponse.CreateResponseForPrompt(userPrompt, userReprompt);

                var voiceCommandConfirmation = await voiceServiceConnection.RequestConfirmationAsync(response);

                // If RequestConfirmationAsync returns null, Cortana's UI has likely been dismissed.
                if (voiceCommandConfirmation != null)
                {
                    if (voiceCommandConfirmation.Confirmed == true)
                    {
                        string changingLightStateInRoom = string.Format(
                            cortanaResourceMap.GetValue("ChangingLightStateInRoom", cortanaContext).ValueAsString,
                            room, stateString);
                        await ShowProgressScreen(changingLightStateInRoom);

                        // Perform the operation to remote the trip from the app's data.
                        // Since the background task runs within the app package of the installed app,
                        // we can access local files belonging to the app without issue.
                        Debug.Write(light.State);

                        light.State = state;
                        Debug.Write(light.State);

                        // Provide a completion message to the user.
                        var    userMessage             = new VoiceCommandUserMessage();
                        string changedLightStateInRoom = string.Format(
                            cortanaResourceMap.GetValue("ChangedLightStateInRoom", cortanaContext).ValueAsString,
                            room, stateString);
                        userMessage.DisplayMessage = userMessage.SpokenMessage = changedLightStateInRoom;
                        response = VoiceCommandResponse.CreateResponse(userMessage);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }
                    else
                    {
                        // Confirm no action for the user.
                        var    userMessage          = new VoiceCommandUserMessage();
                        string keepingLightSettings = string.Format(
                            cortanaResourceMap.GetValue("KeepingLightSettings", cortanaContext).ValueAsString,
                            room);
                        userMessage.DisplayMessage = userMessage.SpokenMessage = keepingLightSettings;

                        response = VoiceCommandResponse.CreateResponse(userMessage);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }
                }
            }
        }
Ejemplo n.º 6
0
        protected async override void OnRun(IBackgroundTaskInstance taskInstance)
        {
            this.serviceDeferral   = taskInstance.GetDeferral();
            taskInstance.Canceled += OnTaskCanceled;

            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            VoiceCommandUserMessage userMessage;
            VoiceCommandResponse    response;

            try
            {
                voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
                voiceServiceConnection.VoiceCommandCompleted += VoiceCommandCompleted;
                VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

                switch (voiceCommand.CommandName)
                {
                case "next":

                    var appointment = (await DataSource.GetInstance().GetAppointmentsAsync()).FirstOrDefault();
                    if (appointment != null)
                    {
                        var tiles = new List <VoiceCommandContentTile>();
                        var tile  = new VoiceCommandContentTile();

                        tile.ContentTileType = VoiceCommandContentTileType.TitleWith280x140IconAndText;

                        tiles.Add(tile);
                        tile.Image = await MapService.GetStaticRoute(280, 140, DataSource.GetCurrentLocation(), appointment.Location);

                        userMessage = new VoiceCommandUserMessage()
                        {
                            SpokenMessage  = "Your next appointment is the " + appointment.FamilyName + " family. It looks like you are 20 minutes away, should I let them know?",
                            DisplayMessage = "Your next appointment is the " + appointment.FamilyName + " family."
                        };

                        var repromptMessage = new VoiceCommandUserMessage()
                        {
                            DisplayMessage = "Should I let the " + appointment.FamilyName + " family know of your arrival?",
                            SpokenMessage  = "Should I let the " + appointment.FamilyName + " family know of your arrival?"
                        };

                        response = VoiceCommandResponse.CreateResponseForPrompt(userMessage, repromptMessage, tiles);
                        var userResponse = await voiceServiceConnection.RequestConfirmationAsync(response);

                        string secondResponse;
                        if (userResponse.Confirmed)
                        {
                            secondResponse = "Great, I'll take care of it!";
                        }
                        else
                        {
                            secondResponse = "OK, no problem!";
                        }

                        //userMessage = new VoiceCommandUserMessage()
                        //{
                        //    DisplayMessage = secondResponse + "Should I start navigation?",
                        //    SpokenMessage = secondResponse + "Should I start navigation?",
                        //};

                        //repromptMessage = new VoiceCommandUserMessage()
                        //{
                        //    DisplayMessage = "Should I start navigation?",
                        //    SpokenMessage = "Should I start navigation?",
                        //};

                        //response = VoiceCommandResponse.CreateResponseForPrompt(userMessage, repromptMessage, tiles);
                        //var userResponse = await voiceServiceConnection.RequestConfirmationAsync(response);

                        ////await Task.Delay(1000);


                        userMessage = new VoiceCommandUserMessage()
                        {
                            DisplayMessage = secondResponse + " Safe driving!",
                            SpokenMessage  = secondResponse + " Safe driving!",
                        };

                        response = VoiceCommandResponse.CreateResponse(userMessage, tiles);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }
                    else
                    {
                        userMessage = new VoiceCommandUserMessage()
                        {
                            DisplayMessage = "All done for today!",
                            SpokenMessage  = "You don't have any appointments for the rest of the day!"
                        };

                        response = VoiceCommandResponse.CreateResponse(userMessage);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }



                    break;

                case "what":

                    var appointments = (await DataSource.GetInstance().GetAppointmentsAsync()).Take(3);
                    if (appointments != null & appointments.Count() > 0)
                    {
                        var tiles = new List <VoiceCommandContentTile>();

                        foreach (var app in appointments)
                        {
                            var tile = new VoiceCommandContentTile();

                            tile.ContentTileType = VoiceCommandContentTileType.TitleWith68x68IconAndText;

                            tile.TextLine1 = app.FamilyName;
                            tile.TextLine2 = app.Address;
                            tile.Title     = app.Time.ToString("hh:mm");
                            tile.Image     = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/house.png"));

                            tiles.Add(tile);
                        }

                        userMessage = new VoiceCommandUserMessage()
                        {
                            SpokenMessage  = "Here are your next " + appointments.Count() + " appointments",
                            DisplayMessage = "Here are your next " + appointments.Count() + " appointments",
                        };

                        response = VoiceCommandResponse.CreateResponse(userMessage, tiles);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }
                    else
                    {
                        userMessage = new VoiceCommandUserMessage()
                        {
                            DisplayMessage = "All done for today!",
                            SpokenMessage  = "You don't have any appointments for the rest of the day!"
                        };

                        response = VoiceCommandResponse.CreateResponse(userMessage);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }



                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                if (this.serviceDeferral != null)
                {
                    //Complete the service deferral
                    this.serviceDeferral.Complete();
                }
            }
        }
Ejemplo n.º 7
0
        protected override async void OnRun(IBackgroundTaskInstance taskInstance)
        {
            this.serviceDeferral   = taskInstance.GetDeferral();
            taskInstance.Canceled += OnTaskCanceled;

            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;


            VoiceCommandResponse response;

            try
            {
                voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
                voiceServiceConnection.VoiceCommandCompleted += VoiceCommandCompleted;
                VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

                VoiceCommandUserMessage userMessage = new VoiceCommandUserMessage();

                List <VoiceCommandContentTile> contentTiles;

                switch (voiceCommand.CommandName)
                {
                case "what":

                    _todoItemRepository = TODOAdaptiveUISample.Repositories.TodoItemFileRepository.GetInstance();
                    var data = await _todoItemRepository.RefreshTodoItemsAsync();

                    contentTiles = new List <VoiceCommandContentTile>();

                    userMessage.SpokenMessage = "Your Top To Do's are: ";

                    foreach (var item in data.Where(x => x.IsComplete == false).OrderBy(x => x.DueDate).Take((int)VoiceCommandResponse.MaxSupportedVoiceCommandContentTiles))
                    {
                        var tile = new VoiceCommandContentTile();
                        tile.ContentTileType = VoiceCommandContentTileType.TitleWithText;
                        tile.Title           = item.Title;
                        //tile.TextLine1 = item.Details;
                        contentTiles.Add(tile);

                        userMessage.SpokenMessage += item.Title + ", ";
                    }

                    userMessage.DisplayMessage = "Here are the top " + contentTiles.Count + " To Do's";



                    response = VoiceCommandResponse.CreateResponse(userMessage, contentTiles);
                    await voiceServiceConnection.ReportSuccessAsync(response);

                    break;


                case "new":
                    var todo = voiceCommand.Properties["todo"][0];

                    var responseMessage = new VoiceCommandUserMessage()
                    {
                        DisplayMessage = String.Format("Add \"{0}\" to your To Do's?", todo),
                        SpokenMessage  = String.Format("Do you want me to add \"{0}\" to your To Do's?", todo)
                    };

                    var repeatMessage = new VoiceCommandUserMessage()
                    {
                        DisplayMessage = String.Format("Are you sure you want me to add \"{0}\" to your To Do's?", todo),
                        SpokenMessage  = String.Format("Are you sure you want me to add \"{0}\" to your To Do's?", todo)
                    };

                    bool confirmed = false;
                    response = VoiceCommandResponse.CreateResponseForPrompt(responseMessage, repeatMessage);
                    try
                    {
                        var confirmation = await voiceServiceConnection.RequestConfirmationAsync(response);

                        confirmed = confirmation.Confirmed;
                    }
                    catch
                    {
                    }
                    if (confirmed)
                    {
                        _todoItemRepository = TODOAdaptiveUISample.Repositories.TodoItemFileRepository.GetInstance();
                        var i = _todoItemRepository.Factory(title: todo);
                        await _todoItemRepository.InsertTodoItem(i);

                        var todos = await _todoItemRepository.RefreshTodoItemsAsync();

                        contentTiles = new List <VoiceCommandContentTile>();

                        foreach (var itm in todos.Where(x => x.IsComplete == false).OrderBy(x => x.DueDate).Take((int)VoiceCommandResponse.MaxSupportedVoiceCommandContentTiles))
                        {
                            var tile = new VoiceCommandContentTile();
                            tile.ContentTileType = VoiceCommandContentTileType.TitleWithText;
                            tile.Title           = itm.Title;
                            contentTiles.Add(tile);
                        }

                        userMessage.SpokenMessage  = "Done and Done! Here are your top To Do's";
                        userMessage.DisplayMessage = "Here are your top " + contentTiles.Count + " To Do's";

                        response = VoiceCommandResponse.CreateResponse(userMessage, contentTiles);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }
                    else
                    {
                        userMessage.DisplayMessage = userMessage.SpokenMessage = "OK then";
                        response = VoiceCommandResponse.CreateResponse(userMessage);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }



                    break;
                }
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }
            }
            finally
            {
                if (this.serviceDeferral != null)
                {
                    //Complete the service deferral
                    this.serviceDeferral.Complete();
                }
            }
        }
Ejemplo n.º 8
0
        private async Task SendCompletionMessage(ParameterAction action, string parameter, CompletionMessage completionMessage)
        {
            var userMessage = new VoiceCommandUserMessage {
                DisplayMessage = completionMessage.Message, SpokenMessage = completionMessage.Message
            };
            var userRepeatMessage = new VoiceCommandUserMessage {
                DisplayMessage = completionMessage.RepeatMessage, SpokenMessage = completionMessage.RepeatMessage
            };

            VoiceCommandResponse           response     = VoiceCommandResponse.CreateResponseForPrompt(userMessage, userRepeatMessage);
            VoiceCommandConfirmationResult confirmation = await voiceServiceConnection.RequestConfirmationAsync(response);

            if (confirmation != null)
            {
                if (confirmation.Confirmed)
                {
                    await ShowProgressScreen(completionMessage.ConfirmMessage);

                    switch (action)
                    {
                    case ParameterAction.ChangeName:
                        ChangeName(parameter);
                        break;

                    case ParameterAction.ChangeTemperature:
                        ChangeTemperature(parameter);
                        break;

                    case ParameterAction.ChangeDistance:
                        ChangeDistance(parameter);
                        break;

                    case ParameterAction.ChangeAddress:
                        ChangeAddress(parameter);
                        break;

                    case ParameterAction.ChangeTown:
                        ChangeTown(parameter);
                        break;

                    case ParameterAction.ChangeWorkAddress:
                        ChangeWorkAddress(parameter);
                        break;

                    default:
                        break;
                    }

                    // Provide a completion message to the user.
                    var nameChangedMessage = new VoiceCommandUserMessage {
                        DisplayMessage = completionMessage.CompletedMessage, SpokenMessage = completionMessage.CompletedMessage
                    };

                    response = VoiceCommandResponse.CreateResponse(nameChangedMessage);
                    await voiceServiceConnection.ReportSuccessAsync(response);
                }
                else
                {
                    // Confirm no action for the user.
                    var cancelledMessage = new VoiceCommandUserMessage();
                    cancelledMessage.DisplayMessage = cancelledMessage.SpokenMessage = completionMessage.CanceledMessage;

                    response = VoiceCommandResponse.CreateResponse(cancelledMessage);
                    await voiceServiceConnection.ReportSuccessAsync(response);
                }
            }
        }
Ejemplo n.º 9
0
        private async Task SendCompletionMessageForAmbiance()
        {
            await ShowProgressScreen("Changement d'ambiance ...");


            var userPrompt = new VoiceCommandUserMessage();

            userPrompt.DisplayMessage    =
                userPrompt.SpokenMessage = "Quelle ambiance voulez vous choisir ?";

            var userReprompt = new VoiceCommandUserMessage();

            userReprompt.DisplayMessage    =
                userReprompt.SpokenMessage = "Quelle ambiance ?";

            var ambianceContentTiles = new List <VoiceCommandContentTile>();

            var ambianceWork = new VoiceCommandContentTile();

            ambianceWork.ContentTileType = VoiceCommandContentTileType.TitleWithText;
            ambianceWork.Title           = "Ambiance de travail";
            ambianceWork.TextLine1       = "Permet de mettre les lampes en vert";
            ambianceWork.AppContext      = "work";

            var ambianceCool = new VoiceCommandContentTile();

            ambianceCool.ContentTileType = VoiceCommandContentTileType.TitleWithText;
            ambianceCool.Title           = "Ambiance de détente";
            ambianceCool.TextLine1       = "Permet de mettre les lampes en bleu";
            ambianceCool.AppContext      = "cool";

            ambianceContentTiles.Add(ambianceWork);
            ambianceContentTiles.Add(ambianceCool);

            var response = VoiceCommandResponse.CreateResponseForPrompt(userPrompt, userReprompt, ambianceContentTiles);

            var voiceCommandDisambiguationResult = await
                                                   _voiceServiceConnection.RequestDisambiguationAsync(response);

            if (voiceCommandDisambiguationResult != null)
            {
                string ambiance = voiceCommandDisambiguationResult.SelectedItem.AppContext as string;
                userPrompt.DisplayMessage   = userPrompt.SpokenMessage = "Activer l'ambiance  " + ambiance;
                userReprompt.DisplayMessage = userReprompt.DisplayMessage = "Voulez vous activer l'ambiance " + ambiance + "?";
                response = VoiceCommandResponse.CreateResponseForPrompt(userPrompt, userReprompt);

                var voiceCommandConfirmation = await _voiceServiceConnection.RequestConfirmationAsync(response);

                // If RequestConfirmationAsync returns null, Cortana's UI has likely been dismissed.
                if (voiceCommandConfirmation != null)
                {
                    if (voiceCommandConfirmation.Confirmed == true)
                    {
                        await ShowProgressScreen("Activation de l'ambiance");

                        var dataAccess = new DataAccess.Light();
                        // Job to Active Ambiance
                        switch (ambiance)
                        {
                        case "work":
                            await dataAccess.On(new Light()
                            {
                                State = true, LightId = 1, Color = new Color()
                                {
                                    B = 1
                                }
                            });

                            break;

                        case "cool":
                            await dataAccess.On(new Light()
                            {
                                State = true, LightId = 1, Color = new Color()
                                {
                                    G = 1
                                }
                            });

                            break;

                        default:
                            break;
                        }

                        var userMessage = new VoiceCommandUserMessage();

                        userMessage.DisplayMessage = userMessage.SpokenMessage = "L'ambiance " + ambiance + " a été activée";
                        response = VoiceCommandResponse.CreateResponse(userMessage);
                        await _voiceServiceConnection.ReportSuccessAsync(response);
                    }
                }
            }
        }
        private async Task CheckPmsForUpdates()
        {
            string progressScreenString = "Checking for new private messages...";

            await ShowProgressScreen(progressScreenString);

            var privateMessages = await _privateMessageManager.GetPrivateMessages(0);

            var userPrompt = new VoiceCommandUserMessage();

            VoiceCommandResponse response;

            if (!privateMessages.Any())
            {
                var userMessage = new VoiceCommandUserMessage();
                userMessage.DisplayMessage = userMessage.SpokenMessage = "You don't have any new private messages (because nobody likes you).";
                response = VoiceCommandResponse.CreateResponse(userMessage);
                await voiceServiceConnection.ReportSuccessAsync(response);

                return;
            }

            var newPms = privateMessages.Where(
                node =>
                !string.IsNullOrEmpty(node.Status) &&
                node.Status == "http://fi.somethingawful.com/images/newpm.gif");

            if (!newPms.Any())
            {
                var userMessage = new VoiceCommandUserMessage();
                userMessage.DisplayMessage = userMessage.SpokenMessage = "You don't have any new private messages (because nobody likes you).";
                response = VoiceCommandResponse.CreateResponse(userMessage);
                await voiceServiceConnection.ReportSuccessAsync(response);

                return;
            }

            if (newPms.Count() == 1)
            {
                string newPmPrompt = string.Format("You have a new private message from {0}: \"{1}\", would you like to view it?",
                                                   newPms.First().Sender, newPms.First().Title);
                userPrompt.DisplayMessage = userPrompt.SpokenMessage = newPmPrompt;
                var    userReprompt       = new VoiceCommandUserMessage();
                string newPmPromptConfirm = "Would you like to view it?";
                userReprompt.DisplayMessage = userReprompt.SpokenMessage = newPmPromptConfirm;

                response = VoiceCommandResponse.CreateResponseForPrompt(userPrompt, userReprompt);

                var voiceCommandConfirmation = await voiceServiceConnection.RequestConfirmationAsync(response);

                if (voiceCommandConfirmation != null)
                {
                    if (voiceCommandConfirmation.Confirmed)
                    {
                        LaunchAppInForegroundPms();
                    }
                    else
                    {
                        // Confirm no action for the user.
                        var    userMessage             = new VoiceCommandUserMessage();
                        string dontShowAnythingMessage = string.Format("Well, {0} is going to be pretty mad you're blowing off his message. But I won't judge.", newPms.First().Sender);
                        userMessage.DisplayMessage = userMessage.SpokenMessage = dontShowAnythingMessage;

                        response = VoiceCommandResponse.CreateResponse(userMessage);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }
                }
            }
            else
            {
                var newPmsString = string.Format("You have {0} new messages. Would you like to view them?", newPms.Count());
                userPrompt.DisplayMessage = userPrompt.SpokenMessage = newPmsString;
                var    userReprompt       = new VoiceCommandUserMessage();
                string newPmPromptConfirm = "Would you like to view them?";
                userReprompt.DisplayMessage = userReprompt.SpokenMessage = newPmPromptConfirm;

                response = VoiceCommandResponse.CreateResponseForPrompt(userPrompt, userReprompt);

                var voiceCommandConfirmation = await voiceServiceConnection.RequestConfirmationAsync(response);

                if (voiceCommandConfirmation != null)
                {
                    if (voiceCommandConfirmation.Confirmed)
                    {
                        LaunchAppInForegroundPms();
                    }
                    else
                    {
                        // Confirm no action for the user.
                        var    userMessage             = new VoiceCommandUserMessage();
                        string dontShowAnythingMessage = "Well those people are going to be pretty mad at you ignoring them. But whatever, that's fine...";
                        userMessage.DisplayMessage = userMessage.SpokenMessage = dontShowAnythingMessage;

                        response = VoiceCommandResponse.CreateResponse(userMessage);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }
                }
            }
        }
Ejemplo n.º 11
0
        protected override async void OnRun(IBackgroundTaskInstance taskInstance)
        {
            serviceDeferral        = taskInstance.GetDeferral();
            taskInstance.Canceled += OnTaskCanceled;
            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            VoiceCommandUserMessage userMessage;
            VoiceCommandResponse    response;

            try
            {
                voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
                voiceServiceConnection.VoiceCommandCompleted += VoiceCommandCompleted;
                VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

                switch (voiceCommand.CommandName)
                {
                case "graphParams":
                    await ShowProgressScreen("Working on it...");

                    var    modelnumber = voiceCommand.Properties["modelnumber"][0];
                    double lambda      = 0;
                    double mu          = 0;
                    int    model       = Models.Point.GetNumberByModel(Models.Point.GetModelByNumber(modelnumber));

                    if (GetAllParameters(model, voiceCommand, ref lambda, ref mu))
                    {
                        bool allowed     = false;
                        bool unsupported = false;
                        if (model.Equals(1) || model.Equals(2))
                        {
                            var responseMessage = new VoiceCommandUserMessage()
                            {
                                DisplayMessage = String.Format("Get likelihood results for the model {0} with λ={1} and μ={2}?", modelnumber, lambda, mu),
                                SpokenMessage  = String.Format("Do you want me to get likelihood results for the model {0} with these input data?", modelnumber)
                            };
                            var repeatMessage = new VoiceCommandUserMessage()
                            {
                                DisplayMessage = String.Format("Do you still want me to get likelihood results for the model {0} with λ={1} and μ={2}?", modelnumber, lambda, mu),
                                SpokenMessage  = String.Format("Do you still want me to get likelihood results for the model {0} with these input data?", modelnumber)
                            };

                            response = VoiceCommandResponse.CreateResponseForPrompt(responseMessage, repeatMessage);
                            try
                            {
                                var confirmation = await voiceServiceConnection.RequestConfirmationAsync(response);

                                allowed = confirmation.Confirmed;
                            }
                            catch
                            { }
                        }
                        else
                        {
                            unsupported = true;
                        }

                        if (allowed)
                        {
                            await ShowProgressScreen("Calculating...");

                            List <VoiceCommandContentTile> resultContentTiles = GetLikelihoodForSelectedModel(lambda, mu, model);
                            userMessage = new VoiceCommandUserMessage()
                            {
                                DisplayMessage = String.Format("Here is your likelihood results for the model {0}", modelnumber),
                                SpokenMessage  = "Done and Done! Here is your results"
                            };
                            response = VoiceCommandResponse.CreateResponse(userMessage, resultContentTiles);
                            response.AppLaunchArgument = modelnumber;
                            await voiceServiceConnection.ReportSuccessAsync(response);
                        }
                        else if (unsupported)
                        {
                            userMessage = new VoiceCommandUserMessage()
                            {
                                DisplayMessage = String.Format("Model {0} is not supported now", modelnumber),
                                SpokenMessage  = "Sorry, this model is not supported now"
                            };
                            response = VoiceCommandResponse.CreateResponse(userMessage);
                            response.AppLaunchArgument = modelnumber;
                            await voiceServiceConnection.ReportFailureAsync(response);
                        }
                        else
                        {
                            userMessage = new VoiceCommandUserMessage()
                            {
                                DisplayMessage = "Okay then",
                                SpokenMessage  = "Okay, then"
                            };
                            response = VoiceCommandResponse.CreateResponse(userMessage);
                            await voiceServiceConnection.ReportSuccessAsync(response);
                        }
                    }
                    else
                    {
                        userMessage = new VoiceCommandUserMessage()
                        {
                            DisplayMessage = "The arguments is incorrect",
                            SpokenMessage  = "Sorry, it seems the arguments is incorrect"
                        };
                        response = VoiceCommandResponse.CreateResponse(userMessage);
                        response.AppLaunchArgument = "";
                        await voiceServiceConnection.ReportFailureAsync(response);
                    }
                    break;

                default:
                    LaunchAppInForeground();
                    break;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                if (serviceDeferral != null)
                {
                    //Complete the service deferral
                    serviceDeferral.Complete();
                }
            }
        }
        /// <summary>
        /// Handle the Trip Cancellation task. This task demonstrates how to prompt a user
        /// for confirmation of an operation, show users a progress screen while performing
        /// a long-running task, and showing a completion screen.
        /// </summary>
        /// <param name="destination">The name of a destination, expected to match the phrase list.</param>
        /// <returns></returns>
        private async Task SendCompletionMessageForCancellation(string destination)
        {
            // Begin loading data to search for the target store. If this operation is going to take a long time,
            // for instance, requiring a response from a remote web service, consider inserting a progress screen
            // here, in order to prevent Cortana from timing out.
            string progressScreenString = string.Format(
                cortanaResourceMap.GetValue("ProgressLookingForTripToDest", cortanaContext).ValueAsString,
                destination);

            await ShowProgressScreen(progressScreenString);

            Model.TripStore store = new Model.TripStore();
            await store.LoadTrips();

            // We might have multiple trips to the destination. For now, we just pick the first.
            IEnumerable <Model.Trip> trips = store.Trips.Where(p => p.Destination == destination);

            Model.Trip trip = null;
            if (trips.Count() > 1)
            {
                // If there is more than one trip, provide a disambiguation screen rather than just picking one
                // however, more advanced logic here might be ideal (ie, if there's a significant number of items,
                // you may want to just fall back to a link to your app where you can provide a deeper search experience.
                string disambiguationDestinationString = string.Format(
                    cortanaResourceMap.GetValue("DisambiguationWhichTripToDest", cortanaContext).ValueAsString,
                    destination);
                string disambiguationRepeatString = cortanaResourceMap.GetValue("DisambiguationRepeat", cortanaContext).ValueAsString;
                trip = await DisambiguateTrips(trips, disambiguationDestinationString, disambiguationRepeatString);
            }
            else
            {
                // One or no trips exist with that destination, so retrieve it, or return null.
                trip = trips.FirstOrDefault();
            }

            var userPrompt = new VoiceCommandUserMessage();

            VoiceCommandResponse response;

            if (trip == null)
            {
                var userMessage = new VoiceCommandUserMessage();
                // In this scenario, perhaps someone has modified data on your service outside of this
                // apps control. If you're accessing a remote service, having a background task that
                // periodically refreshes the phrase list so it's likely to be in sync is ideal.
                // This is unlikely to occur for this sample app, however.
                string noSuchTripToDestination = string.Format(
                    cortanaResourceMap.GetValue("NoSuchTripToDestination", cortanaContext).ValueAsString,
                    destination);
                userMessage.DisplayMessage = userMessage.SpokenMessage = noSuchTripToDestination;

                response = VoiceCommandResponse.CreateResponse(userMessage);
                await voiceServiceConnection.ReportSuccessAsync(response);
            }
            else
            {
                // Prompt the user for confirmation that we've selected the correct trip to cancel.
                string cancelTripToDestination = string.Format(
                    cortanaResourceMap.GetValue("CancelTripToDestination", cortanaContext).ValueAsString,
                    destination);
                userPrompt.DisplayMessage = userPrompt.SpokenMessage = cancelTripToDestination;
                var    userReprompt = new VoiceCommandUserMessage();
                string confirmCancelTripToDestination = string.Format(
                    cortanaResourceMap.GetValue("ConfirmCancelTripToDestination", cortanaContext).ValueAsString,
                    destination);
                userReprompt.DisplayMessage = userReprompt.SpokenMessage = confirmCancelTripToDestination;

                //REVERT

                var cancelledContentTiles = new List <VoiceCommandContentTile>();
                if (xyz != null)
                {
                    cancelledContentTiles.Add(xyz);
                }
                response = VoiceCommandResponse.CreateResponseForPrompt(userPrompt, userReprompt, cancelledContentTiles);

                var voiceCommandConfirmation = await voiceServiceConnection.RequestConfirmationAsync(response);

                // If RequestConfirmationAsync returns null, Cortana's UI has likely been dismissed.
                if (voiceCommandConfirmation != null)
                {
                    if (voiceCommandConfirmation.Confirmed == true)
                    {
                        string cancellingTripToDestination = string.Format(
                            cortanaResourceMap.GetValue("CancellingTripToDestination", cortanaContext).ValueAsString,
                            destination);
                        await ShowProgressScreen(cancellingTripToDestination);

                        // Perform the operation to remote the trip from the app's data.
                        // Since the background task runs within the app package of the installed app,
                        // we can access local files belonging to the app without issue.
                        await store.DeleteTrip(trip);

                        // Provide a completion message to the user.
                        var    userMessage = new VoiceCommandUserMessage();
                        string cancelledTripToDestination = string.Format(
                            cortanaResourceMap.GetValue("CancelledTripToDestination", cortanaContext).ValueAsString,
                            destination);
                        userMessage.DisplayMessage = userMessage.SpokenMessage = cancelledTripToDestination;

                        response = VoiceCommandResponse.CreateResponse(userMessage, cancelledContentTiles); //REVERT cancelledContentTiles
                        response.AppLaunchArgument = destination;                                           //REVERT
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }
                    else
                    {
                        // Confirm no action for the user.
                        var    userMessage = new VoiceCommandUserMessage();
                        string keepingTripToDestination = string.Format(
                            cortanaResourceMap.GetValue("KeepingTripToDestination", cortanaContext).ValueAsString,
                            destination);
                        userMessage.DisplayMessage = userMessage.SpokenMessage = keepingTripToDestination;

                        response = VoiceCommandResponse.CreateResponse(userMessage);
                        response.AppLaunchArgument = destination; //REVERT
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }
                }
            }
        }
Ejemplo n.º 13
0
        protected override async void OnRun(IBackgroundTaskInstance taskInstance)
        {
            this.serviceDeferral = taskInstance.GetDeferral();
            taskInstance.Canceled += OnTaskCanceled;

            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            
            VoiceCommandResponse response;
            try
            {
                voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
                voiceServiceConnection.VoiceCommandCompleted += VoiceCommandCompleted;
                VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();
                VoiceCommandUserMessage userMessage = new VoiceCommandUserMessage();

                List<VoiceCommandContentTile> contentTiles;

                switch (voiceCommand.CommandName)
                {
                    case "what":

                        _todoItemRepository = TODOAdaptiveUISample.Repositories.TodoItemFileRepository.GetInstance();
                        var data = await _todoItemRepository.RefreshTodoItemsAsync();

                        contentTiles = new List<VoiceCommandContentTile>();
                        
                        userMessage.SpokenMessage = "Your Top To Do's are: ";

                        foreach (var item in data.Where(x => x.IsComplete == false).OrderBy(x => x.DueDate).Take((int)VoiceCommandResponse.MaxSupportedVoiceCommandContentTiles))
                        {
                            var tile = new VoiceCommandContentTile();
                            tile.ContentTileType = VoiceCommandContentTileType.TitleWithText;
                            tile.Title = item.Title;
                            //tile.TextLine1 = item.Details;
                            contentTiles.Add(tile);

                            userMessage.SpokenMessage += item.Title + ", ";
                        }

                        userMessage.DisplayMessage = "Here are the top " + contentTiles.Count + " To Do's";

                        
                        
                        response = VoiceCommandResponse.CreateResponse(userMessage, contentTiles);
                        await voiceServiceConnection.ReportSuccessAsync(response);

                        break;


                    case "new":
                        var todo = voiceCommand.Properties["todo"][0];

                        var responseMessage = new VoiceCommandUserMessage()
                        {
                            DisplayMessage = String.Format("Add \"{0}\" to your To Do's?", todo),
                            SpokenMessage = String.Format("Do you want me to add \"{0}\" to your To Do's?", todo)
                        };

                        var repeatMessage = new VoiceCommandUserMessage()
                        {
                            DisplayMessage = String.Format("Are you sure you want me to add \"{0}\" to your To Do's?", todo),
                            SpokenMessage = String.Format("Are you sure you want me to add \"{0}\" to your To Do's?", todo)
                        };

                        bool confirmed = false;
                        response = VoiceCommandResponse.CreateResponseForPrompt(responseMessage, repeatMessage);
                        try
                        {
                            var confirmation = await voiceServiceConnection.RequestConfirmationAsync(response);
                            confirmed = confirmation.Confirmed;
                        }
                        catch
                        {

                        }
                        if (confirmed)
                        {
                            _todoItemRepository = TODOAdaptiveUISample.Repositories.TodoItemFileRepository.GetInstance();
                            var i = _todoItemRepository.Factory(title: todo);
                            await _todoItemRepository.InsertTodoItem(i);

                            var todos = await _todoItemRepository.RefreshTodoItemsAsync();

                            contentTiles = new List<VoiceCommandContentTile>();

                            foreach (var itm in todos.Where(x => x.IsComplete == false).OrderBy(x => x.DueDate).Take((int)VoiceCommandResponse.MaxSupportedVoiceCommandContentTiles))
                            {
                                var tile = new VoiceCommandContentTile();
                                tile.ContentTileType = VoiceCommandContentTileType.TitleWithText;
                                tile.Title = itm.Title;
                                contentTiles.Add(tile);
                            }

                            userMessage.SpokenMessage = "Done and Done! Here are your top To Do's";
                            userMessage.DisplayMessage = "Here are your top " + contentTiles.Count + " To Do's";

                            response = VoiceCommandResponse.CreateResponse(userMessage, contentTiles);
                            await voiceServiceConnection.ReportSuccessAsync(response);
                        }
                        else
                        {
                            userMessage.DisplayMessage = userMessage.SpokenMessage = "OK then";
                            response = VoiceCommandResponse.CreateResponse(userMessage);
                            await voiceServiceConnection.ReportSuccessAsync(response);
                        }



                        break;

                }
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }
            }
            finally
            {
                if (this.serviceDeferral != null)
                {
                    //Complete the service deferral
                    this.serviceDeferral.Complete();
                }
            }
        }
Ejemplo n.º 14
0
        protected override async void OnRun(IBackgroundTaskInstance taskInstance)
        {
            serviceDeferral = taskInstance.GetDeferral();
            taskInstance.Canceled += OnTaskCanceled;
            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            VoiceCommandUserMessage userMessage;
            VoiceCommandResponse response;
            try
            {
                voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
                voiceServiceConnection.VoiceCommandCompleted += VoiceCommandCompleted;
                VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

                switch (voiceCommand.CommandName)
                {
                    case "graphParams":
                        await ShowProgressScreen("Working on it...");
                        var modelnumber = voiceCommand.Properties["modelnumber"][0];
                        double lambda = 0;
                        double mu = 0;
                        int model = Models.Point.GetNumberByModel(Models.Point.GetModelByNumber(modelnumber));
                        
                        if (GetAllParameters(model, voiceCommand, ref lambda, ref mu))
                        {
                            bool allowed = false;
                            bool unsupported = false;
                            if (model.Equals(1) || model.Equals(2))
                            {
                                var responseMessage = new VoiceCommandUserMessage()
                                {
                                    DisplayMessage = String.Format("Get likelihood results for the model {0} with λ={1} and μ={2}?", modelnumber, lambda, mu),
                                    SpokenMessage = String.Format("Do you want me to get likelihood results for the model {0} with these input data?", modelnumber)
                                };
                                var repeatMessage = new VoiceCommandUserMessage()
                                {
                                    DisplayMessage = String.Format("Do you still want me to get likelihood results for the model {0} with λ={1} and μ={2}?", modelnumber, lambda, mu),
                                    SpokenMessage = String.Format("Do you still want me to get likelihood results for the model {0} with these input data?", modelnumber)
                                };

                                response = VoiceCommandResponse.CreateResponseForPrompt(responseMessage, repeatMessage);
                                try
                                {
                                    var confirmation = await voiceServiceConnection.RequestConfirmationAsync(response);
                                    allowed = confirmation.Confirmed;
                                }
                                catch
                                { }
                            }
                            else
                            {
                                unsupported = true;
                            }

                            if (allowed)
                            {
                                await ShowProgressScreen("Calculating...");
                                List<VoiceCommandContentTile> resultContentTiles = GetLikelihoodForSelectedModel(lambda, mu, model);
                                userMessage = new VoiceCommandUserMessage()
                                {
                                    DisplayMessage = String.Format("Here is your likelihood results for the model {0}", modelnumber),
                                    SpokenMessage = "Done and Done! Here is your results"
                                };
                                response = VoiceCommandResponse.CreateResponse(userMessage, resultContentTiles);
                                response.AppLaunchArgument = modelnumber;
                                await voiceServiceConnection.ReportSuccessAsync(response);
                            }
                            else if (unsupported)
                            {
                                userMessage = new VoiceCommandUserMessage()
                                {
                                    DisplayMessage = String.Format("Model {0} is not supported now", modelnumber),
                                    SpokenMessage = "Sorry, this model is not supported now"
                                };
                                response = VoiceCommandResponse.CreateResponse(userMessage);
                                response.AppLaunchArgument = modelnumber;
                                await voiceServiceConnection.ReportFailureAsync(response);
                            }
                            else
                            {
                                userMessage = new VoiceCommandUserMessage()
                                {
                                    DisplayMessage = "Okay then",
                                    SpokenMessage = "Okay, then"
                                };
                                response = VoiceCommandResponse.CreateResponse(userMessage);
                                await voiceServiceConnection.ReportSuccessAsync(response);
                            }
                        }
                        else
                        {
                            userMessage = new VoiceCommandUserMessage()
                            {
                                DisplayMessage = "The arguments is incorrect",
                                SpokenMessage = "Sorry, it seems the arguments is incorrect"
                            };
                            response = VoiceCommandResponse.CreateResponse(userMessage);
                            response.AppLaunchArgument = "";
                            await voiceServiceConnection.ReportFailureAsync(response);
                        }
                        break;
                    default:
                        LaunchAppInForeground();
                        break;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                if (serviceDeferral != null)
                {
                    //Complete the service deferral
                    serviceDeferral.Complete();
                }
            }
        }
Ejemplo n.º 15
0
        private async void DeleteTask(string DeletedTask)
        {
            await ShowProgressScreen("Looking for your tasks.");

            List <string> ListOfTasks;

            ListOfTasks = GetListOfTasks().Result.Where(x => x.Name == DeletedTask).Select(x => x.Name).ToList();

            VoiceCommandUserMessage        UserMessage = new VoiceCommandUserMessage();
            List <VoiceCommandContentTile> TaskTiles   = new List <VoiceCommandContentTile>();
            VoiceCommandResponse           Response;

            if (ListOfTasks.Count == 0)
            {
                UserMessage.DisplayMessage = UserMessage.SpokenMessage = $"Sorry, you don't have any tasks.";

                Response = VoiceCommandResponse.CreateResponse(UserMessage);
                await VoiceServiceConnection.ReportSuccessAsync(Response);
            }
            else
            {
                string Message = "";
                if (ListOfTasks.Count != 1)
                {
                    Message = $"Here are your tasks. Please, select one.";
                    string SelectedTask = await GetSingleTask(ListOfTasks, Message, "Which task do you want to delete?");

                    ListOfTasks.Clear();
                    ListOfTasks.Add(SelectedTask);
                }

                var UserReMessage = new VoiceCommandUserMessage();

                UserMessage.DisplayMessage   = UserMessage.SpokenMessage = $"Do you want delete this {ListOfTasks[0]}?";
                UserReMessage.DisplayMessage = UserReMessage.SpokenMessage = "Do you want delete it?";

                Response = VoiceCommandResponse.CreateResponseForPrompt(UserMessage, UserReMessage);

                var VoiceCommandConfirmation = await VoiceServiceConnection.RequestConfirmationAsync(Response);

                // If RequestConfirmationAsync returns null, Cortana's UI has likely been dismissed.
                if (VoiceCommandConfirmation != null)
                {
                    if (VoiceCommandConfirmation.Confirmed == true)
                    {
                        await ShowProgressScreen("Deleting your task.");

                        int ID = GetListOfTasks().Result.Where(x => x.Name == ListOfTasks[0]).Select(x => x.ID).FirstOrDefault();
                        ObservableCollection <Tasks> TasksList = await GetListOfTasks();

                        await CompleteTask(ID, TasksList);
                    }
                    else
                    {
                        UserMessage.DisplayMessage = UserMessage.SpokenMessage = $"All right. {ListOfTasks[0]} won't be deleted.";

                        Response = VoiceCommandResponse.CreateResponse(UserMessage);
                        await VoiceServiceConnection.ReportSuccessAsync(Response);

                        return;
                    }
                }
            }

            UserMessage.DisplayMessage = UserMessage.SpokenMessage = "Your task has been deleted";
            Response = VoiceCommandResponse.CreateResponse(UserMessage);
            await VoiceServiceConnection.ReportSuccessAsync(Response);

            try
            {
                StorageFile VoiceCommandsStorageFile = await Package.Current.InstalledLocation.GetFileAsync(@"VoiceCommands.xml");

                await VoiceCommandDefinitionManager.InstallCommandDefinitionsFromStorageFileAsync(VoiceCommandsStorageFile);

                UpdatePhraseList();
            }
            catch (Exception)
            {
                //throw;
            }
        }
        /// <summary>
        /// Handle the Trip Cancellation task. This task demonstrates how to prompt a user
        /// for confirmation of an operation, show users a progress screen while performing
        /// a long-running task, and showing a completion screen.
        /// </summary>
        /// <param name="destination">The name of a destination, expected to match the phrase list.</param>
        /// <returns></returns>
        private async Task SendCompletionMessageForCancellation(string destination)
        {
            // Begin loading data to search for the target store. If this operation is going to take a long time,
            // for instance, requiring a response from a remote web service, consider inserting a progress screen
            // here, in order to prevent Cortana from timing out.
            await ShowProgressScreen("Looking for a trip to " + destination);

            Model.TripStore store = new Model.TripStore();
            await store.LoadTrips();

            // We might have multiple trips to the destination. For now, we just pick the first.
            IEnumerable <Model.Trip> trips = store.Trips.Where(p => p.Destination == destination);

            Model.Trip trip = null;
            if (trips.Count() > 1)
            {
                // If there is more than one trip, provide a disambiguation screen rather than just picking one
                // however, more advanced logic here might be ideal (ie, if there's a significant number of items,
                // you may want to just fall back to a link to your app where you can provide a deeper search experience.
                trip = await DisambiguateTrips(
                    trips,
                    "Which trip to " + destination + " did you want to cancel?",
                    "Which one do you want to cancel?");
            }
            else
            {
                // One or no trips exist with that destination, so retrieve it, or return null.
                trip = trips.FirstOrDefault();
            }

            var userPrompt = new VoiceCommandUserMessage();

            VoiceCommandResponse response;

            if (trip == null)
            {
                var userMessage = new VoiceCommandUserMessage();
                // In this scenario, perhaps someone has modified data on your service outside of this
                // apps control. If you're accessing a remote service, having a background task that
                // periodically refreshes the phrase list so it's likely to be in sync is ideal.
                // This is unlikely to occur for this sample app, however.
                userMessage.DisplayMessage = userMessage.SpokenMessage = "Sorry, you don't have any trips to " + destination;

                response = VoiceCommandResponse.CreateResponse(userMessage);
                await voiceServiceConnection.ReportSuccessAsync(response);
            }
            else
            {
                // Prompt the user for confirmation that we've selected the correct trip to cancel.
                userPrompt.DisplayMessage = userPrompt.SpokenMessage = "Cancel this trip to " + destination + "?";
                var userReprompt = new VoiceCommandUserMessage();
                userReprompt.DisplayMessage = userReprompt.SpokenMessage = "Did you want to cancel this trip to " + destination + "?";

                response = VoiceCommandResponse.CreateResponseForPrompt(userPrompt, userReprompt);

                var voiceCommandConfirmation = await voiceServiceConnection.RequestConfirmationAsync(response);

                // If RequestConfirmationAsync returns null, Cortana's UI has likely been dismissed.
                if (voiceCommandConfirmation != null)
                {
                    if (voiceCommandConfirmation.Confirmed == true)
                    {
                        await ShowProgressScreen("Cancelling the trip to " + destination);

                        // Perform the operation to remote the trip from the app's data.
                        // Since the background task runs within the app package of the installed app,
                        // we can access local files belonging to the app without issue.
                        await store.DeleteTrip(trip);

                        // Provide a completion message to the user.
                        var userMessage = new VoiceCommandUserMessage();
                        userMessage.DisplayMessage = userMessage.SpokenMessage = "Cancelled the trip to " + destination;
                        response = VoiceCommandResponse.CreateResponse(userMessage);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }
                    else
                    {
                        // Confirm no action for the user.
                        var userMessage = new VoiceCommandUserMessage();
                        userMessage.DisplayMessage = userMessage.SpokenMessage = "Okay, Keeping the trip to " + destination;

                        response = VoiceCommandResponse.CreateResponse(userMessage);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }
                }
            }
        }