Exemple #1
0
        public void SetCurrent(string botDir)
        {
            IStorage storage           = new MemoryStorage();
            var      userState         = new UserState(storage);
            var      conversationState = new ConversationState(storage);
            var      inspectionState   = new InspectionState(storage);

            // manage all bot resources
            var resourceExplorer = new ResourceExplorer().AddFolder(botDir);

            var adapter = new BotFrameworkHttpAdapter(new ConfigurationCredentialProvider(Config));

            var credentials = new MicrosoftAppCredentials(Config["MicrosoftAppId"], Config["MicrosoftAppPassword"]);

            adapter
            .UseStorage(storage)
            .UseState(userState, conversationState)
            .UseAdaptiveDialogs()
            .UseResourceExplorer(resourceExplorer)
            .UseLanguageGeneration(resourceExplorer, "common.lg")
            .Use(new RegisterClassMiddleware <IConfiguration>(Config))
            .Use(new InspectionMiddleware(inspectionState, userState, conversationState, credentials));

            adapter.OnTurnError = async(turnContext, exception) =>
            {
                await turnContext.SendActivityAsync(exception.Message).ConfigureAwait(false);

                await conversationState.ClearStateAsync(turnContext).ConfigureAwait(false);

                await conversationState.SaveChangesAsync(turnContext).ConfigureAwait(false);
            };
            CurrentAdapter = adapter;

            CurrentBot = new ComposerBot("Main.dialog", conversationState, userState, resourceExplorer, DebugSupport.SourceMap);
        }
Exemple #2
0
    //建造状态机
    private void MakeFSM()
    {
        InspectionState inspection = new InspectionState();

        inspection.AddTransition(Transition.SawPlayer, StateID.ChasingPlayer);
        inspection.AddTransition(Transition.LostPlayer, StateID.FollowingPath);

        PatrolState follow = new PatrolState(transform.position, scope);

        follow.AddTransition(Transition.SawPlayer, StateID.ChasingPlayer);
        follow.AddTransition(Transition.ArrivePath, StateID.Inspection);

        ChasePlayerState chase = new ChasePlayerState();

        chase.AddTransition(Transition.LostPlayer, StateID.FollowingPath);
        chase.AddTransition(Transition.NearPlayer, StateID.AttackPlayer);

        AttackPlayerState attack = new AttackPlayerState();

        attack.AddTransition(Transition.LostPlayer, StateID.FollowingPath);

        fsm = new FsmSystem();
        fsm.AddState(inspection);//添加状态到状态机,第一个添加的状态将作为初始状态
        fsm.AddState(follow);
        fsm.AddState(chase);
        fsm.AddState(attack);
    }
Exemple #3
0
        /// <summary>
        /// Determine Inspection Status and set read-only
        /// </summary>
        public override void beforePropertySetWriteNode(bool Creating)
        {
            if (Creating)
            {
                Status.Value = CswEnumNbtInspectionStatus.Pending;
            }

            _setDefaultValues();

            _InspectionState = new InspectionState(this);

            if (false == _genFutureNodesHasRun)  //redundant--for readability
            {
                //this is written in such a way that it should only execute once per instance of this node
                _genFutureNodes();
            }

            foreach (CswNbtNodePropWrapper PropWrapper in Node.Properties[(CswEnumNbtFieldType)CswEnumNbtFieldType.Question])
            {
                CswNbtNodePropQuestion QuestionProp = PropWrapper;
                if (QuestionProp.IsAnswerCompliant())
                {
                    QuestionProp.CorrectiveAction = string.Empty;
                }
            }

            // !!!
            // Don't clear IsFuture here, like we do with Tasks.  See case 28317.
            // !!!
        } // beforeWriteNode()
Exemple #4
0
        public AdapterWithInspection(IConfiguration configuration, InspectionState inspectionState, UserState userState, ConversationState conversationState)
            : base(configuration)
        {
            // Inspection needs credentiaols because it will be sending the Activities and User and Conversation State to the emulator
            var credentials = new MicrosoftAppCredentials(configuration["MicrosoftAppId"], configuration["MicrosoftAppPassword"]);

            Use(new InspectionMiddleware(inspectionState, userState, conversationState, credentials));
        }
        public async Task ScenarioWithInspectionMiddlwarePassthrough()
        {
            var inspectionState      = new InspectionState(new MemoryStorage());
            var inspectionMiddleware = new InspectionMiddleware(inspectionState);

            var adapter = new TestAdapter();

            adapter.Use(inspectionMiddleware);

            var inboundActivity = MessageFactory.Text("hello");

            await adapter.ProcessActivityAsync(inboundActivity, async (turnContext, cancellationToken) =>
            {
                await turnContext.SendActivityAsync(MessageFactory.Text("hi"));
            });

            var outboundActivity = adapter.ActiveQueue.Dequeue();

            Assert.AreEqual("hi", outboundActivity.Text);
        }
        public AdapterWithMiddleware(
            IConfiguration configuration,
            InspectionState inspectionState,
            ConversationState conversationState,
            CardManager cardManager,
            ILogger <BotFrameworkHttpAdapter> logger)
            : base(configuration, logger)
        {
            // Inspection needs credentials because it will be sending the Activities and User and Conversation State to the emulator
            var credentials = new MicrosoftAppCredentials(configuration["MicrosoftAppId"], configuration["MicrosoftAppPassword"]);

            Use(new InspectionMiddleware(inspectionState, null, conversationState, credentials));

            var cardManagerMiddleware = new CardManagerMiddleware(cardManager);

            cardManagerMiddleware.NonUpdatingOptions.AutoClearEnabledOnSend = false;

            Use(cardManagerMiddleware
                .SetAutoApplyIds(false)
                .SetIdOptions(new DataIdOptions(new[]
            {
                DataIdScopes.Action,
                DataIdScopes.Card,
                DataIdScopes.Carousel,
                DataIdScopes.Batch,
            })));

            OnTurnError = async(turnContext, exception) =>
            {
                // Log any leaked exception from the application.
                logger.LogError(exception, $"[OnTurnError] unhandled error : {exception.Message}");

                // Send a message to the user
                await turnContext.SendActivityAsync("The bot encountered an error or bug.");

                await turnContext.SendActivityAsync("To continue to run this bot, please fix the bot source code.");

                // Send a trace activity, which will be displayed in the Bot Framework Emulator
                await turnContext.TraceActivityAsync("OnTurnError Trace", exception.Message, "https://www.botframework.com/schemas/error", "TurnError");
            };
        }
        public AdapterWithInspection(IConfiguration configuration, InspectionState inspectionState, UserState userState, ConversationState conversationState, ILogger <BotFrameworkHttpAdapter> logger)
            : base(configuration, logger)
        {
            // Inspection needs credentiaols because it will be sending the Activities and User and Conversation State to the emulator
            var credentials = new MicrosoftAppCredentials(configuration["MicrosoftAppId"], configuration["MicrosoftAppPassword"]);

            Use(new InspectionMiddleware(inspectionState, userState, conversationState, credentials));

            OnTurnError = async(turnContext, exception) =>
            {
                // Log any leaked exception from the application.
                logger.LogError(exception, $"[OnTurnError] unhandled error : {exception.Message}");

                // Send a message to the user
                await turnContext.SendActivityAsync("The bot encounted an error or bug.");

                await turnContext.SendActivityAsync("To continue to run this bot, please fix the bot source code.");

                // Send a trace activity, which will be displayed in the Bot Framework Emulator
                await turnContext.TraceActivityAsync("OnTurnError Trace", exception.Message, "https://www.botframework.com/schemas/error", "TurnError");
            };
        }
Exemple #8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddSingleton <IConfiguration>(this.Configuration);

            // Create the credential provider to be used with the Bot Framework Adapter.
            services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>();

            services.AddSingleton <InspectionMiddleware>();

            // Load settings
            var settings = new BotSettings();

            Configuration.Bind(settings);

            IStorage storage = null;

            // Configure storage for deployment
            if (!string.IsNullOrEmpty(settings.CosmosDb.AuthKey))
            {
                storage = new CosmosDbStorage(settings.CosmosDb);
            }
            else
            {
                Console.WriteLine("The settings of CosmosDbStorage is incomplete, please check following settings: settings.CosmosDb");
                storage = new MemoryStorage();
            }

            services.AddSingleton(storage);
            var userState         = new UserState(storage);
            var conversationState = new ConversationState(storage);
            var inspectionState   = new InspectionState(storage);

            // Configure telemetry
            services.AddApplicationInsightsTelemetry();
            var telemetryClient = new BotTelemetryClient(new TelemetryClient());

            services.AddSingleton <IBotTelemetryClient>(telemetryClient);
            services.AddBotApplicationInsights(telemetryClient);

            var botFile = Configuration.GetSection("bot").Get <string>();

            TypeFactory.Configuration = this.Configuration;

            // manage all bot resources
            var resourceExplorer = new ResourceExplorer().AddFolder(botFile);

            var credentials = new MicrosoftAppCredentials(this.Configuration["MicrosoftAppId"], this.Configuration["MicrosoftAppPassword"]);

            services.AddSingleton <IBotFrameworkHttpAdapter, BotFrameworkHttpAdapter>((s) =>
            {
                var adapter = new BotFrameworkHttpAdapter(new ConfigurationCredentialProvider(this.Configuration));
                adapter
                .UseStorage(storage)
                .UseState(userState, conversationState)
                .UseAdaptiveDialogs()
                .UseResourceExplorer(resourceExplorer)
                .UseLanguageGeneration(resourceExplorer, "common.lg")
                .Use(new RegisterClassMiddleware <IConfiguration>(Configuration))
                .Use(new InspectionMiddleware(inspectionState, userState, conversationState, credentials));

                if (!string.IsNullOrEmpty(settings.BlobStorage.ConnectionString) && !string.IsNullOrEmpty(settings.BlobStorage.Container))
                {
                    adapter.Use(new TranscriptLoggerMiddleware(new AzureBlobTranscriptStore(settings.BlobStorage.ConnectionString, settings.BlobStorage.Container)));
                }
                else
                {
                    Console.WriteLine("The settings of TranscriptLoggerMiddleware is incomplete, please check following settings: settings.BlobStorage.ConnectionString, settings.BlobStorage.Container");
                }

                adapter.OnTurnError = async(turnContext, exception) =>
                {
                    await turnContext.SendActivityAsync(exception.Message).ConfigureAwait(false);
                    telemetryClient.TrackException(new Exception("Exceptions: " + exception.Message));
                    await conversationState.ClearStateAsync(turnContext).ConfigureAwait(false);
                    await conversationState.SaveChangesAsync(turnContext).ConfigureAwait(false);
                };
                return(adapter);
            });

            services.AddSingleton <IBot, ComposerBot>((sp) => new ComposerBot("Main.dialog", conversationState, userState, resourceExplorer, DebugSupport.SourceMap, telemetryClient));
        }
        public async Task ScenarioWithInspectionMiddlwareOpenAttach()
        {
            // Arrange

            // any bot state should be returned as trace messages per turn
            var storage           = new MemoryStorage();
            var inspectionState   = new InspectionState(storage);
            var userState         = new UserState(storage);
            var conversationState = new ConversationState(storage);

            // set up the middleware with an http client that will just record the traffic - we are expecting the trace activities here
            var recordingHttpClient  = new RecordingHttpMessageHandler();
            var inspectionMiddleware = new TestInspectionMiddleware(
                inspectionState,
                userState,
                conversationState,
                new HttpClient(recordingHttpClient));

            // Act

            // (1) send the /INSPECT open command from the emulator to the middleware
            var openActivity = MessageFactory.Text("/INSPECT open");

            var inspectionAdapter = new TestAdapter(Channels.Test, true);
            await inspectionAdapter.ProcessActivityAsync(openActivity, async (turnContext, cancellationToken) =>
            {
                await inspectionMiddleware.ProcessCommandAsync(turnContext);
            });

            var inspectionOpenResultActivity = inspectionAdapter.ActiveQueue.Dequeue();

            // (2) send the resulting /INSPECT attach command from the channel to the middleware
            var applicationAdapter = new TestAdapter(Channels.Test, true);

            applicationAdapter.Use(inspectionMiddleware);

            var attachCommand = inspectionOpenResultActivity.Value.ToString();

            await applicationAdapter.ProcessActivityAsync(MessageFactory.Text(attachCommand), async (turnContext, cancellationToken) =>
            {
                // nothing happens - just attach the inspector
                await Task.CompletedTask;
            });

            var attachResponse = applicationAdapter.ActiveQueue.Dequeue();

            // (3) send an application messaage from the channel, it should get the reply and then so should the emulator http endpioint
            await applicationAdapter.ProcessActivityAsync(MessageFactory.Text("hi"), async (turnContext, cancellationToken) =>
            {
                await turnContext.SendActivityAsync(MessageFactory.Text($"echo: {turnContext.Activity.Text}"));

                (await userState.CreateProperty <Scratch>("x").GetAsync(turnContext, () => new Scratch())).Property         = "hello";
                (await conversationState.CreateProperty <Scratch>("y").GetAsync(turnContext, () => new Scratch())).Property = "world";
                await userState.SaveChangesAsync(turnContext);
                await conversationState.SaveChangesAsync(turnContext);
            });

            // Assert
            var outboundActivity = applicationAdapter.ActiveQueue.Dequeue();

            Assert.AreEqual("echo: hi", outboundActivity.Text);
            Assert.AreEqual(3, recordingHttpClient.Requests.Count);

            var inboundTrace = JObject.Parse(recordingHttpClient.Requests[0]);

            Assert.AreEqual("trace", inboundTrace["type"].ToString());
            Assert.AreEqual("ReceivedActivity", inboundTrace["name"].ToString());
            Assert.AreEqual("message", inboundTrace["value"]["type"].ToString());
            Assert.AreEqual("hi", inboundTrace["value"]["text"].ToString());

            var outboundTrace = JObject.Parse(recordingHttpClient.Requests[1]);

            Assert.AreEqual("trace", outboundTrace["type"].ToString());
            Assert.AreEqual("SentActivity", outboundTrace["name"].ToString());
            Assert.AreEqual("message", outboundTrace["value"]["type"].ToString());
            Assert.AreEqual("echo: hi", outboundTrace["value"]["text"].ToString());

            var stateTrace = JObject.Parse(recordingHttpClient.Requests[2]);

            Assert.AreEqual("trace", stateTrace["type"].ToString());
            Assert.AreEqual("BotState", stateTrace["name"].ToString());
            Assert.AreEqual("hello", stateTrace["value"]["userState"]["x"]["Property"].ToString());
            Assert.AreEqual("world", stateTrace["value"]["conversationState"]["y"]["Property"].ToString());
        }
 public TestInspectionMiddleware(InspectionState inspectionState, UserState userState, ConversationState conversationState, HttpClient httpClient)
     : base(inspectionState, userState, conversationState)
 {
     _httpClient = httpClient;
 }
        public async Task ScenarioWithInspectionMiddlwareOpenAttachAndTracePassThrough()
        {
            // Arrange

            // any bot state should be returned as trace messages per turn
            var storage         = new MemoryStorage();
            var inspectionState = new InspectionState(storage);

            // set up the middleware with an http client that will just record the traffic - we are expecting the trace activities here
            var recordingHttpClient  = new RecordingHttpMessageHandler();
            var inspectionMiddleware = new TestInspectionMiddleware(
                inspectionState,
                null,
                null,
                new HttpClient(recordingHttpClient));

            // Act

            // (1) send the /INSPECT open command from the emulator to the middleware
            var openActivity = MessageFactory.Text("/INSPECT open");

            var inspectionAdapter = new TestAdapter(Channels.Test, true);
            await inspectionAdapter.ProcessActivityAsync(openActivity, async (turnContext, cancellationToken) =>
            {
                await inspectionMiddleware.ProcessCommandAsync(turnContext);
            });

            var inspectionOpenResultActivity = inspectionAdapter.ActiveQueue.Dequeue();

            // (2) send the resulting /INSPECT attach command from the channel to the middleware
            var applicationAdapter = new TestAdapter(Channels.Test, true);

            applicationAdapter.Use(inspectionMiddleware);

            var attachCommand = inspectionOpenResultActivity.Value.ToString();

            await applicationAdapter.ProcessActivityAsync(MessageFactory.Text(attachCommand), async (turnContext, cancellationToken) =>
            {
                // nothing happens - just attach the inspector
                await Task.CompletedTask;
            });

            var attachResponse = applicationAdapter.ActiveQueue.Dequeue();

            // (3) send an application messaage from the channel, it should get the reply and then so should the emulator http endpioint
            await applicationAdapter.ProcessActivityAsync(MessageFactory.Text("hi"), async (turnContext, cancellationToken) =>
            {
                var activity = (Activity)Activity.CreateTraceActivity("CustomTrace");
                await turnContext.SendActivityAsync(activity);
            });

            // Assert
            var outboundActivity = applicationAdapter.ActiveQueue.Dequeue();

            Assert.AreEqual("CustomTrace", outboundActivity.Name);
            Assert.AreEqual(2, recordingHttpClient.Requests.Count);

            var inboundTrace = JObject.Parse(recordingHttpClient.Requests[0]);

            Assert.AreEqual("trace", inboundTrace["type"].ToString());
            Assert.AreEqual("ReceivedActivity", inboundTrace["name"].ToString());
            Assert.AreEqual("message", inboundTrace["value"]["type"].ToString());
            Assert.AreEqual("hi", inboundTrace["value"]["text"].ToString());

            var outboundTrace = JObject.Parse(recordingHttpClient.Requests[1]);

            Assert.AreEqual("trace", outboundTrace["type"].ToString());
            Assert.AreEqual("CustomTrace", outboundTrace["name"].ToString());
        }
Exemple #12
0
 /// <summary>
 /// The constructor
 /// </summary>
 public CswNbtObjClassInspectionDesign(CswNbtResources CswNbtResources, CswNbtNode Node)
     : base(CswNbtResources, Node)
 {
     _InspectionState = new InspectionState(this);
 }