private async Task CreateConversationAsync() { var tokenInfo = await GetDirectLineTokenAsync().ConfigureAwait(false); // Create directLine client from token _dlClient = new DirectLineClient(tokenInfo.Token); _dlClient.SetRetryPolicy(new RetryPolicy(new HttpStatusCodeErrorDetectionStrategy(), 0)); // From now on, we'll add an Origin header in directLine calls, with // the trusted origin we sent when acquiring the token as value. _dlClient.HttpClient.DefaultRequestHeaders.Add(_originHeader.Key, _originHeader.Value); // Start the conversation now the the _dlClient has been initialized. _conversation = await _dlClient.Conversations.StartConversationAsync().ConfigureAwait(false); }
public void Install(IWindsorContainer container, IConfigurationStore store) { // TODO: Replace with Check.NotNull (after preparing nuget package) if (container == null) { throw new ArgumentNullException(nameof(container)); } container.Register( Classes.FromThisAssembly() .Pick() .WithServiceDefaultInterfaces() .LifestyleScoped()); var directLineClient = new DirectLineClient( new DirectLineClientCredentials(ConfigurationManager.AppSettings.Get("DirectLineSecret"))); directLineClient.HttpClient.Timeout = TimeSpan.FromMinutes(5); var directLineTimeoutSetting = ConfigurationManager.AppSettings.Get("DirectLineMinutesForTimeout"); int directLineTimeout; if (!int.TryParse(directLineTimeoutSetting, out directLineTimeout)) { directLineTimeout = 5; } directLineClient.SetRetryPolicy( new RetryPolicy( new TransientErrorIgnoreStrategy(), 0, TimeSpan.FromMinutes(directLineTimeout))); container.Register( Component.For <IDirectLineClient>() .Instance(directLineClient)); }
private async Task StartConversationAsync() { var tryCount = 0; var maxTries = _options.StartConversationMaxAttempts; while (tryCount < maxTries && !_activityQueue.Any() && !_futureQueue.Any()) { using var startConversationCts = new CancellationTokenSource(_options.StartConversationTimeout); tryCount++; try { _logger.LogDebug($"{DateTime.Now} Attempting to start conversation (try {tryCount} of {maxTries})."); // Obtain a token using the Direct Line secret var tokenInfo = await GetDirectLineTokenAsync().ConfigureAwait(false); // Ensure we dispose the client after the retries (this helps us make sure we get a new conversation ID on each try) _dlClient?.Dispose(); // Create directLine client from token and initialize settings. _dlClient = new DirectLineClient(tokenInfo.Token); _dlClient.SetRetryPolicy(new RetryPolicy(new HttpStatusCodeErrorDetectionStrategy(), 0)); // From now on, we'll add an Origin header in directLine calls, with // the trusted origin we sent when acquiring the token as value. _dlClient.HttpClient.DefaultRequestHeaders.Add(_originHeader.Key, _originHeader.Value); // Start the conversation now (this will send a ConversationUpdate to the bot) _conversation = await _dlClient.Conversations.StartConversationAsync(startConversationCts.Token).ConfigureAwait(false); _logger.LogDebug($"{DateTime.Now} Got conversation ID {_conversation.ConversationId} from direct line client."); _logger.LogTrace($"{DateTime.Now} {Environment.NewLine}{JsonConvert.SerializeObject(_conversation, Formatting.Indented)}"); // Ensure we dispose the _webSocketClient after the retries. _webSocketClient?.Dispose(); // Initialize web socket client and listener _webSocketClient = new ClientWebSocket(); await _webSocketClient.ConnectAsync(new Uri(_conversation.StreamUrl), startConversationCts.Token).ConfigureAwait(false); _logger.LogDebug($"{DateTime.Now} Connected to websocket, state is {_webSocketClient.State}."); // Block and wait for the first response to come in. ActivitySet activitySet = null; while (activitySet == null) { activitySet = await ReceiveActivityAsync(startConversationCts).ConfigureAwait(false); if (activitySet != null) { ProcessActivitySet(activitySet); } else { _logger.LogDebug($"{DateTime.Now} Got empty ActivitySet while attempting to start the conversation."); } } } catch (Exception ex) { if (tryCount < maxTries) { _logger.LogDebug($"{DateTime.Now} Failed to start conversation (attempt {tryCount} of {maxTries}), retrying...{Environment.NewLine}Exception{Environment.NewLine}{ex}"); } else { _logger.LogCritical($"{DateTime.Now} Failed to start conversation after {maxTries} attempts.{Environment.NewLine}Exception{Environment.NewLine}{ex}"); throw; } } } // We have started a conversation and got at least one activity back. // Start long running background task to read activities from the socket. _webSocketClientCts = new CancellationTokenSource(); _ = Task.Factory.StartNew(() => ListenAsync(_webSocketClientCts), _webSocketClientCts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); }