public void RevokeBidFromAuction(Guid bidId)
        {
            var bidExists = _applicationDbContext.Bids.SingleOrDefault(p => p.Id == bidId);

            if (bidExists == null)
            {
                throw new Exception("Такой ставки не существует!");
            }

            var revokeBidStatus = _applicationDbContext.BidStatuses.SingleOrDefault(p => p.StatusName == "Revoke");

            if (revokeBidStatus == null)
            {
                BidStatus status = new BidStatus()
                {
                    Id         = Guid.NewGuid(),
                    StatusName = "Revoke"
                };
                _applicationDbContext.BidStatuses.Add(status);
                _applicationDbContext.SaveChanges();
                revokeBidStatus = status;
            }

            var auctionFinishDate = _applicationDbContext.Auctions.SingleOrDefault(p => p.Id == bidExists.AuctionId);

            if ((auctionFinishDate.FinishDate - DateTime.Now).Days < 1)
            {
                throw new Exception("Ставку нельзя удалить! До завершение аукциона осталось меньше 24 часов.");
            }

            bidExists.BidStatusId = revokeBidStatus.Id;
            _applicationDbContext.SaveChanges();
        }
Example #2
0
        /// <summary>
        /// Получает тревоги в соответствии с заданным статусом.
        /// </summary>
        /// <param name="status">Статус получаемых тревог.</param>
        /// <returns>Тревоги.</returns>
        public async Task <IEnumerable <Bid> > GetBidsAsync(BidStatus status)
        {
            HttpResponseMessage response;

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse($"{Token.TokenType} {Token.Token}");
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                response = await client.GetAsync(BidApiUri + $"?status={status.ToString()}");
            }

            var jsonString = await response.Content.ReadAsStringAsync();

            Debug.WriteLine(jsonString);

            if (response.IsSuccessStatusCode)
            {
                if (jsonString != null)
                {
                    var jsonData = JsonConvert.DeserializeObject <JsonDataResponse <List <Bid> > >(jsonString);

                    foreach (var bid in jsonData.Data)
                    {
                        bid.Client.ImageSource = "http://lk.asb-security.ru/" + bid.Client.ImageSource;
                    }

                    return(await Task.FromResult(jsonData.Data));
                }
            }

            return(await Task.FromResult(new List <Bid>()));
        }
Example #3
0
        public async Task <IActionResult> Create([Bind("ID,Name")] BidStatus bidStatus)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _context.Add(bidStatus);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction("Index", new { bidStatus.ID }));
                }
            }
            catch (DbUpdateException dex)
            {
                if (dex.GetBaseException().Message.Contains("UNIQUE constraint failed: BidStatus.Name"))
                {
                    ModelState.AddModelError("Name", "Unable to save changes.You cannot have duplicate Bid Status Name.");
                }
                else
                {
                    ModelState.AddModelError("", "Unable to save changes.Try again,and if the problem persists see your system administrator.");
                }
            }

            return(View(bidStatus));
        }
Example #4
0
        /// <summary>
        /// Устанавливает новый статус у тревоги.
        /// </summary>
        /// <param name="bid">Заявка у которой необходимо установить новый статус.</param>
        /// <param name="status">Новый статус тервоги.</param>
        /// <returns>Возвращает <c>true</c> в случае успеха, иначе <c>false</c>.</returns>
        public async Task <bool> SetBidStatusAsync(Bid bid, BidStatus status)
        {
            using (var client = new HttpClient())
            {
                HttpResponseMessage response;
                client.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse($"{Token.TokenType} {Token.Token}");
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                response = await client.PostAsync(ChangeStatusUri,
                                                  new FormUrlEncodedContent(new Dictionary <string, string>
                {
                    {
                        "uid", bid.Guid.ToString()
                    },
                    {
                        "new_status", status.ToString()
                    }
                }));

#if DEBUG
                var jsonString = await response.Content.ReadAsStringAsync();

                Debug.WriteLine(jsonString);
#endif

                return(await Task.FromResult(response.IsSuccessStatusCode));
            }
        }
        //Контекстное меню передачи заявки в работу
        void ContextTransferToStatus_Click(object sender, RoutedEventArgs e)
        {
            MenuItem mi = sender as MenuItem;

            if (mi == null)
            {
                return;
            }

            BidStatus bidStatus = mi.DataContext as BidStatus;

            if (bidStatus == null)
            {
                return;
            }

            Bid bid = dgvBid.SelectedItem as Bid;

            if (bid == null)
            {
                MessageBox.Show("Заявка не выбрана!");
                return;
            }

            PlannedShipmentDateSetWindow window
                = new PlannedShipmentDateSetWindow(bid, new Action <DateTime>((planned_shipment_date) => { SetPlannedShipmentDateChangeStatusAndSave(bid, planned_shipment_date); }));

            window.ShowDialog();
        }
Example #6
0
 public Player GetBidPlayer(BidStatus bidStatus)
 {
     foreach (var p in Players)
     {
         if (p.BidStatus == bidStatus)
         {
             return(p);
         }
     }
     return(null);
 }
        void BtnEditRow_Click(object sender, RoutedEventArgs e)
        {
            BidStatus bidStatus = dgvBidStatus.SelectedItem as BidStatus;

            if (bidStatus == null)
            {
                return;
            }
            BidStatusSaveWindow window = new BidStatusSaveWindow(bidStatus);

            window.ShowDialog();
        }
        public List <BidInfoViewModel> GetAllBidsForAuction(Guid auctionId)
        {
            var auction = _applicationDbContext.Auctions.Include("Organizations").Include("Bids").SingleOrDefault(p => p.Id == auctionId);

            if (auction == null)
            {
                throw new Exception($"Аукциона с таким id {auctionId} не существует");
            }

            var activeBidStatus = _applicationDbContext.BidStatuses.SingleOrDefault(p => p.StatusName == "Active").Id;

            if (activeBidStatus == null)
            {
                BidStatus status = new BidStatus()
                {
                    Id         = Guid.NewGuid(),
                    StatusName = "Active"
                };
                activeBidStatus = status.Id;
            }

            var bidForAuction = auction.Bids.Where(p => p.BidStatusId == activeBidStatus).ToList();

            if (bidForAuction.Count == 0)
            {
                throw new Exception($"По аукциону {auctionId} нет активных ставок");
            }

            List <BidInfoViewModel> bids = new List <BidInfoViewModel>();

            foreach (Bid item in bidForAuction)
            {
                BidInfoViewModel bid = new BidInfoViewModel()
                {
                    BidId              = item.Id.ToString(),
                    AuctionId          = auctionId.ToString(),
                    AuctionType        = item.Auction.AuctionType.ToString(),
                    AuctionDescription = item.Auction.Description,
                    BidStatus          = item.BidStatus.StatusName,
                    OrganizationId     = item.Organization.Id.ToString(),
                    OrganizationName   = item.Organization.FullName,
                    Price              = item.Price,
                    CreatedDate        = item.CreatedDate,
                    BidDescription     = item.Description
                };
                bids.Add(bid);
            }
            return(bids);
        }
Example #9
0
        public bool @remove <T>(T modelItem)
        {
            BidStatus bidStatus = modelItem as BidStatus;

            if (bidStatus == null)
            {
                bidStatus.LastError = "Не удалось преобразовать входные данные.";
                return(false);
            }
            if (!_collection.Contains(bidStatus))
            {
                return(true);
            }
            return(_collection.Remove(bidStatus));
        }
        public BidStatusWindow()
        {
            InitializeComponent();
            viewSource.Source = BidStatusViewModel.instance().Collection;

            viewSource.Filter += delegate(object sender, FilterEventArgs e)
            {
                BidStatus bidStatus = e.Item as BidStatus;
                if (bidStatus == null)
                {
                    return;
                }
                e.Accepted = bidStatus.IsVisible;
            };

            DataContext = new { BidStatusCollection = viewSource.View };
        }
        //Дабл клик по строке таблицы - открывает окно редактирования
        private void RowDoubleClick(object sender, MouseButtonEventArgs e)
        {
            DataGridRow row = sender as DataGridRow;

            BidStatus bidStatus = row.Item as BidStatus;

            if (bidStatus == null)
            {
                return;
            }

            BidStatusSaveWindow window = new BidStatusSaveWindow(bidStatus);

            window.ShowDialog();

            viewSource.View.Refresh();
            dgvBidStatus.CurrentCell = new DataGridCellInfo(row.Item, dgvBidStatus.CurrentCell.Column);
        }
        void BtnDeleteRow_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Подтвердите удаление",
                                "Удалить выбранную запись?",
                                MessageBoxButton.YesNo) != MessageBoxResult.Yes)
            {
                return;
            }
            BidStatus bidStatus = dgvBidStatus.SelectedItem as BidStatus;

            if (bidStatus == null)
            {
                return;
            }
            if (!bidStatus.remove())
            {
                MessageBox.Show(bidStatus.LastError);
            }
        }
Example #13
0
        void BtnTransfer_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;

            if (sender == null)
            {
                return;
            }

            DataGridRow row = Classes.FindItem.FindParentItem <DataGridRow>(button);

            if (row == null)
            {
                return;
            }

            BidStatus status = row.Item as BidStatus;

            if (status == null)
            {
                return;
            }

            if (MessageBox.Show("Передать заявку в статус '" + status.Name + "'?",
                                "Передать заявку в другой статус?",
                                MessageBoxButton.YesNo) != MessageBoxResult.Yes)
            {
                return;
            }
            bid.Id_bid_status = status.Id;
            if (bid.Id_bid_status == (int)Classes.BidStatus.InWork)
            {
                PlannedShipmentDateSetWindow window
                    = new PlannedShipmentDateSetWindow(bid, new Action <DateTime>((planned_shipment_date) => { bid.Planned_shipment_date = planned_shipment_date; }));
                window.ShowDialog();
            }
            if (!bid.save())
            {
                MessageBox.Show(bid.LastError);
                return;
            }
            Close();
        }
Example #14
0
        public bool @add <T>(T modelItem)
        {
            BidStatus bidStatus = modelItem as BidStatus;

            if (bidStatus == null)
            {
                bidStatus.LastError = "Не удалось преобразовать входные данные.";
                return(false);
            }
            BidStatus exist = getById(bidStatus.Id);

            if (exist != null || _collection.Contains(bidStatus))
            {
                bidStatus.LastError = "Либо данная запись уже есть в коллекции.";
                return(false);
            }
            _collection.Add(bidStatus);
            return(true);
        }
Example #15
0
        private void buttonBid_Click(object sender, EventArgs e)
        {
            if (mCalScreen)
            {
                mBidStatus       = BidStatus.IDLE1;
                timerBid.Enabled = true;
                textBoxLog.Text += "开始拍牌... \r\n";

                mPriceTime1 = 0;
                mPriceTime2 = 0;
                Point p = new Point(mInitPosition.X + 494, mInitPosition.Y + 249);
                Mouse.MouseClick(p);
                Directory.CreateDirectory("debug");
                Screen.SaveScreen(mInitPosition.X - 20, mInitPosition.Y - 170, 895, 700);
            }
            else
            {
                MessageBox.Show("请先校准屏幕!", "屏幕未校准", MessageBoxButtons.OK);
            }
        }
Example #16
0
        public TransferToStatusWindow(Bid bid, Action callback = null)
        {
            InitializeComponent();
            Title = "Передача заявки №" + bid.Id.ToString() + " в другой статус.";
            BidStatus        current    = BidStatusViewModel.instance().getById(bid.Id_bid_status);
            List <BidStatus> bid_status = BidStatusViewModel.instance().Collection.ToList();

            if (current != null && bid_status.Contains(current))
            {
                bid_status.Remove(current);
            }

            DataContext = new
            {
                StatusCollection = bid_status
            };

            this.bid      = bid;
            this.callback = callback;
        }
Example #17
0
 public BidStatusSaveWindow(BidStatus bidStatus = null)
 {
     InitializeComponent();
     defaultBrush = tbxName.Background;
     if (bidStatus != null)
     {
         Title        = "Редактирование статуса заявки (" + bidStatus.Name + ")";
         tbxName.Text = bidStatus.Name;
         try
         {
             cpRowColor.SelectedColor = (Color)ColorConverter.ConvertFromString(bidStatus.Record_color);
         }
         catch {}
         this.bidStatus = bidStatus;
     }
     else
     {
         this.bidStatus = new BidStatus();
     }
     tbxName.TextChanged += delegate { tbxName.Background = defaultBrush; };
 }
        //Контекстное меню передачи заявки в статус
        void ContextTransferToStatus_Click(object sender, RoutedEventArgs e)
        {
            MenuItem mi = sender as MenuItem;

            if (mi == null)
            {
                return;
            }

            BidStatus bidStatus = mi.DataContext as BidStatus;

            if (bidStatus == null)
            {
                return;
            }

            Bid bid = dgvBid.SelectedItem as Bid;

            if (bid == null)
            {
                MessageBox.Show("Заявка не выбрана!");
                return;
            }

            if (MessageBox.Show("Изменить статус заявки на '" + bidStatus.Name + "'?",
                                "Изменить статус заявки?",
                                MessageBoxButton.YesNo) != MessageBoxResult.Yes)
            {
                return;
            }

            bid.Id_bid_status = bidStatus.Id;
            if (!bid.save())
            {
                MessageBox.Show(bid.LastError);
                return;
            }

            viewSource.View.Refresh();
        }
Example #19
0
        public bool Bid(User user, decimal bidAmount, out BidStatus status)
        {
            if (!user.LoggedIn)
            {
                status = BidStatus.UserNotLoggedIn;
                return(false);
            }
            if (!Started)
            {
                status = BidStatus.AuctionNotActice;
                return(false);
            }

            if (bidAmount <= CurrentPrice)
            {
                status = BidStatus.BidTooLow;
                return(false);
            }
            status        = BidStatus.Accepted;
            CurrentPrice  = bidAmount;
            HighestBidder = user;
            return(true);
        }
        public void AuctionManagementService_ElectWinnerInAuction()
        {
            ApplicationDbContext applicationDb = new ApplicationDbContext();

            applicationDb.Database.CreateIfNotExists();

            OrganizationType organizationType = new OrganizationType()
            {
                Id   = Guid.NewGuid(),
                Name = "TstTypeA_04"
            };

            applicationDb.OrganizationTypes.Add(organizationType);
            applicationDb.SaveChanges();

            Organization auctionMaster = new Organization()
            {
                Id                 = Guid.NewGuid(),
                FullName           = "TestCompanyA_04",
                RegistrationDate   = DateTime.Now,
                OrganizationTypeId = organizationType.Id
            };

            applicationDb.Organizations.Add(auctionMaster);
            applicationDb.SaveChanges();

            Organization auctionParticipant = new Organization()
            {
                Id                 = Guid.NewGuid(),
                FullName           = "TestCompanyA_042",
                RegistrationDate   = DateTime.Now,
                OrganizationTypeId = organizationType.Id
            };

            applicationDb.Organizations.Add(auctionParticipant);
            applicationDb.SaveChanges();

            AuctionType auctionType = new AuctionType()
            {
                Id   = Guid.NewGuid(),
                Name = "TestAuctionType_04"
            };

            applicationDb.AuctionTypes.Add(auctionType);
            applicationDb.SaveChanges();

            Auction auction = new Auction()
            {
                Id                      = Guid.NewGuid(),
                Description             = "test_any description_04",
                MinRatingForParticipant = 9.5,
                StartPrice              = 600000M,
                MinPrice                = 100000M,
                PriceStep               = 50000M,
                StartDate               = new DateTime(2019, 4, 26),
                FinishDate              = new DateTime(2019, 5, 22),
                Status                  = AuctionStatus.Active,
                AuctionTypeId           = auctionType.Id,
                OrganizationId          = auctionMaster.Id
            };

            applicationDb.Auctions.Add(auction);
            applicationDb.SaveChanges();

            Transaction depositTrans = new Transaction()
            {
                Id = Guid.NewGuid(),
                TransactionType = TransactionType.Deposit,
                Sum             = 400000,
                TransactionDate = DateTime.Now,
                OrganizationId  = auctionParticipant.Id
            };

            applicationDb.Transactions.Add(depositTrans);
            applicationDb.SaveChanges();

            OrganizationRating rating = new OrganizationRating()
            {
                Id             = Guid.NewGuid(),
                Score          = 10,
                OrganizationId = auctionParticipant.Id
            };

            applicationDb.OrganizationRatings.Add(rating);
            applicationDb.SaveChanges();

            var activeBidStatus = applicationDb.BidStatuses.SingleOrDefault(p => p.StatusName == "Active");

            if (activeBidStatus == null)
            {
                BidStatus status = new BidStatus()
                {
                    Id         = Guid.NewGuid(),
                    StatusName = "Active"
                };
                applicationDb.BidStatuses.Add(status);
                applicationDb.SaveChanges();
                activeBidStatus = status;
            }

            Bid bid = new Bid()
            {
                Id             = Guid.NewGuid(),
                Price          = 200000M,
                CreatedDate    = DateTime.Now,
                BidStatusId    = activeBidStatus.Id,
                AuctionId      = auction.Id,
                OrganizationId = auctionParticipant.Id
            };

            applicationDb.Bids.Add(bid);
            applicationDb.SaveChanges();

            BidInfoViewModel model = new BidInfoViewModel()
            {
                BidId          = bid.Id.ToString(),
                AuctionId      = auction.Id.ToString(),
                OrganizationId = auctionParticipant.Id.ToString(),
                CreatedDate    = DateTime.Now,
                Price          = bid.Price
            };

            AuctionManagementService sut = new AuctionManagementService();

            sut.ElectWinnerInAuction(model);

            Bid         newBid      = applicationDb.Bids.SingleOrDefault(p => p.Id.ToString() == model.BidId);
            Transaction transaction = applicationDb.Transactions
                                      .SingleOrDefault(p => p.Sum == model.Price && p.TransactionType == TransactionType.Withdraw &&
                                                       p.OrganizationId.ToString() == model.OrganizationId);

            Assert.IsNotNull(newBid);
            Assert.IsNotNull(transaction);
        }
        public void AuctionManagementService_RevokeBidFromAuction()
        {
            ApplicationDbContext applicationDb = new ApplicationDbContext();

            applicationDb.Database.CreateIfNotExists();

            OrganizationType organizationType = new OrganizationType()
            {
                Id   = Guid.NewGuid(),
                Name = "TstTypeA_03"
            };

            applicationDb.OrganizationTypes.Add(organizationType);
            applicationDb.SaveChanges();

            Organization auctionMaster = new Organization()
            {
                Id                 = Guid.NewGuid(),
                FullName           = "TestCompanyA_03",
                RegistrationDate   = DateTime.Now,
                OrganizationTypeId = organizationType.Id
            };

            applicationDb.Organizations.Add(auctionMaster);
            applicationDb.SaveChanges();

            Organization auctionParticipant = new Organization()
            {
                Id                 = Guid.NewGuid(),
                FullName           = "TestCompanyA_032",
                RegistrationDate   = DateTime.Now,
                OrganizationTypeId = organizationType.Id
            };

            applicationDb.Organizations.Add(auctionParticipant);
            applicationDb.SaveChanges();

            AuctionType auctionType = new AuctionType()
            {
                Id   = Guid.NewGuid(),
                Name = "TestAuctionType_03"
            };

            applicationDb.AuctionTypes.Add(auctionType);
            applicationDb.SaveChanges();

            Auction auction = new Auction()
            {
                Id                      = Guid.NewGuid(),
                Description             = "test_any description_03",
                MinRatingForParticipant = 9.5,
                StartPrice              = 600000M,
                MinPrice                = 100000M,
                PriceStep               = 50000M,
                StartDate               = new DateTime(2019, 4, 26),
                FinishDate              = new DateTime(2019, 5, 22),
                Status                  = AuctionStatus.Active,
                AuctionTypeId           = auctionType.Id,
                OrganizationId          = auctionMaster.Id
            };

            applicationDb.Auctions.Add(auction);
            applicationDb.SaveChanges();

            var activeBidStatus = applicationDb.BidStatuses.SingleOrDefault(p => p.StatusName == "Active");

            if (activeBidStatus == null)
            {
                BidStatus status = new BidStatus()
                {
                    Id         = Guid.NewGuid(),
                    StatusName = "Active"
                };
                applicationDb.BidStatuses.Add(status);
                applicationDb.SaveChanges();
                activeBidStatus = status;
            }

            Bid bid = new Bid()
            {
                Id             = Guid.NewGuid(),
                Price          = 200000M,
                CreatedDate    = DateTime.Now,
                BidStatusId    = activeBidStatus.Id,
                AuctionId      = auction.Id,
                OrganizationId = auctionParticipant.Id
            };

            applicationDb.Bids.Add(bid);
            applicationDb.SaveChanges();

            AuctionManagementService sut = new AuctionManagementService();

            sut.RevokeBidFromAuction(bid.Id);

            Bid checkBid = applicationDb.Bids.Find(bid.Id);

            Assert.IsNotNull(checkBid);
            //Assert.IsTrue(bid.BidStatus.StatusName== "Revoke");
        }
        public void MakeBidToAuction(MakeBidViewModel model, decimal bidCost)
        {
            var bidExists = _applicationDbContext.Bids
                            .Any(p => p.Price == model.Price &&
                                 p.AuctionId.ToString() == model.AuctionId &&
                                 p.Description == model.Description &&
                                 p.OrganizationId.ToString() == model.OrganizationId);

            if (bidExists)
            {
                throw new Exception("Такая ставка уже существует");
            }

            var organization = _applicationDbContext.Organizations.Include("Transactions")
                               .SingleOrDefault(p => p.Id.ToString() == model.OrganizationId);

            if (organization == null)
            {
                throw new Exception("Такой организации в базе нет");
            }

            var auction = _applicationDbContext.Auctions
                          .SingleOrDefault(p => p.Id.ToString() == model.AuctionId);

            if (auction.OrganizationId.ToString() == model.OrganizationId)
            {
                throw new Exception("Создатель аукциона не может подавать ставки для участия в этом аукционе");
            }

            //проверка баланса на наличие средств для оплаты участия в аукционе
            var organizationTransactions = organization.Transactions.ToList();

            if (organizationTransactions.Count == 0)
            {
                throw new Exception($"У организации {organization.FullName} нулевой баланс");
            }

            var organizationBalance = organizationTransactions.Where(p => p.TransactionType == TransactionType.Deposit).Sum(p => p.Sum) -
                                      organizationTransactions.Where(p => p.TransactionType == TransactionType.Withdraw).Sum(p => p.Sum);

            if (organizationBalance < bidCost)
            {
                throw new Exception($"У организации {organization.FullName} не хватает средств на балансе для оплаты стоимости участия в аукционе");
            }

            //проверка ставки на соответствие мин, макс ценам и шагу цены
            var inValidPriceRange = _applicationDbContext.Auctions
                                    .Where(p => p.Id.ToString() == model.AuctionId &&
                                           p.MinPrice <model.Price &&
                                                       p.StartPrice> model.Price).ToList();

            var inStepRange = inValidPriceRange
                              .Any(p => (p.StartPrice - model.Price) % p.PriceStep == 0);

            if (!inStepRange)
            {
                throw new Exception("Invalid bid according price step");
            }

            var activeBidStatus = _applicationDbContext.BidStatuses.SingleOrDefault(p => p.StatusName == "Active");

            if (activeBidStatus == null)
            {
                BidStatus status = new BidStatus()
                {
                    Id         = Guid.NewGuid(),
                    StatusName = "Active"
                };
                _applicationDbContext.BidStatuses.Add(status);
                _applicationDbContext.SaveChanges();
                activeBidStatus = status;
            }

            //делаем ставку и списываем деньги за участие
            Bid bid = new Bid()
            {
                Id             = Guid.NewGuid(),
                Price          = model.Price,
                IsWin          = false,
                Description    = model.Description,
                AuctionId      = new Guid(model.AuctionId),
                OrganizationId = new Guid(model.OrganizationId),
                CreatedDate    = DateTime.Now,
                BidStatusId    = activeBidStatus.Id
            };

            _applicationDbContext.Bids.Add(bid);
            _applicationDbContext.SaveChanges();

            Transaction transaction = new Transaction()
            {
                Id              = Guid.NewGuid(),
                Sum             = bidCost,
                TransactionType = TransactionType.Withdraw,
                TransactionDate = DateTime.Now,
                OrganizationId  = new Guid(model.OrganizationId),
                Description     = $"Withdraw participation cost for auction {model.AuctionId}"
            };

            _applicationDbContext.Transactions.Add(transaction);
            _applicationDbContext.SaveChanges();
        }
        public List <BidInfoViewModel> GetBidsForAuctionWithFitOrganizationRatingAndBalance(Guid auctionId)
        {
            var auction = _applicationDbContext.Auctions.Include("Organizations").Include("Bids").SingleOrDefault(p => p.Id == auctionId);

            if (auction == null)
            {
                throw new Exception($"Аукциона с таким id {auctionId} не существует");
            }

            var activeBidStatus = _applicationDbContext.BidStatuses.SingleOrDefault(p => p.StatusName == "Active").Id;

            if (activeBidStatus == null)
            {
                BidStatus status = new BidStatus()
                {
                    Id         = Guid.NewGuid(),
                    StatusName = "Active"
                };
                activeBidStatus = status.Id;
            }

            var allBids = auction.Bids.Where(p => p.BidStatusId == activeBidStatus).ToList();

            if (allBids.Count == 0)
            {
                throw new Exception($"По аукциону {auctionId} нет активных ставок");
            }

            List <Bid> bidsWithFitRating = new List <Bid>();

            foreach (Bid item in allBids)
            {
                var org = item.OrganizationId;
                var avg = _applicationDbContext.OrganizationRatings.Where(p => p.OrganizationId == org).Average(p => p.Score);
                if (avg >= auction.MinRatingForParticipant)
                {
                    bidsWithFitRating.Add(item);
                }
            }
            if (bidsWithFitRating.Count == 0)
            {
                throw new Exception($"По аукциону {auctionId} нет ставок от организаций с нужным рейтингом");
            }

            List <Bid> bidsWithFitRatingBalance = new List <Bid>();

            foreach (Bid item in bidsWithFitRating)
            {
                var org         = item.OrganizationId;
                var sumDeposits = _applicationDbContext.Transactions
                                  .Where(p => p.OrganizationId == org && p.TransactionType == TransactionType.Deposit).Sum(p => p.Sum);
                var sumWithdraws = _applicationDbContext.Transactions
                                   .Where(p => p.OrganizationId == org && p.TransactionType == TransactionType.Withdraw).Sum(p => p.Sum);
                if (sumDeposits - sumWithdraws > item.Price)
                {
                    bidsWithFitRatingBalance.Add(item);
                }
            }
            if (bidsWithFitRatingBalance.Count == 0)
            {
                throw new Exception($"По аукциону {auctionId} нет ставок от организаций с достаточным балансом");
            }

            List <BidInfoViewModel> bids = new List <BidInfoViewModel>();

            foreach (Bid item in bidsWithFitRatingBalance)
            {
                BidInfoViewModel bid = new BidInfoViewModel()
                {
                    BidId              = item.Id.ToString(),
                    AuctionId          = auctionId.ToString(),
                    AuctionType        = item.Auction.AuctionType.ToString(),
                    AuctionDescription = item.Auction.Description,
                    BidStatus          = item.BidStatus.StatusName,
                    OrganizationId     = item.Organization.Id.ToString(),
                    OrganizationName   = item.Organization.FullName,
                    Price              = item.Price,
                    CreatedDate        = item.CreatedDate,
                    BidDescription     = item.Description
                };
                bids.Add(bid);
            }
            return(bids);
        }
Example #24
0
        public async Task <IActionResult> Edit(int id, int DesignerStatusID, int ClientStatusID, string approvalComment, string ProductsAssigned,
                                               string RolesAssigned, Byte[] RowVersion)
        {
            double total = 0;

            var bidToUpdate = await _context.Bids
                              .Include(a => a.Approval)
                              .ThenInclude(d => d.ApprovalStatuses)
                              .Include(a => a.BidProducts).ThenInclude(p => p.Product)
                              .Include(a => a.BidLabours)
                              .FirstOrDefaultAsync(a => a.ID == id);


            if (bidToUpdate == null)
            {
                return(NotFound());
            }
            _context.Entry(bidToUpdate).Property("RowVersion").OriginalValue = RowVersion;

            List <ProductDeserialize> ProductsToAdd = JsonConvert.DeserializeObject <List <ProductDeserialize> >(ProductsAssigned);
            List <RoleDeserialize>    rolesToAdd    = JsonConvert.DeserializeObject <List <RoleDeserialize> >(RolesAssigned);

            total += UpdateBidProducts(ProductsToAdd, bidToUpdate);
            total += UpdateBidLabours(rolesToAdd, bidToUpdate);
            //total += UpdateBidLabours(selectedRoles, requiredHours, bidToUpdate);

            bidToUpdate.EstAmount = total;

            if (await TryUpdateModelAsync <Bid>(bidToUpdate, "", p => p.DateCreated, p => p.EstBidEndDate, p => p.EstBidStartDate, p => p.Comments, P => P.Budget
                                                , p => p.DesignerID, p => p.SalesAsscociateID, p => p.BidStatusID, p => p.ProjectID))

            {
                try
                {
                    await _context.SaveChangesAsync();

                    UpdateApprovalStatus(bidToUpdate, DesignerStatusID, ClientStatusID, approvalComment);
                    CheckIfFinalaized(bidToUpdate);
                    // return RedirectToAction(nameof(Index));
                    return(RedirectToAction("Details", new { bidToUpdate.ID }));
                }
                catch (DbUpdateConcurrencyException ex)// Added for concurrency
                {
                    var exceptionEntry = ex.Entries.Single();
                    var clientValues   = (Bid)exceptionEntry.Entity;
                    var databaseEntry  = exceptionEntry.GetDatabaseValues();
                    if (databaseEntry == null)
                    {
                        ModelState.AddModelError("",
                                                 "Unable to save changes. The Bid was deleted by another user.");
                    }
                    else
                    {
                        var databaseValues = (Bid)databaseEntry.ToObject();
                        if (databaseValues.EstAmount != clientValues.EstAmount)
                        {
                            ModelState.AddModelError("EstAmount", "Current value: "
                                                     + databaseValues.EstAmount);
                        }
                        if (databaseValues.ProjectStartDate != clientValues.ProjectStartDate)
                        {
                            ModelState.AddModelError("ProjectStartDate", "Current value: "
                                                     + databaseValues.ProjectStartDate?.ToShortDateString());
                        }
                        if (databaseValues.ProjectEndDate != clientValues.ProjectEndDate)
                        {
                            ModelState.AddModelError("ProjectEndDate", "Current value: "
                                                     + databaseValues.ProjectEndDate?.ToShortDateString());
                        }
                        if (databaseValues.EstBidStartDate != clientValues.EstBidStartDate)
                        {
                            ModelState.AddModelError("EstBidStartDate", "Current value: "
                                                     + databaseValues.EstBidStartDate.ToShortDateString());
                        }
                        if (databaseValues.EstBidEndDate != clientValues.EstBidEndDate)
                        {
                            ModelState.AddModelError("EstBidEndDate", "Current value: "
                                                     + databaseValues.EstBidEndDate.ToShortDateString());
                        }
                        if (databaseValues.Comments != clientValues.Comments)
                        {
                            ModelState.AddModelError("comments", "Current value: "
                                                     + databaseValues.Comments);
                        }

                        //For the foreign key, we need to go to the database to get the information to show
                        if (databaseValues.ProjectID != clientValues.ProjectID)
                        {
                            Project databaseProject = await _context.Projects.SingleOrDefaultAsync(i => i.ID == databaseValues.ProjectID);

                            ModelState.AddModelError("ProjectID", $"Current value: {databaseProject?.Name}");
                        }
                        if (databaseValues.DesignerID != clientValues.DesignerID)
                        {
                            Employee databaseEmployee = await _context.Employees.SingleOrDefaultAsync(i => i.ID == databaseValues.DesignerID);

                            ModelState.AddModelError("DesignerID", $"Current value: {databaseEmployee?.FormalName}");
                        }

                        if (databaseValues.SalesAsscociateID != clientValues.SalesAsscociateID)
                        {
                            Employee databaseEmployee = await _context.Employees.SingleOrDefaultAsync(i => i.ID == databaseValues.SalesAsscociateID);

                            ModelState.AddModelError("SalesAsscociateID", $"Current value: {databaseEmployee?.FormalName}");
                        }

                        if (databaseValues.BidStatusID != clientValues.BidStatusID)
                        {
                            BidStatus databaseBidStatus = await _context.BidStatuses.SingleOrDefaultAsync(i => i.ID == databaseValues.BidStatusID);

                            ModelState.AddModelError("BidStatusID", $"Current value: {databaseBidStatus?.Name}");
                        }

                        if (databaseValues.Approval.ClientStatusID != clientValues.Approval.ClientStatusID) //fail
                        {
                            ApprovalStatus databaseApprovalStatus = await _context.ApprovalStatuses.SingleOrDefaultAsync(i => i.ID == databaseValues.Approval.ClientStatusID);

                            ModelState.AddModelError("Approval.ClientStatusID", $"Current value: {databaseApprovalStatus?.Name}");
                        }

                        if (databaseValues.Approval.DesignerStatusID != clientValues.Approval.DesignerStatusID) // fail
                        {
                            ApprovalStatus databaseApprovalStatus = await _context.ApprovalStatuses.SingleOrDefaultAsync(i => i.ID == databaseValues.Approval.DesignerStatusID);

                            ModelState.AddModelError("Approval.DesignerStatusID", $"Current value: {databaseApprovalStatus?.Name}");
                        }

                        if (databaseValues.Approval.Comments != clientValues.Approval.Comments) // pass
                        {
                            Approval databaseApproval = await _context.Approvals.SingleOrDefaultAsync(i => i.BidID == databaseValues.ID);

                            ModelState.AddModelError("Approval.Comments", $"Current value: {databaseApproval?.Comments}");
                        }


                        //// Get all the Bidproduct.productID in db and client input
                        //var dbBidProudct = _context.BidProducts.Where(p => p.BidID == bidToUpdate.ID);
                        //List<int> dbBidproductIds = new List<int>();

                        //foreach (var i in dbBidProudct)
                        //{
                        //    dbBidproductIds.Add(i.ProductID);
                        //}
                        //var ClientProducIds = clientValues.BidProducts.Select(p => p.ProductID).ToList();

                        //// if the two arrays match dont match the values were upated throw errror with values in db
                        //if (!dbBidproductIds.Equals(ClientProducIds))
                        //{
                        //    string returnValue = "";
                        //    var AllBidProducts = _context.BidProducts.Where(p => p.BidID == bidToUpdate.ID); // related bidProducts


                        //    foreach (var item in AllBidProducts)
                        //    {
                        //        returnValue += "/n" + item.Product.Code + " - " + item.Quantity;
                        //    }

                        //    ModelState.AddModelError("BidProducts", $"Current value: {returnValue}");

                        //}

                        ModelState.AddModelError(string.Empty, "The record you attempted to edit "
                                                 + "was modified by another user after you received your values. The "
                                                 + "edit operation was canceled and the current values in the database "
                                                 + "have been displayed. If you still want to save your version of this record, click "
                                                 + "the Save button again. Otherwise click the 'Back to List' hyperlink.");

                        bidToUpdate.RowVersion = (byte[])databaseValues.RowVersion;
                        ModelState.Remove("RowVersion");
                    }
                }
            }
            PopulateDropDownLists(bidToUpdate, DesignerStatusID, ClientStatusID, approvalComment);
            PopuateSelectedProducts(bidToUpdate);
            PopuateSelectedRoles(bidToUpdate);
            return(View(bidToUpdate));
        }
Example #25
0
        public static void Initialize(IServiceProvider serviceProvider)
        {
            Random random = new Random();

            string[] baconNotes = new string[] { "Bacon ipsum dolor amet meatball corned beef kevin, alcatra kielbasa biltong drumstick strip steak spare ribs swine. Pastrami shank swine leberkas bresaola, prosciutto frankfurter porchetta ham hock short ribs short loin andouille alcatra. Andouille shank meatball pig venison shankle ground round sausage kielbasa. Chicken pig meatloaf fatback leberkas venison tri-tip burgdoggen tail chuck sausage kevin shank biltong brisket.", "Sirloin shank t-bone capicola strip steak salami, hamburger kielbasa burgdoggen jerky swine andouille rump picanha. Sirloin porchetta ribeye fatback, meatball leberkas swine pancetta beef shoulder pastrami capicola salami chicken. Bacon cow corned beef pastrami venison biltong frankfurter short ribs chicken beef. Burgdoggen shank pig, ground round brisket tail beef ribs turkey spare ribs tenderloin shankle ham rump. Doner alcatra pork chop leberkas spare ribs hamburger t-bone. Boudin filet mignon bacon andouille, shankle pork t-bone landjaeger. Rump pork loin bresaola prosciutto pancetta venison, cow flank sirloin sausage.", "Porchetta pork belly swine filet mignon jowl turducken salami boudin pastrami jerky spare ribs short ribs sausage andouille. Turducken flank ribeye boudin corned beef burgdoggen. Prosciutto pancetta sirloin rump shankle ball tip filet mignon corned beef frankfurter biltong drumstick chicken swine bacon shank. Buffalo kevin andouille porchetta short ribs cow, ham hock pork belly drumstick pastrami capicola picanha venison.", "Picanha andouille salami, porchetta beef ribs t-bone drumstick. Frankfurter tail landjaeger, shank kevin pig drumstick beef bresaola cow. Corned beef pork belly tri-tip, ham drumstick hamburger swine spare ribs short loin cupim flank tongue beef filet mignon cow. Ham hock chicken turducken doner brisket. Strip steak cow beef, kielbasa leberkas swine tongue bacon burgdoggen beef ribs pork chop tenderloin.", "Kielbasa porchetta shoulder boudin, pork strip steak brisket prosciutto t-bone tail. Doner pork loin pork ribeye, drumstick brisket biltong boudin burgdoggen t-bone frankfurter. Flank burgdoggen doner, boudin porchetta andouille landjaeger ham hock capicola pork chop bacon. Landjaeger turducken ribeye leberkas pork loin corned beef. Corned beef turducken landjaeger pig bresaola t-bone bacon andouille meatball beef ribs doner. T-bone fatback cupim chuck beef ribs shank tail strip steak bacon." };

            using (var context = new OasisContext(
                       serviceProvider.GetRequiredService <DbContextOptions <OasisContext> >()))
            {
                string[] approvalStatus = new string[] { "Approved", "Disapproved", "RequiresApproval" };
                string[] bidStatus      = new string[] { "In Progress", "Stoped Due To Weather", "Completed", "Not Started", "Waiting approval", "Design stage", "Approved by client", "Approved by NBD", "Needs revision", };
                string[] productTypes   = new string[] { "Plant Inventory", "Pottery Inventory", "Materials Inventory" };
                string[] _firstName     = new string[] { "Adam", "Alex", "Aaron", "Ben", "Carl", "Dan", "David", "Edward", "Fred", "Frank", "George", "Hal", "Hank", "Ike", "John", "Jack", "Joe", "Larry", "Monte", "Matthew", "Mark", "Nathan", "Otto", "Paul", "Peter", "Roger", "Roger", "Steve", "Thomas", "Tim", "Ty", "Victor", "Walter" };
                string[] _lastName      = new string[] { "Anderson", "Ashwoon", "Aikin", "Bateman", "Bongard", "Bowers", "Boyd", "Cannon", "Cast", "Deitz", "Dewalt", "Ebner", "Frick", "Hancock", "Haworth", "Hesch", "Hoffman", "Kassing", "Knutson", "Lawless", "Lawicki", "Mccord", "McCormack", "Miller", "Myers", "Nugent", "Ortiz", "Orwig", "Ory", "Paiser", "Pak", "Pettigrew", "Quinn", "Quizoz", "Ramachandran", "Resnick", "Sagar", "Schickowski", "Schiebel", "Sellon", "Severson", "Shaffer", "Solberg", "Soloman", "Sonderling", "Soukup", "Soulis", "Stahl", "Sweeney", "Tandy", "Trebil", "Trusela", "Trussel", "Turco", "Uddin", "Uflan", "Ulrich", "Upson", "Vader", "Vail", "Valente", "Van Zandt", "Vanderpoel", "Ventotla", "Vogal", "Wagle", "Wagner", "Wakefield", "Weinstein", "Weiss", "Woo", "Yang", "Yates", "Yocum", "Zeaser", "Zeller", "Ziegler", "Bauer", "Baxster", "Casal", "Cataldi", "Caswell", "Celedon", "Chambers", "Chapman", "Christensen", "Darnell", "Davidson", "Davis", "DeLorenzo", "Dinkins", "Doran", "Dugelman", "Dugan", "Duffman", "Eastman", "Ferro", "Ferry", "Fletcher", "Fietzer", "Hylan", "Hydinger", "Illingsworth", "Ingram", "Irwin", "Jagtap", "Jenson", "Johnson", "Johnsen", "Jones", "Jurgenson", "Kalleg", "Kaskel", "Keller", "Leisinger", "LePage", "Lewis", "Linde", "Lulloff", "Maki", "Martin", "McGinnis", "Mills", "Moody", "Moore", "Napier", "Nelson", "Norquist", "Nuttle", "Olson", "Ostrander", "Reamer", "Reardon", "Reyes", "Rice", "Ripka", "Roberts", "Rogers", "Root", "Sandstrom", "Sawyer", "Schlicht", "Schmitt", "Schwager", "Schutz", "Schuster", "Tapia", "Thompson", "Tiernan", "Tisler" };
                string[] countryList    = new string[] { "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas (the)", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia (Plurinational State of)", "Bonaire, Sint Eustatius and Saba", "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory (the)", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cabo Verde", "Cambodia", "Cameroon", "Canada", "Cayman Islands (the)", "Central African Republic (the)", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands (the)", "Colombia", "Comoros (the)", "Congo (the Democratic Republic of the)", "Congo (the)", "Cook Islands (the)", "Costa Rica", "Croatia", "Cuba", "Curaçao", "Cyprus", "Czechia", "Côte d'Ivoire", "Denmark", "Djibouti", "Dominica", "Dominican Republic (the)", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Eswatini", "Ethiopia", "Falkland Islands (the) [Malvinas]", "Faroe Islands (the)", "Fiji", "Finland", "France", "French Guiana", "French Polynesia", "French Southern Territories (the)", "Gabon", "Gambia (the)", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guernsey", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard Island and McDonald Islands", "Holy See (the)", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran (Islamic Republic of)", "Iraq", "Ireland", "Isle of Man", "Israel", "Italy", "Jamaica", "Japan", "Jersey", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea (the Democratic People's Republic of)", "Korea (the Republic of)", "Kuwait", "Kyrgyzstan", "Lao People's Democratic Republic (the)", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", "Macao", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands (the)", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia (Federated States of)", "Moldova (the Republic of)", "Monaco", "Mongolia", "Montenegro", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands (the)", "New Caledonia", "New Zealand", "Nicaragua", "Niger (the)", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands (the)", "Norway", "Oman", "Pakistan", "Palau", "Palestine, State of", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines (the)", "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Republic of North Macedonia", "Romania", "Russian Federation (the)", "Rwanda", "Réunion", "Saint Barthélemy", "Saint Helena, Ascension and Tristan da Cunha", "Saint Kitts and Nevis", "Saint Lucia", "Saint Martin (French part)", "Saint Pierre and Miquelon", "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Serbia", "Seychelles", "Sierra Leone", "Singapore", "Sint Maarten (Dutch part)", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Sudan", "Spain", "Sri Lanka", "Sudan (the)", "Suriname", "Svalbard and Jan Mayen", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan", "Tajikistan", "Tanzania, United Republic of", "Thailand", "Timor-Leste", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands (the)", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates (the)", "United Kingdom of Great Britain and Northern Ireland (the)", "United States Minor Outlying Islands (the)", "United States of America (the)", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela (Bolivarian Republic of)", "Viet Nam", "Virgin Islands (British)", "Virgin Islands (U.S.)", "Wallis and Futuna", "Western Sahara", "Yemen", "Zambia", "Zimbabwe", "Åland Islands" };
                string[] streetNumber   = new string[] { "25489", "87459", "35478", "15975", "95125", "78965" };
                string[] CompanyName    = new string[] { "Media", "Inc", "Builders", "Shop", "Demolishers", "Styles" };
                string[] position       = new string[] { "CEO", "Manager", "Employee", "Supervisor", "CTO" };

                string[] streetName = new string[] { "A street", "B street", "C street", "D street", "E street", "F street" };
                ;
                string[] cityName = new string[] { "Riyadh", "Damman", "Jedda", "Tabouk", "Makka", "Maddena", "Haiel" };

                string[] stateName = new string[] { "Qassem State", "North State", "East State", "South State", "West State" };

                string[] zipCode = new string[] { "28889", "96459", "35748", "15005", "99625", "71465" };

                //bool Checkarrray(List<string> list, string s)
                //{
                //    if (list.Contains(s))
                //        return true;
                //    return false;
                //}


                if (!context.Roles.Any())
                {
                    context.Roles.AddRange(

                        new Role
                    {
                        Name             = "Designer",
                        LabourCostPerHr  = Convert.ToDecimal(40.0),
                        LabourPricePerHr = Convert.ToDecimal(65.0)
                    },
                        new Role
                    {
                        Name             = "Botanist",
                        LabourCostPerHr  = Convert.ToDecimal(50.0),
                        LabourPricePerHr = Convert.ToDecimal(75.0)
                    },
                        new Role
                    {
                        Name             = "Sales Associate",
                        LabourCostPerHr  = Convert.ToDecimal(50.0),
                        LabourPricePerHr = Convert.ToDecimal(75.0)
                    }
                        );
                    context.SaveChanges();
                }


                int[] roleID = context.Roles.Select(p => p.ID).ToArray();


                if (!context.Employees.Any())
                {
                    for (int i = 0; i < 10; i++)
                    {
                        var a = new Employee()
                        {
                            FirstName      = _firstName[random.Next(_firstName.Count())],
                            MiddleName     = _firstName[random.Next(_firstName.Count())],
                            LastName       = _lastName[random.Next(_lastName.Count())],
                            AddressLineOne = streetNumber[random.Next(streetNumber.Count())] + streetName[random.Next(streetName.Count())],
                            City           = cityName[random.Next(cityName.Count())],
                            Province       = stateName[random.Next(stateName.Count())],
                            Country        = countryList[random.Next(countryList.Count())],
                            Phone          = 1234567890,
                            Email          = _firstName[random.Next(_firstName.Count())] + _lastName[random.Next(_lastName.Count())] + "@outlook.com",
                            RoleID         = roleID[random.Next(roleID.Count())],
                            IsUser         = true,
                        };

                        try
                        {
                            context.Add(a);
                            context.SaveChanges();
                        }
                        catch
                        {
                        }
                    }
                }

                //if (!context.Customers.Any())
                //{
                //    for (int i = 0; i < 50; i++)
                //    {

                //        var a = new Customer()
                //        {
                //            FirstName = _firstName[random.Next(_firstName.Count())],
                //            MiddleName = _firstName[random.Next(_firstName.Count())],
                //            LastName = _lastName[random.Next(_lastName.Count())],
                //            AddressLineOne = streetNumber[random.Next(streetNumber.Count())] + " " + streetName[random.Next(streetName.Count())],
                //            City = cityName[random.Next(cityName.Count())],
                //            Province = stateName[random.Next(stateName.Count())],
                //            Country = countryList[random.Next(countryList.Count())],
                //            Phone = 1234567890,
                //            Email = _firstName[random.Next(_firstName.Count())] + _lastName[random.Next(_lastName.Count())] + "@outlook.com",
                //            OrgName = _firstName[random.Next(_firstName.Count())] + " " + CompanyName[random.Next(CompanyName.Count())],
                //            Position = position[random.Next(position.Count())]
                //        };

                //        try
                //        {
                //            context.Add(a);
                //            context.SaveChanges();
                //        }
                //        catch
                //        {
                //            //do nothing
                //        }
                //    }

                //}



                //int[] CustomerIDs = context.Customers.Select(p => p.ID).ToArray();
                ////if (!context.Projects.Any())
                ////{
                ////    List<string> projectName = new List<string>();

                ////    foreach (int i in CustomerIDs)
                ////    {

                ////        var project = _firstName[random.Next(_firstName.Count())] + "Project";

                ////        while (Checkarrray(projectName, project))
                ////        {
                ////            project = _lastName[random.Next(_lastName.Count())] + "Project";

                ////        }

                ////        projectName.Add(project);

                ////        try {
                ////        context.Projects.Add(
                ////           new Project
                ////           {
                ////               Name = project,
                ////               SiteAddressLineOne = "586 First Ave",
                ////               City = "Welland",
                ////               Province = "Ontario",
                ////               Country = "Canada",
                ////               CustomerID = random.Next(CustomerIDs.Count())
                ////           });

                ////            context.SaveChangesAsync();
                ////        }
                ////        catch
                ////        {

                ////        }

                ////    }
                ////}

                ////if (!context.Projects.Any())
                ////{
                ////    List<string> projectName = new List<string>();
                ////    foreach (int i in CustomerIDs)
                ////    {
                ////        for (int j = 0; j < 5; j++)
                ////        {

                ////            var project = _firstName[random.Next(_firstName.Count())] + "Project";

                ////            while (Checkarrray(projectName, project))
                ////            {
                ////                project = _lastName[random.Next(_lastName.Count())] + "Project";

                ////            }

                ////            Project a = new Project()
                ////            {
                ////                Name = project,
                ////                SiteAddressLineOne = streetNumber[random.Next(streetNumber.Count())] + " " + streetName[random.Next(streetName.Count())],
                ////                City = cityName[random.Next(cityName.Count())],
                ////                Province = stateName[random.Next(stateName.Count())],
                ////                Country = countryList[random.Next(countryList.Count())],
                ////                CustomerID = i


                ////            };

                ////            try
                ////            {
                ////                context.Add(a);
                ////                context.SaveChanges();

                ////            }
                ////            catch
                ////            {
                ////                dod nothing repeat
                ////            }
                ////        }



                ////    }
                ////    context.SaveChanges();
                ////}



                //if (!context.Projects.Any())
                //{
                //    context.Projects.AddRange(
                //    new Project
                //    {
                //        Name = "Alpha",
                //        SiteAddressLineOne = "586 First Ave",
                //        City = "Welland",
                //        Province = "Ontario",
                //        Country = "Canada",
                //        CustomerID = random.Next(CustomerIDs.Count())
                //    },
                //    new Project
                //    {
                //        Name = "Beta",
                //        SiteAddressLineOne = "586",
                //        SiteAddressLineTwo = "First Ave",
                //        City = "Welland",
                //        Province = "Ontario",
                //        Country = "Canada",
                //        CustomerID = random.Next(CustomerIDs.Count())
                //    },
                //     new Project
                //     {
                //         Name = "Mall",
                //         SiteAddressLineOne = "586 First Ave",
                //         City = "Welland",
                //         Province = "Ontario",
                //         Country = "Canada",
                //         CustomerID = random.Next(CustomerIDs.Count())
                //     },
                //     new Project
                //     {
                //         Name = "Seaway Mall",
                //         SiteAddressLineOne = "586 First Ave",
                //         City = "Welland",
                //         Province = "Ontario",
                //         Country = "Canada",
                //         CustomerID = random.Next(CustomerIDs.Count())
                //     },
                //      new Project
                //      {
                //          Name = "Start up",
                //          SiteAddressLineOne = "586 First Ave",
                //          City = "Welland",
                //          Province = "Ontario",
                //          Country = "Canada",
                //          CustomerID = random.Next(CustomerIDs.Count())
                //      }, new Project
                //      {
                //          Name = "Walmart",
                //          SiteAddressLineOne = "786 First Ave",
                //          City = "Niagara",
                //          Province = "Ontario",
                //          Country = "Canada",
                //          CustomerID = random.Next(CustomerIDs.Count())
                //      },
                //        new Project
                //        {
                //            Name = "BestBuy",
                //            SiteAddressLineOne = "5096 First Ave",
                //            City = "Hamilton",
                //            Province = "Ontario",
                //            Country = "Canada",
                //            CustomerID = random.Next(CustomerIDs.Count())
                //        },
                //         new Project
                //         {
                //             Name = "Staples",
                //             SiteAddressLineOne = "596 First Ave",
                //             City = "St Chatehrines",
                //             Province = "Ontario",
                //             Country = "Canada",
                //             CustomerID = random.Next(CustomerIDs.Count())
                //         },
                //          new Project
                //          {
                //              Name = "Burger King",
                //              SiteAddressLineOne = "176 First Ave",
                //              City = "Toronto",
                //              Province = "Ontario",
                //              Country = "Canada",
                //              CustomerID = random.Next(CustomerIDs.Count())
                //          },
                //           new Project
                //           {
                //               Name = "Tim Hortons",
                //               SiteAddressLineOne = "586 First Ave",
                //               City = "Welland",
                //               Province = "Ontario",
                //               Country = "Canada",
                //               CustomerID = random.Next(CustomerIDs.Count())
                //           },
                //            new Project
                //            {
                //                Name = "A&W Canada",
                //                SiteAddressLineOne = "586 First Ave",
                //                City = "Welland",
                //                Province = "Ontario",
                //                Country = "Canada",
                //                CustomerID = random.Next(CustomerIDs.Count())
                //            }
                //      ); ;
                //    context.SaveChanges();
                //}


                if (!context.Customers.Any())
                {
                    context.Customers.AddRange(
                        new Customer
                    {
                        OrgName        = "Wonderboy Media",
                        FirstName      = "Amal",
                        MiddleName     = "E",
                        LastName       = "Shaiju",
                        Position       = "CEO",
                        AddressLineOne = "586 First Ave",
                        City           = "Welland",
                        Province       = "Ontario",
                        Country        = "Canada",
                        Phone          = 9055551212,
                        Email          = "*****@*****.**",
                    },
                        new Customer
                    {
                        OrgName         = "Weiner Media",
                        FirstName       = "Jesline",
                        LastName        = "Stanly",
                        Position        = "CTO",
                        AddressLineOne  = "596",
                        AddressLineTwo  = "First Ave",
                        ApartmentNumber = "Flat 96",
                        City            = "Welland",
                        Province        = "Ontario",
                        Country         = "Canada",
                        Phone           = 9055551213,
                        Email           = "*****@*****.**",
                    },
                        new Customer
                    {
                        OrgName        = "VAl Media",
                        FirstName      = "Val",
                        LastName       = "Garaskky",
                        Position       = "Manager",
                        AddressLineOne = "598 First Ave",
                        City           = "Welland",
                        Province       = "Ontario",
                        Country        = "Canada",
                        Phone          = 9055551215,
                        Email          = "*****@*****.**",
                    },
                        new Customer
                    {
                        OrgName        = "Yasmeen Designers",
                        FirstName      = "Yasmeen",
                        LastName       = "Faager",
                        Position       = "CFO",
                        AddressLineOne = "590 First Ave",
                        City           = "Welland",
                        Province       = "Ontario",
                        Country        = "Canada",
                        Phone          = 9055554213,
                        Email          = "*****@*****.**",
                    },
                        new Customer
                    {
                        OrgName        = "Rufaro Media",
                        FirstName      = "Rufaro",
                        Position       = "CKO",
                        LastName       = "Gonsalaz",
                        AddressLineOne = "580 First Ave",
                        City           = "Welland",
                        Province       = "Ontario",
                        Country        = "Canada",
                        Phone          = 9255554213,
                        Email          = "*****@*****.**",
                    });
                    context.SaveChanges();
                }


                if (!context.Projects.Any())
                {
                    context.Projects.AddRange(
                        new Project
                    {
                        Name = "Alpha",
                        SiteAddressLineOne = "586 First Ave",
                        City       = "Welland",
                        Province   = "Ontario",
                        Country    = "Canada",
                        CustomerID = context.Customers.FirstOrDefault(d => d.FirstName == "Amal").ID
                    },
                        new Project
                    {
                        Name = "Beta",
                        SiteAddressLineOne = "586",
                        SiteAddressLineTwo = "First Ave",
                        City       = "Welland",
                        Province   = "Ontario",
                        Country    = "Canada",
                        CustomerID = context.Customers.FirstOrDefault(d => d.FirstName == "Jesline").ID
                    },
                        new Project
                    {
                        Name = "Mall",
                        SiteAddressLineOne = "586 First Ave",
                        City       = "Welland",
                        Province   = "Ontario",
                        Country    = "Canada",
                        CustomerID = context.Customers.FirstOrDefault(d => d.FirstName == "Yasmeen").ID
                    },
                        new Project
                    {
                        Name = "Seaway Mall",
                        SiteAddressLineOne = "586 First Ave",
                        City       = "Welland",
                        Province   = "Ontario",
                        Country    = "Canada",
                        CustomerID = context.Customers.FirstOrDefault(d => d.FirstName == "Val").ID
                    },
                        new Project
                    {
                        Name = "Start up",
                        SiteAddressLineOne = "586 First Ave",
                        City       = "Welland",
                        Province   = "Ontario",
                        Country    = "Canada",
                        CustomerID = context.Customers.FirstOrDefault(d => d.FirstName == "Rufaro").ID
                    }, new Project
                    {
                        Name = "Walmart",
                        SiteAddressLineOne = "786 First Ave",
                        City       = "Niagara",
                        Province   = "Ontario",
                        Country    = "Canada",
                        CustomerID = context.Customers.FirstOrDefault(d => d.FirstName == "Amal").ID
                    },
                        new Project
                    {
                        Name = "BestBuy",
                        SiteAddressLineOne = "5096 First Ave",
                        City       = "Hamilton",
                        Province   = "Ontario",
                        Country    = "Canada",
                        CustomerID = context.Customers.FirstOrDefault(d => d.FirstName == "Jesline").ID
                    },
                        new Project
                    {
                        Name = "Staples",
                        SiteAddressLineOne = "596 First Ave",
                        City       = "St Chatehrines",
                        Province   = "Ontario",
                        Country    = "Canada",
                        CustomerID = context.Customers.FirstOrDefault(d => d.FirstName == "Val").ID
                    },
                        new Project
                    {
                        Name = "Burger King",
                        SiteAddressLineOne = "176 First Ave",
                        City       = "Toronto",
                        Province   = "Ontario",
                        Country    = "Canada",
                        CustomerID = context.Customers.FirstOrDefault(d => d.FirstName == "Yasmeen").ID
                    },
                        new Project
                    {
                        Name = "Tim Hortons",
                        SiteAddressLineOne = "586 First Ave",
                        City       = "Welland",
                        Province   = "Ontario",
                        Country    = "Canada",
                        CustomerID = context.Customers.FirstOrDefault(d => d.FirstName == "Rufaro").ID
                    },
                        new Project
                    {
                        Name = "A&W Canada",
                        SiteAddressLineOne = "586 First Ave",
                        City       = "Welland",
                        Province   = "Ontario",
                        Country    = "Canada",
                        CustomerID = context.Customers.FirstOrDefault(d => d.FirstName == "Amal").ID
                    }
                        );
                    context.SaveChanges();
                }



                if (!context.ApprovalStatuses.Any())
                {
                    foreach (string i in approvalStatus)
                    {
                        ApprovalStatus a = new ApprovalStatus()
                        {
                            Name = i
                        };
                        context.Add(a);
                    }
                    context.SaveChanges();
                }


                if (!context.ProductTypes.Any())
                {
                    foreach (string i in productTypes)
                    {
                        ProductType a = new ProductType()
                        {
                            Name = i
                        };
                        context.Add(a);
                    }
                    context.SaveChanges();
                }

                if (!context.Products.Any())
                {
                    context.Products.AddRange(
                        new Product
                    {
                        Code          = "Lacco",
                        Description   = "Lacco Australasica",
                        size          = "15 Gal",
                        Price         = 450.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Plant Inventory").ID
                    },
                        new Product
                    {
                        Code          = "Cham",
                        Description   = "Chamaedorea",
                        size          = "15 Gal",
                        Price         = 499.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Plant Inventory").ID
                    },
                        new Product
                    {
                        Code          = "Cera",
                        Description   = "Ceratozamia molongo",
                        size          = "14 in",
                        Price         = 400.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Plant Inventory").ID
                    },
                        new Product
                    {
                        Code          = "Areca",
                        Description   = "arecastum coco",
                        size          = "15 gal",
                        Price         = 458.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Plant Inventory").ID
                    },
                        new Product
                    {
                        Code          = "Cary",
                        Description   = "caryota mitius",
                        size          = "15 gal",
                        Price         = 154.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Plant Inventory").ID
                    },
                        new Product
                    {
                        Code          = "Margi",
                        Description   = "marginata",
                        size          = "2 gal",
                        Price         = 75.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Plant Inventory").ID
                    },
                        new Product
                    {
                        Code          = "TCP50",
                        Description   = "t/c Pot",
                        size          = "50 Gal",
                        Price         = 110.95,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Pottery Inventory").ID
                    },
                        new Product
                    {
                        Code          = "GP50",
                        Description   = "Granite pot",
                        size          = "50 Gal",
                        Price         = 195.95,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Pottery Inventory").ID
                    },
                        new Product
                    {
                        Code          = "TCF03",
                        Description   = "t/c figurine-swan",
                        size          = "",
                        Price         = 45.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Pottery Inventory").ID
                    },
                        new Product
                    {
                        Code          = "MBBB30",
                        Description   = "Marble bird bath",
                        size          = "30 in",
                        Price         = 250.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Pottery Inventory").ID
                    },
                        new Product
                    {
                        Code          = "GFN48",
                        Description   = "Granite Fountain",
                        size          = "48 in",
                        Price         = 750.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Pottery Inventory").ID
                    },
                        new Product
                    {
                        Code          = "CBRK5",
                        Description   = "Decorative Cedar Bark",
                        size          = "bag(5 cu Ft)",
                        Price         = 15.95,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Materials Inventory").ID
                    },
                        new Product
                    {
                        Code          = "CRGRN",
                        Description   = "Crushed granite",
                        size          = "Yard",
                        Price         = 14.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Materials Inventory").ID
                    },
                        new Product
                    {
                        Code          = "PGRV",
                        Description   = "Pea gravel",
                        size          = "Yard",
                        Price         = 20.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Materials Inventory").ID
                    },
                        new Product
                    {
                        Code          = "GRVI",
                        Description   = "1 Gravel",
                        size          = "Yard",
                        Price         = 12.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Materials Inventory").ID
                    },
                        new Product
                    {
                        Code          = "TSOIL",
                        Description   = "Top soil",
                        size          = "Yard",
                        Price         = 20.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Materials Inventory").ID
                    },
                        new Product
                    {
                        Code          = "PBLKG",
                        Description   = "Patio block-gray",
                        size          = "each",
                        Price         = 0.84,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Materials Inventory").ID
                    },
                        new Product
                    {
                        Code          = "PBLKR",
                        Description   = "Patio block-red",
                        size          = "each",
                        Price         = 0.84,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Materials Inventory").ID
                    },


                        new Product
                    {
                        Code          = "Arenga",
                        Description   = "Arenga Pinnata",
                        size          = "15 Gal",
                        Price         = 516.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Plant Inventory").ID
                    });
                    context.SaveChanges();
                }

                if (!context.BidStatuses.Any())
                {
                    foreach (string i in bidStatus)
                    {
                        BidStatus a = new BidStatus()
                        {
                            Name = i
                        };
                        context.Add(a);
                    }
                    context.SaveChanges();
                }

                int[] projectID           = context.Projects.Select(s => s.ID).ToArray();
                int[] designerID          = context.Employees.Where(p => p.Role.Name == "Designer").Select(p => p.ID).ToArray();
                int[] salesAssociateID    = context.Employees.Where(p => p.Role.Name == "Sales Associate").Select(p => p.ID).ToArray();
                int[] approvalStatusID    = context.ApprovalStatuses.Select(p => p.ID).ToArray();
                int[] bidStatusID         = context.BidStatuses.Select(p => p.ID).ToArray();
                int   ProjectCount        = projectID.Count();
                int   designerCount       = designerID.Count();
                int   bidStatusCount      = bidStatusID.Count();
                int   salesAssociateCount = salesAssociateID.Count();

                if (!context.Bids.Any())
                {
                    foreach (int i in projectID)
                    {
                        for (int j = 0; j < 2; j++)
                        {
                            int range = 5 * 365; //5 years

                            Bid a = new Bid()
                            {
                                DateCreated       = DateTime.Today.AddDays(random.Next(range)),
                                EstAmount         = 0,
                                EstBidStartDate   = DateTime.Today.AddDays(random.Next(range)),
                                EstBidEndDate     = DateTime.Today.AddDays(random.Next(range)),
                                Comments          = baconNotes[random.Next(4)],
                                DesignerID        = designerID[random.Next(designerCount)],
                                SalesAsscociateID = salesAssociateID[random.Next(salesAssociateCount)],
                                ProjectID         = projectID[random.Next(ProjectCount)],
                                BidStatusID       = bidStatusID[random.Next(bidStatusCount)],
                            };


                            a.Approval.ClientStatusID   = approvalStatusID[random.Next(approvalStatusID.Count())];
                            a.Approval.DesignerStatusID = approvalStatusID[random.Next(approvalStatusID.Count())];
                            try
                            {
                                if (a.Approval.ClientStatusID == context.ApprovalStatuses.SingleOrDefault(p => p.Name == "Approved").ID&& a.Approval.DesignerStatusID == context.ApprovalStatuses.SingleOrDefault(p => p.Name == "Approved").ID)
                                {
                                    a.IsFinal = true;
                                }

                                context.Add(a);
                                context.SaveChanges();
                            }
                            catch
                            {
                                // dod nothing repeat
                            }
                        }
                    }
                    context.SaveChanges();
                }



                int[] bidID     = context.Bids.Select(s => s.ID).ToArray();
                int[] productID = context.Products.Select(p => p.ID).ToArray();

                //Bid Products
                if (!context.BidProducts.Any())
                {
                    // loop over bid

                    foreach (int i in bidID)
                    {
                        int breaker = random.Next(productID.Count());
                        // loop over products
                        foreach (var j in productID)
                        {
                            if (j == breaker)
                            {
                                break;
                            }
                            BidProduct bidProduct = new BidProduct()
                            {
                                BidID     = i,
                                Quantity  = random.Next(1, 100),
                                ProductID = j
                            };

                            try
                            {
                                context.Add(bidProduct);
                                context.SaveChanges();
                            }
                            catch
                            {
                                // do nothing
                            }
                        }
                    }
                }

                if (!context.BidLabours.Any())
                {
                    // loop over bid

                    foreach (int i in bidID)
                    {
                        int breaker = random.Next(productID.Count());

                        // loop over role
                        foreach (var j in roleID)
                        {
                            if (j == breaker)
                            {
                                break;
                            }

                            BidLabour bidLabour = new BidLabour()
                            {
                                BidID  = i,
                                Hours  = random.Next(1, 8),
                                RoleID = j
                            };

                            try
                            {
                                context.Add(bidLabour);
                                context.SaveChanges();
                            }
                            catch
                            {
                                // do nothing
                            }
                        }
                    }
                }


                Thread.Sleep(2000);
                //loop over bids
                if (context.Bids.Where(p => p.EstAmount == 0).Any())
                {
                    var allBids = context.Bids.ToList();

                    //Loop over bids
                    foreach (var i in allBids)
                    {
                        var    allBidProducts = context.BidProducts.Where(p => p.BidID == i.ID);
                        var    allBidLabour   = context.BidLabours.Where(p => p.BidID == i.ID);
                        double total          = 0;

                        // loop over bid products
                        foreach (var j in allBidProducts)
                        {
                            // Add bid price * qnty to total
                            total += j.Product.Price * j.Quantity;
                        }

                        foreach (var j in allBidLabour)
                        {
                            total += (double)j.Role.LabourPricePerHr * j.Hours;
                        }

                        context.Bids.SingleOrDefault(p => p.ID == i.ID).EstAmount = total;

                        try
                        {
                            context.SaveChangesAsync();
                        }
                        catch
                        {
                            // do nothing
                        }
                    }
                }
            }
        }
Example #26
0
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new OasisContext(
                       serviceProvider.GetRequiredService <DbContextOptions <OasisContext> >()))
            {
                Random   random         = new Random();
                string[] approvalStatus = new string[] { "Approved", "Disapproved", "RequiresApproval" };
                string[] bidStatus      = new string[] { "In Progress", "Stoped Due To Weather", "Completed", "Not Started", "Waiting approval", "Design stage", "Approved by client", "Approved by NBD", "Needs revision", };
                string[] productTypes   = new string[] { "Plant Inventory", "Pottery Inventory", "Materials Inventory" };
                string[] _firstName     = new string[] { "Adam", "Alex", "Aaron", "Ben", "Carl", "Dan", "David", "Edward", "Fred", "Frank", "George", "Hal", "Hank", "Ike", "John", "Jack", "Joe", "Larry", "Monte", "Matthew", "Mark", "Nathan", "Otto", "Paul", "Peter", "Roger", "Roger", "Steve", "Thomas", "Tim", "Ty", "Victor", "Walter" };
                string[] _lastName      = new string[] { "Anderson", "Ashwoon", "Aikin", "Bateman", "Bongard", "Bowers", "Boyd", "Cannon", "Cast", "Deitz", "Dewalt", "Ebner", "Frick", "Hancock", "Haworth", "Hesch", "Hoffman", "Kassing", "Knutson", "Lawless", "Lawicki", "Mccord", "McCormack", "Miller", "Myers", "Nugent", "Ortiz", "Orwig", "Ory", "Paiser", "Pak", "Pettigrew", "Quinn", "Quizoz", "Ramachandran", "Resnick", "Sagar", "Schickowski", "Schiebel", "Sellon", "Severson", "Shaffer", "Solberg", "Soloman", "Sonderling", "Soukup", "Soulis", "Stahl", "Sweeney", "Tandy", "Trebil", "Trusela", "Trussel", "Turco", "Uddin", "Uflan", "Ulrich", "Upson", "Vader", "Vail", "Valente", "Van Zandt", "Vanderpoel", "Ventotla", "Vogal", "Wagle", "Wagner", "Wakefield", "Weinstein", "Weiss", "Woo", "Yang", "Yates", "Yocum", "Zeaser", "Zeller", "Ziegler", "Bauer", "Baxster", "Casal", "Cataldi", "Caswell", "Celedon", "Chambers", "Chapman", "Christensen", "Darnell", "Davidson", "Davis", "DeLorenzo", "Dinkins", "Doran", "Dugelman", "Dugan", "Duffman", "Eastman", "Ferro", "Ferry", "Fletcher", "Fietzer", "Hylan", "Hydinger", "Illingsworth", "Ingram", "Irwin", "Jagtap", "Jenson", "Johnson", "Johnsen", "Jones", "Jurgenson", "Kalleg", "Kaskel", "Keller", "Leisinger", "LePage", "Lewis", "Linde", "Lulloff", "Maki", "Martin", "McGinnis", "Mills", "Moody", "Moore", "Napier", "Nelson", "Norquist", "Nuttle", "Olson", "Ostrander", "Reamer", "Reardon", "Reyes", "Rice", "Ripka", "Roberts", "Rogers", "Root", "Sandstrom", "Sawyer", "Schlicht", "Schmitt", "Schwager", "Schutz", "Schuster", "Tapia", "Thompson", "Tiernan", "Tisler" };
                string[] countryList    = new string[] { "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas (the)", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia (Plurinational State of)", "Bonaire, Sint Eustatius and Saba", "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory (the)", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cabo Verde", "Cambodia", "Cameroon", "Canada", "Cayman Islands (the)", "Central African Republic (the)", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands (the)", "Colombia", "Comoros (the)", "Congo (the Democratic Republic of the)", "Congo (the)", "Cook Islands (the)", "Costa Rica", "Croatia", "Cuba", "Curaçao", "Cyprus", "Czechia", "Côte d'Ivoire", "Denmark", "Djibouti", "Dominica", "Dominican Republic (the)", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Eswatini", "Ethiopia", "Falkland Islands (the) [Malvinas]", "Faroe Islands (the)", "Fiji", "Finland", "France", "French Guiana", "French Polynesia", "French Southern Territories (the)", "Gabon", "Gambia (the)", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guernsey", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard Island and McDonald Islands", "Holy See (the)", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran (Islamic Republic of)", "Iraq", "Ireland", "Isle of Man", "Israel", "Italy", "Jamaica", "Japan", "Jersey", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea (the Democratic People's Republic of)", "Korea (the Republic of)", "Kuwait", "Kyrgyzstan", "Lao People's Democratic Republic (the)", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", "Macao", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands (the)", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia (Federated States of)", "Moldova (the Republic of)", "Monaco", "Mongolia", "Montenegro", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands (the)", "New Caledonia", "New Zealand", "Nicaragua", "Niger (the)", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands (the)", "Norway", "Oman", "Pakistan", "Palau", "Palestine, State of", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines (the)", "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Republic of North Macedonia", "Romania", "Russian Federation (the)", "Rwanda", "Réunion", "Saint Barthélemy", "Saint Helena, Ascension and Tristan da Cunha", "Saint Kitts and Nevis", "Saint Lucia", "Saint Martin (French part)", "Saint Pierre and Miquelon", "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Serbia", "Seychelles", "Sierra Leone", "Singapore", "Sint Maarten (Dutch part)", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Sudan", "Spain", "Sri Lanka", "Sudan (the)", "Suriname", "Svalbard and Jan Mayen", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan", "Tajikistan", "Tanzania, United Republic of", "Thailand", "Timor-Leste", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands (the)", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates (the)", "United Kingdom of Great Britain and Northern Ireland (the)", "United States Minor Outlying Islands (the)", "United States of America (the)", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela (Bolivarian Republic of)", "Viet Nam", "Virgin Islands (British)", "Virgin Islands (U.S.)", "Wallis and Futuna", "Western Sahara", "Yemen", "Zambia", "Zimbabwe", "Åland Islands" };
                string[] streetNumber   = new string[] { "25489", "87459", "35478", "15975", "95125", "78965" };
                string[] CompanyName    = new string[] { "Media", "Inc", "Builders", "Shop", "Demolishers", "Styles" };
                string[] position       = new string[] { "CEO", "Manager", "Employee", "Supervisor", "CTO" };
                string[] streetName     = new string[] { "A street", "B street", "C street", "D street", "E street", "F street" };
                string[] cityName       = new string[] { "Riyadh", "Damman", "Jedda", "Tabouk", "Makka", "Maddena", "Haiel" };
                string[] stateName      = new string[] { "Qassem State", "North State", "East State", "South State", "West State" };
                string[] zipCode        = new string[] { "28889", "96459", "35748", "15005", "99625", "71465" };

                if (!context.Roles.Any())
                {
                    context.Roles.AddRange(

                        new Role
                    {
                        Name             = "Designer",
                        LabourCostPerHr  = Convert.ToDecimal(40.0),
                        LabourPricePerHr = Convert.ToDecimal(65.0)
                    },
                        new Role
                    {
                        Name             = "Botanist",
                        LabourCostPerHr  = Convert.ToDecimal(50.0),
                        LabourPricePerHr = Convert.ToDecimal(75.0)
                    },
                        new Role
                    {
                        Name             = "Sales Associate",
                        LabourCostPerHr  = Convert.ToDecimal(50.0),
                        LabourPricePerHr = Convert.ToDecimal(75.0)
                    },
                        new Role
                    {
                        Name             = "Management",
                        LabourCostPerHr  = Convert.ToDecimal(100.0),
                        LabourPricePerHr = Convert.ToDecimal(175.0)
                    },
                        new Role
                    {
                        Name             = "Production Worker",
                        LabourCostPerHr  = Convert.ToDecimal(20.0),
                        LabourPricePerHr = Convert.ToDecimal(55.0)
                    }
                        );
                    context.SaveChanges();
                }

                if (!context.Employees.Any())
                {
                    context.Employees.AddRange(
                        new Employee
                    {
                        FirstName      = "Keri",
                        LastName       = "Yamaguchi",
                        AddressLineOne = streetNumber[random.Next(streetNumber.Count())] + " " + streetName[random.Next(streetName.Count())],
                        City           = cityName[random.Next(cityName.Count())],
                        Province       = stateName[random.Next(stateName.Count())],
                        Country        = countryList[random.Next(countryList.Count())],
                        Phone          = 1234567890,
                        Email          = "*****@*****.**",
                        IsUser         = true,
                        RoleID         = context.Roles.FirstOrDefault(p => p.Name == "Management").ID
                    },
                        new Employee
                    {
                        FirstName      = "Stan",
                        LastName       = "Fenton",
                        AddressLineOne = streetNumber[random.Next(streetNumber.Count())] + " " + streetName[random.Next(streetName.Count())],
                        City           = cityName[random.Next(cityName.Count())],
                        Province       = stateName[random.Next(stateName.Count())],
                        Country        = countryList[random.Next(countryList.Count())],
                        Phone          = 1234567890,
                        Email          = "*****@*****.**",
                        IsUser         = true,
                        RoleID         = context.Roles.FirstOrDefault(p => p.Name == "Management").ID
                    },
                        new Employee
                    {
                        FirstName      = "Cheryl",
                        LastName       = "Poy",
                        AddressLineOne = streetNumber[random.Next(streetNumber.Count())] + " " + streetName[random.Next(streetName.Count())],
                        City           = cityName[random.Next(cityName.Count())],
                        Province       = stateName[random.Next(stateName.Count())],
                        Country        = countryList[random.Next(countryList.Count())],
                        Phone          = 1234567890,
                        Email          = "*****@*****.**",
                        IsUser         = true,
                        RoleID         = context.Roles.FirstOrDefault(p => p.Name == "Management").ID
                    },
                        new Employee
                    {
                        FirstName      = "Sue",
                        LastName       = "Kaufman",
                        AddressLineOne = streetNumber[random.Next(streetNumber.Count())] + " " + streetName[random.Next(streetName.Count())],
                        City           = cityName[random.Next(cityName.Count())],
                        Province       = stateName[random.Next(stateName.Count())],
                        Country        = countryList[random.Next(countryList.Count())],
                        Phone          = 1234567890,
                        Email          = "*****@*****.**",
                        IsUser         = true,
                        RoleID         = context.Roles.FirstOrDefault(p => p.Name == "Management").ID
                    },
                        new Employee
                    {
                        FirstName      = "Bob",
                        LastName       = "Reinhardt",
                        AddressLineOne = streetNumber[random.Next(streetNumber.Count())] + " " + streetName[random.Next(streetName.Count())],
                        City           = cityName[random.Next(cityName.Count())],
                        Province       = stateName[random.Next(stateName.Count())],
                        Country        = countryList[random.Next(countryList.Count())],
                        Phone          = 1234567890,
                        Email          = "*****@*****.**",
                        IsUser         = true,
                        RoleID         = context.Roles.FirstOrDefault(p => p.Name == "Sales Associate").ID
                    },
                        new Employee
                    {
                        FirstName      = "Tamara",
                        LastName       = "Bakken",
                        AddressLineOne = streetNumber[random.Next(streetNumber.Count())] + " " + streetName[random.Next(streetName.Count())],
                        City           = cityName[random.Next(cityName.Count())],
                        Province       = stateName[random.Next(stateName.Count())],
                        Country        = countryList[random.Next(countryList.Count())],
                        Phone          = 1234567890,
                        Email          = "*****@*****.**",
                        IsUser         = true,
                        RoleID         = context.Roles.FirstOrDefault(p => p.Name == "Designer").ID
                    },
                        new Employee
                    {
                        FirstName      = "Monica",
                        LastName       = "goce",
                        AddressLineOne = streetNumber[random.Next(streetNumber.Count())] + " " + streetName[random.Next(streetName.Count())],
                        City           = cityName[random.Next(cityName.Count())],
                        Province       = stateName[random.Next(stateName.Count())],
                        Country        = countryList[random.Next(countryList.Count())],
                        Phone          = 1234567890,
                        Email          = "*****@*****.**",
                        RoleID         = context.Roles.FirstOrDefault(p => p.Name == "Production Worker").ID
                    },
                        new Employee
                    {
                        FirstName      = "Bert",
                        LastName       = "Swenson ",
                        AddressLineOne = streetNumber[random.Next(streetNumber.Count())] + " " + streetName[random.Next(streetName.Count())],
                        City           = cityName[random.Next(cityName.Count())],
                        Province       = stateName[random.Next(stateName.Count())],
                        Country        = countryList[random.Next(countryList.Count())],
                        Phone          = 1234567890,
                        Email          = "*****@*****.**",
                        RoleID         = context.Roles.FirstOrDefault(p => p.Name == "Production Worker").ID
                    },
                        new Employee
                    {
                        FirstName      = "Connie",
                        LastName       = "Nguyen",
                        AddressLineOne = streetNumber[random.Next(streetNumber.Count())] + " " + streetName[random.Next(streetName.Count())],
                        City           = cityName[random.Next(cityName.Count())],
                        Province       = stateName[random.Next(stateName.Count())],
                        Country        = countryList[random.Next(countryList.Count())],
                        Phone          = 1234567890,
                        IsUser         = true,
                        Email          = "*****@*****.**",
                        RoleID         = context.Roles.FirstOrDefault(p => p.Name == "Botanist").ID
                    });

                    context.SaveChanges();
                }



                if (!context.ApprovalStatuses.Any())
                {
                    foreach (string i in approvalStatus)
                    {
                        ApprovalStatus a = new ApprovalStatus()
                        {
                            Name = i
                        };
                        context.Add(a);
                        context.SaveChanges();
                    }
                }


                if (!context.ProductTypes.Any())
                {
                    foreach (string i in productTypes)
                    {
                        ProductType a = new ProductType()
                        {
                            Name = i
                        };
                        context.Add(a);
                    }
                    context.SaveChanges();
                }

                if (!context.Products.Any())
                {
                    context.Products.AddRange(
                        new Product
                    {
                        Code          = "Lacco",
                        Description   = "Lacco Australasica",
                        size          = "15 Gal",
                        Price         = 450.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Plant Inventory").ID
                    },
                        new Product
                    {
                        Code          = "Cham",
                        Description   = "Chamaedorea",
                        size          = "15 Gal",
                        Price         = 499.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Plant Inventory").ID
                    },
                        new Product
                    {
                        Code          = "Cera",
                        Description   = "Ceratozamia molongo",
                        size          = "14 in",
                        Price         = 400.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Plant Inventory").ID
                    },
                        new Product
                    {
                        Code          = "Areca",
                        Description   = "arecastum coco",
                        size          = "15 gal",
                        Price         = 458.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Plant Inventory").ID
                    },
                        new Product
                    {
                        Code          = "Cary",
                        Description   = "caryota mitius",
                        size          = "15 gal",
                        Price         = 154.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Plant Inventory").ID
                    },
                        new Product
                    {
                        Code          = "Margi",
                        Description   = "marginata",
                        size          = "2 gal",
                        Price         = 75.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Plant Inventory").ID
                    },
                        new Product
                    {
                        Code          = "TCP50",
                        Description   = "t/c Pot",
                        size          = "50 Gal",
                        Price         = 110.95,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Pottery Inventory").ID
                    },
                        new Product
                    {
                        Code          = "GP50",
                        Description   = "Granite pot",
                        size          = "50 Gal",
                        Price         = 195.95,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Pottery Inventory").ID
                    },
                        new Product
                    {
                        Code          = "TCF03",
                        Description   = "t/c figurine-swan",
                        size          = "",
                        Price         = 45.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Pottery Inventory").ID
                    },
                        new Product
                    {
                        Code          = "MBBB30",
                        Description   = "Marble bird bath",
                        size          = "30 in",
                        Price         = 250.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Pottery Inventory").ID
                    },
                        new Product
                    {
                        Code          = "GFN48",
                        Description   = "Granite Fountain",
                        size          = "48 in",
                        Price         = 750.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Pottery Inventory").ID
                    },
                        new Product
                    {
                        Code          = "CBRK5",
                        Description   = "Decorative Cedar Bark",
                        size          = "bag(5 cu Ft)",
                        Price         = 15.95,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Materials Inventory").ID
                    },
                        new Product
                    {
                        Code          = "CRGRN",
                        Description   = "Crushed granite",
                        size          = "Yard",
                        Price         = 14.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Materials Inventory").ID
                    },
                        new Product
                    {
                        Code          = "PGRV",
                        Description   = "Pea gravel",
                        size          = "Yard",
                        Price         = 20.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Materials Inventory").ID
                    },
                        new Product
                    {
                        Code          = "GRVI",
                        Description   = "1 Gravel",
                        size          = "Yard",
                        Price         = 12.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Materials Inventory").ID
                    },
                        new Product
                    {
                        Code          = "TSOIL",
                        Description   = "Top soil",
                        size          = "Yard",
                        Price         = 20.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Materials Inventory").ID
                    },
                        new Product
                    {
                        Code          = "PBLKG",
                        Description   = "Patio block-gray",
                        size          = "each",
                        Price         = 0.84,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Materials Inventory").ID
                    },
                        new Product
                    {
                        Code          = "PBLKR",
                        Description   = "Patio block-red",
                        size          = "each",
                        Price         = 0.84,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Materials Inventory").ID
                    },


                        new Product
                    {
                        Code          = "Arenga",
                        Description   = "Arenga Pinnata",
                        size          = "15 Gal",
                        Price         = 516.00,
                        ProductTypeID = context.ProductTypes.SingleOrDefault(p => p.Name == "Plant Inventory").ID
                    });
                    context.SaveChanges();
                }

                if (!context.BidStatuses.Any())
                {
                    foreach (string i in bidStatus)
                    {
                        BidStatus a = new BidStatus()
                        {
                            Name = i
                        };
                        context.Add(a);
                    }
                    context.SaveChanges();
                }
            }
        }
Example #27
0
        private void timerBid_Tick(object sender, EventArgs e)
        {
            //Stopwatch sw = new Stopwatch();
            //sw.Start();
            int price = 0;
            int time  = 0;

            var stime = Screen.GetTime(mInitPosition.X + mTimeOffsetX, mInitPosition.Y + mTimeOffsetY, 85, 17);
            var bid   = Screen.GetBid(mInitPosition.X + mPriceOffsetX, mInitPosition.Y + mPriceOffsetY, 55, 17);

            //Console.WriteLine("BID:" + bid + " TIME:" + stime);

            Int32.TryParse(bid, out price);
            Int32.TryParse(stime.Replace(":", ""), out time);

            if (mScreenPrice != price)
            {
                mScreenPrice = price;
            }

            if (mScreenTime != time)
            {
                mScreenTime = time;
                if (mScreenTime >= 112948 && mPriceTime1 == 0)
                {
                    mPriceTime1      = mScreenPrice;
                    textBoxLog.Text += "采样1:" + stime + " 价格:" + mScreenPrice + "\r\n";
                }

                if (mScreenTime >= 112951 && mPriceTime2 == 0)
                {
                    mPriceTime2      = mScreenPrice;
                    textBoxLog.Text += "采样2:" + stime + " 价格:" + mScreenPrice + "\r\n";
                    if (mPriceTime2 - mPriceTime1 > 100)
                    {
                        textBoxLog.Text += "服务器响应慢\r\n";
                    }
                    else
                    {
                        textBoxLog.Text += "服务器响应快\r\n";
                    }
                }

                if (mScreenTime < 113001)
                {
                    textBoxLog.Text += "时间:" + stime + " 价格:" + bid + "\r\n";
                }
                else
                {
                    mBidStatus = BidStatus.END;
                }
            }

            switch (mBidStatus)
            {
            case BidStatus.IDLE1:
                if (mScreenTime >= mSettingBidTime1)
                {
                    mBidStatus = BidStatus.PRICE1;
                }
                break;

            case BidStatus.IDLE2:
                if (mScreenTime > mSettingBidEnd)
                {
                    Console.WriteLine("END");
                    mBidStatus = BidStatus.END;
                }
                else if (mScreenTime >= mSettingBidTime2)
                {
                    Console.WriteLine("PRICE2");
                    mBidStatus = BidStatus.PRICE2;
                }
                break;

            case BidStatus.PRICE1:
                mBidPrice1 = price + mPriceTable[mScreenTime];
                InputPrice(mBidPrice1);
                mBidStatus  = BidStatus.BID1;
                mCapInputed = false;
                break;

            case BidStatus.BID1:
                if (mBidPrice1 <= mScreenPrice + 300 + mSettingEarlyBid)
                {
                    textBoxLog.Text += "到达出价区间\r\n";
                    mBidStatus       = BidStatus.BIDC1;
                }
                else if (Settings.ScreenTime)
                {
                    if (mScreenTime >= mSettingBidEnd)
                    {
                        textBoxLog.Text += "强制出价:屏幕时间\r\n";
                        mBidStatus       = BidStatus.BIDC1;
                    }
                }
                else
                {
                    double localTime = double.Parse(DateTime.Now.ToString("HHmmss.f"));
                    Console.WriteLine("Local Time: {0}", localTime);
                    if (localTime >= mSettingBidEnd)
                    {
                        textBoxLog.Text += "强制出价:本地时间\r\n";
                        mBidStatus       = BidStatus.BIDC1;
                    }
                }
                break;

            case BidStatus.PRICE2:
                mBidPrice2 = price + mPriceTable[mScreenTime];
                InputPrice(mBidPrice2);
                mBidStatus  = BidStatus.BID2;
                mCapInputed = false;
                break;

            case BidStatus.BID2:
                if (mBidPrice2 <= mScreenPrice + 300 + mSettingEarlyBid)
                {
                    textBoxLog.Text += "到达出价区间\r\n";
                    mBidStatus       = BidStatus.BIDC2;
                }
                else if (Settings.ScreenTime)
                {
                    if (mScreenTime >= mSettingBidEnd)
                    {
                        textBoxLog.Text += "强制出价:屏幕时间\r\n";
                        mBidStatus       = BidStatus.BIDC2;
                    }
                }
                else
                {
                    double localTime = double.Parse(DateTime.Now.ToString("HHmmss.f"));
                    Console.WriteLine("Local Time: {0}", localTime);
                    if (localTime >= mSettingBidEnd)
                    {
                        textBoxLog.Text += "强制出价:本地时间\r\n";
                        mBidStatus       = BidStatus.BIDC2;
                    }
                }
                break;

            case BidStatus.BIDC1:
                Point p = new Point(mInitPosition.X + 528, mInitPosition.Y + 327);
                if (mCapInputed)
                {
                    Console.WriteLine("WAIT1");
                    Mouse.MouseClick(p);
                    mCapInputed = false;
                    mBidStatus  = BidStatus.WAIT1;
                }
                break;

            case BidStatus.BIDC2:
                p = new Point(mInitPosition.X + 528, mInitPosition.Y + 327);
                if (mCapInputed)
                {
                    Console.WriteLine("WAIT2");
                    Mouse.MouseClick(p);
                    mCapInputed = false;
                    mBidStatus  = BidStatus.WAIT2;
                }
                break;

            case BidStatus.WAIT1:
                Point p1 = new Point(mInitPosition.X + 515, mInitPosition.Y + 315);
                Point p2 = new Point(mInitPosition.X + 585, mInitPosition.Y + 320);
                Point p3 = new Point(mInitPosition.X + 680, mInitPosition.Y + 315);
                Point p4 = new Point(mInitPosition.X + 630, mInitPosition.Y + 315);
                if (ClickButton(p1, p2, p3, p4))
                {
                    Console.WriteLine("IDLE2");
                    mBidStatus = BidStatus.IDLE2;
                }
                break;

            case BidStatus.WAIT2:
                p1 = new Point(mInitPosition.X + 515, mInitPosition.Y + 315);
                p2 = new Point(mInitPosition.X + 585, mInitPosition.Y + 320);
                p3 = new Point(mInitPosition.X + 680, mInitPosition.Y + 315);
                p4 = new Point(mInitPosition.X + 630, mInitPosition.Y + 315);
                if (ClickButton(p1, p2, p3, p4))
                {
                    Console.WriteLine("END");
                    mBidStatus = BidStatus.END;
                }
                break;

            case BidStatus.END:
                Console.WriteLine("END");
                timerBid.Enabled   = false;
                timerCheck.Enabled = false;
                textBoxLog.Text   += "拍牌结束\r\n";
                Screen.SaveScreen(mInitPosition.X, mInitPosition.Y, 850, 600);
                string startPath = "debug";

                FileStream fs   = new FileStream("debug\\log.txt", FileMode.Create);
                byte[]     data = System.Text.Encoding.Default.GetBytes(textBoxLog.Text);
                fs.Write(data, 0, data.Length);
                fs.Flush();
                fs.Close();

                DateTime now     = DateTime.Now;
                string   zipPath = "bid" + now.ToString("_yyyy_MMdd_HHmmss") + ".zip";
                ZipFile.CreateFromDirectory(startPath, zipPath);
                Directory.Delete(startPath, true);
                break;
            }

            if (mHandle != GetForegroundWindow())
            {
                SetForegroundWindow(mHandle);
            }
            textBoxCap.Focus();
            //sw.Stop();
            //Console.WriteLine("Run (ms):" + +sw.ElapsedMilliseconds);
        }