public void MessageShouldBeSameAfterSerializationAndDeserialization()
        {
            var writer = new BinaryWriter(new MemoryStream());
            IMessageFactory msgFactory = new MessageFactory(new Message[]
                {
                    new ISomeServiceComplexRequest()
                });

            var fixture = new Fixture();
            fixture.Customize<ISomeServiceComplexRequest>(ob =>
                ob.With(x => x.datas,
                    fixture.CreateMany<SubData>().ToList()));
            fixture.Customize<ComplexData>(ob => ob
                .With(x => x.SomeArrString, fixture.CreateMany<string>().ToList())
                .With(x => x.SomeArrRec, fixture.CreateMany<SubData>().ToList()));

            var msg = fixture.CreateAnonymous<ISomeServiceComplexRequest>();

            //serialize and deserialize msg1
            msg.Serialize(writer);
            writer.Seek(0, SeekOrigin.Begin);
            var reader = new BinaryReader(writer.BaseStream);
            Message retMsg = msgFactory.Deserialize(reader);

            retMsg.Should().BeOfType<ISomeServiceComplexRequest>();
            msg.ShouldBeEqualTo((ISomeServiceComplexRequest)retMsg);
        }
示例#2
0
        static void Main(string[] args)
        {
            // Create the NetMQ context
            using (var context = NetMQContext.Create())
            {
                // Setup a default message factory
                var messageFactory = new MessageFactory();

                // Setup a message handler and register a request handler
                var messageHandler = 
                    RequestDispatcher.Create()
                        .Register<RandomNumberRequest, RandomNumberResponse>(new RandomNumberRequestHandler());

                // Create the server and client
                Server server = new Server(new NetMQReceiverManager(context, "tcp://127.0.0.1:5556"), messageFactory, messageHandler, "ExampleServer");
                Client client = new Client(new NetMQSenderManager(context, "tcp://127.0.0.1:5556"), messageFactory);

                // Run the server in a task with a cancellation token to cancel the task later
                var cancellationTokenSource = new CancellationTokenSource();
                Task.Run(() => server.Run(cancellationTokenSource.Token));

                // Send 10 requests to the server and display results 
                for (int i = 0; i < 10; i++)
                {
                    var request = new RandomNumberRequest() { Min = i, Max = 10 * i * i };
                    var response = client.Send<RandomNumberResponse, RandomNumberRequest>(request);
                    Console.WriteLine("Request random number betweem {0} to {1}", request.Min, request.Max);
                    Console.WriteLine("Response: {0}\n", response.RandomNumber);
                }

                // Stop the server
                cancellationTokenSource.Cancel();
            }
        }
示例#3
0
        static void Main(string[] args)
        {
            using (var context = NetMQContext.Create())
            {
                var receiverManager = new NetMQReceiverManager(context, "tcp://127.0.0.1:5556");
                var messageFactory = new MessageFactory();
                var messageHandler = RequestDispatcher.Create()
                                                      .Register<App1RandomNumberRequest, App1RandomNumberResponse>(request => {
                                                          Console.WriteLine("Received request for random number between {0} and {1}", request.MinBound, request.MaxBound);
                                                          var random = new Random();
                                                          return new App1RandomNumberResponse(random.Next(request.MinBound, request.MaxBound));
                                                      });

                IServer server = new Server(receiverManager, messageFactory, messageHandler, "ExampleServer");

                var cancellationTokenSource = new CancellationTokenSource();

                Console.WriteLine("Starting server...");

                server.Start(cancellationTokenSource.Token);

                Console.WriteLine("Server started, press enter to shutdown");

                Console.ReadLine();

                Console.WriteLine("Stopping server");
                cancellationTokenSource.Cancel();
            }
        }
示例#4
0
        static void Main(string[] args)
        {
            using (var context = NetMQContext.Create())
            {
                var messageFactory = new MessageFactory();
                var requestDispatcher = RequestDispatcher.Create().Register<RandomNumberRequest, int>(new RandomNumberRequestHandler());
                var name = "ServerName";

                Server server = new Server(new NetMQReceiverManager(context, "tcp://127.0.0.1:5556"), messageFactory, requestDispatcher, name);
                Client client = new Client(new NetMQSenderManager(context, "tcp://127.0.0.1:5556"), messageFactory);

                var cancellationTokenSource = new CancellationTokenSource();
                var serverTask = Task.Run(() => server.Run(cancellationTokenSource.Token));

                int response;

                for (int i = 0; i < 10; i++)
                {
                    response = client.Send<int, RandomNumberRequest>(new RandomNumberRequest() { Min = 10, Max = 100 });
                    Console.WriteLine(response);
                }

                cancellationTokenSource.Cancel();
            }
        }
示例#5
0
        public void GenericV23AdtA01MessageIsOfTypeAdtA01()
        {
            MessageFactory messageFactory = new MessageFactory();
            Message newMessage = messageFactory.MakeMessage(TestMessages.GenericV23_ADT_A01);

            Assert.AreEqual(EnumUtils.stringValueOf(MessageTypes.ADT_A01), (newMessage.Type.Type + newMessage.Type.TriggerEvent));
        }
        /// <summary>
        /// Creates the needed requirements for the game, initializes it and starts it.
        /// </summary>
        private void Initialize()
        {
            NumberCommandProcessor numberCommandProcessor = new NumberCommandProcessor();
            HelpCommandProcessor helpCommandProcessor = new HelpCommandProcessor();
            numberCommandProcessor.SetSuccessor(helpCommandProcessor);

            TopCommandProcessor topCommandProcessor = new TopCommandProcessor();
            helpCommandProcessor.SetSuccessor(topCommandProcessor);

            RestartCommandProcessor restartCommandProcessor = new RestartCommandProcessor();
            topCommandProcessor.SetSuccessor(restartCommandProcessor);

            ExitCommandProcessor exitCommandProcessor = new ExitCommandProcessor();
            restartCommandProcessor.SetSuccessor(exitCommandProcessor);

            InvalidCommandProcessor invalidCommandProcessor = new InvalidCommandProcessor();
            exitCommandProcessor.SetSuccessor(invalidCommandProcessor);

            ScoreBoard scoreBoard = new ScoreBoard(MaxPlayersInScoreboard);
            MessageFactory messageFactory = new MessageFactory();
            IPrinter printer = new Printer(messageFactory);
            IRandomNumberProvider randomNumberProvider = RandomNumberProvider.Instance;

            BullsAndCowsGame game = new BullsAndCowsGame(randomNumberProvider, scoreBoard, printer, numberCommandProcessor);

            game.Initialize();
            game.Play();
        }
示例#7
0
        static void Main(string[] args)
        {
            var messageSerializer = new MessageSerializer();
              var messageBodySerializer = new MessageBodySerializer();
              var messageFactory = new MessageFactory();
              var pathFactory = new PathFactory();
              var broker = new Broker(1337,
                              messageSerializer,
                              messageBodySerializer,
                              messageFactory,
                              pathFactory);
              var messageObserver = new MessageObserver<Foo>(broker.ID,
                                                     messageBodySerializer)
                            {
                              InterceptRemoteMessagesOnly = false,
                              InterceptOnNext = foo =>
                                                {
                                                  // TODO what to do next ...
                                                }
                            };
              broker.Subscribe(messageObserver);
              broker.Start();

              broker.Publish(new Foo
                     {
                       Bar = "hello" // Not L10N
                     });

              Console.ReadLine();
        }
示例#8
0
        public void MessageWithNoMshWillReturnNull()
        {
            MessageFactory messageFactory = new MessageFactory();
            Message newMessage = messageFactory.MakeMessage(TestMessages.InvalidMessage_MissingMSH);

            Assert.IsNull(newMessage);
        }
示例#9
0
        static void Main(string[] args)
        {
            using (var context = NetMQContext.Create())
            {
                var receiverManager = new NetMQReceiverManager(context, "tcp://127.0.0.1:5557");
                var messageFactory = new MessageFactory();
                var messageHandler = RequestDispatcher.Create()
                                                      .Register<App2ComplementRequest, App2ComplementResponse>(request =>
                                                      {
                                                          Console.WriteLine("Received a {0} urgency request for a complement", request.Urgency.ToString());

                                                          if (request.Urgency == Urgency.Low)
                                                              return new App2ComplementResponse("You're hair looks nice today");
                                                          else if (request.Urgency == Urgency.Medium)
                                                              return new App2ComplementResponse("Hey, you're pretty excellent");
                                                          else
                                                              return new App2ComplementResponse("You are probably a better programmer than me");
                                                      });

                IServer server = new Server(receiverManager, messageFactory, messageHandler, "ExampleServer");

                var cancellationTokenSource = new CancellationTokenSource();

                Console.WriteLine("Starting App2 server...");

                server.Start(cancellationTokenSource.Token);

                Console.WriteLine("Server started, press enter to shutdown");

                Console.ReadLine();

                Console.WriteLine("Stopping server");
                cancellationTokenSource.Cancel();
            }
        }
 public void Run()
 {
   var registerer = new MessageRegisterer();
   registerer.AddMessageTypes(typeof(IPerformSingleTaskOnComputersMessage), typeof(IInstallAssemblyMessage));
   var implementations = new MessageInterfaceImplementations(new DefaultMessageInterfaceImplementationFactory(), registerer);
   var factory = new MessageFactory(implementations, new MessageDefinitionFactory());
   var assembly = factory.Create<IInstallAssemblyMessage>(m =>
   {
     m.ArtifactId = Guid.Empty;
     m.AssemblyFilename = "Jacob.exe";
   });
   var message = factory.Create<IPerformSingleTaskOnComputersMessage>(m =>
   {
     m.OperationId = Guid.NewGuid();
     m.Title = "Nothing";
     m.Message = assembly;
     m.ComputerNames = new string[0];
     m.Birthday = DateTime.UtcNow;
   });
   var formatter = new XmlTransportMessageBodyFormatter(registerer, new MtaMessageMapper(implementations, factory, registerer));
   formatter.Initialize();
   using (var stream = new MemoryStream())
   {
     formatter.Serialize(new IMessage[] { message }, stream);
     Console.WriteLine(Encoding.ASCII.GetString(stream.ToArray()));
     using (var reading = new MemoryStream(stream.ToArray()))
     {
       var read = formatter.Deserialize(reading);
     }
   }
 }
示例#11
0
 static public MessageFactory getInstance()
 {
     if (instance == null)
     {
         instance = new MessageFactory();
     }
     return instance;
 }
 public static IMessageFactory NewFactoryForMessages(params Type[] messageTypes)
 {
   var registerer = new MessageRegisterer();
   registerer.AddMessageTypes(typeof(IMessage));
   registerer.AddMessageTypes(messageTypes);
   var factory = new MessageFactory();
   factory.Initialize(messageTypes);
   return factory;
 }
示例#13
0
        public void MessageFactory_CreateRequestTest()
        {
            var messageFactory = new MessageFactory();

            Assert.IsTrue(messageFactory.CreateRequest<int>(10) is DataMessage<int>);
            Assert.IsTrue(messageFactory.CreateRequest<DateTime>(DateTime.Now) is DataMessage<DateTime>);
            Assert.IsTrue(messageFactory.CreateRequest<IEnumerable<String>>(new List<String>()) is DataMessage<IEnumerable<String>>);
            Assert.IsTrue(messageFactory.CreateRequest<DataMessage<int>>(new DataMessage<int>(10)) is DataMessage<int>);
        }
示例#14
0
        public void MessageFactory_CreateResponseTest()
        {
            var messageFactory = new MessageFactory();
            var response = DateTime.Now;
            var responseMessage = new DataMessage<DateTime>(response);

            Assert.AreEqual(response, messageFactory.CreateResponse<DateTime>(response).MessageObject);
            Assert.AreEqual(responseMessage, messageFactory.CreateResponse<Message>(responseMessage));
        }
示例#15
0
        public void MessageFactory_ExtractResponse()
        {
            var messageFactory = new MessageFactory();
            var response = DateTime.Now;
            var responseMessage = new DataMessage<DateTime>(response);

            Assert.AreEqual(response, messageFactory.ExtractResponse<DateTime>(responseMessage));
            Assert.AreEqual(responseMessage, messageFactory.ExtractResponse<DataMessage<DateTime>>(responseMessage));
            AssertException.Throws<InvalidCastException>(() => messageFactory.ExtractResponse<Guid>(responseMessage));
        }
示例#16
0
        static void Main(string[] args)
        {
            // Create the NetMQ context
            using (var context = NetMQContext.Create())
            {
                // Setup a default message factory
                var messageFactory = new MessageFactory();

                // Setup a message handler and register two request handlers
                var messageHandler =
                    RequestDispatcher.Create()
                        .Register<EchoRequest, EchoResponse>(new EchoRequestHandler())
                        .Register<QuadraticRequest, QuadraticResponse>(new QuadraticRequestHandler());

                // Create the server and client
                Server server = new Server(new NetMQReceiverManager(context, "tcp://127.0.0.1:5556"), messageFactory, messageHandler, "ExampleServer");
                Client client = new Client(new NetMQSenderManager(context, "tcp://127.0.0.1:5556"), messageFactory);

                // Run the server in a task with a cancellation token to cancel the task later
                var cancellationTokenSource = new CancellationTokenSource();
                Task.Run(() => server.Run(cancellationTokenSource.Token));


                // Make some requests from the server
                var echo1 = new EchoRequest() { Name = "Jon", Message = "My first message!" };
                var echo2 = client.Send<EchoResponse, EchoRequest>(echo1);
                Display(echo1);
                Display(echo2);

                var echo3 = new EchoRequest() { Name = "Steve", Message = "Hi, I am steve" };
                var echo4 = client.Send<EchoResponse, EchoRequest>(echo3);
                Display(echo3);
                Display(echo4);

                var quad1 = new QuadraticRequest() { A = 1, B = 2, C = 3 };
                var quad2 = client.Send<QuadraticResponse, QuadraticRequest>(quad1);
                Display(quad1);
                Display(quad2);

                var quad3 = new QuadraticRequest() { A = -1, B = 5, C = 4 };
                var quad4 = client.Send<QuadraticResponse, QuadraticRequest>(quad3);
                Display(quad3);
                Display(quad4);


                // Stop the server
                cancellationTokenSource.Cancel();
            }
        }
示例#17
0
        public void MessageFactory_ExtractRequestTest()
        {
            var messageFactory = new MessageFactory();

            // Test types match
            Assert.IsTrue(messageFactory.ExtractRequest(new DataMessage<int>(10)) is int);
            Assert.IsTrue(messageFactory.ExtractRequest(new DataMessage<DateTime>(DateTime.Now)) is DateTime);
            Assert.IsTrue(messageFactory.ExtractRequest(new DataMessage<List<String>>(new List<String>())) is List<String>);

            var dt = DateTime.Now;
            var message = messageFactory.CreateRequest<DateTime>(dt);
            var result = messageFactory.ExtractRequest(message);

            Assert.AreEqual(dt, result);
        }
示例#18
0
        public void TennesseeHealthCareAdtA01MessagePatientIsThomasCChapman()
        {
            MessageFactory messageFactory = new MessageFactory();
            ExtendedPersonName expectedExtendedPersonName = new ExtendedPersonName()
            {
                GivenName = "THOMAS",
                MiddleNameOrInitial = "C",
                FamilyName = "CHAPMAN"
            };

            Message newMessage = messageFactory.MakeMessage(TestMessages.TennesseeHealthCare_ADT_A01);
            PID pidSegment = (PID)newMessage.Segments.Find(s => s.SegmentType == SegmentTypes.PID);
            ExtendedPersonName actualExtendedPersonName = pidSegment.GetPatientName();

            Assert.AreEqual(expectedExtendedPersonName, actualExtendedPersonName);
        }
示例#19
0
        public void TennesseeHealthSystemsAdtA01MessagePatientIsDarthAVader()
        {
            MessageFactory messageFactory = new MessageFactory();
            ExtendedPersonName expectedExtendedPersonName = new ExtendedPersonName()
            {
                GivenName = "DARTH",
                MiddleNameOrInitial = "A",
                FamilyName = "VADER"
            };

            Message newMessage = messageFactory.MakeMessage(TestMessages.TennesseeHealthSystems_ADT_A01);
            PID pidSegment = (PID)newMessage.Segments.Find(s => s.SegmentType == SegmentTypes.PID);
            ExtendedPersonName actualExtendedPersonName = pidSegment.GetPatientName();

            Assert.AreEqual(expectedExtendedPersonName, actualExtendedPersonName);
        }
示例#20
0
        public void GenericV23AdtA01MessagePatientIsDonaldDDuck()
        {
            MessageFactory messageFactory = new MessageFactory();
            ExtendedPersonName expectedExtendedPersonName = new ExtendedPersonName()
            {
                GivenName = "DONALD",
                MiddleNameOrInitial = "D",
                FamilyName = "DUCK"
            };

            Message newMessage = messageFactory.MakeMessage(TestMessages.GenericV23_ADT_A01);
            PID pidSegment = (PID)newMessage.Segments.Find(s => s.SegmentType == SegmentTypes.PID);
            ExtendedPersonName actualExtendedPersonName = pidSegment.GetPatientName();

            Assert.AreEqual(expectedExtendedPersonName, actualExtendedPersonName);
        }
        public void EntityProxyShouldTranslateMethodCallToMessage()
        {
            var fixture = new Fixture();
            IMessageFactory msgFactory = new MessageFactory(new List<Message>() { new ISomeServiceSimpleRequest(), new ISomeServiceSimpleReply() });
            int input = fixture.CreateAnonymous<int>();
            int output = fixture.CreateAnonymous<int>();
            var proxy = new ISomeServiceProxy();
            var executor = Substitute.For<IOperationExecutor>();
            executor.ExecuteOperation(Arg.Is<OperationContext>(x => ((ISomeServiceSimpleRequest)x.Message).requestId == input))
                .Returns(x => Task.FromResult<Message>(new ISomeServiceSimpleReply() { RetVal = output }));
            proxy.Init(null, msgFactory, executor);

            Task<int> retTask = proxy.Simple(input);

            executor.Received(1).ExecuteOperation(Arg.Is<OperationContext>(x => ((ISomeServiceSimpleRequest)x.Message).requestId == input));
            retTask.Should().NotBeNull();
            retTask.Result.Should().Be(output);
        }
示例#22
0
        public FixApplication(String configFile)
        {
            try
            {
                logonCount = 0;
                Current = this;
                settings = new SessionSettings(configFile);
                storeFactory = new FileStoreFactory(settings);
                logFactory = new FileLogFactory(settings);
                messageFactory = new DefaultMessageFactory();
                SetSessionIndexes(configFile);

                initiator = new SocketInitiator(this, storeFactory, settings, logFactory, messageFactory);
                initiator.start();
                AddText("Created initiator." + Environment.NewLine);
            }
            catch (Exception exception)
            {
                AddText(exception.Message + Environment.NewLine);
                throw;
            }
        }
示例#23
0
 protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
 {
     await turnContext.SendActivityAsync(MessageFactory.Text($"echo: {turnContext.Activity.Text}"), cancellationToken);
 }
示例#24
0
 static MessageFactory()
 {
     Instance = new MessageFactory();
 }
示例#25
0
        private async Task ShowSigninCard(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            //StateClient stateClient = new StateClient(new MicrosoftAppCredentials("xxxxxxxxxxx-4d43-4131-be5b-xxxxxxxxxxxx", "jkmbt39>:xxxxxxxxxxxx!~"));
            ////BotData userData = stateClient.BotState.GetUserData(context.Activity.ChannelId, context.Activity.From.Id);
            //BotData userData = stateClient.BotState.GetUserData("Azure", turnContext.Activity.From.Id);
            //string accesstoken = userData.GetProperty<string>("AccessToken");

            string botClientUserId   = turnContext.Activity.From.Id;
            string botConversationId = turnContext.Activity.Conversation.Id;
            string botchannelID      = turnContext.Activity.ChannelId;
            //var loginUrl = "http://localhost:3978/index.html?userid={botClientUserId}&conversationid={botConversationId}";
            //var loginUrl = "https://localhost:44327?userid={" + botClientUserId+"}&conversationid={"+botConversationId+"}";

            // string loginUrl = "http://localhost:29190/home/Index?botId={" + botClientUserId + "}&conversationid={" + botConversationId + "}";
            // string loginUrl = "http://localhost:29190/Home/Index?botId=" + botClientUserId + "&conversationid=" + botConversationId + "";
            string loginUrl = _iconfiguration["RedirectURL"] + "?botId=" + botClientUserId + "&conversationid=" + botConversationId + "&request_Type=artMainLogin";



            var attachments = new List <Attachment>();
            var reply       = MessageFactory.Attachment(attachments);
            var signinCard  = new SigninCard
            {
                Text    = "Please Sign In",
                Buttons = new List <CardAction> {
                    new CardAction(ActionTypes.Signin, "Sign-in", value: loginUrl)
                },
            };

            reply.Attachments.Add(signinCard.ToAttachment());

            //List<CacheUser> users;
            //if (!_cache.TryGetValue("users", out users))
            //{
            //    users = new List<CacheUser>();
            //}
            //if (!users.Any(u => u.BotClientUserId == botClientUserId && u.BotConversationId == botConversationId))
            //{
            //    users.Add(new CacheUser(botClientUserId, botConversationId, turnContext, cancellationToken));
            //    _cache.Set("users", users, new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromDays(7)));
            //}
            await turnContext.SendActivityAsync(reply, cancellationToken);

            //string cacheConnectionString = "HexaChatBotRedis.redis.cache.windows.net:6380,password=gItUtui8ogouVxo48BUEozsSnMg4JeHkgg2RX7TmPH8=,ssl=True,abortConnect=False";
            string cacheConnectionString = _iconfiguration["RedisCacheConnection"];

            try
            {
                ConnectionMultiplexer connection = ConnectionMultiplexer.Connect(cacheConnectionString);

                StackExchange.Redis.IDatabase db = connection.GetDatabase();

                SessionModel SessionModel = new SessionModel();
                SessionModel.DisplayName    = "";
                SessionModel.EmailId        = "";
                SessionModel.SessionKey     = botClientUserId;
                SessionModel.ConversationID = botConversationId;
                SessionModel.IsSkipIntro    = false;

                db.StringSet(botClientUserId, JsonConvert.SerializeObject(SessionModel));
                db.StringSet(botClientUserId + "artEnroll", JsonConvert.SerializeObject(SessionModel));

                //var userStateAccessors = UserState.CreateProperty<UserProfile>(nameof(SessionModel));
                //var userProfile = await userStateAccessors.GetAsync(turnContext, () => new SessionModel());
                //if (string.IsNullOrEmpty(userProfile.DisplayName))
                //{

                //    //// Set the name to what the user provided.
                //    //userProfile.Name = turnContext.Activity.Text?.Trim();
                //    //userProfile.botID = turnContext.Activity.From.Id;
                //    //// Acknowledge that we got their name.
                //    //await turnContext.SendActivityAsync($"Thanks {userProfile.Name}. To see conversation data, type anything.");
                //}
            }
            catch (Exception ex)
            {
            }

            var sessionModelsAccessors = UserState.CreateProperty <SessionModel>(nameof(SessionModel));
            var sessionModels          = await sessionModelsAccessors.GetAsync(turnContext, () => new SessionModel());

            if (string.IsNullOrWhiteSpace(sessionModels.DisplayName))
            {
                sessionModels.Password       = "";
                sessionModels.DisplayName    = "";
                sessionModels.EmailId        = "";
                sessionModels.SessionKey     = botClientUserId;
                sessionModels.ConversationID = botConversationId;
                sessionModels.IsSkipIntro    = false;
            }
            UserLoginDetectService userLoginDetect = new UserLoginDetectService(cancellationToken, _cache, turnContext, cacheConnectionString, UserState);
        }
		public SaferPayPaymentProcessor(SaferPayProcessorSettings settings)
		{
			_messageFactory = new MessageFactory();
			_messageFactory.Open(SaferPayConstants.Config);
			_settings = settings;
		}
示例#27
0
 public virtual void SendOneWay(string queueName, object requestDto)
 {
     Publish(queueName, MessageFactory.Create(requestDto));
 }
示例#28
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            Logger.LogInformation("Running dialog with Message Activity.");

            // Run the Dialog with the new message Activity.
            //await Dialog.RunAsync(turnContext, ConversationState.CreateProperty<DialogState>("DialogState"), cancellationToken);

            var val      = turnContext.Activity.Value;
            var activity = turnContext.Activity;

            if (val != null)
            {
                if (val.ToString().Contains("Employeeid"))
                {
                    activity.Text       = "ART Enrollment";
                    activity.TextFormat = "message";
                }
            }
            //var activity = turnContext.Activity;

            IMessageActivity reply = null;

            if (activity.Attachments != null && activity.Attachments.Any())
            {
                // We know the user is sending an attachment as there is at least one item
                // in the Attachments list.
                reply = HandleIncomingAttachment(activity);
            }
            else
            {
                await Dialog.RunAsync(turnContext, ConversationState.CreateProperty <DialogState>(nameof(DialogState)), cancellationToken);

                // Send at attachment to the user.
                //reply = await HandleOutgoingAttachment(turnContext, activity, cancellationToken);
            }


            //await Dialog.RunAsync(turnContext, ConversationState.CreateProperty<DialogState>(nameof(DialogState)), cancellationToken);

            CacheUser user = GetLogOnUser(turnContext);

            if (user == null)
            {
                //(bool, string, bool) stat = CheckSignin(turnContext.Activity.From.Id);
                //if (!stat.Item1)
                //{
                //    var text = "Please login first";
                //    await turnContext.SendActivityAsync(MessageFactory.Text(text, text), cancellationToken);
                //    await ShowSigninCard(turnContext, cancellationToken);
                //}
                //else
                //{
                //    if (!stat.Item3)
                //    {
                //        string cacheConnectionString = "HexaChatBotRedis.redis.cache.windows.net:6380,password=gItUtui8ogouVxo48BUEozsSnMg4JeHkgg2RX7TmPH8=,ssl=True,abortConnect=False";
                //        ConnectionMultiplexer connection = ConnectionMultiplexer.Connect(cacheConnectionString);

                //        StackExchange.Redis.IDatabase db = connection.GetDatabase();

                //        SessionModel SessionModel = new SessionModel();
                //        SessionModel.IsSkipIntro = true;

                //        db.StringSet("RamukDB", JsonConvert.SerializeObject(SessionModel));

                //        var text = $"Hi {stat.Item2}, welcome to use the Bot!";
                //        await turnContext.SendActivityAsync(MessageFactory.Text(text, text), cancellationToken);
                //        IsSkipIntro = true;
                //    }
                //}

                //var userStateAccessors = UserState.CreateProperty<UserProfile>(nameof(UserProfile));
                //var userProfile = await userStateAccessors.GetAsync(turnContext, () => new UserProfile());
                //if (string.IsNullOrEmpty(userProfile.Name))
                //{
                //    // Set the name to what the user provided.
                //    userProfile.Name = turnContext.Activity.Text?.Trim();
                //    userProfile.botID = turnContext.Activity.From.Id;
                //    // Acknowledge that we got their name.
                //    await turnContext.SendActivityAsync($"Thanks {userProfile.Name}. To see conversation data, type anything.");
                //}

                //var sessionModelsAccessors = UserState.CreateProperty<SessionModel>(nameof(SessionModel));
                //var sessionModels = await sessionModelsAccessors.GetAsync(turnContext, () => new SessionModel());
                //sessionModels.Password = "******";
                //sessionModels.DisplayName = "1234567";
                //sessionModels.EmailId = "*****@*****.**";
                //sessionModels.SessionKey = turnContext.Activity.From.Id.ToString();

                string botClientUserId   = turnContext.Activity.From.Id;
                string botConversationId = turnContext.Activity.Conversation.Id;
                string botchannelID      = turnContext.Activity.ChannelId;

                string cacheConnectionString = _iconfiguration["RedisCacheConnection"];

                try
                {
                    ConnectionMultiplexer connection = ConnectionMultiplexer.Connect(cacheConnectionString);

                    StackExchange.Redis.IDatabase db = connection.GetDatabase();

                    SessionModel SessionModel = new SessionModel();
                    SessionModel.DisplayName               = "";
                    SessionModel.EmailId                   = "";
                    SessionModel.SessionKey                = botClientUserId;
                    SessionModel.ConversationID            = botConversationId;
                    SessionModel.IsSkipIntro               = false;
                    SessionModel.UserLoginDetectServiceChk = 0;

                    db.StringSet(botClientUserId, JsonConvert.SerializeObject(SessionModel));
                    db.StringSet(botClientUserId + "artEnroll", JsonConvert.SerializeObject(SessionModel));

                    var sessionModelsAccessors = UserState.CreateProperty <SessionModel>(nameof(SessionModel));
                    var sessionModels          = await sessionModelsAccessors.GetAsync(turnContext, () => new SessionModel());

                    if (string.IsNullOrWhiteSpace(sessionModels.DisplayName) && sessionModels.UserLoginDetectServiceChk == 0)
                    {
                        sessionModels.Password       = "";
                        sessionModels.DisplayName    = "";
                        sessionModels.EmailId        = "";
                        sessionModels.SessionKey     = botClientUserId;
                        sessionModels.ConversationID = botConversationId;
                        sessionModels.IsSkipIntro    = false;
                        UserLoginDetectService userLoginDetect = new UserLoginDetectService(cancellationToken, _cache, turnContext, cacheConnectionString, UserState);
                    }
                }
                catch (Exception ex)
                {
                }
            }
            else
            {
                var text = $"Hi {user.UserName}, welcome to use the Bot!";
                await turnContext.SendActivityAsync(MessageFactory.Text(text, text), cancellationToken);
            }
        }
示例#29
0
        // Waterfall step function for saving his name and asking the User, if he needs the Bot's help
        private async Task <DialogTurnResult> NameConfirmStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            // Get the current profile object from user state.
            var userProfile = await _accessors.UserProfile.GetAsync(stepContext.Context, () => new UserProfile(), cancellationToken);

            var nameSentence      = (string)stepContext.Result;
            var nameSentenceArray = nameSentence.Split(' ');
            var userProfileName   = string.Empty;

            // Loop for separating the User's name from the sentence
            if (nameSentenceArray.Length > 3)
            {
                if (nameSentenceArray[0].ToLowerInvariant() == "it" && nameSentenceArray[1].ToLowerInvariant() == "is")
                {
                    for (int i = 2; i < nameSentenceArray.Length; i++)
                    {
                        userProfileName = userProfileName + nameSentenceArray[i] + " ";
                    }

                    userProfileName = userProfileName.TrimEnd();
                }
                else
                {
                    // Greet user and Close the dialog activity
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text("Sorry!!! I am unable to understand you."), cancellationToken);

                    return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
                }
            }
            else if (nameSentenceArray.Length == 3)
            {
                userProfileName = nameSentenceArray[2];
            }
            else
            {
                // Greet user and Close the dialog activity
                await stepContext.Context.SendActivityAsync(MessageFactory.Text("Sorry!!! I am unable to understand you."), cancellationToken);

                return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
            }

            // Update the profile.
            userProfile.Name = userProfileName;

            // Prompt Yes or No for User to continue the Execution
            return(await stepContext.PromptAsync("confirm", new PromptOptions { Prompt = MessageFactory.Text($"Okay {userProfile.Name}. Would you like to have my assistance in your Shopping??") }, cancellationToken));
        }
        private void ReadMessages(byte[] input, int size)
        {
            List <PowerLineModemMessage> receivedMessages = new List <PowerLineModemMessage>();

            lock (port)
            {
                string strDebug = "Input: [";
                // First we look for a 0x2, which they all start with.
                for (int i = 0; i < size; i++)
                {
                    int data = input[i];
                    strDebug += String.Format("{0:x2}-", data, readData, (this.data == null ? 0 :this.data.Length), state.ToString());
                    switch (state)
                    {
                    case ReadState.START:
                        if (data == START_OF_MESSAGE)
                        {
                            state = ReadState.MESSAGE_TYPE;
                        }
                        break;

                    case ReadState.MESSAGE_TYPE:
                        // This next one is the message type.
                        message   = (PowerLineModemMessage.Message)data;
                        state     = ReadState.MESSAGE_DATA;
                        this.data = new byte[MessageFactory.SizeOfMessage(message, sending)];
                        readData  = 0;
                        break;

                    case ReadState.MESSAGE_DATA:
                        if (readData < this.data.Length)
                        {
                            this.data[readData++] = (byte)data;
                        }
                        if (readData >= this.data.Length)
                        {
                            // If this is a response, update the request with the response data.
                            if (sending != null && message == sending.MessageType)
                            {
                                sendingResponse = sending.VerifyResponse(this.data);
                                sending         = null;
                                receivedAck.Set();
                            }
                            else
                            {
                                // Create the received message.
                                PowerLineModemMessage packet = MessageFactory.GetReceivedMessage(message, this.data);
                                if (packet != null)
                                {
                                    receivedMessages.Add(packet);
                                }
                            }
                            state = ReadState.START;
                        }
                        break;
                    }
                }
                log.Debug(strDebug + "]");
            }
            if (ReceivedMessage != null)
            {
                // Switch context so we don't end up deadlocked.
                ThreadPool.QueueUserWorkItem(delegate
                {
                    foreach (PowerLineModemMessage mess in receivedMessages)
                    {
                        ReceivedMessage(this, new RecievedMessageEventArgs(mess));
                    }
                });
            }
        }
        public void AttachmentNull()
        {
            IMessageActivity message = MessageFactory.Attachment((Attachment)null);

            Assert.Fail("Exception not thrown");
        }
示例#32
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            //var adaptiveCardAttachment = CardsDemoWithTypes();
            //await turnContext.SendActivityAsync(MessageFactory.Attachment(adaptiveCardAttachment));

            if (turnContext.Activity.Type == ActivityTypes.Message)
            {
                // Check if user submitted AdaptiveCard input
                if (turnContext.Activity.Value != null)
                {
                    //var activityValue = turnContext.Activity.AsMessageActivity().Value as Newtonsoft.Json.Linq.JObject;
                    //if (activityValue != null)
                    //{
                    //    var categorySelection = activityValue.ToObject<CategorySelection>();
                    //    var category = categorySelection.Category;
                    //    await turnContext.SendActivityAsync(category);
                    //}

                    // Convert String to JObject
                    String  value   = turnContext.Activity.Value.ToString();
                    JObject results = JObject.Parse(value);

                    // Get type from input field
                    String submitType = results.GetValue("Type").ToString().Trim();
                    switch (submitType)
                    {
                    case "email":
                        IMessageActivity message = Activity.CreateMessageActivity();
                        message.Type       = ActivityTypes.Message;
                        message.Text       = "email \n <br> sent";
                        message.Locale     = "en-Us";
                        message.TextFormat = TextFormatTypes.Plain;
                        await turnContext.SendActivityAsync(message, cancellationToken);

                        /* */
                        return;

                    default:
                        await turnContext.SendActivityAsync("No Action Logic Written for this button", cancellationToken : cancellationToken);

                        break;
                    }

                    String name = results.GetValue("Type").ToString().Trim();
                    //String actionText = results.GetValue("ActionText").ToString();
                    //await turnContext.SendActivityAsync("Respond to user " + actionText, cancellationToken: cancellationToken);

                    // Get Keywords from input field
                    String userInputKeywords = "";
                    //                    if (name == "GetPPT") {
                    if (name == "ViewProfile")
                    {
                        //String DisplayVal = results.GetValue("DisplayText").ToString();
                        //await turnContext.SendActivityAsync(MessageFactory.Text(DisplayVal), cancellationToken);

                        userInputKeywords = "View Profile";

                        AdaptiveCard ViewcardAttachment = null;
                        ViewcardAttachment = AdaptiveCardBotHelper.ViewProfile();

                        var attachment = new Attachment
                        {
                            ContentType = AdaptiveCard.ContentType,
                            Content     = ViewcardAttachment
                        };

                        if (attachment != null)
                        {
                            await turnContext.SendActivityAsync(MessageFactory.Attachment(attachment), cancellationToken);

                            //await turnContext.SendActivityAsync(MessageFactory.Text("Please enter any text to see another card."), cancellationToken);
                        }
                    }
                    else if (name == "UpdateProfile")
                    {
                        userInputKeywords = "Update Profile";

                        AdaptiveCard UpdatecardAttachment = null;
                        UpdatecardAttachment = AdaptiveCardBotHelper.UpdateProfile();

                        var attachment = new Attachment
                        {
                            ContentType = AdaptiveCard.ContentType,
                            Content     = UpdatecardAttachment
                        };

                        if (attachment != null)
                        {
                            await turnContext.SendActivityAsync(MessageFactory.Attachment(attachment), cancellationToken);

                            //await turnContext.SendActivityAsync(MessageFactory.Text("Please enter any text to see another card."), cancellationToken);
                        }

                        //userInputKeywords = results.GetValue("GetUserInputKeywords").ToString();
                    }
                    else if (name == "SendIssue")
                    {
                        AdaptiveCard IssuecardAttachment = null;
                        IssuecardAttachment = AdaptiveCardBotHelper.ReportIssue();

                        var attachment = new Attachment
                        {
                            ContentType = AdaptiveCard.ContentType,
                            Content     = IssuecardAttachment
                        };

                        if (attachment != null)
                        {
                            await turnContext.SendActivityAsync(MessageFactory.Attachment(attachment), cancellationToken);

                            //await turnContext.SendActivityAsync(MessageFactory.Text("Please enter any text to see another card."), cancellationToken);
                        }

                        userInputKeywords = "Report Issue";
                    }
                    else if (name == "Update")
                    {
                        userInputKeywords = "Update Info";
                        userInputKeywords = results.GetValue("GetUserInputKeywords").ToString();
                    }
                    //

                    // Make Http request to api with paramaters
                    //String myUrl = $"http://myurl.com/api/{userInputKeywords}";

                    //...

                    // Respond to user
                    await turnContext.SendActivityAsync("Respond to user" + userInputKeywords, cancellationToken : cancellationToken);
                }
                else
                {
                    //Conversation Text:- hi, "*****@*****.**", "i want to raise an issue", "hardware", "software"
                    turnContext.Activity.RemoveRecipientMention();
                    var text = turnContext.Activity.Text.Trim().ToLower();
                    Body.Text    = text;
                    apiHelperObj = new BotAPIHelper();
                    CreateResponseBody responseBody = apiHelperObj.CreateApiPostCall(Body);
                    if (responseBody != null)
                    {
                        if (responseBody.OutputStack != null && responseBody.OutputStack.Count() > 0)
                        {
                            foreach (var OutputStack in responseBody.OutputStack)
                            {
                                if (!string.IsNullOrEmpty(OutputStack.Text))
                                {
                                    await turnContext.SendActivityAsync(MessageFactory.Text(OutputStack.Text), cancellationToken);

                                    //IMessageActivity message = Activity.CreateMessageActivity();
                                    //message.Type = ActivityTypes.Message;
                                    //message.Text = "your \n <br> text";
                                    //message.Locale = "en-Us";
                                    //message.TextFormat = TextFormatTypes.Plain;
                                    //await turnContext.SendActivityAsync(message);
                                }
                                else
                                {
                                    var mainCard = new AdaptiveCard(new AdaptiveSchemaVersion(1, 0));
                                    if (OutputStack.Data.type == "buttons")
                                    {
                                        //===========================Add DropDownList
                                        //AdaptiveChoiceSetInput choiceSet = AdaptiveCardBotHelper.AddDropDownList();
                                        AdaptiveChoiceSetInput choiceSet = AdaptiveCardHelper.AddDropDownToAdaptiveCard(OutputStack);
                                        mainCard.Body.Add(choiceSet);

                                        //=========================== Add Button
                                        var adaptiveButtonList = AdaptiveCardHelper.AddButtonsToAdaptiveCard(OutputStack);
                                        if (adaptiveButtonList != null && adaptiveButtonList.Count() > 0)
                                        {
                                            mainCard.Body.Add(AdaptiveCardHelper.AddTextBlock(OutputStack.Data._cognigy._default._buttons.text));
                                            mainCard.Actions = adaptiveButtonList;
                                        }
                                        //var card = AdaptiveCardBotHelper.GetCard(OutputStack);
                                    }
                                    if (mainCard != null)
                                    {
                                        var cardAttachment = new Attachment()
                                        {
                                            ContentType = AdaptiveCard.ContentType,
                                            Content     = mainCard,
                                            Name        = "CardName"
                                        };
                                        await turnContext.SendActivityAsync(MessageFactory.Attachment(cardAttachment), cancellationToken);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
示例#33
0
        private async Task <DialogTurnResult> SearchRequestAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            // Check if a user has already started searching, and if you know what to search for
            var state = await _accessors.BotState.GetAsync(stepContext.Context);

            // If they're just starting to search for photos
            if (state.Searching == "no")
            {
                // Update the searching state
                state.Searching = "yes";
                // Save the new state into the conversation state.
                await _accessors.ConversationState.SaveChangesAsync(stepContext.Context);

                // Prompt the user for what they want to search for.
                // Instead of using SearchResponses.ReplyWithSearchRequest,
                // we're experimenting with using text prompts
                return(await stepContext.PromptAsync("searchPrompt", new PromptOptions { Prompt = MessageFactory.Text("What would you like to search for?") }, cancellationToken));
            }
            else // This means they just told us what they want to search for
                 // Go to the next step in the dialog, which is "SearchAsync"
            {
                return(await stepContext.NextAsync());
            }
        }
示例#34
0
        private async Task <DialogTurnResult> LoginStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            // Get the token from the previous step. Note that we could also have gotten the
            // token directly from the prompt itself. There is an example of this in the next method.
            var tokenResponse = (TokenResponse)stepContext.Result;

            if (tokenResponse?.Token != null)
            {
                // Pull in the data from the Microsoft Graph.
                var client = new SimpleGraphClient(tokenResponse.Token);
                var me     = await client.GetMeAsync();

                var title = !string.IsNullOrEmpty(me.JobTitle) ?
                            me.JobTitle : "Unknown";

                await stepContext.Context.SendActivityAsync($"You're logged in as {me.DisplayName} ({me.UserPrincipalName}); you job title is: {title}");

                return(await stepContext.PromptAsync(nameof(ConfirmPrompt), new PromptOptions { Prompt = MessageFactory.Text("Would you like to view your token?") }, cancellationToken));
            }

            await stepContext.Context.SendActivityAsync(MessageFactory.Text("Login was not successful please try again."), cancellationToken);

            return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
        }
示例#35
0
        private async Task <DialogTurnResult> InterruptAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (innerDc.Context.Activity.Type == ActivityTypes.Message)
            {
                var text = innerDc.Context.Activity.Text.ToLowerInvariant();

                if (text == "help" || text == "hilfe")
                {
                    // Help message!
                    await innerDc.Context.SendActivityAsync(MessageFactory.Text(interruptDialogHelpText), cancellationToken);

                    await innerDc.EndDialogAsync(cancellationToken : cancellationToken);

                    return(await innerDc.BeginDialogAsync(nameof(OverviewDialog), null, cancellationToken));
                }
                else if ((text.Contains("wurde") || text.Contains("worden")) && text.Contains("heute") && text.Contains("bestellt"))
                {
                    // Get the Order from the BlobStorage and the current day ID
                    int weeknumber = (DateTime.Now.DayOfYear / 7) + 1;
                    //orderBlob = JsonConvert.DeserializeObject<OrderBlob>(BotMethods.GetDocument("orders", "orders_" + weeknumber + "_" + DateTime.Now.Year + ".json"));
                    HttpRequestMessage req = new HttpRequestMessage();
                    List <OrderBlob>   tmp = await BotMethods.GetDailyOverview(this.botConfig.Value.GetDailyOverviewFunc);

                    string orderlist = string.Empty;

                    foreach (var item in tmp)
                    {
                        foreach (var items in item.OrderList)
                        {
                            if (items.Quantaty > 1)
                            {
                                orderlist += $"{items.Name}: {items.Meal} x{items.Quantaty}  {Environment.NewLine}";
                            }
                            else
                            {
                                orderlist += $"{items.Name}: {items.Meal}  {Environment.NewLine}";
                            }
                        }
                    }

                    await innerDc.Context.SendActivityAsync(MessageFactory.Text($"Es wurde bestellt:  {Environment.NewLine}{orderlist}"), cancellationToken);

                    await innerDc.EndDialogAsync(cancellationToken : cancellationToken);

                    return(await innerDc.BeginDialogAsync(nameof(OverviewDialog), null, cancellationToken));
                }
                else if (text.Contains("ich") && text.Contains("heute") && text.Contains("bestellt"))
                {
                    // Get the Order from the BlobStorage, the current day ID and nameId from the user
                    OrderBlob orderBlob  = new OrderBlob();
                    int       weeknumber = (DateTime.Now.DayOfYear / 7) + 1;
                    orderBlob = JsonConvert.DeserializeObject <OrderBlob>(BotMethods.GetDocument("orders", "orders_" + weeknumber + "_" + DateTime.Now.Year + ".json", this.botConfig.Value.StorageAccountUrl, this.botConfig.Value.StorageAccountKey));
                    var nameID = orderBlob.OrderList.FindAll(x => x.Name == innerDc.Context.Activity.From.Name);

                    if (nameID.Count != 0)
                    {
                        string message = $"Du hast heute {nameID.LastOrDefault().Meal} bei {nameID.LastOrDefault().Restaurant} bestellt.";
                        if (nameID.Count > 1)
                        {
                            message = string.Empty;
                            string orders = string.Empty;
                            foreach (var item in nameID)
                            {
                                if (item.CompanyStatus.ToLower().ToString() == "kunde" || item.CompanyStatus.ToLower().ToString() == "privat" || item.CompanyStatus.ToLower().ToString() == "praktikant")
                                {
                                    orders += $"Für {item.CompanyName}: {item.Meal} x{item.Quantaty}  {Environment.NewLine}";
                                }
                                else if (item.CompanyStatus == "intern")
                                {
                                    orders += $"{item.Name}: {item.Meal}  {Environment.NewLine}";
                                }
                                else
                                {
                                    orders += $"{item.Name}: {item.Meal}  {Environment.NewLine}";
                                }

                                if (nameID.LastOrDefault() != item)
                                {
                                    orders += " und ";
                                }
                            }

                            message = $"Du hast heute {orders} bestellt";
                        }

                        await innerDc.Context.SendActivityAsync(MessageFactory.Text(message), cancellationToken);
                    }
                    else
                    {
                        await innerDc.Context.SendActivityAsync(MessageFactory.Text($"Du hast heute noch nichts bestellt!"), cancellationToken);
                    }

                    await innerDc.EndDialogAsync(cancellationToken : cancellationToken);

                    return(await innerDc.BeginDialogAsync(nameof(OverviewDialog), null, cancellationToken));
                }
                else if (text.Contains("ende") || text.Contains("exit"))
                {
                    await innerDc.EndDialogAsync(cancellationToken : cancellationToken);

                    return(await innerDc.BeginDialogAsync(nameof(OverviewDialog), null, cancellationToken));
                }
                else if (text.Contains("excel"))
                {
                    await innerDc.Context.SendActivityAsync(MessageFactory.Text($"Einen Moment ich suche schnell alles zusammen!"), cancellationToken);

                    await innerDc.EndDialogAsync(cancellationToken : cancellationToken);

                    return(await innerDc.BeginDialogAsync(nameof(ExcellDialog), null, cancellationToken));

                    //await innerDc.Context.SendActivityAsync(MessageFactory.Text(message), cancellationToken);
                }
            }
            return(null);
        }
示例#36
0
        private async Task <DialogTurnResult> IntroStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(Configuration["LuisAppId"]) || string.IsNullOrEmpty(Configuration["LuisAPIKey"]) || string.IsNullOrEmpty(Configuration["LuisAPIHostName"]))
            {
                await stepContext.Context.SendActivityAsync(
                    MessageFactory.Text("NOTE: LUIS is not configured. To enable all capabilities, add 'LuisAppId', 'LuisAPIKey' and 'LuisAPIHostName' to the appsettings.json file."), cancellationToken);

                return(await stepContext.NextAsync(null, cancellationToken));
            }
            else
            {
                return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text("How can I help you ?") }, cancellationToken));
            }
        }
示例#37
0
        private static async Task <DialogTurnResult> Waterfall5_Step2(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            await stepContext.Context.SendActivityAsync(MessageFactory.Text("step2.2"), cancellationToken);

            return(await stepContext.EndDialogAsync(cancellationToken));
        }
示例#38
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            //check what type of message was sent
            if (turnContext.Activity.Text == null)
            {
                await turnContext.SendActivityAsync(MessageFactory.Text(Message.MessageType_Error), cancellationToken);
            }
            else
            {
                RestartUser(turnContext, cancellationToken);
                //user definitions
                foreach (var item in Users.UsersList)
                {
                    if (item.Id == turnContext.Activity.Recipient.Id)
                    {
                        current_user = item;
                    }
                }
                //checking the executable command
                CheckCommands(turnContext, current_user);
                //testing process implementation
                if (Check.Was_test)
                {
                    //sending the correct answer
                    if (turnContext.Activity.Text.ToLower() == "/prompt")
                    {
                        await send_image.SendRightReply(turnContext, cancellationToken, current_user);

                        await send_image.SendImageAsync(turnContext, cancellationToken, current_user);

                        //check if the user has passed all the questions
                        if (!SendImages.Was_ended)
                        {
                            await send_image.SendButtonAsync(turnContext, cancellationToken, current_user);
                        }
                        SendImages.Was_ended = false;
                    }
                    else
                    {
                        //validation of the answer
                        if (!SendImages.Was_answer)
                        {
                            await send_image.CheckReplyAsync(turnContext, cancellationToken, current_user);
                        }
                        //sending the next question if the previous one was correct
                        if (SendImages.Right_answer)
                        {
                            await send_image.SendImageAsync(turnContext, cancellationToken, current_user);

                            if (!SendImages.Was_ended)
                            {
                                await send_image.SendButtonAsync(turnContext, cancellationToken, current_user);
                            }
                            SendImages.Was_answer = false;
                            SendImages.Was_ended  = false;
                        }
                    }
                }
                //sending a response from the knowledge base
                else
                {
                    if (turnContext.Activity.Text.ToLower() == "/prompt")
                    {
                        await turnContext.SendActivityAsync(MessageFactory.Text(Message.Prompt_Error), cancellationToken);
                    }
                    else
                    {
                        await Dialog.RunAsync(turnContext, ConversationState.CreateProperty <DialogState>(nameof(DialogState)), cancellationToken);
                    }
                }
            }
        }
示例#39
0
 public void SendMessage(IMessageData msg)
 {
     TaskFactory.StartNew(() => NetworkSender.QueueOutgoingMessage(MessageFactory.CreateNew <MotdCliMsg>(msg)));
 }
示例#40
0
        private void RunThread()
        {
            Socket     sending_socket    = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPAddress  send_to_address   = IPAddress.Parse(mConfig.mIPAddress);
            IPEndPoint sending_end_point = new IPEndPoint(send_to_address, mConfig.mRCPort);

            UdpClient  listener = new UdpClient(mConfig.mDSPort);
            IPEndPoint groupEP  = new IPEndPoint(IPAddress.Any, mConfig.mDSPort);

            listener.Client.ReceiveTimeout = 30;
            byte theDouble = 0;

            while (true == mRunThread)
            {
                mCurStatusMessage.SetStatus(mStatus);
                mCurStatusMessage.SetTime((UInt32)DateTime.Now.Subtract(mStartTime).TotalMilliseconds);
                mCurStatusMessage.RollSequenceNumber();

                mController.SetNumber(1);
                for (int i = 0; i < MAX_BUTTONS; i++)
                {
                    mController.SetButton(i, ((1 << i) == (mButtons & (1 << i)))?true:false);
                }
                mController.SetAnalog(0, (short)(mLeftX / 256));
                mController.SetAnalog(1, (short)(mLeftY / 256));
                mController.SetAnalog(2, (short)(mRightX / 256));
                mController.SetAnalog(3, (short)(mRightY / 256));

                theDouble += 1;

                byte[] theData = mCurStatusMessage.GetData();

                sending_socket.SendTo(theData, sending_end_point); //  Repeat this as many times you want

                theData = mController.GetData();
                sending_socket.SendTo(theData, sending_end_point); //  Repeat this as many times you want

                Thread.Sleep(2);

                try
                {
                    theData = listener.Receive(ref groupEP); // You can repeat this as many times, but you can’t send stuff using this port.
                    PiMessage.Message theMessage = MessageFactory.Build(theData);
                    if (null != theMessage)
                    {
                        switch (theMessage.GetMessageID())
                        {
                        case (PiMessage.Message.MessageIDs.DS_STATUS):
                            mDSMessage = (DS_Status_Message)theMessage;
                            break;

                        case (PiMessage.Message.MessageIDs.RC_STATUS):
                            mRCMessage = (RC_Status_Message)theMessage;
                            break;
                        }
                    }

                    if (mCurStatusMessage.GetSequence() != mRCMessage.GetSequence())
                    {
                        mMessage = "Skipped";
                    }
                    else
                    {
                        mMessage = "OK";
                    }
                }
                catch (Exception e)
                {
                    mMessage = e.Message;
                }

                mCount++;
                Thread.Sleep(50);
            }
            sending_socket.Close();
        }
        public void Run()
        {
            var netConfiguration = new NetPeerConfiguration("ChatApp")
            {
                ConnectionTimeout = 10000,
            };
            var messageFactory = new MessageFactory(ProtocolDescription.GetAllMessages());
            var dispatcher = new OperationDispatcher(messageFactory, ProtocolDescription.GetAllProxies());
            var client = new NetNode<NetPeer>(new LidgrenNetProvider(netConfiguration), messageFactory, dispatcher);
            client.Start();

            client.PeerDisconnectedEvent.Subscribe((_) => Console.WriteLine("OnDisconnected"));
            client.PeerConnectedEvent.Subscribe((_) => Console.WriteLine("OnConnected"));

            var connFuture = client.ConnectToServer("127.0.0.1:5055");

            while (connFuture.State == FutureState.InProgress)
            {
                client.Update();
                Thread.Sleep(10);
            }
            NetPeer peer = connFuture.Result;
            peer.MessageEvent.Subscribe((msg) => Console.WriteLine("OnReceived " + msg));
            var loginService = peer.GetProxy<IChatLogin>();

            var loginFuture = loginService.Login("UnityTester");
            while (loginFuture.State == FutureState.InProgress)
            {
                client.Update();
                Thread.Sleep(10);
            }

            Console.WriteLine("Login Reply:" + loginFuture.Result);

            var chatServiceProxy = peer.GetProxy<IChatService>();
            var joinRoomFuture = chatServiceProxy.JoinOrCreateRoom("TestRoom");
            while (joinRoomFuture.State == FutureState.InProgress)
            {
                client.Update();
                Thread.Sleep(10);
            }

            Console.WriteLine("CreateRoom RoomId:" + joinRoomFuture.Result.RoomActorId);
            connFuture = client.ConnectToServer(joinRoomFuture.Result.ServerEndpoint);
            while (connFuture.State == FutureState.InProgress)
            {
                client.Update();
                Thread.Sleep(10);
            }

            var roomPeer = connFuture.Result;
            roomPeer.SetHandler<IChatRoomServiceCallback>(this);
            var chatRoomServiceProxy = roomPeer.GetProxy<IChatRoomService>(joinRoomFuture.Result.RoomActorId);

            var connectRoomFuture = chatRoomServiceProxy.Join(joinRoomFuture.Result.Ticket);

            while (connectRoomFuture.State == FutureState.InProgress)
            {
                client.Update();
                Thread.Sleep(10);
            }

            foreach (var msg in connectRoomFuture.Result)
                Console.WriteLine(msg);

            while (true)
            {
                client.Update();
                Thread.Sleep(10);
            }
        }
示例#42
0
        public void USAHealthCareAdtA01MessagePatientIsBobaBountyhunterFett()
        {
            MessageFactory messageFactory = new MessageFactory();
            ExtendedPersonName expectedExtendedPersonName = new ExtendedPersonName()
            {
                GivenName = "BOBA",
                MiddleNameOrInitial = "BOUNTYHUNTER",
                FamilyName = "FETT"
            };

            Message newMessage = messageFactory.MakeMessage(TestMessages.USAHealthCare_ADT_A01);
            PID pidSegment = (PID)newMessage.Segments.Find(s => s.SegmentType == SegmentTypes.PID);
            ExtendedPersonName actualExtendedPersonName = pidSegment.GetPatientName();

            Assert.AreEqual(expectedExtendedPersonName, actualExtendedPersonName);
        }
示例#43
0
 /// <summary>
 ///
 /// </summary>
 public NetClient(MessageFactory messageFactory)
 {
     m_messageFactory = messageFactory;
 }
示例#44
0
 public virtual void SendOneWay(object requestDto)
 {
     Publish(MessageFactory.Create(requestDto));
 }
        public void CarouselNull()
        {
            IMessageActivity message = MessageFactory.Carousel((IList <Attachment>)null);

            Assert.Fail("Exception not thrown");
        }
示例#46
0
 internal IncomingMessageAgent(Message.Categories cat, IMessageCenter mc, ActivationDirectory ad, OrleansTaskScheduler sched, Dispatcher dispatcher, MessageFactory messageFactory, ILoggerFactory loggerFactory) :
     base(cat.ToString(), loggerFactory)
 {
     category            = cat;
     messageCenter       = mc;
     directory           = ad;
     scheduler           = sched;
     this.dispatcher     = dispatcher;
     this.messageFactory = messageFactory;
     OnFault             = FaultBehavior.RestartOnFault;
 }
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            if (turnContext.Activity.Attachments != null)
            {
                var activity = MessageFactory.Text($" I got {turnContext.Activity.Attachments.Count} attachments");
                foreach (var attachment in turnContext.Activity.Attachments)
                {
                    var image = new Attachment(
                        "image/png",
                        "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQtB3AwMUeNoq4gUBGe6Ocj8kyh3bXa9ZbV7u1fVKQoyKFHdkqU");

                    activity.Attachments.Add(image);
                }

                await turnContext.SendActivityAsync(activity, cancellationToken);
            }
            else
            {
                var activity = turnContext.Activity.Text == "cards" ? MessageFactory.Attachment(CreateAdaptiveCardAttachment(Directory.GetCurrentDirectory() + @"/Resources/adaptive_card.json")) : MessageFactory.Text($"Echo: {turnContext.Activity.Text}");

                await turnContext.SendActivityAsync(activity, cancellationToken);
            }
        }
示例#48
0
        // </GetTokenSnippet>

        // <AddEventSnippet>
        private async Task <DialogTurnResult> AddEventAsync(
            WaterfallStepContext stepContext,
            CancellationToken cancellationToken)
        {
            if (stepContext.Result != null)
            {
                var tokenResponse = stepContext.Result as TokenResponse;
                if (tokenResponse?.Token != null)
                {
                    var subject   = stepContext.Values["subject"] as string;
                    var attendees = stepContext.Values["attendees"] as string;
                    var start     = stepContext.Values["start"] as DateTime?;
                    var end       = stepContext.Values["end"] as DateTime?;

                    // Get an authenticated Graph client using
                    // the access token
                    var graphClient = _graphClientService
                                      .GetAuthenticatedGraphClient(tokenResponse?.Token);

                    try
                    {
                        // Get user's preferred time zone
                        var user = await graphClient.Me
                                   .Request()
                                   .Select(u => new { u.MailboxSettings })
                                   .GetAsync();

                        // Initialize an Event object
                        var newEvent = new Event
                        {
                            Subject = subject,
                            Start   = new DateTimeTimeZone
                            {
                                DateTime = start?.ToString("o"),
                                TimeZone = user.MailboxSettings.TimeZone
                            },
                            End = new DateTimeTimeZone
                            {
                                DateTime = end?.ToString("o"),
                                TimeZone = user.MailboxSettings.TimeZone
                            }
                        };

                        // If attendees were provided, add them
                        if (!string.IsNullOrEmpty(attendees))
                        {
                            // Initialize a list
                            var attendeeList = new List <Attendee>();

                            // Split the string into an array
                            var emails = attendees.Split(";");
                            foreach (var email in emails)
                            {
                                // Skip empty strings
                                if (!string.IsNullOrEmpty(email))
                                {
                                    // Build a new Attendee object and
                                    // add to the list
                                    attendeeList.Add(new Attendee {
                                        Type         = AttendeeType.Required,
                                        EmailAddress = new EmailAddress
                                        {
                                            Address = email
                                        }
                                    });
                                }
                            }

                            newEvent.Attendees = attendeeList;
                        }

                        // Add the event
                        // POST /me/events
                        await graphClient.Me
                        .Events
                        .Request()
                        .AddAsync(newEvent);

                        await stepContext.Context.SendActivityAsync(
                            MessageFactory.Text("Event added"),
                            cancellationToken);
                    }
                    catch (ServiceException ex)
                    {
                        _logger.LogError(ex, "Could not add event");
                        await stepContext.Context.SendActivityAsync(
                            MessageFactory.Text("Something went wrong. Please try again."),
                            cancellationToken);
                    }
                    return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
                }
            }

            await stepContext.Context.SendActivityAsync(
                MessageFactory.Text("We couldn't log you in. Please try again later."),
                cancellationToken);

            return(await stepContext.EndDialogAsync(cancellationToken: cancellationToken));
        }
 public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
 {
     await turnContext.SendActivityAsync(MessageFactory.Text("rage.rage.against.the.dying.of.the.light"));
 }
示例#50
0
 public BasicRequest(object requestDto,
                     RequestAttributes requestAttributes = RequestAttributes.LocalSubnet | RequestAttributes.MessageQueue)
     : this(MessageFactory.Create(requestDto), requestAttributes)
 {
 }
示例#51
0
        // Waterfall step function for asking the User his name
        private static async Task <DialogTurnResult> NameStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            // WaterfallStep always finishes with the end of the Waterfall or with another dialog; here it is a Prompt Dialog.
            // Running a prompt here means the next WaterfallStep will be run when the users response is received.
            await stepContext.Context.SendActivityAsync(MessageFactory.Text("May I know your name please??"), cancellationToken);

            return(await stepContext.PromptAsync("name", new PromptOptions { Prompt = MessageFactory.Text("<< In the format 'It is NAME' >>") }, cancellationToken));
        }
示例#52
0
        /*
         * You can @mention the bot the text "1", "2", or "3". "1" will send back adaptive cards. "2" will send back a
         * task module that contains an adpative card. "3" will return an adpative card that contains BF card actions.
         *
         */
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            if (turnContext.Activity.Text != null)
            {
                turnContext.Activity.RemoveRecipientMention();
                string actualText = turnContext.Activity.Text;

                if (actualText.Equals("1"))
                {
                    var adaptiveCard = new AdaptiveCard();
                    adaptiveCard.Body.Add(new AdaptiveTextBlock("Bot Builder actions"));

                    var action1 = new CardAction(ActionTypes.ImBack, "imBack", null, null, null, "text");
                    var action2 = new CardAction(ActionTypes.MessageBack, "message back", null, null, null, JObject.Parse(@"{ ""key"" : ""value"" }"));
                    var action3 = new CardAction(ActionTypes.MessageBack, "message back local echo", null, "text received by bots", "display text message back", JObject.Parse(@"{ ""key"" : ""value"" }"));
                    var action4 = new CardAction("invoke", "invoke", null, null, null, JObject.Parse(@"{ ""key"" : ""value"" }"));

                    adaptiveCard.Actions.Add(action1.ToAdaptiveCardAction());
                    adaptiveCard.Actions.Add(action2.ToAdaptiveCardAction());
                    adaptiveCard.Actions.Add(action3.ToAdaptiveCardAction());
                    adaptiveCard.Actions.Add(action4.ToAdaptiveCardAction());

                    var replyActivity = MessageFactory.Attachment(adaptiveCard.ToAttachment());
                    await turnContext.SendActivityAsync(replyActivity, cancellationToken);
                }
                else if (actualText.Equals("2"))
                {
                    var taskModuleAction = new TaskModuleAction("Launch Task Module", @"{ ""hiddenKey"": ""hidden value from task module launcher"" }");

                    var adaptiveCard = new AdaptiveCard();
                    adaptiveCard.Body.Add(new AdaptiveTextBlock("Task Module Adaptive Card"));
                    adaptiveCard.Actions.Add(taskModuleAction.ToAdaptiveCardAction());

                    var replyActivity = MessageFactory.Attachment(adaptiveCard.ToAttachment());
                    await turnContext.SendActivityAsync(replyActivity, cancellationToken);
                }
                else if (actualText.Equals("3"))
                {
                    var adaptiveCard = new AdaptiveCard();
                    adaptiveCard.Body.Add(new AdaptiveTextBlock("Bot Builder actions"));
                    adaptiveCard.Body.Add(new AdaptiveTextInput {
                        Id = "x"
                    });
                    adaptiveCard.Actions.Add(new AdaptiveSubmitAction {
                        Type = "Action.Submit", Title = "Action.Submit", Data = new JObject {
                            { "key", "value" }
                        }
                    });

                    var replyActivity = MessageFactory.Attachment(adaptiveCard.ToAttachment());
                    await turnContext.SendActivityAsync(replyActivity, cancellationToken);
                }
                else
                {
                    await turnContext.SendActivityAsync(MessageFactory.Text($"You said: {turnContext.Activity.Text}"), cancellationToken);
                }
            }
            else
            {
                await turnContext.SendActivityAsync(MessageFactory.Text($"App sent a message with null text"), cancellationToken);

                // TODO: process the response from the card

                if (turnContext.Activity.Value != null)
                {
                    await turnContext.SendActivityAsync(MessageFactory.Text($"but with value {turnContext.Activity.Value}"), cancellationToken);
                }
            }
        }
        public void AttachmentMultipleNull()
        {
            IMessageActivity message = MessageFactory.Attachment((IList <Attachment>)null);

            Assert.Fail("Exception not thrown");
        }
示例#54
0
        public void ConsumeMessage_PersistPatientInfoToDatabase_RetrievePatientInfo_IsSuccess()
        {
            // Consume a message
            MessageFactory messageFactory = new MessageFactory();
            Message newMessage = messageFactory.MakeMessage(TestMessages.TennesseeHealthCare_ADT_A01);

            // Parse some segments
            PID pidSegment = (PID)newMessage.Segments.Find(s => s.SegmentType == SegmentTypes.PID);
            DG1 dg1Segment = (DG1)newMessage.Segments.Find(s => s.SegmentType == SegmentTypes.DG1);
            PV1 pv1Segment = (PV1)newMessage.Segments.Find(s => s.SegmentType == SegmentTypes.PV1);

            // Populate some models with the parsed data
            ExtendedPersonName patientExtendedPersonName = pidSegment.GetPatientName();
            var name = new HL7Model.PersonName();
            name.FirstName = patientExtendedPersonName.GivenName;
            name.LastName = patientExtendedPersonName.FamilyName;
            name.MiddleName = patientExtendedPersonName.MiddleNameOrInitial;

            var newDiagnosis1 = new HL7Model.Diagnosis();
            newDiagnosis1.SetId = dg1Segment.GetSetId();
            newDiagnosis1.DiagnosisDateTime = dg1Segment.GetDiagnosisDateTime();
            newDiagnosis1.Description = dg1Segment.GetDiagnosisDescription();
            newDiagnosis1.Clinician = dg1Segment.GetDiagnosingClinician();

            PersonLocation patientLocation = pv1Segment.GetAssignedPatientLocation();
            var newPatientVisit = new HL7Model.PatientVisit();
            newPatientVisit.SetId = pv1Segment.GetSetID();
            newPatientVisit.Location.Bed = patientLocation.Bed;
            newPatientVisit.Location.Building = patientLocation.Building;
            newPatientVisit.Location.Facility = patientLocation.Facility;
            newPatientVisit.Location.Floor = patientLocation.Floor;
            newPatientVisit.Location.LocationDescription = patientLocation.LocationDescription;
            newPatientVisit.Location.LocationStatus = patientLocation.LocationStatus;
            newPatientVisit.Location.Room = patientLocation.Room;

            Address patientAddress = pidSegment.GetPatientAddress();
            PhoneNumber patientPhoneNumber = pidSegment.GetHomePhoneNumber();
            var newPatient = new HL7Model.Patient();
            newPatient.ExternalPatientId = pidSegment.GetExternalPatientId();
            newPatient.InternalPatientId = pidSegment.GetInternalPatientId();
            newPatient.Address.Address1 = patientAddress.Address1;
            newPatient.Address.Address2 = patientAddress.Address2;
            newPatient.Address.City = patientAddress.City;
            newPatient.Address.State = patientAddress.State;
            newPatient.Address.PostalCode = patientAddress.ZipCode;
            newPatient.Gender = pidSegment.GetGender();
            newPatient.DateOfBirth = pidSegment.GetDateOfBirth();
            newPatient.PrimaryPhoneNumber.AreaCode = patientPhoneNumber.AreaCode;
            newPatient.PrimaryPhoneNumber.CountryCode = patientPhoneNumber.CountryCode;
            newPatient.PrimaryPhoneNumber.LineNumber = patientPhoneNumber.LineNumber;
            newPatient.Names.Add(name);
            newPatient.Diagnosis.Add(newDiagnosis1);
            newPatient.PatientVisit.Add(newPatientVisit);

            // Commit the patient to the database
            IHL7UnitOfWork uow = new HL7UnitOfWork();
            uow.Patients.Add(newPatient);
            uow.Commit();

            // Retrieve the patient back from the database
            Patient patient = uow.Patients.GetPatientByExternalId(pidSegment.GetExternalPatientId());

            // Assert that the data retrieved from the database is the same as what went in.
            Assert.AreEqual(pidSegment.GetInternalPatientId(), patient.InternalPatientId);
            Assert.AreEqual(patientExtendedPersonName.GivenName, patient.Names[0].FirstName);
            Assert.AreEqual(dg1Segment.GetDiagnosisDescription(), patient.Diagnosis[0].Description);
            Assert.AreEqual(patientLocation.Room, patient.PatientVisit[0].Location.Room);
        }
示例#55
0
        private static async Task <DialogTurnResult> Waterfall4_Step1(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            await stepContext.Context.SendActivityAsync(MessageFactory.Text("step1.1"), cancellationToken);

            return(Dialog.EndOfTurn);
        }
示例#56
0
        private static async Task <DialogTurnResult> Waterfall3_Step2(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            await stepContext.Context.SendActivityAsync(MessageFactory.Text("step2"), cancellationToken);

            return(await stepContext.BeginDialogAsync("test-waterfall-c", null, cancellationToken));
        }
示例#57
0
        private async Task ProcessCovid19LuisAsync(ITurnContext <IMessageActivity> turnContext, LuisResult luisResult, CancellationToken cancellationToken)
        {
            _logger.LogInformation("ProcessCovid19LuisAsync");

            // Retrieve LUIS result for Process Automation.
            var result    = luisResult.ConnectedServiceResult;
            var topIntent = result.TopScoringIntent.Intent;

            if (topIntent == "Covid19India")
            {
                var           url          = $"https://api.covid19api.com/live/country/india";
                var           repositories = ProcessRepo(url);
                List <string> Ystdata      = new List <string>();
                List <string> Tdydata      = new List <string>();

                if (repositories.Count > 0)
                {
                    var ystData   = repositories[repositories.Count - 2];
                    var todayData = repositories.LastOrDefault();

                    DateTime Todaydatetime = DateTime.Parse(todayData.date);
                    DateTime Ystdatetime   = DateTime.Parse(ystData.date);

                    var confirmedInc    = todayData.confirmed - ystData.confirmed;
                    var confirmedIncPCT = (((Math.Abs(Convert.ToDecimal(confirmedInc))) / (Math.Abs(Convert.ToDecimal(todayData.confirmed)))) * 100).ToString("0.00");

                    var activeInc    = todayData.active - ystData.active;
                    var activeIncPCT = (((Math.Abs(Convert.ToDecimal(activeInc))) / (Math.Abs(Convert.ToDecimal(todayData.active)))) * 100).ToString("0.00"); //(activeInc / todayData.active) * 100;

                    var recoveredInc    = todayData.recovered - ystData.recovered;
                    var recoveredIncPCT = (((Math.Abs(Convert.ToDecimal(recoveredInc))) / (Math.Abs(Convert.ToDecimal(todayData.recovered)))) * 100).ToString("0.00"); //(recoveredInc / todayData.recovered) * 100;

                    var deceasedInc    = todayData.deaths - ystData.deaths;
                    var deceasedIncPCT = (((Math.Abs(Convert.ToDecimal(deceasedInc))) / (Math.Abs(Convert.ToDecimal(todayData.deaths)))) * 100).ToString("0.00"); //(deceasedInc / todayData.deaths) * 100;

                    Ystdata.Add(ystData.confirmed.ToString());
                    Ystdata.Add(ystData.deaths.ToString());
                    Ystdata.Add(ystData.recovered.ToString());
                    Ystdata.Add(ystData.active.ToString());
                    Ystdata.Add(Ystdatetime.ToString("dd MMM yyyy"));

                    Tdydata.Add(todayData.confirmed.ToString());
                    Tdydata.Add(todayData.deaths.ToString());
                    Tdydata.Add(todayData.recovered.ToString());
                    Tdydata.Add(todayData.active.ToString());
                    Tdydata.Add(Todaydatetime.ToString("dd MMM yyyy") + " " + "India");
                    Tdydata.Add("▲ " + " " + confirmedInc + " " + "(" + confirmedIncPCT + " " + "%" + ")");
                    Tdydata.Add("▲ " + " " + activeInc + " " + "(" + activeIncPCT + " " + "%" + ")");
                    Tdydata.Add("▲ " + " " + recoveredInc + " " + "(" + recoveredIncPCT + " " + "%" + ")");
                    Tdydata.Add("▲ " + " " + deceasedInc + " " + "(" + deceasedIncPCT + " " + "%" + ")");
                }

                var Covid19StatusCardRead = readFileforUpdate_jobj(_cards[0]);

                JToken Date         = Covid19StatusCardRead.SelectToken("body[0].items[2].text");
                JToken ConfirmedInc = Covid19StatusCardRead.SelectToken("body[0].items[3].columns[0].items[1].text");
                JToken Confirmed    = Covid19StatusCardRead.SelectToken("body[0].items[3].columns[0].items[2].text");

                JToken ActiveInc = Covid19StatusCardRead.SelectToken("body[0].items[3].columns[1].items[1].text");
                JToken Active    = Covid19StatusCardRead.SelectToken("body[0].items[3].columns[1].items[2].text");

                JToken RecoveredInc = Covid19StatusCardRead.SelectToken("body[0].items[3].columns[2].items[1].text");
                JToken Recovered    = Covid19StatusCardRead.SelectToken("body[0].items[3].columns[2].items[2].text");

                JToken DeceasedInc = Covid19StatusCardRead.SelectToken("body[0].items[3].columns[3].items[1].text");
                JToken Deceased    = Covid19StatusCardRead.SelectToken("body[0].items[3].columns[3].items[2].text");

                Date.Replace(Tdydata[4]);
                Confirmed.Replace(Tdydata[0]);
                Active.Replace(Tdydata[3]);
                Recovered.Replace(Tdydata[2]);
                Deceased.Replace(Tdydata[1]);

                ConfirmedInc.Replace(Tdydata[5]);
                ActiveInc.Replace(Tdydata[6]);
                RecoveredInc.Replace(Tdydata[7]);
                DeceasedInc.Replace(Tdydata[8]);

                var Covid19StatusCardFinal = UpdateAdaptivecardAttachment(Covid19StatusCardRead);
                var response = MessageFactory.Attachment(Covid19StatusCardFinal, ssml: "Covid19 Live status card!");
                await turnContext.SendActivityAsync(response, cancellationToken);
            }
            else
            if (topIntent == "WorldCovid19")
            {
                var           url          = $"https://api.covid19api.com/summary";
                var           repositories = ProcessRepoWorldJ(url);
                List <string> Tdydata      = new List <string>();

                var TotalConfirmed = (string)repositories.SelectToken("Global.TotalConfirmed");
                var NewConfirmed   = (string)repositories.SelectToken("Global.NewConfirmed");
                var TotalDeaths    = (string)repositories.SelectToken("Global.TotalDeaths");
                var NewDeaths      = (string)repositories.SelectToken("Global.NewDeaths");
                var TotalRecovered = (string)repositories.SelectToken("Global.TotalRecovered");
                var NewRecovered   = (string)repositories.SelectToken("Global.NewRecovered");
                var date           = (DateTime)repositories.SelectToken("Date");
                //DateTime datetime1 = DateTime.Parse(date);
                //DateTime datetime1 = DateTime.Parse(date);
                var Todaydatetime   = date.ToString("dd MMM yyyy") + " " + "Global";
                var confirmedIncPCT = (((Math.Abs(Convert.ToDecimal(NewConfirmed))) / (Math.Abs(Convert.ToDecimal(TotalConfirmed)))) * 100).ToString("0.00");
                var recoveredIncPCT = (((Math.Abs(Convert.ToDecimal(NewRecovered))) / (Math.Abs(Convert.ToDecimal(TotalRecovered)))) * 100).ToString("0.00");
                var deathsIncPCT    = (((Math.Abs(Convert.ToDecimal(NewDeaths))) / (Math.Abs(Convert.ToDecimal(TotalDeaths)))) * 100).ToString("0.00");

                var confirmIncFinal = "▲ " + " " + NewConfirmed + " " + "(" + confirmedIncPCT + " " + "%" + ")";
                var recoveredFinal  = "▲ " + " " + NewRecovered + " " + "(" + recoveredIncPCT + " " + "%" + ")";
                var deathsIncFinal  = "▲ " + " " + NewDeaths + " " + "(" + deathsIncPCT + " " + "%" + ")";

                var GlobalStatusCardRead = readFileforUpdate_jobj(_cards[1]);

                JToken Date         = GlobalStatusCardRead.SelectToken("body[0].items[2].text");
                JToken ConfirmedInc = GlobalStatusCardRead.SelectToken("body[0].items[3].columns[0].items[1].text");
                JToken Confirmed    = GlobalStatusCardRead.SelectToken("body[0].items[3].columns[0].items[2].text");

                JToken RecoveredInc = GlobalStatusCardRead.SelectToken("body[0].items[3].columns[1].items[1].text");
                JToken Recovered    = GlobalStatusCardRead.SelectToken("body[0].items[3].columns[1].items[2].text");

                JToken DeceasedInc = GlobalStatusCardRead.SelectToken("body[0].items[3].columns[2].items[1].text");
                JToken Deceased    = GlobalStatusCardRead.SelectToken("body[0].items[3].columns[2].items[2].text");

                Date.Replace(Todaydatetime);
                ConfirmedInc.Replace(confirmIncFinal);
                Confirmed.Replace(TotalConfirmed);
                RecoveredInc.Replace(recoveredFinal);
                Recovered.Replace(TotalRecovered);
                DeceasedInc.Replace(deathsIncFinal);
                Deceased.Replace(TotalDeaths);
                //var GlobalStatusCardFinal = CreateAdaptiveCardAttachment(_cards[1]);
                var GlobalStatusCardFinal = UpdateAdaptivecardAttachment(GlobalStatusCardRead);
                var response = MessageFactory.Attachment(GlobalStatusCardFinal, ssml: "Global Live status card!");
                await turnContext.SendActivityAsync(response, cancellationToken);
            }
            else
            {
                _logger.LogInformation($"Luis unrecognized intent.");
                await turnContext.SendActivityAsync(MessageFactory.Text($"Bot unrecognized your inputs, kindly reply as live covid19 status."), cancellationToken);
            }
        }