Exemplo n.º 1
0
        public async Task HandleAsync_HappyPath_MessageIsAdded()
        {
            // Arrange
            var user = UserGenerator.GenerateUser();

            await using (var dbContext = new DatingAppDbContext(_options))
            {
                dbContext.Users.Add(user);
                await dbContext.SaveChangesAsync();
            }

            var userMock = new Mock <IAuthenticatedUser>();

            userMock.SetupGet(u => u.Id).Returns(1);

            _userRepositoryMock
            .Setup(r => r.Single(It.IsAny <Expression <Func <User, bool> > >(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(user);

            var command = new AddMessageCommand(user.Id, "text", userMock.Object);

            var fakeNow = Instant.FromDateTimeUtc(DateTime.UtcNow.AddDays(-1));

            _clockMock.Setup(c => c.GetCurrentInstant()).Returns(fakeNow);

            // Act
            var messageDto = await _requestHandler.Handle(command, default);

            // Assert
            Assert.NotNull(messageDto);
            Assert.Equal(command.Content, messageDto.Content);
            Assert.Equal(messageDto.SendDate, fakeNow);
        }
Exemplo n.º 2
0
        public void AddMessage(AddMessageCommand command)
        {
            command.Validate();

            if (AddNotifications(command))
            {
                return;
            }

            Ticket             ticket = _ticketRepository.GetById(command.TicketId);
            LedgerIdentityUser user   = _identityResolver.GetUser();

            if (NotifyNullTicket(ticket))
            {
                return;
            }

            //User authenticity threated inside AddMessage() method
            ticket.AddMessage(command.Body, user.Id);

            if (AddNotifications(ticket))
            {
                return;
            }

            _ticketRepository.Update(ticket);

            if (Commit())
            {
                PublishLocal(new AddedTicketMessageEvent(command.Body, ticket.Id, user.Id));
            }
        }
Exemplo n.º 3
0
        public async Task <ApiResponse> AddMessage([FromBody] AddMessageCommand command)
        {
            ApiResponse Response = null;
            var         userId   = User.FindFirst(ClaimTypes.NameIdentifier).Value;

            if (userId != null)
            {
                command.CreatedById = userId;
                command.IsDeleted   = false;
                command.CreatedDate = DateTime.UtcNow;
                Response            = await _mediator.Send(command);

                command = (AddMessageCommand)Response.ResponseData;
                if (Response.StatusCode == 200)
                {
                    ChatModel obj = new ChatModel()
                    {
                        ChatId                 = command.ChatId,
                        EntityId               = command.EntityId,
                        ChatSourceEntityId     = command.ChatSourceEntityId,
                        Message                = command.Message,
                        UserName               = command.UserName,
                        EntitySourceDocumentId = command.EntitySourceDocumentId
                    };
                    await _hubContext.Clients.All.BroadcastMessage(obj);
                }
            }
            return(Response);
        }
Exemplo n.º 4
0
        public IActionResult AddMessage(Guid id, [FromBody] AddMessageCommand command)
        {
            command.TicketId = id;

            _ticketApplicationService.AddMessage(command);

            return(CreateResponse());
        }
Exemplo n.º 5
0
        public Task SaveMessageAsync(DiscordRequest request, Contexts contexts)
        {
            Log.Information("Started saving the message");
            var command = new AddMessageCommand(request.OriginalMessage,
                                                contexts.User.Id, contexts.User.Name,
                                                contexts.Channel.Id, contexts.Channel.Name,
                                                contexts.Server.Id, contexts.Server.Name,
                                                request.SentAt);

            Log.Information("Command created");
            return(this._commandBus.ExecuteAsync(command).ContinueWith(x => Log.Information("Message saved")));
        }
        public void Should_HaveValidationError_When_DateIsEmpty(DateTime when)
        {
            // arrange
            var command = new AddMessageCommand("userName", "body", when);

            // act
            var result = _validator.TestValidate(command);

            // assert
            result.ShouldHaveValidationErrorFor(x => x.When)
            .WithErrorCode(((int)ValidationErrorCode.MessageWhenEmpty).ToString())
            .WithErrorMessage("The message When date is required");
        }
        public void Should_HaveValidationError_When_BodyIsEmpty(string body)
        {
            // arrange
            var command = new AddMessageCommand("userName", body, DateTime.Now);

            // act
            var result = _validator.TestValidate(command);

            // assert
            result.ShouldHaveValidationErrorFor(x => x.Body)
            .WithErrorCode(((int)ValidationErrorCode.MessageBodyEmpty).ToString())
            .WithErrorMessage("The message Body is required");
        }
        public void ShouldAddMessage()
        {
            AddMessageCommand command = new AddMessageCommand
            {
                TicketId = new Guid("36f90131-8ab3-4764-a56c-2ee78284562f"),
                Body     = "Olá!"
            };

            applicationService.AddMessage(command);

            Ticket ticket = applicationService.GetById(new Guid("36f90131-8ab3-4764-a56c-2ee78284562f"));

            Assert.AreEqual(1, ticket.GetMessages().Count);
        }
Exemplo n.º 9
0
        public async Task SaveMessageAsync(DiscordRequest request, Contexts contexts)
        {
            //TODO maybe there should be builder... but it doesn't looks very bad
            Log.Information("Started saving the message");
            var command = new AddMessageCommand(request.OriginalMessage,
                                                contexts.User.Id, contexts.User.Name,
                                                contexts.Channel.Id, contexts.Channel.Name,
                                                contexts.Server.Id, contexts.Server.Name,
                                                contexts.Server.Owner.Id, contexts.Server.Owner.Name,
                                                request.SentAt);

            Log.Information("Command created");
            await this._commandBus.ExecuteAsync(command);

            Log.Information("Message saved");
        }
Exemplo n.º 10
0
        public void ShouldFailToAddMessageAndAddNotification()
        {
            identityResolver.RefreshId();

            AddMessageCommand command = new AddMessageCommand
            {
                TicketId = new Guid("36f90131-8ab3-4764-a56c-2ee78284562f"),
                Body     = "Olá!"
            };

            applicationService.AddMessage(command);

            Ticket ticket = applicationService.GetById(new Guid("36f90131-8ab3-4764-a56c-2ee78284562f"));

            Assert.AreEqual("Não possui acesso às mensagens", domainNotificationHandler.GetNotifications().First().Title);
        }
        public async Task AddMessageAsync(string body, string userName, DateTime when)
        {
            if (IsCommandMessage(body))
            {
                var stockName = body.Split("=")[1];
                _rabbitMqService.PushMessageToWorker(stockName);
                return;
            }

            var command = new AddMessageCommand
            {
                Body     = body,
                UserName = userName,
                When     = when
            };

            await _mediator.Send(command);
        }
Exemplo n.º 12
0
        public async Task <IActionResult> Execute(JObject obj, string subject, string commonId)
        {
            if (obj == null)
            {
                throw new ArgumentNullException(nameof(obj));
            }

            if (string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentNullException(nameof(subject));
            }

            // 1. Check the request
            AddMessageCommand command = null;

            try
            {
                command = _requestBuilder.GetAddMessage(obj);
            }
            catch (ArgumentException ex)
            {
                var error = _responseBuilder.GetError(ErrorCodes.Request, ex.Message);
                return(_controllerHelper.BuildResponse(HttpStatusCode.BadRequest, error));
            }

            command.From = subject;
            var validationResult = await _addMessageValidator.Validate(command);

            if (!validationResult.IsValid)
            {
                var error = _responseBuilder.GetError(ErrorCodes.Request, validationResult.Message);
                return(_controllerHelper.BuildResponse(HttpStatusCode.BadRequest, error));
            }

            command.Id             = Guid.NewGuid().ToString();
            command.CreateDateTime = DateTime.UtcNow;
            command.CommonId       = commonId;

            // 2. Send the command.
            var res = new { id = command.Id };

            _commandSender.Send(command);
            return(new OkObjectResult(res));
        }
Exemplo n.º 13
0
        public void SaveMessage(int userDestinationId, int userSenderId, string message)
        {
            var command = new AddMessageCommand(_scopeFactory);

            command.Execute(userDestinationId, userSenderId, message);
        }
Exemplo n.º 14
0
        public async Task <AddMessageValidationResult> Validate(AddMessageCommand command)
        {
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            if (command.From == command.To)
            {
                return(new AddMessageValidationResult(ErrorDescriptions.TheMessageCannotBeSentToYourself));
            }

            if (string.IsNullOrWhiteSpace(command.ServiceId) && string.IsNullOrWhiteSpace(command.ProductId) &&
                string.IsNullOrWhiteSpace(command.To) && string.IsNullOrWhiteSpace(command.ClientServiceId))    // Check mandatories parameters.
            {
                return(new AddMessageValidationResult(string.Format(ErrorDescriptions.TheParametersAreMandatories,
                                                                    Constants.DtoNames.UserMessage.ServiceId + "," + Constants.DtoNames.UserMessage.ProductId + "," + Constants.DtoNames.UserMessage.To + "," + Constants.DtoNames.UserMessage.ClientServiceId)));
            }

            if (string.IsNullOrWhiteSpace(command.Content))
            {
                return(new AddMessageValidationResult(string.Format(ErrorDescriptions.TheParameterIsMandatory, Constants.DtoNames.UserMessage.Content)));
            }

            if (command.Content.Length > 255)
            {
                return(new AddMessageValidationResult(string.Format(ErrorDescriptions.TheParameterLengthCannotExceedNbCharacters, Constants.DtoNames.UserMessage.Content, "255")));
            }

            if ((!string.IsNullOrWhiteSpace(command.ProductId) && !string.IsNullOrWhiteSpace(command.ServiceId)) ||
                (!string.IsNullOrWhiteSpace(command.ProductId) && !string.IsNullOrWhiteSpace(command.ClientServiceId)) ||
                (!string.IsNullOrWhiteSpace(command.ServiceId) && !string.IsNullOrWhiteSpace(command.ClientServiceId))) // Check parameters are not specified at same time.
            {
                return(new AddMessageValidationResult(ErrorDescriptions.TheProductAndServiceCannotBeSpecifiedAtSameTime));
            }

            if (!string.IsNullOrWhiteSpace(command.ServiceId))
            {
                var service = await _serviceRepository.Get(command.ServiceId);

                if (service == null)
                {
                    return(new AddMessageValidationResult(ErrorDescriptions.TheServiceDoesntExist));
                }
            }

            if (!string.IsNullOrWhiteSpace(command.ProductId))
            {
                var product = await _productRepository.Get(command.ProductId);

                if (product == null)
                {
                    return(new AddMessageValidationResult(ErrorDescriptions.TheProductDoesntExist));
                }
            }

            if (!string.IsNullOrWhiteSpace(command.ClientServiceId))
            {
                var clientService = await _clientServiceRepository.Get(command.ClientServiceId);

                if (clientService == null)
                {
                    return(new AddMessageValidationResult(ErrorDescriptions.TheClientServiceDoesntExist));
                }
            }

            if (string.IsNullOrWhiteSpace(command.ParentId)) // Check messageSubject contains a correct subject.
            {
                if (string.IsNullOrWhiteSpace(command.Subject))
                {
                    return(new AddMessageValidationResult(string.Format(ErrorDescriptions.TheParameterIsMandatory, Constants.DtoNames.UserMessage.Subject)));
                }

                if (command.Subject.Length > 100)
                {
                    return(new AddMessageValidationResult(string.Format(ErrorDescriptions.TheParameterLengthCannotExceedNbCharacters, Constants.DtoNames.UserMessage.Subject, "100")));
                }
            }
            else
            {
                var parent = await _messageRepository.Get(command.ParentId);

                if (parent == null)
                {
                    return(new AddMessageValidationResult(ErrorDescriptions.TheParentMessageDoesntExist));
                }
            }

            return(new AddMessageValidationResult());
        }
Exemplo n.º 15
0
        /// <summary>
        /// Read .tgpa files outside TGPA Game class
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static Map BuildMapFromTGPAFile(String file, Vector2 screenResolution)
        {
            Map map = new Map();

            StreamReader reader = new StreamReader(file);

            String line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//")) line = reader.ReadLine();

            //Check version
            try
            {
                if (Convert.ToDouble((line.Split(' '))[1]) > Convert.ToDouble(TheGreatPaperGame.version))
                {
                    reader.Close();
                    throw new Exception("Insupported game version.");
                }
            }
            catch (FormatException) { throw new Exception("Invalid game version : " + line); }

            map.GameVersion = line.Split(' ')[1];

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//")) line = reader.ReadLine();

            //Map informations
            #region Map Infos

            try
            {
                map.Level = Convert.ToInt32((line.Split(' '))[1]);
            }
            catch (FormatException) { reader.Close(); throw new Exception("Invalid map level number : " + line); }

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//")) line = reader.ReadLine();

            map.Name = line.Replace("name ", "");

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//")) line = reader.ReadLine();

            String filedesc = line.Replace("desc ", "");
            String s = null;
            try
            {
                s = Localization.GetString(filedesc);
            }
            catch (Exception) { /* Map Editor */}
            map.Description = s == null ? filedesc : s;

            #endregion

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//")) line = reader.ReadLine();

            //Backgrounds
            #region Backgrounds

            for (int i = 1; i < 4; i++)
            {
                ScrollingBackground bg = null;

                if (i == 1)
                    bg = map.Background1;
                else if (i == 2)
                    bg = map.Background2;
                else if (i == 3)
                    bg = map.Background3;

                string[] tokens = line.Split(' ');

                ScrollingBackground.ScrollDirection direction = ScrollingBackground.ScrollDirection.Left;
                if (tokens[1].Equals(ScrollingBackground.ScrollDirection.Up.ToString()))
                {
                    direction = ScrollingBackground.ScrollDirection.Up;
                }
                else if (tokens[1].Equals(ScrollingBackground.ScrollDirection.Down.ToString()))
                {
                    direction = ScrollingBackground.ScrollDirection.Down;
                }
                else if (tokens[1].Equals(ScrollingBackground.ScrollDirection.Right.ToString()))
                {
                    direction = ScrollingBackground.ScrollDirection.Right;
                }
                else if (tokens[1].Equals(ScrollingBackground.ScrollDirection.Left.ToString()))
                {
                    direction = ScrollingBackground.ScrollDirection.Left;
                }
                else
                {
                    reader.Close();
                    throw new Exception("Invalid scrolling direction : " + line);
                }

                bool inf = false;
                try
                {
                    inf = Convert.ToBoolean(tokens[4]);
                }
                catch (FormatException) { reader.Close(); throw new Exception("Invalid boolean for Infinite scroll : " + line); }

                Vector2 speed = Vector2.Zero;
                try
                {
                    speed = new Vector2(Convert.ToInt32(tokens[2]), Convert.ToInt32(tokens[3]));
                }
                catch (FormatException) { reader.Close();  throw new Exception("Invalid Vector for scroll speed : " + line); }

                bg = new ScrollingBackground(direction, speed, inf);

                //Parts
                while ((line = reader.ReadLine()).Split(' ')[0].Equals("bgpart"))
                {
                    bg.AddBackground(line.Split(' ')[1]);
                }

                if (bg.BackgroundSprites.Count == 0) { reader.Close(); throw new Exception("No BGPart found for Background "+i); }

                if (i == 1)
                    map.Background1 = bg;
                else if (i == 2)
                    map.Background2 = bg;
                else if (i == 3)
                    map.Background3 = bg;

                line = reader.ReadLine();
                while (line.Equals("") || line.StartsWith("//")) line = reader.ReadLine();

            }

            #endregion

            //Initialization
            #region Init

            if (!line.Split(' ')[0].Equals("init"))
            {
                reader.Close();
                throw new Exception("Invalid TGPA map : init section not found");
            }

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//")) line = reader.ReadLine();

            //level music
            string[] tokens2 = line.Split('\"');
            if (tokens2.Length < 4)
            {
                Console.WriteLine("No music loaded");
            }
            else
            {
                map.Music = new MySong(tokens2[0].Split(' ')[1], tokens2[1], tokens2[3]);
            }
            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//")) line = reader.ReadLine();

            //Initial datas
            try
            {
                map.InitialScore = Convert.ToInt32(line.Split(' ')[1]);
            }
            catch (FormatException) { reader.Close(); throw new Exception("Invalid integer for score : " + line); }

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//")) line = reader.ReadLine();

            try
            {
                map.InitialLivesCount = Convert.ToInt32(line.Split(' ')[1]);
            }
            catch (FormatException) { reader.Close(); throw new Exception("Invalid integer for lives : " + line); }

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//")) line = reader.ReadLine();

            string weaponName = line.Split(' ')[1];
            map.InitialWeapon = Weapon.TypeToWeapon(weaponName);

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//")) line = reader.ReadLine();

            //End conditions
            Event endmap = new Event(Vector2.Zero, null);
            String winflag = line.Split(' ')[1];
            line = reader.ReadLine();
            String loseflag = line.Split(' ')[1];
            endmap.AddCommand(new EndLevelCommand(winflag, loseflag));

            map.Events.Add(endmap);

            #endregion

            //Script
            #region Script event

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//")) line = reader.ReadLine();

            if (!line.Split(' ')[0].Equals("begin"))
            {
                reader.Close();
                throw new Exception("Invalid TGPA map : begin keyword not found");
            }

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//")) line = reader.ReadLine();

            //Read all events
            while (!line.Split(' ')[0].Equals("end"))
            {
                tokens2 = line.Split(' ');

                if (!tokens2[0].Equals("event"))
                {
                    reader.Close();
                    throw new Exception("Invalid TGPA map : event section missing (line : "+line+")");
                }

                Vector2 vector = Vector2.Zero;
                try
                {
                    vector = new Vector2((float)Convert.ToDouble(tokens2[2]), (float)Convert.ToDouble(tokens2[3]));
                }
                catch (FormatException) { reader.Close(); throw new Exception("Invalid Vector for event scroll value : " + line); }

                line = reader.ReadLine();
                tokens2 = line.Split(' ');
                if (!tokens2[0].Equals("start"))
                {
                    reader.Close();
                    throw new Exception("Invalid TGPA map : start keyword missing");
                }

                String startFlag = null;
                IfCommand ifc = null;

                try
                {
                    startFlag = line.Split(' ')[1];
                    if (!startFlag.Equals("")) ifc = new IfCommand(startFlag);
                }
                catch (IndexOutOfRangeException) { }

                Event e = new Event(vector, ifc);

                line = reader.ReadLine();
                while (line.Equals("") || line.StartsWith("//")) line = reader.ReadLine();

                List<Command> commands = new List<Command>();

                //Add actions
                while (!line.Split(' ')[0].Equals("endevent"))
                {
                    Command c = null;

                    switch (line.Split(' ')[0])
                    {
                        case "addenemy":
                            c = new AddEnemyCommand(line, screenResolution);

                            AddEnemyRessourcesToLoadIfNecessary(map, (AddEnemyCommand)c);

                            break;

                        case "addbge":
                            c = new AddBackgroundElementCommand(line, screenResolution);
                            AddBGERessourcesToLoadIfNecessary(map, (AddBackgroundElementCommand)c);
                            break;

                        case "message":
                            c = new AddMessageCommand(line);
                            break;

                        case "if":
                            c = new IfCommand(line);
                            break;

                        case "whilenot":
                            c = new WhileNotCommand(line);

                            line = reader.ReadLine();
                            while (line.Equals("") || line.StartsWith("//")) line = reader.ReadLine();

                            List<String> lines = new List<String>();
                            while (!line.Split(' ')[0].Equals("done"))
                            {
                                if (line.Split(' ')[0].Equals("addenemy"))
                                {
                                    AddEnemyRessourcesToLoadIfNecessary(map, new AddEnemyCommand(line, screenResolution));
                                }
                                lines.Add(line);

                                line = reader.ReadLine();
                                while (line.Equals("") || line.StartsWith("//")) line = reader.ReadLine();
                            }

                            ((WhileNotCommand)c).AddCommands(lines);

                            break;

                        case "scrollspeedreset":
                            c = new ResetScrollingSpeedCommand(line);
                            break;

                        case "scrollspeed":
                            c = new NewScrollingSpeedCommand(line);
                            break;

                        case "changemusic":
                            c = new ChangeMusicCommand(line);

                            map.MusicRessourcesToLoad.Add(((ChangeMusicCommand)c).Song);

                            break;

                        case "autogen":
                            c = new EnemyAutoGenerationCommand(line);
                            break;

                        case "addrandombonus":
                            c = new AddRandomBonusCommand(line);
                            break;

                        case "changemusicstate":
                            c = new ChangeMusicStateCommand(line);
                            break;

                        default:
                            throw new Exception("Unknown TGPA script command " + line);
                    }

                    commands.Add(c);

                    line = reader.ReadLine();
                    while (line.Equals("") || line.StartsWith("//")) line = reader.ReadLine();
                } //commands

                e.AddCommands(commands);

                map.Events.Add(e);

                line = reader.ReadLine();
                while (line.Equals("") || line.StartsWith("//")) line = reader.ReadLine();

            } //events

            #endregion

            reader.Close();

            return map;
        }
Exemplo n.º 16
0
        public async Task <Result> Push(AddMessageCommand cmd)
        {
            var result = await _mediator.Send(cmd, HttpContext.RequestAborted);

            return(result);
        }
Exemplo n.º 17
0
 public async Task <HandleResultDto> AddMessage([FromBody] AddMessageCommand cmd)
 {
     return(await _mediator.Send(cmd, HttpContext.RequestAborted));
 }
        /// <summary>
        /// Read .tgpa files outside TGPA Game class
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static Map BuildMapFromTGPAFile(String file, Vector2 screenResolution)
        {
            Map map = new Map();

            StreamReader reader = new StreamReader(file);

            String line = reader.ReadLine();

            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            //Check version
            try
            {
                if (Convert.ToDouble((line.Split(' '))[1]) > Convert.ToDouble(TheGreatPaperGame.version))
                {
                    reader.Close();
                    throw new Exception("Insupported game version.");
                }
            }
            catch (FormatException) { throw new Exception("Invalid game version : " + line); }

            map.GameVersion = line.Split(' ')[1];

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            //Map informations
            #region Map Infos

            try
            {
                map.Level = Convert.ToInt32((line.Split(' '))[1]);
            }
            catch (FormatException) { reader.Close(); throw new Exception("Invalid map level number : " + line); }

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            map.Name = line.Replace("name ", "");

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            String filedesc = line.Replace("desc ", "");
            String s        = null;
            try
            {
                s = Localization.GetString(filedesc);
            }
            catch (Exception) { /* Map Editor */ }
            map.Description = s == null ? filedesc : s;

            #endregion

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            //Backgrounds
            #region Backgrounds

            for (int i = 1; i < 4; i++)
            {
                ScrollingBackground bg = null;

                if (i == 1)
                {
                    bg = map.Background1;
                }
                else if (i == 2)
                {
                    bg = map.Background2;
                }
                else if (i == 3)
                {
                    bg = map.Background3;
                }


                string[] tokens = line.Split(' ');

                ScrollingBackground.ScrollDirection direction = ScrollingBackground.ScrollDirection.Left;
                if (tokens[1].Equals(ScrollingBackground.ScrollDirection.Up.ToString()))
                {
                    direction = ScrollingBackground.ScrollDirection.Up;
                }
                else if (tokens[1].Equals(ScrollingBackground.ScrollDirection.Down.ToString()))
                {
                    direction = ScrollingBackground.ScrollDirection.Down;
                }
                else if (tokens[1].Equals(ScrollingBackground.ScrollDirection.Right.ToString()))
                {
                    direction = ScrollingBackground.ScrollDirection.Right;
                }
                else if (tokens[1].Equals(ScrollingBackground.ScrollDirection.Left.ToString()))
                {
                    direction = ScrollingBackground.ScrollDirection.Left;
                }
                else
                {
                    reader.Close();
                    throw new Exception("Invalid scrolling direction : " + line);
                }

                bool inf = false;
                try
                {
                    inf = Convert.ToBoolean(tokens[4]);
                }
                catch (FormatException) { reader.Close(); throw new Exception("Invalid boolean for Infinite scroll : " + line); }

                Vector2 speed = Vector2.Zero;
                try
                {
                    speed = new Vector2(Convert.ToInt32(tokens[2]), Convert.ToInt32(tokens[3]));
                }
                catch (FormatException) { reader.Close();  throw new Exception("Invalid Vector for scroll speed : " + line); }

                bg = new ScrollingBackground(direction, speed, inf);

                //Parts
                while ((line = reader.ReadLine()).Split(' ')[0].Equals("bgpart"))
                {
                    bg.AddBackground(line.Split(' ')[1]);
                }

                if (bg.BackgroundSprites.Count == 0)
                {
                    reader.Close(); throw new Exception("No BGPart found for Background " + i);
                }

                if (i == 1)
                {
                    map.Background1 = bg;
                }
                else if (i == 2)
                {
                    map.Background2 = bg;
                }
                else if (i == 3)
                {
                    map.Background3 = bg;
                }

                line = reader.ReadLine();
                while (line.Equals("") || line.StartsWith("//"))
                {
                    line = reader.ReadLine();
                }
            }

            #endregion

            //Initialization
            #region Init

            if (!line.Split(' ')[0].Equals("init"))
            {
                reader.Close();
                throw new Exception("Invalid TGPA map : init section not found");
            }

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            //level music
            string[] tokens2 = line.Split('\"');
            if (tokens2.Length < 4)
            {
                Console.WriteLine("No music loaded");
            }
            else
            {
                map.Music = new MySong(tokens2[0].Split(' ')[1], tokens2[1], tokens2[3]);
            }
            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            //Initial datas
            try
            {
                map.InitialScore = Convert.ToInt32(line.Split(' ')[1]);
            }
            catch (FormatException) { reader.Close(); throw new Exception("Invalid integer for score : " + line); }

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            try
            {
                map.InitialLivesCount = Convert.ToInt32(line.Split(' ')[1]);
            }
            catch (FormatException) { reader.Close(); throw new Exception("Invalid integer for lives : " + line); }

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            string weaponName = line.Split(' ')[1];
            map.InitialWeapon = Weapon.TypeToWeapon(weaponName);

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            //End conditions
            Event  endmap  = new Event(Vector2.Zero, null);
            String winflag = line.Split(' ')[1];
            line = reader.ReadLine();
            String loseflag = line.Split(' ')[1];
            endmap.AddCommand(new EndLevelCommand(winflag, loseflag));

            map.Events.Add(endmap);

            #endregion

            //Script
            #region Script event

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            if (!line.Split(' ')[0].Equals("begin"))
            {
                reader.Close();
                throw new Exception("Invalid TGPA map : begin keyword not found");
            }

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            //Read all events
            while (!line.Split(' ')[0].Equals("end"))
            {
                tokens2 = line.Split(' ');

                if (!tokens2[0].Equals("event"))
                {
                    reader.Close();
                    throw new Exception("Invalid TGPA map : event section missing (line : " + line + ")");
                }

                Vector2 vector = Vector2.Zero;
                try
                {
                    vector = new Vector2((float)Convert.ToDouble(tokens2[2]), (float)Convert.ToDouble(tokens2[3]));
                }
                catch (FormatException) { reader.Close(); throw new Exception("Invalid Vector for event scroll value : " + line); }

                line    = reader.ReadLine();
                tokens2 = line.Split(' ');
                if (!tokens2[0].Equals("start"))
                {
                    reader.Close();
                    throw new Exception("Invalid TGPA map : start keyword missing");
                }

                String    startFlag = null;
                IfCommand ifc       = null;

                try
                {
                    startFlag = line.Split(' ')[1];
                    if (!startFlag.Equals(""))
                    {
                        ifc = new IfCommand(startFlag);
                    }
                }
                catch (IndexOutOfRangeException) { }

                Event e = new Event(vector, ifc);

                line = reader.ReadLine();
                while (line.Equals("") || line.StartsWith("//"))
                {
                    line = reader.ReadLine();
                }

                List <Command> commands = new List <Command>();

                //Add actions
                while (!line.Split(' ')[0].Equals("endevent"))
                {
                    Command c = null;

                    switch (line.Split(' ')[0])
                    {
                    case "addenemy":
                        c = new AddEnemyCommand(line, screenResolution);

                        AddEnemyRessourcesToLoadIfNecessary(map, (AddEnemyCommand)c);

                        break;

                    case "addbge":
                        c = new AddBackgroundElementCommand(line, screenResolution);
                        AddBGERessourcesToLoadIfNecessary(map, (AddBackgroundElementCommand)c);
                        break;

                    case "message":
                        c = new AddMessageCommand(line);
                        break;

                    case "if":
                        c = new IfCommand(line);
                        break;

                    case "whilenot":
                        c = new WhileNotCommand(line);

                        line = reader.ReadLine();
                        while (line.Equals("") || line.StartsWith("//"))
                        {
                            line = reader.ReadLine();
                        }

                        List <String> lines = new List <String>();
                        while (!line.Split(' ')[0].Equals("done"))
                        {
                            if (line.Split(' ')[0].Equals("addenemy"))
                            {
                                AddEnemyRessourcesToLoadIfNecessary(map, new AddEnemyCommand(line, screenResolution));
                            }
                            lines.Add(line);

                            line = reader.ReadLine();
                            while (line.Equals("") || line.StartsWith("//"))
                            {
                                line = reader.ReadLine();
                            }
                        }

                        ((WhileNotCommand)c).AddCommands(lines);

                        break;

                    case "scrollspeedreset":
                        c = new ResetScrollingSpeedCommand(line);
                        break;

                    case "scrollspeed":
                        c = new NewScrollingSpeedCommand(line);
                        break;

                    case "changemusic":
                        c = new ChangeMusicCommand(line);

                        map.MusicRessourcesToLoad.Add(((ChangeMusicCommand)c).Song);

                        break;

                    case "autogen":
                        c = new EnemyAutoGenerationCommand(line);
                        break;

                    case "addrandombonus":
                        c = new AddRandomBonusCommand(line);
                        break;

                    case "changemusicstate":
                        c = new ChangeMusicStateCommand(line);
                        break;

                    default:
                        throw new Exception("Unknown TGPA script command " + line);
                    }

                    commands.Add(c);

                    line = reader.ReadLine();
                    while (line.Equals("") || line.StartsWith("//"))
                    {
                        line = reader.ReadLine();
                    }
                } //commands

                e.AddCommands(commands);

                map.Events.Add(e);

                line = reader.ReadLine();
                while (line.Equals("") || line.StartsWith("//"))
                {
                    line = reader.ReadLine();
                }
            } //events

            #endregion

            reader.Close();

            return(map);
        }