public Dispatcher(IServiceProvider serviceProvider,
                          ILogger <Dispatcher> logger,
                          IBotProvider botProvider)
        {
            this.logger      = logger;
            this.botProvider = botProvider;
            commands         = typeof(Startup)
                               .Assembly
                               .GetTypes()
                               .Where(typeof(ICommand).IsAssignableFrom)
                               .Select(serviceProvider.GetService)
                               .OfType <ICommand>()
                               .ToDictionary <ICommand, string, Func <Message, Task> >(x => x.Name, x => x.ExecuteAsync);
            logger.LogInformation($"Found {commands.Count} commands.");
            var parameter = Expression.Parameter(typeof(Update));
            var constant  = Expression.Constant(this);

            updateHandlers = typeof(Dispatcher)
                             .GetMethods(BindingFlags.Instance | BindingFlags.NonPublic)
                             .Select(x => new
            {
                HandlerAttribute = x.GetCustomAttribute <UpdateHandlerAttribute>(),
                Method           = x
            })
                             .Where(x => x.HandlerAttribute != null)
                             .ToDictionary(x => x.HandlerAttribute.UpdateType,
                                           x => Expression
                                           .Lambda <Func <Update, Task> >(Expression
                                                                          .Call(constant, x.Method, parameter),
                                                                          parameter).CompileFast());
            logger.LogInformation($"Found {updateHandlers.Count} update handlers.");
        }
Exemple #2
0
 public Task TakeAction(
     IBotProvider provider, IBotEvent evt, IEventMatchResult match,
     IReadOnlyDictionary <string, IBotPlugin> plugins
     ) => provider.SendMessage(
     evt.ChannelInfo,
     Expand(evt, match, plugins)
     );
Exemple #3
0
#pragma warning disable 1998        // Task needs to be async for API
            public async Task TakeAction(
                IBotProvider provider, IBotEvent @event, IEventMatchResult match,
                IReadOnlyDictionary <string, IBotPlugin> plugins
                )
            {
                plugin.vars[varname] += adjustment;
            }
Exemple #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AuthenticationProvider"/> class.
        /// </summary>
        /// <param name="provider">Provides access to core services.</param>
        /// <param name="customerId">Identifier for customer whose resources are being accessed.</param>
        /// <exception cref="System.ArgumentException">
        /// <paramref name="customerId"/> is empty or null.
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="provider"/> is null.
        /// </exception>
        public AuthenticationProvider(IBotProvider provider, string customerId)
        {
            provider.AssertNotNull(nameof(provider));
            customerId.AssertNotEmpty(nameof(customerId));

            this.customerId = customerId;
            this.provider   = provider;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="GraphClient"/> class.
        /// </summary>
        /// <param name="provider">Provides access to core application services.</param>
        /// <param name="client">Provides the ability to interact with the Microsoft Graph.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="provider"/> is null.
        /// or
        /// <paramref name="client"/> is null.
        /// </exception>
        public GraphClient(IBotProvider provider, IGraphServiceClient client)
        {
            provider.AssertNotNull(nameof(provider));
            client.AssertNotNull(nameof(client));

            this.provider = provider;
            this.client   = client;
        }
 public SearchTracksCommand(IBotProvider botProvider,
                            ISoundCloudInteractor soundCloudInteractor,
                            ISearchCache searchCache)
     : base(botProvider)
 {
     this.soundCloudInteractor = soundCloudInteractor;
     this.searchCache          = searchCache;
 }
Exemple #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AuthDialog"/> class.
        /// </summary>
        /// <param name="provider">Provides access to core application services.</param>
        /// <param name="message">Message received by the bot from the end user.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="provider"/> is null.
        /// or
        /// <paramref name="message"/> is null.
        /// </exception>
        public AuthDialog(IBotProvider provider, IMessageActivity message)
        {
            provider.AssertNotNull(nameof(provider));
            message.AssertNotNull(nameof(message));

            this.provider         = provider;
            conversationReference = message.ToConversationReference();
        }
Exemple #8
0
        /// <summary>
        /// Add a provider for the bot to listen to
        /// </summary>
        /// <param name="provider">a provider wrapped into IBotProvider</param>
        public void AddProvider(IBotProvider provider)
        {
            provider.OnMessageReceive += OnMessageReceive;
            provider.OnMessageEdit    += OnMessageEdit;
            provider.OnMessageDelete  += OnMessageDelete;

            providers.Add(provider);
        }
Exemple #9
0
 public BotFactory()
 {
     this.providers      = new Dictionary <string, CreateProvider>();
     this.plugins        = new Dictionary <string, CreatePlugin>();
     this.loadedProvider = null;
     this.loadedAuth     = null;
     this.loadedChannels = new List <IChannelConfig>();
     this.loadedPlugins  = new Dictionary <string, IBotPlugin>();
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="GraphClient"/> class.
        /// </summary>
        /// <param name="provider">Provides access to core application services.</param>
        /// <param name="customerId">Identifier for customer whose resources are being accessed.</param>
        /// <exception cref="ArgumentException">
        /// <paramref name="customerId"/> is empty or null.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="provider"/> is null.
        /// </exception>
        public GraphClient(IBotProvider provider, string customerId)
        {
            provider.AssertNotNull(nameof(provider));
            customerId.AssertNotEmpty(nameof(customerId));

            this.customerId = customerId;
            this.provider   = provider;
            client          = new GraphServiceClient(new AuthenticationProvider(this.provider, customerId));
        }
Exemple #11
0
 public BotInitializerHostedService(IBotProvider botProvider,
                                    ILogger <BotInitializerHostedService> logger,
                                    IAppConfiguration appConfiguration,
                                    IDispatcher dispatcher)
 {
     this.botProvider      = botProvider;
     this.logger           = logger;
     this.appConfiguration = appConfiguration;
     this.dispatcher       = dispatcher;
 }
Exemple #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="QuestionDialog"/> class.
        /// </summary>
        /// <param name="provider">Provides access to core services.</param>
        public QuestionDialog(IBotProvider provider)
        {
            provider.AssertNotNull(nameof(provider));

            QnAService = new QnAMakerService(new QnAMakerAttribute(
                                                 provider.Configuration.QnASubscriptionKey.ToUnsecureString(),
                                                 provider.Configuration.QnAKnowledgebaseId,
                                                 "default message",
                                                 0.6));
        }
        /// <summary>
        ///  Occurs before the action method is invoked.
        /// </summary>
        /// <param name="actionContext">The action context.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>An instance of <see cref="Task"/> that represents the asynchronous operation.</returns>
        public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            using (ILifetimeScope scope = WebApiApplication.Container.BeginLifetimeScope())
            {
                IBotProvider provider = scope.Resolve <IBotProvider>();

                MicrosoftAppId       = provider.Configuration.MicrosoftAppId;
                MicrosoftAppPassword = provider.Configuration.MicrosoftAppPassword.ToUnsecureString();
            }

            return(base.OnActionExecutingAsync(actionContext, cancellationToken));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DistributedTokenCache"/> class.
        /// </summary>
        /// <param name="provider">Provides access to the core explorer providers.</param>
        /// <param name="resource">The resource being accessed.</param>
        /// <param name="key">The unique identifier for the cache entry.</param>
        /// <exception cref="ArgumentException">
        /// <paramref name="resource"/> is empty or null.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="provider"/> is null.
        /// </exception>
        public DistributedTokenCache(IBotProvider provider, string resource, string key = null)
        {
            provider.AssertNotNull(nameof(provider));
            resource.AssertNotEmpty(nameof(resource));

            this.provider = provider;
            keyValue      = key;
            this.resource = resource;

            AfterAccess  = AfterAccessNotification;
            BeforeAccess = BeforeAccessNotification;
        }
        /// <summary>
        /// Logs the specified exception.
        /// </summary>
        /// <param name="context">The exception logger context</param>
        public override void Log(ExceptionLoggerContext context)
        {
            using (ILifetimeScope scope = WebApiApplication.Container.BeginLifetimeScope())
            {
                IBotProvider provider = scope.Resolve <IBotProvider>();

                if (context?.Exception != null)
                {
                    provider.Telemetry.TrackException(context.Exception);
                }
            }

            base.Log(context);
        }
Exemple #16
0
Fichier : Bot.cs Projet : binn/Meru
        public void AddProvider(IBotProvider provider)
        {
            provider.OnMessageReceive += async(m) =>
            {
                await OnMessageReceive.Invoke(m);
            };

            provider.OnMessageEdit += async(m) =>
            {
                await OnMessageEdit.Invoke(m);
            };

            provider.OnMessageDelete += async(m) =>
            {
                await OnMessageDelete.Invoke(m);
            };

            providers.Add(provider);
        }
        /// <summary>
        /// Logic required to start the application.
        /// </summary>
        protected void Application_Start()
        {
            RegisterContainer();
            GlobalConfiguration.Configure(WebApiConfig.Register);

            using (ILifetimeScope scope = Container.BeginLifetimeScope())
            {
                IBotProvider provider = scope.Resolve <IBotProvider>();

                Task.Run(() => provider.InitializeAsync()).Wait();

                ApplicationInsights.Extensibility.TelemetryConfiguration.Active.InstrumentationKey =
                    provider.Configuration.InstrumentationKey;

                Conversation.UpdateContainer(
                    builder =>
                {
                    builder.RegisterModule(new AzureModule(Assembly.GetExecutingAssembly()));

                    DocumentDbBotDataStore store = new DocumentDbBotDataStore(
                        new Uri(provider.Configuration.CosmosDbEndpoint),
                        provider.Configuration.CosmosDbAccessKey.ToUnsecureString());

                    builder.Register(c =>
                    {
                        return(new MicrosoftAppCredentials(
                                   provider.Configuration.MicrosoftAppId,
                                   provider.Configuration.MicrosoftAppPassword.ToUnsecureString()));
                    }).SingleInstance();

                    builder.Register(c => store)
                    .Keyed <IBotDataStore <BotData> >(AzureModule.Key_DataStore)
                    .AsSelf()
                    .SingleInstance();

                    builder.Register(c => new CachingBotDataStore(store, CachingBotDataStoreConsistencyPolicy.ETagBasedConsistency))
                    .As <IBotDataStore <BotData> >()
                    .AsSelf()
                    .InstancePerLifetimeScope();
                });
            }
        }
Exemple #18
0
 public DownloadCommand(IBotProvider botProvider, ISoundCloudInteractor soundCloudInteractor) : base(botProvider)
 {
     this.soundCloudInteractor = soundCloudInteractor;
 }
 protected CommandBase(IBotProvider botProvider)
 {
     BotProvider = botProvider;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="PartnerOperations"/> class.
 /// </summary>
 /// <param name="provider">Provides access to core services.</param>
 /// <exception cref="ArgumentException">
 /// <paramref name="provider"/> is null.
 /// </exception>
 public PartnerOperations(IBotProvider provider)
 {
     provider.AssertNotNull(nameof(provider));
     this.provider = provider;
 }
Exemple #21
0
        /// <summary>
        /// Performs the operation represented by this intent.
        /// </summary>
        /// <param name="context">The context of the conversational process.</param>
        /// <param name="message">The message from the authenticated user.</param>
        /// <param name="result">The result from Language Understanding cognitive service.</param>
        /// <param name="provider">Provides access to core services.</param>
        /// <returns>An instance of <see cref="Task"/> that represents the asynchronous operation.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="context"/> is null.
        /// or
        /// <paramref name="message"/> is null.
        /// or
        /// <paramref name="result"/> is null.
        /// or
        /// <paramref name="provider"/> is null.
        /// </exception>
        public async Task ExecuteAsync(IDialogContext context, IAwaitable <IMessageActivity> message, LuisResult result, IBotProvider provider)
        {
            CustomerPrincipal           principal;
            DateTime                    startTime;
            Dictionary <string, double> eventMeasurements;
            Dictionary <string, string> eventProperties;
            IMessageActivity            response;
            List <Customer>             customers;

            context.AssertNotNull(nameof(context));
            message.AssertNotNull(nameof(message));
            result.AssertNotNull(nameof(result));
            provider.AssertNotNull(nameof(provider));

            try
            {
                startTime = DateTime.Now;

                principal = await context.GetCustomerPrincipalAsync(provider).ConfigureAwait(false);

                customers = await provider.PartnerOperations.GetCustomersAsync(principal).ConfigureAwait(false);

                response = context.MakeMessage();
                response.AttachmentLayout = AttachmentLayoutTypes.Carousel;

                response.Attachments = customers.Select(c => (new ThumbnailCard
                {
                    Buttons = new List <CardAction>
                    {
                        new CardAction
                        {
                            Title = Resources.SelectCaptial,
                            Type = ActionTypes.PostBack,
                            Value = $"select customer {c.Id}"
                        }
                    },
                    Subtitle = c.CompanyProfile.Domain,
                    Title = c.CompanyProfile.CompanyName
                }).ToAttachment()).ToList();

                await context.PostAsync(response).ConfigureAwait(false);

                // Capture the request for the customer summary for analysis.
                eventProperties = new Dictionary <string, string>
                {
                    { "ChannelId", context.Activity.ChannelId },
                    { "CustomerId", principal.CustomerId },
                    { "LocalTimeStamp", context.Activity.LocalTimestamp.ToString() },
                    { "Locale", response.Locale },
                    { "UserId", principal.ObjectId }
                };

                // Track the event measurements for analysis.
                eventMeasurements = new Dictionary <string, double>
                {
                    { "ElapsedMilliseconds", DateTime.Now.Subtract(startTime).TotalMilliseconds },
                    { "NumberOfCustomers", response.Attachments.Count }
                };

                provider.Telemetry.TrackEvent("ListCustomers/Execute", eventProperties, eventMeasurements);
            }
            finally
            {
                customers         = null;
                eventMeasurements = null;
                eventProperties   = null;
            }
        }
 /// <summary>
 /// Initializes a new instance of <see cref="AccessTokenProvider"/> class.
 /// </summary>
 /// <param name="provider">Provides access to core explorer providers.</param>
 /// <exception cref="System.ArgumentNullException">
 /// <paramref name="provider"/> is null.
 /// </exception>
 public AccessTokenProvider(IBotProvider provider)
 {
     provider.AssertNotNull(nameof(provider));
     this.provider = provider;
 }
Exemple #23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ConfigurationProvider" /> class.
 /// </summary>
 /// <param name="provider">Provides access to core services.</param>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="provider"/> is null.
 /// </exception>
 public ConfigurationProvider(IBotProvider provider)
 {
     provider.AssertNotNull(nameof(provider));
     this.provider = provider;
 }
Exemple #24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RedisCacheProvider"/> class.
 /// </summary>
 /// <param name="provider">Provides access to the core bot providers.</param>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="provider"/> is null.
 /// </exception>
 public RedisCacheProvider(IBotProvider provider)
 {
     provider.AssertNotNull(nameof(provider));
     this.provider = provider;
 }
Exemple #25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LocalizationProvider"/> class.
 /// </summary>
 /// <param name="provider">Provides access to core application services.</param>
 /// <exception cref="System.ArgumentNullException">
 /// <paramref name="provider"/> is null.
 /// </exception>
 public LocalizationProvider(IBotProvider provider)
 {
     provider.AssertNotNull(nameof(provider));
     this.provider = provider;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="OAuthCallbackController"/> class.
 /// </summary>
 /// <param name="provider">Provides access to core services.</param>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="provider"/> is null.
 /// </exception>
 public OAuthCallbackController(IBotProvider provider) : base(provider)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ActionDialog"/> class.
 /// </summary>
 /// <param name="provider">Provides access to core application services.</param>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="provider"/> is null.
 /// </exception>
 public ActionDialog(IBotProvider provider) :
     base(new LuisService(new LuisModelAttribute(provider.Configuration.LuisAppId, provider.Configuration.LuisApiKey.ToUnsecureString())))
 {
     provider.AssertNotNull(nameof(provider));
     this.provider = provider;
 }
 public ResolveCommand(IBotProvider botProvider, ISearchCache searchCache,
                       ISoundCloudInteractor soundCloudInteractor) : base(botProvider)
 {
     this.searchCache          = searchCache;
     this.soundCloudInteractor = soundCloudInteractor;
 }
        /// <summary>
        /// Performs the operation represented by this intent.
        /// </summary>
        /// <param name="context">The context of the conversational process.</param>
        /// <param name="message">The message from the authenticated user.</param>
        /// <param name="result">The result from Language Understanding cognitive service.</param>
        /// <param name="provider">Provides access to core services;.</param>
        /// <returns>An instance of <see cref="Task"/> that represents the asynchronous operation.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="context"/> is null.
        /// or
        /// <paramref name="message"/> is null.
        /// or
        /// <paramref name="result"/> is null.
        /// or
        /// <paramref name="provider"/> is null.
        /// </exception>
        public async Task ExecuteAsync(IDialogContext context, IAwaitable <IMessageActivity> message, LuisResult result, IBotProvider provider)
        {
            Customer                    customer = null;
            CustomerPrincipal           principal;
            DateTime                    startTime;
            Dictionary <string, double> eventMetrics;
            Dictionary <string, string> eventProperties;
            IMessageActivity            response;
            List <Subscription>         subscriptions;

            context.AssertNotNull(nameof(context));
            message.AssertNotNull(nameof(message));
            result.AssertNotNull(nameof(result));
            provider.AssertNotNull(nameof(principal));

            try
            {
                startTime = DateTime.Now;

                principal = await context.GetCustomerPrincipalAsync(provider).ConfigureAwait(false);

                if (principal.CustomerId.Equals(provider.Configuration.PartnerCenterAccountId))
                {
                    customer = await provider.PartnerOperations.GetCustomerAsync(principal).ConfigureAwait(false);

                    response      = context.MakeMessage();
                    response.Text = string.Format(Resources.SubscriptionRequestMessage, customer.CompanyProfile.CompanyName);
                    await context.PostAsync(response).ConfigureAwait(false);
                }

                subscriptions = await provider.PartnerOperations.GetSubscriptionsAsync(principal).ConfigureAwait(false);

                response = context.MakeMessage();
                response.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                response.Attachments      = subscriptions.Select(s => s.ToAttachment()).ToList();

                await context.PostAsync(response).ConfigureAwait(false);

                // Track the event measurements for analysis.
                eventMetrics = new Dictionary <string, double>
                {
                    { "ElapsedMilliseconds", DateTime.Now.Subtract(startTime).TotalMilliseconds },
                    { "NumberOfSubscriptions", response.Attachments.Count }
                };

                // Capture the request for the customer summary for analysis.
                eventProperties = new Dictionary <string, string>
                {
                    { "ChannelId", context.Activity.ChannelId },
                    { "CustomerId", principal.CustomerId },
                    { "LocalTimeStamp", context.Activity.LocalTimestamp.ToString() },
                    { "UserId", principal.ObjectId }
                };

                provider.Telemetry.TrackEvent("ListCustomers/Execute", eventProperties, eventMetrics);
            }
            finally
            {
                customer        = null;
                eventMetrics    = null;
                eventProperties = null;
                principal       = null;
                response        = null;
                subscriptions   = null;
            }
        }
Exemple #30
0
 public Bot(IBotProvider provider)
 {
     this.provider = provider;
     this.channels = new Dictionary <IChannelInfo, IChannelConfig>();
     this.plugins  = new Dictionary <string, IBotPlugin>();
 }