Ejemplo n.º 1
0
 public void StartNewConversation()
 {
     watermark = null;
     fromUser  = Guid.NewGuid().ToString();
     if (directLineClient != null)
     {
         directLineClient.Dispose();
     }
     directLineClient = new DirectLineClient(directLineToken);
     conversation     = directLineClient.Conversations.StartConversation();
 }
Ejemplo n.º 2
0
        public void Dispose()
        {
            if (client == null)
            {
                return;
            }

            var userActivity = new Activity
            {
                From = new ChannelAccount(Constants.Email, Constants.Username),
                Type = ActivityTypes.EndOfConversation
            };

            client.Conversations.PostActivityAsync(conversation.ConversationId, userActivity);
            client.Dispose();
            client       = null;
            conversation = null;

            webSocket.OnMessage -= WebSocket_OnMessage;
            webSocket.OnClose   -= WebSocket_OnClose;
            webSocket.OnError   -= WebSocket_OnError;
            if (webSocket.IsAlive)
            {
                webSocket.CloseAsync();
            }
            webSocket = null;
            viewModel = null;
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Use directlineClient to get bot response
        /// </summary>
        /// <returns>List of DirectLine activities</returns>
        /// <param name="directLineClient">directline client</param>
        /// <param name="conversationtId">current conversation ID</param>
        /// <param name="botName">name of bot to connect to</param>
        private static async Task <List <Activity> > GetBotResponseActivitiesAsync(DirectLineClient directLineClient, string conversationtId)
        {
            ActivitySet     response = null;
            List <Activity> result   = new List <Activity>();

            do
            {
                response = await directLineClient.Conversations.GetActivitiesAsync(conversationtId, _watermark);

                if (response == null)
                {
                    // response can be null if directLineClient token expires
                    Console.WriteLine("Conversation expired. Press any key to exit.");
                    Console.Read();
                    directLineClient.Dispose();
                    Environment.Exit(0);
                }

                _watermark = response?.Watermark;
                result     = response?.Activities?.Where(x =>
                                                         x.Type == ActivityTypes.Message &&
                                                         string.Equals(x.From.Name, s_botService.BotName, StringComparison.Ordinal)).ToList();

                if (result != null && result.Any())
                {
                    return(result);
                }

                Thread.Sleep(1000);
            } while (response != null && response.Activities.Any());

            return(new List <Activity>());
        }
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <param name="disposing">Boolean value that determines whether to free resources or not.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            if (disposing)
            {
                // Dispose managed objects owned by the class here.
                _dlClient?.Dispose();

                _webSocketClientCts?.Cancel();
                _webSocketClientCts?.Dispose();
                _webSocketClient?.Dispose();
            }

            _disposed = true;
        }
        private void StopBotConversation()
        {
            if (_client != null)
            {
                _client.Dispose();
                _client = null;
            }

            _conversation = null;

            Activities.Clear();
        }
Ejemplo n.º 6
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                directLineClient.Dispose();
            }

            disposed = true;
        }
Ejemplo n.º 7
0
        void DisposeConnection()
        {
            if (_chatClient != null)
            {
                _chatClient.Dispose();
                _chatClient = null;
            }

            if (_webSocket != null)
            {
                _webSocket.OnMessage -= WebSocketOnOnMessage;
                _webSocket.Close();
                _webSocket = null;
            }

            _channelAccount = null;
            _conversation   = null;
        }
Ejemplo n.º 8
0
        public void Dispose()
        {
            if (client == null)
            {
                return;
            }

            var userActivity = new Activity
            {
                From = new ChannelAccount(Constants.Email),
                Type = ActivityTypes.EndOfConversation
            };

            client.Conversations.PostActivityAsync(conversation.ConversationId, userActivity);
            client.Dispose();
            client            = null;
            userAccount       = null;
            conversation      = null;
            readMessageThread = null;
            viewModel         = null;
        }
Ejemplo n.º 9
0
        public static async void StartService()
        {
            try
            {
                if (isRunning)
                {
                    // If the service is already running, exits.
                    return;
                }

                isRunning = true;

                var isConnected = false;
                while (!isConnected)
                {
                    // Be sure to be connected to the Internet.
                    var profile = NetworkInformation.GetInternetConnectionProfile();
                    isConnected = profile?.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess;
                    await Task.Delay(200);
                }

                if (Settings.Instance == null)
                {
                    await LoadSettingsAsync();
                }

                if (directLineClient == null)
                {
                    // Obtain a token using the Direct Line secret
                    var tokenResponse = await new DirectLineClient(Settings.Instance.DirectLineSecret).Tokens.GenerateTokenForNewConversationAsync();

                    // Use token to create conversation
                    directLineClient = new DirectLineClient(tokenResponse.Token);
                    conversation     = await directLineClient.Conversations.StartConversationAsync();

                    // Connect using a WebSocket.
                    webSocketClient = new MessageWebSocket();
                    webSocketClient.MessageReceived += WebSocketClient_MessageReceived;
                    await webSocketClient.ConnectAsync(new Uri(conversation.StreamUrl));
                }

                if (assistantInvokerSpeechRecognizer == null)
                {
                    // Create an instance of SpeechRecognizer.
                    assistantInvokerSpeechRecognizer = new SpeechRecognizer(new Language(Settings.Instance.Culture));
                    assistantInvokerSpeechRecognizer.Timeouts.InitialSilenceTimeout = TimeSpan.MaxValue;
                    assistantInvokerSpeechRecognizer.Timeouts.BabbleTimeout         = TimeSpan.MaxValue;

                    // Add a list constraint to the recognizer.
                    var listConstraint = new SpeechRecognitionListConstraint(new string[] { Settings.Instance.AssistantName }, "assistant");
                    assistantInvokerSpeechRecognizer.Constraints.Add(listConstraint);
                    await assistantInvokerSpeechRecognizer.CompileConstraintsAsync();
                }

                if (commandSpeechRecognizer == null)
                {
                    commandSpeechRecognizer = new SpeechRecognizer(new Language(Settings.Instance.Culture));

                    // Apply the dictation topic constraint to optimize for dictated freeform speech.
                    var dictationConstraint = new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario.WebSearch, "dictation");
                    commandSpeechRecognizer.Constraints.Add(dictationConstraint);
                    await commandSpeechRecognizer.CompileConstraintsAsync();
                }

                // The assistant is ready to receive input.
                SoundPlayer.Instance.Play(Sounds.SpeechActive);

                while (isRunning)
                {
                    try
                    {
                        var assistantInvocationResult = await assistantInvokerSpeechRecognizer.RecognizeAsync();

                        if (assistantInvocationResult.Status == SpeechRecognitionResultStatus.Success && assistantInvocationResult.Confidence != SpeechRecognitionConfidence.Rejected)
                        {
                            OnStartRecognition?.Invoke(null, EventArgs.Empty);
                            SoundPlayer.Instance.Play(Sounds.Ready);

                            // Starts command recognition. It returns when the first utterance has been recognized.
                            var commandResult = await commandSpeechRecognizer.RecognizeAsync();

                            if (commandResult.Status == SpeechRecognitionResultStatus.Success && commandResult.Confidence != SpeechRecognitionConfidence.Rejected)
                            {
                                var command = commandResult.NormalizeText();
                                Debug.WriteLine(command);

                                OnCommandReceived?.Invoke(null, EventArgs.Empty);

                                // Sends the activity to the Bot. The answer will be received in the WebSocket received event handler.
                                var userMessage = new Activity
                                {
                                    From = new ChannelAccount(Settings.Instance.UserName),
                                    Text = command,
                                    Type = ActivityTypes.Message
                                };

                                await directLineClient.Conversations.PostActivityAsync(conversation.ConversationId, userMessage);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        OnResponseReceived?.Invoke(null, new BotEventArgs(ex.Message));
                    }
                }

                // Clean up used resources.
                SoundPlayer.Instance.Play(Sounds.SpeechStopped);
            }
            catch (Exception ex)
            {
                OnResponseReceived?.Invoke(null, new BotEventArgs(ex.Message));
                SoundPlayer.Instance.Play(Sounds.SpeechStopped);
            }

            assistantInvokerSpeechRecognizer?.Dispose();
            commandSpeechRecognizer?.Dispose();
            webSocketClient?.Dispose();
            directLineClient?.Dispose();

            assistantInvokerSpeechRecognizer = null;
            commandSpeechRecognizer          = null;
            webSocketClient  = null;
            conversation     = null;
            directLineClient = null;

            isRunning = false;
        }