예제 #1
0
        private ReadOnlyCollection <IWebElement> _findElements(CommandDTO cmd)
        {
            if (!string.IsNullOrEmpty(cmd.IDToClick))
            {
                var elem = WebDriver.FindElements(By.Id(cmd.IDToClick));
                if (elem == null)
                {
                    throw new Exception("Cannot find element list by id :" + cmd.IDToClick);
                }

                return(elem);
            }

            if (!string.IsNullOrEmpty(cmd.ClassNameToClick))
            {
                var elem = WebDriver.FindElements(By.ClassName(cmd.ClassNameToClick));
                if (elem == null)
                {
                    throw new Exception("Cannot find element list by class name :" + cmd.ClassNameToClick);
                }

                return(elem);
            }

            return(null);
        }
예제 #2
0
        private static async Task HandleCustomCommand(string command, SocketUserMessage message, string mentionedUsers, IResult result)
        {
            CommandDTO cmd = CommandManager.TheCommandManager.GetCommandByName(command);

            if (cmd != null && cmd.CommandData != string.Empty)
            {
                cmd.CommandCount += 1;
                CommandManager.TheCommandManager.UpdateCommand(cmd);
                await message.Channel.SendMessageAsync(mentionedUsers + cmd.CommandData);
            }
            else
            {
                if (result.IsSuccess)
                {
                    return;
                }

                // command not found, look it up and see if there are any results.
                string lookupResult = Sitemap.Lookup(command);
                if (string.Empty != lookupResult)
                {
                    await message.Channel.SendMessageAsync(mentionedUsers + lookupResult);
                }
            }
        }
예제 #3
0
        static void Main(string[] args)
        {
            var engine = new GameService(Player.A);
            int index  = 0;

            while (true)
            {
                try
                {
                    Console.Write("> ");
                    string input = Console.ReadLine();
                    if (Enum.TryParse <MoveType>(input, out var move))
                    {
                        var command = new CommandDTO(index++, Player.A, move);
                        engine.ProcessCommand(command);
                    }
                    else
                    {
                        Console.WriteLine("?!");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
        }
예제 #4
0
        /// <summary>
        /// http://www.jarloo.com/c-udp-multicasting-tutorial/
        /// https://en.wikipedia.org/wiki/Multicast_address
        /// </summary>
        public void SendJSONCommandsMultiCast()
        {
            UdpClient udpclient = new UdpClient();

            //IPAddress multicastaddress = IPAddress.Parse("239.0.0.222");
            IPAddress multicastaddress = IPAddress.Parse("224.0.1.222");

            udpclient.JoinMulticastGroup(multicastaddress);
            IPEndPoint remoteep    = new IPEndPoint(multicastaddress, 2222);
            CommandDTO sendCommand = new CommandDTO()
            {
                sendID = "Laptop 57", ComNo = 45
            };

            byte[] jsonUtf8Bytes;
            JsonSerializerOptions sendopt = new JsonSerializerOptions()
            {
                WriteIndented = true
            };
            string com;

            Console.WriteLine("Start sending ! Press ENTER Ctr C quit.");
            while (true)
            {
                System.Console.Write("Send en kommando: ");
                com = System.Console.ReadLine();
                sendCommand.ComNo = IntegerType.FromString(com);
                jsonUtf8Bytes     = JsonSerializer.SerializeToUtf8Bytes(sendCommand, sendopt);
                udpclient.Send(jsonUtf8Bytes, jsonUtf8Bytes.Length, remoteep); //Remark no specific endpoint given

                Console.WriteLine($"Message sent to the broadcast address {sendCommand}");
            }
        }
예제 #5
0
        public void SendJSONCommands()
        {
            Socket     s           = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPAddress  broadcast   = IPAddress.Parse("192.168.1.255"); //10.255.255.255 class A B + C
            IPEndPoint ep          = new IPEndPoint(broadcast, listenPortCommand);
            CommandDTO sendCommand = new CommandDTO()
            {
                sendID = "Laptop 57", ComNo = 45
            };

            byte[] jsonUtf8Bytes;
            JsonSerializerOptions sendopt = new JsonSerializerOptions()
            {
                WriteIndented = true
            };
            string com;

            while (true)
            {
                System.Console.WriteLine("Send en kommando: ");
                com = System.Console.ReadLine();
                sendCommand.ComNo = IntegerType.FromString(com);
                jsonUtf8Bytes     = JsonSerializer.SerializeToUtf8Bytes(sendCommand, sendopt);
                s.SendTo(jsonUtf8Bytes, ep);

                Console.WriteLine("Message sent to the broadcast address");
            }
        }
        public void WithNull_ShouldReturnNull()
        {
            PlcInformationDtoAssembler assembler = CreateAssembler();
            CommandDTO dto = assembler.AssembleCommandDto(null);

            dto.Should().BeNull();
        }
예제 #7
0
        public ActionResult CreateCommand(CommandDTO commandDTO) //<CommandDTO>
        {
            _telemetryClient.TrackEvent("Logging - in CreateCommand (controller) | telemetry");
            _logger.LogInformation("Logging - in CreateCommand (controller) | serilog");

            //throw new Exce

            if (ModelState.IsValid)
            {
                _telemetryClient.TrackEvent("Logging - Model Valid in CreateCommand (controller) | telemetry");
                _logger.LogInformation("Logging - Model Valid in CreateCommand (controller) | serilog");

                var details  = _mapper.Mapper.Map <CommandDTO, Command>(commandDTO);
                var response = _commander.CreateCommand(details);

                var result = _mapper.Mapper.Map <Command, CommandDTO>(response);

                return(new OkObjectResult(result));
            }
            else
            {
                _telemetryClient.TrackEvent("Logging - Model Not Valid in CreateCommand (controller) | telemetry");
                _logger.LogInformation("Logging - Model Not Valid in CreateCommand (controller) | serilog");
                //throw new Exception("not correct tsm");
                return(BadRequest());
            }
        }
        public void WithCommandStop_ShouldReturnDtoStop()
        {
            ICommand command = Command(Stop(), StopsIt());
            PlcInformationDtoAssembler assembler = CreateAssembler();
            CommandDTO dto = assembler.AssembleCommandDto(command);

            dto.ShouldHaveValues(Stop(), StopsIt());
        }
예제 #9
0
 public static Command Unmapper(CommandDTO model)
 {
     return(new Command()
     {
         CommandID = model.CommandID,
         Country = model.Country,
         Name = model.Name,
         PlayerID = model.PlayerID
     });
 }
예제 #10
0
        public async Task <UserDto> Handle(CreateUserCommand request, CancellationToken cancellationToken)
        {
            var input = request.Data.Attributes;

            var user = new Users_()
            {
                name     = input.name,
                username = input.username,
                email    = input.email,
                password = input.password,
                address  = input.address
            };

            _context.UsersData.Add(user);
            await _context.SaveChangesAsync();

            var user1  = _context.UsersData.First(x => x.username == request.Data.Attributes.username);
            var target = new Target()
            {
                Id = user.id, Email_destination = user.email
            };

            var command = new NotifInput()
            {
                Title   = "rabbit - test",
                Message = "this is only testing",
                Type    = "email",
                From    = 123456,
                Targets = new List <Target>()
                {
                    target
                }
            };

            var attributes = new Attribute <NotifInput>()
            {
                Attributes = command
            };

            var httpContent = new CommandDTO <NotifInput>()
            {
                Data = attributes
            };

            var jsonObject = JsonConvert.SerializeObject(httpContent);
            var content    = new StringContent(jsonObject, Encoding.UTF8, "application/json");

            await client.PostAsync("http://localhost:5800/api/notification", content);

            return(new UserDto
            {
                message = "Success add a user data",
                success = true
            });
        }
예제 #11
0
        public void GivenNullCommand_WhenProcess_ThenThrows()
        {
            var service = new GameService(Player.A);

            CommandDTO command = null;

            var exception = Record.Exception(() => service.ProcessCommand(command));

            Assert.NotNull(exception);
            Assert.IsType <ArgumentNullException>(exception);
        }
예제 #12
0
        public List <CommandDTO> GetByDevice(int deviceId)
        {
            System.Collections.Generic.ICollection <Command> coms = commRep.GetByDevice(deviceId);
            List <CommandDTO> res = new List <CommandDTO>();

            foreach (Command d in coms)
            {
                res.Add(CommandDTO.Convert(d));
            }
            return(res);
        }
예제 #13
0
        public async Task CustomCommandAsync([Remainder] string cmd)
        {
            if (!CheckModPermissions())
            {
                var embed = new EmbedBuilder();
                embed.WithTitle("Success! :thumbsdown:");
                embed.WithColor(Color.DarkRed);
                embed.AddInlineField("Sorry!", "You do not have permissions to create command. Only Moderators can create commands.");
                await ReplyAsync("", false, embed);

                return;
            }

            string command = cmd;
            string value   = string.Empty;

            if (cmd.Length > 0)
            {
                int i = cmd.IndexOf(' ');
                if (i != -1)
                {
                    command = cmd.Substring(0, i);
                    value   = cmd.Substring(i, cmd.Length - i);
                }

                value = (value != null) ? value.Trim() : string.Empty;
                if (value == string.Empty)
                {
                    // passed empty value - remove that command from list
                    CommandManager.TheCommandManager.RemoveCommandByName(command);
                    return;
                }

                CommandDTO cmdDTO = CommandManager.TheCommandManager.GetCommandByName(command);
                if (cmdDTO == null)
                {
                    cmdDTO = new CommandDTO();
                    cmdDTO.CommandCount       = 0;
                    cmdDTO.CommandData        = value;
                    cmdDTO.CommandCreatedDate = DateTime.Now;
                    cmdDTO.CommandName        = command;
                }
                cmdDTO.CommandCount += 1;
                cmdDTO.CommandAuthor = Context.User.Mention;
                CommandManager.TheCommandManager.UpdateCommand(cmdDTO);

                var embed = new EmbedBuilder();
                embed.WithTitle("Success! :thumbsup:");
                embed.WithColor(Helper.GetRandomColor());
                embed.AddInlineField("You are all set!",
                                     string.Format("Go ahead and run the command using `~{0}`", command));
                await ReplyAsync("", false, embed);
            }
        }
예제 #14
0
 private static void _onTestCommandComplete(CommandDTO commandDTO)
 {
     if (commandDTO.CommandStatus == CommandResponseStatus.Failed)
     {
         Console.ForegroundColor = ConsoleColor.Red;
     }
     else
     {
         Console.ForegroundColor = ConsoleColor.Green;
     }
     Console.WriteLine("Command completed:" + commandDTO.CommandType.ToString() + "- ID: " + commandDTO.IDToClick.ToString() + "- Class: " + commandDTO.ClassNameToClick.ToString() + "- Value: " + commandDTO.Value + ": " + commandDTO.CommandStatus.ToString());
 }
예제 #15
0
        public void GivenTooBigIndex_WhenProcess_ThenThrows()
        {
            var service = new GameService(Player.A);

            var command = new CommandDTO(GameService.MaxMoves + 1, Player.A, MoveType.DrawCard);

            var exception = Record.Exception(() => service.ProcessCommand(command));

            Assert.NotNull(exception);
            Assert.IsType <InvalidMoveException>(exception);
            Assert.Equal("Invalid game index", exception.Message);
        }
예제 #16
0
        public async Task <UserDTO> Handle(PostUserCommand request, CancellationToken cancellationToken)
        {
            var data = new userModel()
            {
                Name     = request.Data.Attributes.Name,
                Username = request.Data.Attributes.Username,
                Email    = request.Data.Attributes.Email,
                Password = request.Data.Attributes.Password,
                Address  = request.Data.Attributes.Address
            };

            _context.Add(data);
            await _context.SaveChangesAsync();

            var user   = _context.userModels.First(x => x.Username == request.Data.Attributes.Username);
            var target = new TargetCommand()
            {
                Id = user.Id, Email_destination = user.Email
            };

            var command = new PostCommand()
            {
                Title   = "hello",
                Message = "this is message body",
                Type    = "email",
                From    = 123456,
                Targets = new List <TargetCommand>()
                {
                    target
                }
            };

            var attributes = new Attribute <PostCommand>()
            {
                Attributes = command
            };

            var httpContent = new CommandDTO <PostCommand>()
            {
                Data = attributes
            };

            var jsonObject = JsonConvert.SerializeObject(httpContent);
            var content    = new StringContent(jsonObject, Encoding.UTF8, "application/json");

            await client.PostAsync("http://localhost:5007/notification", content);

            return(new UserDTO()
            {
                Message = "Successfully Added",
                Success = true
            });
        }
예제 #17
0
        public void GivenInvalidSideB_WhenProcess_ThenThrows()
        {
            var service = new GameService(Player.A);

            var command = new CommandDTO(0, Player.B, MoveType.DrawCard);

            var exception = Record.Exception(() => service.ProcessCommand(command));

            Assert.NotNull(exception);
            Assert.IsType <InvalidMoveException>(exception);
            Assert.Equal("Invalid player side", exception.Message);
        }
예제 #18
0
        //Sending queue when transaction_status is changed
        public void SendQueue()
        {
            var target = new TargetCommand {
                Id = 1, Email_destination = "*****@*****.**"
            };
            PostCommand command = new PostCommand()
            {
                Title   = "Payment Successfull",
                Message = "Your payment has been accepted",
                Type    = "email",
                From    = 1,
                Targets = new List <TargetCommand>()
                {
                    target
                }
            };

            var attributes = new Data <PostCommand>()
            {
                Attributes = command
            };

            var httpContent = new CommandDTO <PostCommand>()
            {
                Data = attributes
            };

            var mObj = JsonConvert.SerializeObject(httpContent);

            var factory = new ConnectionFactory()
            {
                HostName = "some-rabbit"
            };

            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    channel.ExchangeDeclare("directExchange", "direct");
                    channel.QueueDeclare("notification", true, false, false, null);
                    channel.QueueBind("notification", "directExchange", string.Empty);

                    var body = Encoding.UTF8.GetBytes(mObj);

                    channel.BasicPublish(
                        exchange: "directExchange",
                        routingKey: "",
                        basicProperties: null,
                        body: body
                        );
                    Console.WriteLine("Data has been forwarded");
                }
        }
예제 #19
0
        private CommandDTO GetCommandByName(string name)
        {
            if (_commands == null)
            {
                return(null);
            }

            CommandDTO retCommand = _commands.Find(delegate(CommandDTO dto) {
                return(dto.CommandName.Trim().ToLower() == name.Trim().ToLower());
            }
                                                   );

            return(retCommand);
        }
예제 #20
0
        private ScreenShot _takeScreenShot(CommandDTO cmdExec)
        {
            var returnValue = new ScreenShot();

            byte[] screenshotAsByteArray = null;
            if (cmdExec.ScreenShot.Take == true)
            {
                Screenshot ss = ((ITakesScreenshot)WebDriver).GetScreenshot();
                screenshotAsByteArray = ss.AsByteArray;
            }
            returnValue.Name = cmdExec.ScreenShot.Name;
            returnValue.Img  = screenshotAsByteArray;
            returnValue.Take = cmdExec.ScreenShot.Take;
            return(returnValue);
        }
예제 #21
0
        public void RemoveCommandByName(string name)
        {
            if (_commands == null)
            {
                return;
            }

            CommandDTO retCommand = _commands.Find(delegate(CommandDTO dto) {
                return(dto.CommandName.Trim().ToLower() == name.Trim().ToLower());
            }
                                                   );

            _commands.Remove(retCommand);
            SaveCommands();
        }
예제 #22
0
        public string Lookup(string cmd)
        {
            CommandDTO retCommand = _commands.Find(delegate(CommandDTO dto)
            {
                return(dto.CommandName.Trim().ToLower() == cmd.Trim().ToLower());
            });

            if (null != retCommand)
            {
                return(retCommand.CommandData);
            }
            else
            {
                return(string.Empty);
            }
        }
예제 #23
0
 // TODO: Brain exercise :) Without changing Process method signature, change
 // ProcessCommand to use pattern matching and as little ifs as possible
 // (or none at all, the best solution!)
 public bool ProcessCommand(CommandDTO command)
 {
     if (command is null)
     {
         throw new ArgumentNullException(nameof(command));
     }
     if (command.PlayerSide != _currentMovePlayer)
     {
         throw new InvalidMoveException("Invalid player side");
     }
     if (command.Index > MaxMoves || command.Index < 0)
     {
         throw new InvalidMoveException("Invalid game index");
     }
     return(Process(command.PlayerSide, (uint)command.Index, command.Move));
 }
예제 #24
0
        private CommandDTO _getErrorCmd(CommandDTO cmdExec, Exception ex)
        {
            var returnValue = cmdExec;

            if (cmdExec.OverrideErrorOnNotFound == true)
            {
                returnValue.CommandStatus = CommandResponseStatus.Success;
                returnValue.Message       = "Exception overridden";
                return(returnValue);
            }
            else
            {
                returnValue.CommandStatus = CommandResponseStatus.Failed;
                returnValue.Message       = ex.Message;
                return(cmdExec);
            }
        }
예제 #25
0
        public void UpdateCommand(CommandDTO cmd)
        {
            if (null != cmd)
            {
                _commands.Remove(cmd);
            }

            CommandDTO newCmd = new CommandDTO();

            newCmd.CommandAuthor      = cmd.CommandAuthor;
            newCmd.CommandCreatedDate = DateTime.Now;
            newCmd.CommandData        = cmd.CommandData;
            newCmd.CommandName        = cmd.CommandName;
            newCmd.CommandCount       = cmd.CommandCount;

            _commands.Add(newCmd);
            SaveCommands();
        }
예제 #26
0
        private CommandDTO _executeLoadURL(CommandDTO cmd, ref TestResponseDTO testResponseDTO)
        {
            var cmdExec = cmd;

            cmdExec.CommandStatus = CommandResponseStatus.Success;
            cmdExec.Message       = "Success";
            try
            {
                cmdExec.ScreenShot = _takeScreenShot(cmdExec);
                WebDriver.Navigate().GoToUrl(cmd.Value);
            }
            catch (Exception ex)
            {
                cmdExec = _getErrorCmd(cmdExec, ex);
            }

            testResponseDTO.CommandsExecuted.Add(cmdExec);
            return(cmdExec);
        }
예제 #27
0
        private CommandDTO _executeExecuteWaitSecond(CommandDTO cmd, ref TestResponseDTO testResponseDTO)
        {
            var cmdExec = cmd;

            cmdExec.CommandStatus = CommandResponseStatus.Success;
            cmdExec.Message       = "Success";
            try
            {
                //WebDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(Convert.ToInt32(cmd.Value));
                Thread.Sleep(new TimeSpan(0, 0, Convert.ToInt32(cmd.Value)));
                cmdExec.ScreenShot = _takeScreenShot(cmdExec);
            }
            catch (Exception ex)
            {
                cmdExec = _getErrorCmd(cmdExec, ex);
            }

            testResponseDTO.CommandsExecuted.Add(cmdExec);
            return(cmdExec);
        }
예제 #28
0
        private CommandDTO _executeExecuteJS(CommandDTO cmd, ref TestResponseDTO testResponseDTO)
        {
            var cmdExec = cmd;

            cmdExec.CommandStatus = CommandResponseStatus.Success;
            cmdExec.Message       = "Success";
            try
            {
                IJavaScriptExecutor js = (IJavaScriptExecutor)WebDriver;
                js.ExecuteScript(cmd.Value);
                cmdExec.ScreenShot = _takeScreenShot(cmdExec);
            }
            catch (Exception ex)
            {
                cmdExec = _getErrorCmd(cmdExec, ex);
            }

            testResponseDTO.CommandsExecuted.Add(cmdExec);
            return(cmdExec);
        }
예제 #29
0
        private CommandDTO _executeClickFromList(CommandDTO cmd, ref TestResponseDTO testResponseDTO)
        {
            var cmdExec = cmd;

            cmdExec.CommandStatus = CommandResponseStatus.Success;
            cmdExec.Message       = "Success";
            try
            {
                var elemList = _findElements(cmd);
                cmdExec.ScreenShot = _takeScreenShot(cmdExec);
                elemList[cmd.IndexToClick].Click();
            }
            catch (Exception ex)
            {
                cmdExec = _getErrorCmd(cmdExec, ex);
            }

            testResponseDTO.CommandsExecuted.Add(cmdExec);
            return(cmdExec);
        }
예제 #30
0
        public static CommandEN Convert(CommandDTO dto)
        {
            CommandEN newinstance = null;

            try
            {
                if (dto != null)
                {
                    newinstance = new CommandEN();



                    if (dto.DeviceTemplate_oid != -1)
                    {
                        MoSIoTGenNHibernate.CAD.MosIoT.IDeviceTemplateCAD deviceTemplateCAD = new MoSIoTGenNHibernate.CAD.MosIoT.DeviceTemplateCAD();

                        newinstance.DeviceTemplate = deviceTemplateCAD.ReadOIDDefault(dto.DeviceTemplate_oid);
                    }
                    newinstance.Id            = dto.Id;
                    newinstance.Name          = dto.Name;
                    newinstance.IsSynchronous = dto.IsSynchronous;
                    if (dto.Telemetries_oid != null)
                    {
                        MoSIoTGenNHibernate.CAD.MosIoT.IEventTelemetryCAD eventTelemetryCAD = new MoSIoTGenNHibernate.CAD.MosIoT.EventTelemetryCAD();

                        newinstance.Telemetries = new System.Collections.Generic.List <MoSIoTGenNHibernate.EN.MosIoT.EventTelemetryEN>();
                        foreach (int entry in dto.Telemetries_oid)
                        {
                            newinstance.Telemetries.Add(eventTelemetryCAD.ReadOIDDefault(entry));
                        }
                    }
                    newinstance.Type        = dto.Type;
                    newinstance.Description = dto.Description;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(newinstance);
        }
예제 #31
0
 public void ShowDTO(CommandDTO dto)
 {
 }