Example #1
0
        public void PersistBatchTest()
        {
            this.CreateUser();
            if (!this.CreateVehicle())
            {
                List <string> vehicles = new List <string>();
                vehicles.Add("TEST1234");

                BatchDTO expectedBatch = new BatchDTO();
                expectedBatch.Name            = "Lote 1";
                expectedBatch.CreatorUserName = "******";
                expectedBatch.Description     = "Primer lote de autos";
                expectedBatch.Vehicles        = vehicles;

                BatchDAO batchDAO = new BatchDAOImp();
                Guid     idBatch  = batchDAO.AddBatch(expectedBatch);

                BatchDTO resultBatch = batchDAO.FindBatchById(idBatch);

                Assert.AreEqual(idBatch, resultBatch.Id);
                Assert.AreEqual(expectedBatch.CreatorUserName, resultBatch.CreatorUserName);
                Assert.AreEqual(expectedBatch.Description, resultBatch.Description);
                Assert.AreEqual(expectedBatch.Name, resultBatch.Name);
                foreach (var vehicle in expectedBatch.Vehicles)
                {
                    Assert.IsNotNull(resultBatch.Vehicles.Find(v => v == vehicle));
                }
            }
        }
Example #2
0
        public void MapBatchToBatchDTOTest()
        {
            BatchMapper mapper = new BatchMapper();
            Batch       batch  = new Batch();

            batch.IdUser      = this.CreateUser();
            batch.Description = "Primer Lote";
            batch.Name        = "Lote1";
            batch.Vehicles    = new List <Vehicle>();

            Vehicle vehicle = new Vehicle();

            vehicle.Vin = "TEST1234";
            batch.Vehicles.Add(vehicle);

            BatchDTO batchDTO = mapper.ToDTO(batch);

            Assert.AreEqual(batch.Id, batchDTO.Id);
            Assert.AreEqual(batch.IdUser.UserName, batchDTO.CreatorUserName);
            Assert.AreEqual(batch.Description, batchDTO.Description);
            Assert.AreEqual(batch.Name, batchDTO.Name);
            foreach (Vehicle ve in batch.Vehicles)
            {
                Assert.IsTrue(batchDTO.Vehicles.Contains(ve.Vin));
            }
        }
Example #3
0
        private List <BatchDTO> CreateBatches()
        {
            List <BatchDTO> batches = new List <BatchDTO>();
            BatchDTO        batch   = new BatchDTO();

            batch.Description     = "Es el lote 1";
            batch.Description     = "pepito123";
            batch.Name            = "Lote1";
            batch.CreatorUserName = "******";
            List <VehicleDTO> vehiclesDTO = this.CreateVehicles();
            List <string>     vehicles    = new List <string>();

            foreach (VehicleDTO vehicle in vehiclesDTO)
            {
                vehicles.Add(vehicle.Vin);
            }
            batch.Vehicles = vehicles;

            BatchDAO batchDAO = new BatchDAOImp();

            batchDAO.AddBatch(batch);

            batches.Add(batch);

            return(batches);
        }
Example #4
0
        public void ErrorCreateBatchWhitoutVehiclesTest()
        {
            BatchDTO batch = new BatchDTO();

            batch.CreatorUserName = "******";
            batch.CreatorUserName = "******";
            batch.Name            = "Lote1";

            UserDTO userDTO = createUserDTO();
            Guid    token   = Guid.NewGuid();

            var mockBatchService = new Mock <BatchService>();

            mockBatchService.Setup(b => b.CreateBatch(batch)).Throws(new VehicleNotFoundException());
            var mockUserService = new Mock <UserService>();

            mockUserService.Setup(us => us.GetUserLoggedIn(token)).Returns(userDTO);

            BatchController batchController = new BatchController(mockBatchService.Object, mockUserService.Object);

            batchController.Request = createBatchControllerRequest();
            this.addTokenHeaderToRequest(batchController.Request, token);

            ResponseMessageResult response = (ResponseMessageResult)batchController.Post(batch);

            Assert.AreEqual(HttpStatusCode.BadRequest, response.Response.StatusCode);
        }
Example #5
0
        /// <summary>
        /// Get the Batches from PCO.
        /// </summary>
        /// <param name="modifiedSince">The modified since.</param>
        /// <returns></returns>
        public static List <BatchDTO> GetBatches(DateTime?modifiedSince)
        {
            var batches = new List <BatchDTO>();

            var apiOptions = new Dictionary <string, string>
            {
                { "include", "owner" },
                { "per_page", "100" }
            };

            var batchesQuery = GetAPIQuery(ApiEndpoint.API_BATCHES, apiOptions, modifiedSince);

            if (batchesQuery == null)
            {
                return(batches);
            }

            foreach (var item in batchesQuery.Items)
            {
                var batch = new BatchDTO(item);
                if (batch != null)
                {
                    batches.Add(batch);
                }
            }

            return(batches);
        }
Example #6
0
        public void ErrorCreatingBatchWithoutVehiclesTest()
        {
            Role    role = new Role(Roles.PORT_OPERATOR);
            UserDTO user = new UserDTO();

            user.Name     = "Carlos";
            user.LastName = "Perez";
            user.UserName = "******";
            user.Phone    = 091234567;
            user.Password = "******";
            user.Role     = Roles.PORT_OPERATOR.GetName();

            List <string> vehicles = new List <string>();

            BatchDTO batch = new BatchDTO();

            batch.Id              = Guid.NewGuid();
            batch.Name            = "Lote 1";
            batch.Description     = "Primer lote";
            batch.Vehicles        = vehicles;
            batch.CreatorUserName = user.UserName;

            var mockBatchDAO = new Mock <BatchDAO>();

            mockBatchDAO.Setup(vs => vs.FindBatchById(batch.Id)).Returns(batch);
            var mockUserDAO = new Mock <UserDAO>();

            mockUserDAO.Setup(vs => vs.FindUserByUserName(batch.CreatorUserName)).Returns(user);
            VehicleDAO vehicleDAO = new VehicleDAOImpl();

            var batchService = new BatchServiceImpl(mockBatchDAO.Object, mockUserDAO.Object, vehicleDAO);

            Guid batchId = batchService.CreateBatch(batch);
        }
Example #7
0
        public async Task AddAsyncTest_Added(BatchDTO batchDto, Batch batchEntity)
        {
            _mapperMock.Setup(m => m.Map <BatchDTO, Batch>(It.IsAny <BatchDTO>()))
            .Returns(batchEntity);
            _mapperMock.Setup(m => m.Map <Batch, BatchDTO>(It.IsAny <Batch>()))
            .Returns(batchDto);

            _repositoryMock.Setup(r => r.InsertAsync(It.IsAny <Batch>()))
            .Returns(Task.FromResult(batchEntity));

            _transactionMock.Setup(t => t.GetByDateWithCategoryAsync(It.IsAny <DateTime>(), It.IsAny <DateTime>()))
            .Returns(Task.FromResult(batchDto.Transactions.Take(2).ToList()));

            _categoryMock.Setup(c => c.GetByNameAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(new CategoryDTO {
            }));

            _repositoryMock.Setup(r => r.GetByIdAsync(It.IsAny <int>()))
            .Returns(Task.FromResult(batchEntity));

            _transactionMock.Setup(t => t.AddAsync(It.IsAny <TransactionDTO>()))
            .Returns(Task.FromResult(new TransactionDTO {
            }));

            var result = await _service.AddAsync(batchDto);

            Assert.Equal(24, result.Added);
        }
Example #8
0
        public async Task <IActionResult> PutBatch(long id, BatchDTO batchDTO)
        {
            if (id != batchDTO.Id)
            {
                return(BadRequest());
            }

            var batch = await _context.Batches.FindAsync(id);

            if (batch == null)
            {
                return(NotFound());
            }

            batch.DateUpdated = DateTime.Now;
            batch.Name        = batchDTO.Name;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException) when(!BatchExists(id))
            {
                return(NotFound());
            }

            return(NoContent());
        }
Example #9
0
        public async Task <ActionResult> MockCard(BatchDTO request)
        {
            var cardDTO = new CardDTO()
            {
                CardTypeId = request.CardTypeId,
                TPCode     = request.CardTPCode
            };
            var batch = await _loadAppService.PerformLoadAsync(request.Client, request.Client.MainContact, cardDTO, request);

            return(Ok(batch));
        }
Example #10
0
        public async Task GetByIdAsyncTest_ReturnsOk()
        {
            var batch = new BatchDTO();

            _serviceMock.Setup(s => s.GetByIdAsync(1))
            .Returns(Task.FromResult(batch));

            var result = await controller.GetByIdAsync(1);

            var assert = Assert.IsType <OkObjectResult>(result);
        }
Example #11
0
        public IHttpActionResult Get(string id)
        {
            HttpResponseMessage response = new HttpResponseMessage();

            Guid guidId;

            try
            {
                guidId = Guid.Parse(id);
            }
            catch (FormatException)
            {
                string message = "El id enviado no tiene un formato valido.";
                response = this.Request.CreateResponse(HttpStatusCode.BadRequest, message);
                return(ResponseMessage(response));
            }

            try
            {
                Guid              token             = this.GetToken();
                UserDTO           user              = this.userService.GetUserLoggedIn(token);
                PermissionHandler permissionHandler = new PermissionHandler();
                if (permissionHandler.IsUserAllowedToListBatches(user.Role))
                {
                    BatchDTO batch = this.batchService.FindBatchById(guidId);
                    response = this.Request.CreateResponse(HttpStatusCode.OK, batch);
                }
                else
                {
                    response = this.Request.CreateResponse(HttpStatusCode.Unauthorized, "El usuario no tiene permisos para ejecutar esta accion");
                }
            }
            catch (VehicleNotFoundException e)
            {
                response = this.Request.CreateResponse(HttpStatusCode.BadRequest, e.Message);
            }
            catch (UserNotExistException e)
            {
                response = this.Request.CreateResponse(HttpStatusCode.BadRequest, e.Message);
            }
            catch (InvalidOperationException)
            {
                string message = "No se ha enviado header de autenticación.";
                response = this.Request.CreateResponse(HttpStatusCode.BadRequest, message);
            }
            catch (FormatException)
            {
                string message = "El token enviado no tiene un formato valido.";
                response = this.Request.CreateResponse(HttpStatusCode.BadRequest, message);
            }

            return(ResponseMessage(response));
        }
Example #12
0
        private BatchDTO createBatchDTO()
        {
            BatchDTO batch = new BatchDTO();

            batch.Id = Guid.NewGuid();
            batch.CreatorUserName = "******";
            batch.CreatorUserName = "******";
            batch.Name            = "Lote1";
            batch.Vehicles        = new List <string>();
            batch.Vehicles.Add("Vehiculo1");
            batch.Vehicles.Add("Vehiculo2");
            return(batch);
        }
Example #13
0
        public static FinancialBatch Translate(BatchDTO batch)
        {
            var slingshotBatch = new FinancialBatch();

            slingshotBatch.Id        = batch.BatchId;
            slingshotBatch.StartDate = batch.BatchDate;
            slingshotBatch.Name      = batch.BatchName;

            //There's no status in the MDF, so just marked all imported batches as closed
            slingshotBatch.Status = BatchStatus.Closed;

            return(slingshotBatch);
        }
        /// <summary>
        /// Saves a new batch or updates an already existing Batch.
        /// </summary>
        /// <param name="Batch">Batch to be saved or updated.</param>
        /// <param name="BatchId">BatchId of the Batch creating or updating</param>
        /// <returns>BatchId</returns>
        public long SaveBatch(BatchDTO batchDTO, string userId)
        {
            long batchId = 0;

            if (batchDTO.BatchId == 0)
            {
                var batch = new Batch()
                {
                    Name     = batchDTO.Name,
                    SectorId = batchDTO.SectorId,
                    Quantity = batchDTO.Quantity,

                    BranchId = batchDTO.BranchId,

                    CreatedOn = DateTime.Now,
                    TimeStamp = DateTime.Now,
                    CreatedBy = userId,
                    Deleted   = false,
                };

                this.UnitOfWork.Get <Batch>().AddNew(batch);
                this.UnitOfWork.SaveChanges();
                batchId = batch.BatchId;


                return(batchId);
            }

            else
            {
                var result = this.UnitOfWork.Get <Batch>().AsQueryable()
                             .FirstOrDefault(e => e.BatchId == batchDTO.BatchId);
                if (result != null)
                {
                    result.Name     = batchDTO.Name;
                    result.Quantity = batchDTO.Quantity;
                    result.BranchId = batchDTO.BranchId;
                    result.SectorId = batchDTO.SectorId;

                    result.UpdatedBy = userId;
                    result.TimeStamp = DateTime.Now;
                    result.Deleted   = batchDTO.Deleted;
                    result.DeletedBy = batchDTO.DeletedBy;
                    result.DeletedOn = batchDTO.DeletedOn;

                    this.UnitOfWork.Get <Batch>().Update(result);
                    this.UnitOfWork.SaveChanges();
                }
                return(batchDTO.BatchId);
            }
        }
Example #15
0
        public async Task PostAsyncTest_ReturnsCreated()
        {
            var batch     = new BatchDTO();
            var postBatch = new PostBatch();

            _mapperMock.Setup(m => m.Map <PostBatch, BatchDTO>(postBatch))
            .Returns(batch);
            _serviceMock.Setup(s => s.AddAsync(batch))
            .Returns(Task.FromResult(batch));

            var result = await controller.PostAsync(postBatch);

            var assert = Assert.IsType <CreatedResult>(result);
        }
Example #16
0
        private bool BatchesAreReady(List <Guid> batchesId)
        {
            bool areReady = true;

            foreach (Guid id in batchesId)
            {
                BatchDTO batchDTO = this.batchService.FindBatchById(id);
                foreach (string vin in batchDTO.Vehicles)
                {
                    areReady = (this.inspectionService.ExistVehicleInspection(vin)) ? areReady : false;
                }
            }
            return(areReady);
        }
        public static FinancialBatch Translate(BatchDTO inputBatch)
        {
            var financialBatch = new FinancialBatch
            {
                Id                = inputBatch.Id,
                StartDate         = inputBatch.CreatedAt,
                Name              = inputBatch.Description,
                CreatedDateTime   = inputBatch.CreatedAt,
                ModifiedDateTime  = inputBatch.UpdatedAt,
                CreatedByPersonId = inputBatch.OwnerId,
                Status            = (inputBatch.CommittedAt.HasValue) ? BatchStatus.Closed : BatchStatus.Open
            };

            return(financialBatch);
        }
 public IActionResult Edit(BatchDTO model)
 {
     try
     {
         model.UpdatedBy = User.FindFirstValue(ClaimTypes.NameIdentifier);
         var oldQuantity = this._batch.UpdateQuantity(model);
         this._stock.UpdateStock(model, oldQuantity);
         TempData["Message"] = "Successfully updated the quantity of the batch with batched Id " + model.BatchId;
     }
     catch (Exception e)
     {
         TempData["Message"] = "An error occured while processing your request";
     }
     return(RedirectToAction("Index"));
 }
Example #19
0
        public void ErrorCreateBatchWithoutTokenTest()
        {
            BatchDTO batch = createBatchDTO();

            var mockBatchService = new Mock <BatchService>();

            mockBatchService.Setup(b => b.CreateBatch(batch)).Verifiable();

            BatchController batchController = new BatchController(mockBatchService.Object, null);

            batchController.Request = createBatchControllerRequest();

            ResponseMessageResult response = (ResponseMessageResult)batchController.Post(batch);

            Assert.AreEqual(HttpStatusCode.BadRequest, response.Response.StatusCode);
        }
Example #20
0
 public void AddBatch(BatchDTO model)
 {
     using (var unitOfWork = new UnitOfWork())
     {
         var repo = new Repository <TcBatch>(unitOfWork);
         repo.Add(new TcBatch()
         {
             CreatedBy      = model.CreatedBy,
             CreatedDateUtc = DateTime.UtcNow,
             FruitId        = model.FruitId,
             IsDelete       = false,
             Quantity       = model.Quantity,
             VarietyId      = model.VarietyId
         });
     }
 }
Example #21
0
        public void CreateBatchSuccessfullyAsAdministratorTest()
        {
            VehicleDAO vehicleDAO = new VehicleDAOImpl();

            List <Vehicle> vehicles = new List <Vehicle>();
            Vehicle        vehicle  = new Vehicle("Chevrolet", "Onyx", 2016, "Gris", "Auto", "TEST1234");

            vehicle.CurrentLocation = "Puerto";
            vehicles.Add(vehicle);

            if (!vehicleDAO.IsAssigned("TEST1234"))
            {
                Role    role = new Role(Roles.ADMINISTRATOR);
                UserDTO user = new UserDTO();
                user.Name     = "Carlos";
                user.LastName = "Perez";
                user.UserName = "******";
                user.Phone    = 091234567;
                user.Password = "******";
                user.Role     = Roles.PORT_OPERATOR.GetName();

                BatchDTO batch = new BatchDTO();
                batch.Id          = Guid.NewGuid();
                batch.Name        = "Lote 1";
                batch.Description = "Primer lote";
                batch.Vehicles    = new List <string>();
                batch.Vehicles.Add(vehicle.Vin);
                batch.CreatorUserName = user.UserName;

                var mockBatchDAO = new Mock <BatchDAO>();
                mockBatchDAO.Setup(vs => vs.FindBatchById(batch.Id)).Returns(batch);
                var mockUserDAO = new Mock <UserDAO>();
                mockUserDAO.Setup(vs => vs.FindUserByUserName(batch.CreatorUserName)).Returns(user);

                var batchService = new BatchServiceImpl(mockBatchDAO.Object, mockUserDAO.Object, vehicleDAO);

                Guid batchId = batchService.CreateBatch(batch);

                BatchDTO resultBatch = batchService.FindBatchById(batchId);

                Assert.AreEqual(batch.Id, resultBatch.Id);
                Assert.AreEqual(batch.Name, resultBatch.Name);
                Assert.AreEqual(batch.Description, resultBatch.Description);
                Assert.AreEqual(batch.CreatorUserName, resultBatch.CreatorUserName);
                Assert.AreEqual(batch.Vehicles, resultBatch.Vehicles);
            }
        }
 public void UpdateStock(BatchDTO model, int oldQuantity)
 {
     using (var unitOfWork = new UnitOfWork())
     {
         var repo         = new Repository <TcStock>(unitOfWork);
         var currentStock = repo.FirstOrDefault(x => x.FruitId == model.FruitId && x.VarietyId == model.VarietyId);
         if (currentStock == null)
         {
             // It's an exception, throw an error
             throw new Exception("Cann't find the stock");
         }
         currentStock.Quantity -= oldQuantity;
         currentStock.Quantity += model.Quantity;
         unitOfWork.SaveChanges();
         return;
     }
 }
Example #23
0
        public IHttpActionResult Post([FromBody] BatchDTO batch)
        {
            HttpResponseMessage response = new HttpResponseMessage();

            try
            {
                Guid    token = this.GetToken();
                UserDTO user  = this.userService.GetUserLoggedIn(token);
                batch.CreatorUserName = user.UserName;
                PermissionHandler permissionHandler = new PermissionHandler();
                if (permissionHandler.IsUserAllowedToCreateBatch(user.Role))
                {
                    this.batchService.CreateBatch(batch);
                    response = this.Request.CreateResponse(HttpStatusCode.OK);
                }
                else
                {
                    response = this.Request.CreateResponse(HttpStatusCode.Unauthorized, "El usuario no tiene permisos para ejecutar esta accion");
                }
            }
            catch (UserNotExistException e)
            {
                response = this.Request.CreateResponse(HttpStatusCode.BadRequest, e.Message);
            }
            catch (VehicleInOtherBatchException e)
            {
                response = this.Request.CreateResponse(HttpStatusCode.BadRequest, e.Message);
            }
            catch (InvalidOperationException)
            {
                string message = "No se ha enviado header de autenticación.";
                response = this.Request.CreateResponse(HttpStatusCode.BadRequest, message);
            }
            catch (FormatException)
            {
                string message = "El token enviado no tiene un formato valido.";
                response = this.Request.CreateResponse(HttpStatusCode.BadRequest, message);
            }
            catch (VehicleNotFoundException e)
            {
                response = this.Request.CreateResponse(HttpStatusCode.BadRequest, e.Message);
            }

            return(ResponseMessage(response));
        }
Example #24
0
        public List <BatchDTO> GetAllBatches()
        {
            List <BatchDTO> batches = new List <BatchDTO>();

            using (VehicleTrackingDbContext context = new VehicleTrackingDbContext())
            {
                List <Batch> batchesEntities = context.Batches
                                               .Include("Vehicles")
                                               .Include("IdUser")
                                               .ToList();
                foreach (Batch batch in context.Batches)
                {
                    BatchDTO batchDTO = this.batchMapper.ToDTO(batch);
                    batches.Add(batchDTO);
                }
            }
            return(batches);
        }
Example #25
0
 public int UpdateQuantity(BatchDTO model)
 {
     using (var unitOfWork = new UnitOfWork())
     {
         var repo  = new Repository <TcBatch>(unitOfWork);
         var batch = repo.FirstOrDefault(x => x.BatchId == model.BatchId && x.IsDelete == false);
         if (batch == null)
         {
             throw new NullReferenceException();
         }
         var oldQuantity = batch.Quantity;
         batch.Quantity       = model.Quantity;
         batch.UpdatedBy      = model.UpdatedBy;
         batch.UpdatedDateUtc = DateTime.UtcNow;
         unitOfWork.SaveChanges();
         return(oldQuantity);
     }
 }
Example #26
0
        public async Task <ActionResult <Batch> > PostBatch(BatchDTO batchDTO)
        {
            var batch = new Batch
            {
                DateCreated = DateTime.Now,
                DateUpdated = null,
                Name        = batchDTO.Name
            };

            _context.Batches.Add(batch);
            await _context.SaveChangesAsync();

            return(CreatedAtAction(
                       nameof(GetBatch),
                       new { id = batch.Id },
                       BatchToDTO(batch)
                       ));
        }
Example #27
0
        public Guid AddBatch(BatchDTO batchDTO)
        {
            Batch batch = this.batchMapper.ToEntity(batchDTO);

            using (VehicleTrackingDbContext context = new VehicleTrackingDbContext())
            {
                var queryUser = from u in context.Users
                                where u.UserName == batchDTO.CreatorUserName
                                select u;
                User user = queryUser.ToList().FirstOrDefault();
                context.Users.Attach(user);

                List <Vehicle> realVehicles = new List <Vehicle>();
                foreach (Vehicle vehicle in batch.Vehicles)
                {
                    var queryVehicle = from v in context.Vehicles
                                       where v.Vin == vehicle.Vin
                                       select v;
                    Vehicle realVehicle = queryVehicle.ToList().FirstOrDefault();

                    context.Vehicles.Attach(realVehicle);
                    realVehicles.Add(realVehicle);
                    if (realVehicle.Status == StatusCode.InspectedInPort)
                    {
                        realVehicle.Status = StatusCode.ReadyToGo;
                        var entry = context.Entry(realVehicle);
                        entry.Property(sz => sz.Status).IsModified = true;

                        HistoricVehicle historicVehicle = mapVehicleToHistoricVehicle(realVehicle);
                        context.HistoricVehicles.Add(historicVehicle);
                    }
                }
                batch.Vehicles = realVehicles;
                batch.IdUser   = user;

                if (batch.Vehicles.Count > 0)
                {
                    context.Batches.Add(batch);
                    context.SaveChanges();
                }
            }
            return(batch.Id);
        }
Example #28
0
        public BatchDTO FindBatchById(Guid id)
        {
            Batch    batch    = null;
            BatchDTO batchDTO = null;

            using (VehicleTrackingDbContext context = new VehicleTrackingDbContext())
            {
                batch = context.Batches
                        .Include("IdUser")
                        .Include("Vehicles")
                        .Where(b => b.Id == id)
                        .ToList().FirstOrDefault();
            }
            if (batch != null)
            {
                batchDTO = this.batchMapper.ToDTO(batch);
            }

            return(batchDTO);
        }
 public IActionResult Create(BatchDTO model)
 {
     try
     {
         if (ModelState.IsValid)
         {
             model.CreatedBy = User.FindFirstValue(ClaimTypes.NameIdentifier);
             this._batch.AddBatch(model);
             this._stock.AddStock(model);
             TempData["Message"] = "Created the batch successfully!";
             return(RedirectToAction("Index"));
         }
         return(View());
     }
     catch (Exception e)
     {
         TempData["Message"] = "An error occured while processing your request";
         return(RedirectToAction("Index"));
     }
 }
Example #30
0
        public void MapBatchDTOToBatchTest()
        {
            BatchMapper mapper = new BatchMapper();
            BatchDTO    batch  = new BatchDTO();

            batch.CreatorUserName = "******";
            batch.Description     = "Primer Lote";
            batch.Name            = "Lote1";
            batch.Vehicles        = new List <string>();
            batch.Vehicles.Add("TEST1234");
            batch.CreatorUserName = "******";

            Batch batchEntity = mapper.ToEntity(batch);

            Assert.AreEqual(batch.Id, batchEntity.Id);
            Assert.AreEqual(batch.CreatorUserName, batchEntity.IdUser.UserName);
            Assert.AreEqual(batch.Description, batchEntity.Description);
            Assert.AreEqual(batch.Name, batchEntity.Name);
            Vehicle vehicle = batchEntity.Vehicles.Find(v => v.Vin == "TEST1234");

            Assert.IsNotNull(vehicle);
        }
Example #31
0
        public CrawlerResultsDTO StartCrawlingProcess(IEnumerable<SeedDTO> seedsToCrawl, int maxCrawlLevel = 2)
        {
            var timetracker = new Stopwatch();

            timetracker.Start();

            var startTime = DateTime.Now;

            _maxPageLevel = maxCrawlLevel;
            _forceStop = false;
            foreach (var seed in seedsToCrawl)
            {
                var startingAddress = seed.SeedDomainName;

                _internalLinksIdCounter = 1;
                if (startingAddress == string.Empty)
                {
                    continue;
                }

                //if (_allLinks.Contains(startingAddress))
                //{
                //    AddInternalLink(startingAddress, startingAddress, 0, StartingPageName);
                //}

                FindLinks(startingAddress, 0, startingAddress);

                while (_internalUnprocessedLinks.Count > 0 & _forceStop != true)
                {
                    var selectedLink = _internalUnprocessedLinks.Pop();

                    selectedLink.IsProcessed = true;
                    FindLinks(selectedLink.PageLink, selectedLink.PageLevel, startingAddress);

                }

                //_allLinks.Clear();
            }
            if (_forceStop)
            {
                _forceStop = false;
            }

            timetracker.Stop();
            var runingTime = timetracker.Elapsed.Seconds;
            //MessageBox.Show(RuningTime);
            var batchInfo = new BatchDTO();
            batchInfo.CrawlingTime = runingTime;
            batchInfo.StartTime = startTime;
            batchInfo.NumberOfCrawledExternalLinks = _externalLinksDictionary.Count;
            batchInfo.NumberOfCrawledInternalLinks = _internalLinksIdCounter;
            batchInfo.SeedId = seedsToCrawl.FirstOrDefault().SeedIndex;

            var result = new CrawlerResultsDTO
            {
                BadLinksList = _badLinksList.ToList(),
                ExternalLinksList = _externalLinksDictionary.Select(pair => pair.Value).ToList(),
                InternalLinksList = _internalLinksDictionary.Select(pair => pair.Value).ToList(),
                BatchInfo= batchInfo,
                ProcessedSeed = seedsToCrawl.FirstOrDefault()
            };

            return result;
        }