public ApartmentHouse GetStateApartmentHouse()
 {
     var apartments = new Apartment[this._mementoApartments.Length];
     for (var i = 0; i < this._mementoApartments.Length; i++)
     {
         apartments[i] = this._mementoApartments[i].GetStateApartment();
     }
     return new ApartmentHouse(this._number, this._adress, apartments);
 }
 public ApartmentMemento(Apartment apartment)
 {
     _number = apartment.Number;
     _owner = apartment.Owner;
     _mementoRooms = new RoomMemento[apartment.Rooms.Count];
     var i = 0;
     foreach (var room in apartment)
     {
         _mementoRooms[i] = room.CreateMemento();
         i++;
     }
 }
    public void loadApartment()
    {
        if (null != Request.QueryString["idEdit"])
        {

            int id = Convert.ToInt16(Request.QueryString["idEdit"]);
            apartment = ApartmentDAO.getApartment(id);
            if (null != apartment)
            {
                text_nameApartment.Value = apartment.nameApartment;
            }
        }
    }
        /// <summary>
        /// Получение списка квартир в базе
        /// </summary>
        public static List<Apartment> GetAll()
        {
            // Преобразование квартир в базе в объекты Apartment
            List<Apartment> apartments = new List<Apartment>();
            using (var entities = BaseApartments.ConnectEntities())
            {
                entities.F_R_Flats.Load();

                using (var progress = new ProgressMeter())
                {
                    progress.SetLimit(entities.F_R_Flats.Local.Count);
                    progress.Start("Считывание квартир из базы...");

                    var flatsLastRev = entities.F_R_Flats.Local.GroupBy(g => g.WORKNAME).Select(f => f.MaxBy(r => r.REVISION)).ToList();
                    foreach (var flatEnt in flatsLastRev)
                    {
                        progress.MeterProgress();

                        Apartment apart = new Apartment(flatEnt);
                        apartments.Add(apart);

                        //Все модули в квартире
                        var fmsLastModRev = flatEnt.F_nn_FlatModules.GroupBy(fm => fm.F_R_Modules.NAME_MODULE)
                                             .Select(m => m.MaxBy(r => r.F_R_Modules.REVISION)).ToList();

                        foreach (var fmEnt in fmsLastModRev)
                        {
                            Module module = new Module(fmEnt, apart);

                            // Елементы в модуле
                            var emsEnt = fmEnt.F_R_Modules.F_nn_Elements_Modules.ToList();
                            foreach (var emEnt in emsEnt)
                            {
                                // Создание элемента из элемента базы базы
                                Element elem = ElementFactory.CreateElementDB(module, emEnt);
                            }
                            // Для дверей определение элемента стены
                            var doors = module.Elements.OfType<DoorElement>();
                            foreach (var door in doors)
                            {
                                door.SearchHostWallDB(fmEnt.F_R_Modules);
                            }
                        }
                    }
                    progress.Stop();
                }
            }
            return apartments;
        }
    protected void addApartment(object sender, EventArgs e)
    {
        string nameApartment = text_nameApartment.Value;
        double priceSale = Double.Parse(text_priceSale.Value);
        double priceRent = Double.Parse(text_priceRent.Value);
        string size = text_size.Value;
        DateTime dateTime = DateTime.Now;
        string dateCreate = dateTime.Day + "/" + dateTime.Month + "/" + dateTime.Year;
        string userCreate = "Nguyen";
        string typeApartment = type.Items[type.SelectedIndex].Value;
        string statusApartment = status.Items[status.SelectedIndex].Value;
        int numberStatus = int.Parse(statusApartment);
        apartment = new Apartment(10, nameApartment, typeApartment, size, priceSale, priceRent, numberStatus, dateCreate, userCreate, "", "");

        apartmentDBO.addAparment(apartment);
        clear();
        loadApartments();
    }
    //根据选择的公寓信息执行删除操作
    protected void Btn_Del_Click(object sender, EventArgs e)
    {
        int    selectCount  = 0;   //要删除的公寓总数
        string apartmentNos = "";  //保存要删除的公寓编号
        string oneapartmentNo;     //保存某行记录的编号

        foreach (GridViewRow gr in GridView1.Rows)
        {
            CheckBox chk = (CheckBox)gr.Cells[0].FindControl("checkBox");
            if (chk.Checked) //如果要删除该公寓
            {
                oneapartmentNo = gr.Cells[1].Text;
                if (0 == selectCount)
                {
                    apartmentNos = "'" + oneapartmentNo + "'";
                }
                else
                {
                    apartmentNos = apartmentNos + ",'" + oneapartmentNo + "'";
                }
                selectCount++;
            }
        }
        if (0 == selectCount) //如果用户没有选择公寓
        {
            Response.Write("<script>alert('对不起,你没有选择公寓!');</script>");
        }
        else
        {
            Apartment apartment = new Apartment();
            bool      result    = apartment.DeleteApartments(apartmentNos);
            if (true == result)
            {
                Response.Write("<script>alert('公寓信息删除成功!');location.href='apartmentInfoManage.aspx';</script>");
            }
            else
            {
                Response.Write("<script>alert('" + apartment.ErrMessage + "');</script>");
            }
        }
    }
        public async Task <IActionResult> Post([FromBody] Apartment requestApartment)
        {
            try
            {
                var apartments = await this._apartmentService.GetApartmentsAsync();

                if (apartments.Any(x => x.ApartmentNumber == requestApartment.ApartmentNumber))
                {
                    return(this.BadRequest("Квартира с таким номером уже существует в базе."));
                }

                requestApartment.Id = Guid.NewGuid();
                requestApartment    = await this._apartmentService.CreateApartmentAsync(requestApartment);

                return(this.Created(requestApartment));
            }
            catch (Exception)
            {
                return(this.BadRequest("Произошла непредвиденная ошибка. Пожалуйста обратитесь к администратору."));
            }
        }
        public void AddApartment(Apartment apartment)
        {
            Apartment existingApartment = FindApartment(apartment);

            if (existingApartment == null)
            {
                apartment.Sold = false;
                _apartmentRepository.Add(apartment);
                NewApartments++;
            }
            else
            {
                existingApartment.Price    = apartment.Price;
                existingApartment.Currency = apartment.Currency;
                existingApartment.Notice   = apartment.Notice;
                existingApartment.Sold     = false;

                _apartmentRepository.SetModified(existingApartment);
            }
            _apartmentRepository.SaveChanges();
        }
 public string UpdateApartment(Apartment apart)
 {
     if (apart != null)
     {
         {
             int no            = Convert.ToInt32(apart.Id);
             var apartmentList = db.Apartments.Where(x => x.Id == no).FirstOrDefault();
             apartmentList.ApartmentName = apart.ApartmentName;
             apartmentList.Address       = apart.Address;
             apartmentList.Price         = apart.Price;
             apartmentList.Status        = apart.Status;
             apartmentList.CustomerId    = apart.CustomerId;
             db.SaveChanges();
             return(" Updated");
         }
     }
     else
     {
         return("Invalid ");
     }
 }
Beispiel #10
0
        static void Main()
        {
            RealEstateAgency rea = new RealEstateAgency();

            Asset house           = new House();
            var   housecommission = new HouseCommissionCalculator();

            Asset apartment           = new Apartment();
            var   apartmentcommission = new ApartmentCommissionCalculator();

            Asset singleroom           = new Singleroom();
            var   singleroomcommission = new SingleroomCommissionCalculator();

            Asset field           = new Field();
            var   fieldcommission = new FieldCommissionCalculator();

            rea.CalculatePricefor(house, 130000m, "center", housecommission);
            rea.CalculatePricefor(apartment, 140000m, "periphery", apartmentcommission);
            rea.CalculatePricefor(singleroom, 13000m, "center", singleroomcommission);
            rea.CalculatePricefor(field, 150000m, "center", fieldcommission);
        }
Beispiel #11
0
        public async Task TestDeleteBillWithGoodData()
        {
            ACMDbContext context     = ACMDbContextInMemoryFactory.InitializeContext();
            BillService  billService = new BillService(context);
            Apartment    apartment1  = new Apartment {
                Number = 1
            };
            Bill bill = new Bill {
                Amount = 10, Apartment = apartment1, Text = "beer"
            };
            await context.Apartments.AddAsync(apartment1);

            await context.Bills.AddAsync(bill);

            await context.SaveChangesAsync();

            bool output = await billService.DeleteBill(bill.Id);

            Assert.True(output);
            Assert.Equal(0, context.Bills.Count());
        }
        public async Task <IActionResult> Create([Bind("Name,Description,Price,Id")] Apartment apartment, IFormFile uploadFile)
        {
            if (ModelState.IsValid)
            {
                // upload image
                apartment.MainPhoto = await fileService.UploadFileAsync(uploadFile, serverDirectories : IMAGE_DIRECTORIES);

                if (string.IsNullOrWhiteSpace(apartment.MainPhoto))
                {
                    apartment.MainPhoto = DEFAULT_IMAGE;
                }

                // insert apartment
                await apartmentsRepository.InsertAsync(apartment);

                await unitOfWork.SaveAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(apartment));
        }
Beispiel #13
0
        public async Task <CreateApartmentCommandResult> Handle(CreateApartmentCommand request, CancellationToken cancellationToken)
        {
            try
            {
                Validate(request);
                var apartment = Apartment.New(request.Number, request.Block, FromDwellerDtoList(request.Dwellers));

                uow.ApartmentRepository.Add(apartment);
                await uow.CommitChanges();

                return(new CreateApartmentCommandResult {
                    Success = true, Message = "Apartamento criado com sucesso.", ApartmentId = apartment.Id
                });
            }
            catch (Exception e)
            {
                return(new CreateApartmentCommandResult {
                    Success = false, Message = e.Message
                });
            }
        }
Beispiel #14
0
        public void updatePerson(Person oldPerson, Person newPerson)
        {
            /// <summary>
            /// Updates a person
            /// </summary>
            /// <param name="oldPerson">Person to be updated</param>
            /// <param name="newPerson">Person to replace the old one</param>

            this.repository.update(oldPerson, newPerson);
            if (newPerson.noApartment != oldPerson.noApartment)
            {
                incrementNoResidents(this.repository.read(newPerson.noApartment));
                decrementNoResidents(this.repository.read(oldPerson.noApartment));

                Apartment oldApartment = this.repository.read(oldPerson.noApartment);
                Apartment newApartment = this.repository.read(oldPerson.noApartment);
                String    newOwner     = this.findNewOwner(oldPerson.noApartment, oldPerson);
                newApartment.owner = newOwner;
                this.repository.update(oldApartment, newApartment);
            }
        }
        public void Test1()
        {
            var expectedApartment = new Apartment();

            expectedApartment.Localization = new Location();
            expectedApartment.m2           = 50;
            expectedApartment.name         = "ładna";
            expectedApartment.Typ          = "nowe";


            Home home = new Home();

            home.Localization = new Location();
            home.m2           = 50;
            home.name         = "ładna";
            home.Typ          = "nowe";

            var result = HomeToApartment.ConverToApartment(home);

            result.Should().BeEquivalentTo(expectedApartment);
        }
Beispiel #16
0
        public List <Apartment> GenerateApartments(GenerateApartment generateModel)
        {
            List <Apartment> listApartments = new List <Apartment>();

            for (var i = 1; i <= generateModel.QuantityByFloor; i++)
            {
                Apartment apartment = new Apartment
                {
                    Number    = generateModel.Floor.ToString() + i.ToString(),
                    Floor     = generateModel.Floor.ToString(),
                    Active    = true,
                    TowerId   = generateModel.TowerId,
                    CreatedAt = DateTime.Now
                };
                listApartments.Add(apartment);
            }

            _apartmentRepository.CreateRange(listApartments);

            return(listApartments);
        }
        public async void EditIdsAreDifferent_NotFoundResult()
        {
            // Arrange
            int       id        = 1;
            Apartment apartment = new Apartment {
                Id = 7, Name = "NewApartament"
            };

            Mock <IUnitOfWork> mockIUnitOfWork = new Mock <IUnitOfWork>();

            Mock <IFileService> mockIFileService = new Mock <IFileService>();

            ApartmentsController controller = new ApartmentsController(mockIUnitOfWork.Object, mockIFileService.Object);

            // Act
            IActionResult result = await controller.Edit(id, apartment, null);

            // Assert
            Assert.NotNull(result);
            Assert.IsType <NotFoundResult>(result);
        }
Beispiel #18
0
        public async Task <IActionResult> Edit(int id, [Bind("ID,ApartmentType,ApartmentArea,PropertyArea,CustomerID")] Apartment apartment)
        {
            GetSessionData();
            if (userID == null)
            {
                return(RedirectToAction("Index", "Home"));
            }
            if (id != apartment.ID)
            {
                return(RedirectToAction("Index", "Home"));
            }
            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(apartment);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ApartmentExists(apartment.ID))
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        throw;
                    }
                }

                return(Json(new { status = "OK" }));
            }

            return(Json(new
            {
                status = "FAILED",
                errorMessages = ModelState.Where(x => x.Value.Errors.Count > 0)
                                .ToDictionary(k => k.Key, v => v.Value.Errors[0].ErrorMessage)
            }));
        }
        //===================== Apartments CSV Import=======================
        public async Task <ActionResult> ProcessCsv(EventItem[] model)
        {
            int BuildingID = (int)Session["BuildingID"];

            if (ModelState.IsValid)

            //if(User.Identity.IsAuthenticated)
            {
                {
                    foreach (var item in model)
                    {
                        var apartment = new Apartment
                        {
                            ApartmentNumber = item.AparmentNumber,
                            BuildingID      = BuildingID,
                            FloorNumber     = item.Floor
                        };
                        db.Apartment.Add(apartment);
                        await db.SaveChangesAsync();

                        //======================insert Add Building Activity================
                        var         UserID = User.Identity.GetUserId();                                     // gets logged user ID
                        AspNetUsers myUser = await db.AspNetUsers.FirstOrDefaultAsync(c => c.Id == UserID); // select from db where logged use match

                        var newActivity = new UserActivityLog
                        {
                            BuildingID        = BuildingID,
                            UserID            = "84a4092e-0bcc-4e4f-b007-c87a99eccae3",
                            DateOfEvent       = DateTime.Now,
                            FunctionPerformed = "Added apartment",
                            Message           = "Apartment # " + item.AparmentNumber + " was added by " + myUser.UserName
                        };
                        db.UserActivityLog.Add(newActivity);
                        await db.SaveChangesAsync();
                    }
                }
            }

            return(RedirectToAction("BuildingProfile", "Building"));
        }
Beispiel #20
0
        public async Task <bool> AddApartment(ApartmentAnnounceModel announce)
        {
            try
            {
                DateTime addedDate = DateTime.Now;

                Apartment unicodeAnnounce = await _dbContext.Apartments.FindAsync(_dbContext.Apartments.Max(c => c.Id));

                string unicode = (Int32.Parse(unicodeAnnounce.AnnounceUniqueCode) + 1).ToString();

                Apartment apartment = new Apartment(announce.ApartmentRoomCount, announce.ApartamentLocation, announce.ApartmentArea)
                {
                    AnnounceAddedDate  = addedDate,
                    AnnounceTypeId     = announce.AnnounceTypeId,
                    Price              = announce.Price,
                    CityId             = announce.CityId,
                    Description        = announce.Description,
                    PersonTypeId       = announce.PersonTypeId,
                    Email              = announce.Email,
                    PhoneNumber        = announce.PhoneNumber,
                    ApartmentTypeId    = announce.ApartmentTypeId,
                    AnnounceUniqueCode = unicode,
                    RSAnnounceTypeId   = announce.RSAnnounceTypeId,
                };

                await _dbContext.Apartments.AddAsync(apartment);

                //car files upload start
                AddDataPhoto(announce.Paths, apartment.Id, "lib/images/realestate/apartment", FindTable.Apartment);


                //car files upload end
                await _dbContext.SaveChangesAsync();
            }
            catch (Exception exp)
            {
                throw exp;
            }
            return(true);
        }
Beispiel #21
0
 public async Task TestFinancialSummaryEmptySpendings()
 {
     ACMDbContext context = ACMDbContextInMemoryFactory.InitializeContext();
     SummaryService summaryService = new SummaryService(context);
     Apartment apartment1 = new Apartment { Number = 1 };
     Apartment apartment2 = new Apartment { Number = 2 };
     Apartment apartment3 = new Apartment { Number = 3 };
     Apartment apartment4 = new Apartment { Number = 4 };
     Bill bill1 = new Bill { Amount = 10, Apartment = apartment1, IsPayed = true };
     Bill bill2 = new Bill { Amount = 20, Apartment = apartment2, IsPayed = true };
     Bill bill3 = new Bill { Amount = 30, Apartment = apartment3, IsPayed = false };
     Bill bill4 = new Bill { Amount = 40, Apartment = apartment4, IsPayed = false };
     await context.Apartments.AddAsync(apartment1);
     await context.Apartments.AddAsync(apartment2);
     await context.Apartments.AddAsync(apartment3);
     await context.Apartments.AddAsync(apartment4);
     await context.Bills.AddAsync(bill1);
     await context.Bills.AddAsync(bill2);
     await context.Bills.AddAsync(bill3);
     await context.Bills.AddAsync(bill4);
     await context.SaveChangesAsync();
     FinancialSummaryDTO output = summaryService.FinancialSummary();
     Assert.Equal(2, output.GoodHomeowners.Count);
     Assert.Equal(1, output.GoodHomeowners[0].ApartmentNumber);
     Assert.Equal(0, output.GoodHomeowners[0].Amount);
     Assert.Equal(2, output.GoodHomeowners[1].ApartmentNumber);
     Assert.Equal(0, output.GoodHomeowners[1].Amount);
     Assert.Equal(2, output.BadHomeowners.Count);
     Assert.Equal(3, output.BadHomeowners[1].ApartmentNumber);
     Assert.Equal(30, output.BadHomeowners[1].Amount);
     Assert.Equal(4, output.BadHomeowners[0].ApartmentNumber);
     Assert.Equal(40, output.BadHomeowners[0].Amount);
     Assert.Empty(output.PaidSpendings);
     Assert.Empty(output.UnpaidSpendings);
     Assert.Equal(30, output.Paid);
     Assert.Equal(70, output.ToBePaid);
     Assert.Equal(0, output.Spend);
     Assert.Equal(0, output.ToBeSpend);
     Assert.Equal(100, output.CurrentBalance);
 }
Beispiel #22
0
 public async Task TestFinancialSummaryEmptyBills()
 {
     ACMDbContext context = ACMDbContextInMemoryFactory.InitializeContext();
     SummaryService summaryService = new SummaryService(context);
     Apartment apartment1 = new Apartment { Number = 1 };
     Apartment apartment2 = new Apartment { Number = 2 };
     Apartment apartment3 = new Apartment { Number = 3 };
     Apartment apartment4 = new Apartment { Number = 4 };
     Spending spending1 = new Spending { Amount = 100, Text = "beer1", IsPayed = true };
     Spending spending2 = new Spending { Amount = 200, Text = "beer2", IsPayed = true };
     Spending spending3 = new Spending { Amount = 300, Text = "beer3", IsPayed = false };
     Spending spending4 = new Spending { Amount = 400, Text = "beer4", IsPayed = false };
     await context.Apartments.AddAsync(apartment1);
     await context.Apartments.AddAsync(apartment2);
     await context.Apartments.AddAsync(apartment3);
     await context.Apartments.AddAsync(apartment4);
     await context.Spendings.AddAsync(spending1);
     await context.Spendings.AddAsync(spending2);
     await context.Spendings.AddAsync(spending3);
     await context.Spendings.AddAsync(spending4);
     await context.SaveChangesAsync();
     FinancialSummaryDTO output = summaryService.FinancialSummary();
     Assert.Equal(4, output.GoodHomeowners.Count);
     Assert.Empty(output.BadHomeowners);
     Assert.Equal(2, output.PaidSpendings.Count);
     Assert.Equal(100, output.PaidSpendings[1].Amount);
     Assert.Equal("beer1", output.PaidSpendings[1].Text);
     Assert.Equal(200, output.PaidSpendings[0].Amount);
     Assert.Equal("beer2", output.PaidSpendings[0].Text);
     Assert.Equal(2, output.UnpaidSpendings.Count);
     Assert.Equal(300, output.UnpaidSpendings[1].Amount);
     Assert.Equal("beer3", output.UnpaidSpendings[1].Text);
     Assert.Equal(400, output.UnpaidSpendings[0].Amount);
     Assert.Equal("beer4", output.UnpaidSpendings[0].Text);
     Assert.Equal(0, output.Paid);
     Assert.Equal(0, output.ToBePaid);
     Assert.Equal(300, output.Spend);
     Assert.Equal(700, output.ToBeSpend);
     Assert.Equal(-1000, output.CurrentBalance);
 }
 public ApartmentModel(Apartment apartment, Guid buildingId)
 {
     Number     = apartment.Number;
     OwnerEmail = apartment.OwnerEmail;
     OwnerPhone = apartment.OwnerPhone;
     Cut        = apartment.Cut;
     Id         = apartment.Id;
     BuildingId = buildingId;
     Entrance   = apartment.Entrance;
     if (apartment.FirstName != null && apartment.FirstName.Count > 0)
     {
         FirstName = apartment.FirstName.Last().Value;
     }
     if (apartment.LastName != null && apartment.LastName.Count > 0)
     {
         LastName = apartment.LastName.Last().Value;
     }
     if (apartment.NoOfPersons != null && apartment.NoOfPersons.Count > 0)
     {
         NoOfPersons = byte.Parse(apartment.NoOfPersons.Last().Value);
     }
 }
 public static IEstate CreateEstate(EstateType type)
 {
     IEstate estate = null;
     switch (type)
     {
         case EstateType.Apartment:
             estate = new Apartment();
             break;
         case EstateType.Office:
             estate = new Office();
             break;
         case EstateType.House:
             estate = new House();
             break;
         case EstateType.Garage:
             estate = new Garage();
             break;
         default:
             break;
     }
     return estate;
 }
Beispiel #25
0
        public async Task <Apartment> UpdateApartmentAsync(Guid apartmentId, Apartment modifiedApartment)
        {
            var apartment = await this.Context.Apartments.FirstOrDefaultAsync(x => x.Id == apartmentId);

            if (apartment == null)
            {
                throw new Exception("Apartment not found.");
            }

            apartment.ApartmentNumber = modifiedApartment.ApartmentNumber;
            apartment.FloorNumber     = modifiedApartment.FloorNumber;
            apartment.TotalAreaSnb    = modifiedApartment.TotalAreaSnb;
            apartment.TotalArea       = modifiedApartment.TotalArea;
            apartment.LivingSpace     = modifiedApartment.LivingSpace;
            apartment.VoteRate        = modifiedApartment.VoteRate;
            apartment.RoomsCount      = modifiedApartment.RoomsCount;

            this.Context.Apartments.Update(apartment);
            await this.Context.SaveChangesAsync();

            return(apartment);
        }
        public void AppendElement(Apartment apartment)
        {
            Type fileType = apartment.GetType();

            XmlApartmentReader reader = new XmlApartmentReader(this._filePath);

            _ = reader.Exist(apartment) ? throw new ArgumentException($"The same {fileType.Name} already exists.") : "Create new one";

            XmlElement newElement = this.Xml.CreateElement(string.Empty, fileType.Name, string.Empty);

            _ = this.Xml.DocumentElement?.AppendChild(newElement) ?? throw new ArgumentException("There is no root in xml file");

            foreach (var propertyInfo in fileType.GetProperties())
            {
                XmlElement child     = this.Xml.CreateElement(string.Empty, propertyInfo.Name, string.Empty);
                XmlText    childText = this.Xml.CreateTextNode(propertyInfo.GetValue(apartment).ToString());
                child.AppendChild(childText);
                newElement.AppendChild(child);
            }

            this.Xml.Save(this._filePath);
        }
Beispiel #27
0
        public void addPerson(String forename, String surname, int noApartment, String birthdate, String job)
        {
            /// <summary>
            /// Adds a person
            /// </summary>
            /// <param name="forename">Person's forename</param>
            /// <param name="surname">Person's surname</param>
            /// <param name="noApartment">Person's apartment number</param>
            /// <param name="birthdate">Person's birthdate</param>
            /// <param name="job">Person's job</param>

            Person    person    = new Person(forename, surname, noApartment, birthdate, job);
            Apartment apartment = this.repository.read(noApartment);

            if (apartment.owner.Equals("fara"))
            {
                apartment.owner = person.forename + " " + person.surname;
            }
            apartment.noResidents++;
            this.repository.update(this.repository.read(noApartment), apartment);
            this.repository.create(person);
        }
Beispiel #28
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if ((Session["adminUserName"] == null) && (Session["adminUserRole"] == null))
     {
         Response.Redirect("../error.aspx");
     }
     if (!IsPostBack)
     {
         //初始化公寓编号下拉框的内容
         ListItem li = new ListItem("请选择", "");
         this.apartmentNo.Items.Add(li);
         Apartment apartment = new Apartment();
         DataSet   ds        = apartment.GetAllApartment();
         for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
         {
             DataRow dr = ds.Tables[0].Rows[i];
             li = new ListItem(dr["apartmentNo"].ToString(), dr["apartmentNo"].ToString());
             this.apartmentNo.Items.Add(li);
         }
         GridViewBind();
     }
 }
Beispiel #29
0
        private string GenerateJwtToken(Apartment apartment)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var secret       = Encoding.ASCII.GetBytes(_jwtSettings.Value.Secret);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(
                    new[]
                {
                    new Claim(ClaimTypes.Name, $"{apartment.Name}"),
                    new Claim(ClaimTypes.NameIdentifier, apartment.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(_jwtSettings.Value.ExpireDays),
                SigningCredentials = new SigningCredentials(
                    new SymmetricSecurityKey(secret), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
Beispiel #30
0
        public override void saveEntity()
        {
            if (this.entity == null)
            {
                this.entity = new Apartment();
            }
            this.entity.floorplan_id      = (string)this.comboBox_Floorplan.SelectedValue;
            this.entity.building_id       = (string)this.comboBox_Building.SelectedValue;
            this.entity.colorscheme       = this.textBox_ColorScheme.Text;
            this.entity.lot_number        = this.textBox_LotNumber.Text;
            this.entity.unit_number       = this.textBox_UnitNumber.Text;
            this.entity.car_parking_count = (Int16)this.numericUpDown_CarParking.Value;
            this.entity.storageroom_count = (Int16)this.numericUpDown_StorageRoom.Value;
            this.entity.floor             = (Int16)this.numericUpDown_Floor.Value;
            this.entity.price             = (Int32)this.numericUpDown_Price.Value;
            this.entity.unit_entitle_ment = (Int16)this.numericUpDown_UnitEntitlement.Value;
            this.entity.penthouse         = this.checkBox_Penthouse.Checked;
            this.entity.sold_out          = this.checkBox_SoldOut.Checked;
            this.entity.description       = this.richTextBox_Description.Text;

            this.dao.save(this.entity);
        }
Beispiel #31
0
        public async Task TestGetAppartmentsWithGoodData()
        {
            ACMDbContext     context          = ACMDbContextInMemoryFactory.InitializeContext();
            ApartmentService apartmentService = new ApartmentService(context);
            Apartment        apartment1       = new Apartment {
                Number = 1
            };
            Apartment apartment2 = new Apartment {
                Number = 2
            };
            await context.Apartments.AddAsync(apartment1);

            await context.Apartments.AddAsync(apartment2);

            await context.SaveChangesAsync();

            List <Models.ApartmentListElementDTO> list = apartmentService.GetAppartments();

            Assert.Equal(2, list.Count);
            Assert.Equal("1", list[0].Number);
            Assert.Equal("2", list[1].Number);
        }
        public JsonResult classify_extra_stuff(string address, int month)
        {
            if (month < 1 || month > 12)
            {
                return(Json($"{{\"message\":\"Month should be numerical and between 1 and 12\"}}"));
            }
            Apartment apartment = _context.Apartment.Include(m => m.Companies).FirstOrDefault(x => x.Address.Contains(address));

            InitiallizeTrainData(month);
            Classifier classifier = new Classifier();

            classifier.TrainClassifier(table);
            var name = classifier.Classify(new double[] { apartment.RoomsNumber, month, apartment.Longitude + apartment.Latitude });

            string message;

            message = name.ToLower() == "above" ?
                      "Consider putting more stuff at this area and this month, there should be a lot of Companies" :
                      "Your Stuff is quiet enough! :) No need to get extra.";

            return(Json($"{{\"message\":\"{message}\"}}"));
        }
Beispiel #33
0
        protected override void LoadTestData()
        {
            this.dbApartment = this.Context.Add(new Apartment()
            {
                Title         = "Test Apartment",
                ActivityState = ActivityStates.Inactive
            }).Entity;

            this.Context.AddRange(new[]
            {
                new Amenity()
                {
                    Name = "TV"
                },
                new Amenity()
                {
                    Name = "Kitchen"
                }
            });

            this.Context.SaveChanges();
        }
Beispiel #34
0
        public async Task TestPayBillBadId()
        {
            ACMDbContext context     = ACMDbContextInMemoryFactory.InitializeContext();
            BillService  billService = new BillService(context);
            Apartment    apartment1  = new Apartment {
                Number = 1
            };
            Bill bill1 = new Bill
            {
                Amount    = 10,
                Apartment = apartment1,
                Text      = "beer",
                IsPayed   = false,
            };
            await context.Apartments.AddAsync(apartment1);

            await context.Bills.AddAsync(bill1);

            await context.SaveChangesAsync();

            await Assert.ThrowsAsync <ACMException>(() => billService.PayBill(bill1.Id + "Random string"));
        }
Beispiel #35
0
        public ActionResult ChangeApartment(int apartmentid, int userid)
        {
            ViewBag.basic    = dal.availableamenitiesdb.Where(x => x.type == 1).Where(x => x.IsDeleted == false).Select(x => x.name).ToList();
            ViewBag.family   = dal.availableamenitiesdb.Where(x => x.type == 2).Where(x => x.IsDeleted == false).Select(x => x.name).ToList();
            ViewBag.facility = dal.availableamenitiesdb.Where(x => x.type == 3).Where(x => x.IsDeleted == false).Select(x => x.name).ToList();
            ViewBag.dining   = dal.availableamenitiesdb.Where(x => x.type == 4).Where(x => x.IsDeleted == false).Select(x => x.name).ToList();

            User      u  = dal.usersdb.ToDictionary(x => x.UserId, x => x)[userid];
            Apartment ap = dal.apartmentsdb.ToDictionary(x => x.ApartmentId, x => x)[apartmentid];

            ap.images    = new List <Photo>();
            ap.amenities = new List <Amenity>();


            ap.amenities = dal.amenitiesdb.Where(x => x.ApartmentId == ap.ApartmentId).Where(x => x.IsDeleted == false).Select(x => x).ToList();
            ap.images    = dal.photosdb.Where(x => x.ApartmentId == ap.ApartmentId).Select(x => x).ToList();


            ViewBag.ap = ap;

            return(View());
        }
Beispiel #36
0
        public Apartment AddApartment(Apartment apartment)
        {
            var user = Users.Where(u => u.IsDeleted == false && u.Username == apartment.Host.Username).FirstOrDefault();

            apartment.Host = user as Host;

            ICollection <Amenities> amenities = new List <Amenities>();

            foreach (var item in apartment.Amenities)
            {
                amenities.Add(Amenities.SingleOrDefault(a => item.Id == a.Id));
            }
            apartment.Amenities = amenities;

            Apartments.Add(apartment);
            SaveChanges();
            var apartment1 = Apartments.Where(a => a.Id == apartment.Id).FirstOrDefault();

            apartment1.PicturesLocation += $"{apartment.Id}";
            SaveChanges();
            return(apartment1);
        }
        public static IEstate CreateEstate(EstateType type)
        {
            Estate estate;
            switch (type)
            {
                   case EstateType.Apartment:
                    estate =  new Apartment();
                    break;
                    case EstateType.Garage:
                    estate = new Garage();
                    break;
                    case EstateType.House:
                    estate =  new House();
                    break;
                    case EstateType.Office:
                    estate = new Office();
                    break;
                default:
                    throw new ArgumentException("Invalid type for estste.");
            }

            return estate;
        }
Beispiel #38
0
	public virtual void AddApartment(Apartment ap)
	{
		throw new System.NotImplementedException();
	}
        private static F_R_Flats defineFlatEnt(Apartment apart)
        {
            // Определение квартиры - для новой записи квартиры выполняется привязка модулей.
            F_R_Flats flatEnt = null;
            int revision = 0;
            if (apart.BaseStatus == EnumBaseStatus.Changed)
            {
                // Новая ревизия квартиры
                var lastRevision = entities.F_R_Flats.Local
                                  .Where(f => f.WORKNAME.Equals(apart.Name, StringComparison.OrdinalIgnoreCase))
                                  .Max(r => r.REVISION);
                revision = lastRevision + 1;
            }
            else
            {
                flatEnt = entities.F_R_Flats.Local
                                  .Where(f => f.WORKNAME.Equals(apart.Name, StringComparison.OrdinalIgnoreCase))
                                  .OrderByDescending(r => r.REVISION).FirstOrDefault();
            }

            if (flatEnt == null)
            {
                flatEnt = entities.F_R_Flats.Add(new F_R_Flats() { WORKNAME = apart.Name, COMMERCIAL_NAME = "",
                    REVISION = revision, TYPE_FLAT = apart.TypeFlat });
                // Привязка модулей
                attachModulesToFlat(flatEnt, apart);
            }

            return flatEnt;
        }
 private static void attachModulesToFlat(F_R_Flats flatEnt, Apartment apart)
 {
     foreach (var module in apart.Modules)
     {
         // Модуль
         var moduleEnt = getModuleEnt(module);
         // Квартира-модуль
         var fmEnt = getFMEnt(flatEnt, moduleEnt, module);
     }
 }
    //edit apartment
    protected void editApartment(object sender, EventArgs e)
    {
        if (null != Request.QueryString["idEdit"])
        {

            string nameApartment = text_nameApartment.Value;
            //  Response.Write(nameApartment + "TEST");
            double priceSale = Double.Parse(text_priceSale.Value);
            //  Response.Write(priceSale + "TEST");
            double priceRent = Double.Parse(text_priceRent.Value);
            string size = text_size.Value;
            DateTime dateTime = DateTime.Now;
            string dateUpdate = dateTime.Day + "/" + dateTime.Month + "/" + dateTime.Year;
            string userUpdate = "Nguyen";
            string typeApartment = type.Items[type.SelectedIndex].Value;
            string statusApartment = status.Items[status.SelectedIndex].Value;
            int numberStatus = int.Parse(statusApartment);
            Apartment a = new Apartment(apartment.idApartment, nameApartment, typeApartment, size, priceSale, priceRent, numberStatus, apartment.dateCreate, apartment.userCreate, dateUpdate, userUpdate);
            apartmentDBO.updateApartment(a);
            clear();
            loadApartments();
        }
    }
Beispiel #42
0
        //När användaren trycker på knappen Lägg till
        //Läs all indata från GUI i ett lokalt objekt av fastighet
        //Gör indata kontroll
        //Spara objektet i fastighetMngr
        private void btnAdd_Click(object sender, EventArgs e)
        {
            Estate estate;  //holder for input - create in ReadInput

            //Send this object to ReadInput
            //for filling in values (input)
            //out tells ReadInput that the variable
            //is data out. All changes to this object
            //comes back here.
            //ReadInput creates all data used for the common fields of all estates.
            //The special for each are filled in later in the switch case.
            bool ok = ReadInput(out estate);

            if (ok)  //If all common data (in variable estate) is OK
            {
              // Now create a correct estate according to the type combo
              switch ((EstateType)cmbTyp.SelectedIndex)
              {
                case EstateType.WareHouse:
                  {
                    // Use a copy constructor to set a warehouse with common data
                    WareHouse  wHouse = new WareHouse(estate);
                    // If more data in GUI to fill in for this estate, do it here
                    //Then send it to the manager for adding to the list
                    estateMngr.Add(wHouse);
                    break;
                  }
                case EstateType.Villa:
                  {
                    // Same procedure all different types of estates
                    Villa vHouse = new Villa(estate);
                    // But here we need to add landSize size
                    bool landSizeOk = false;
                    vHouse.LandSize = ReadLandSize(out landSizeOk);
                    if (!landSizeOk)
                      return;
                    estateMngr.Add(vHouse);
                    break;
                  }
                case EstateType.Store:
                  {
                    Store store = new Store(estate);
                    estateMngr.Add(store);
                    break;
                  }
                case EstateType.RowHouse:
                  {
                    RowHouse rHouse = new RowHouse(estate);
                    // Here we need to add landSize size
                    bool gardenok = false;
                    rHouse.LandSize = ReadLandSize(out gardenok);
                    if (!gardenok)
                      return;
                    estateMngr.Add(rHouse);
                    break;
                  }
                case EstateType.Apartment:
                  {
                    Apartment apart = new Apartment(estate);
                    // We need to add floor
                    bool floorok = false;
                    apart.Floor = ReadFloor(out floorok);
                    if (!floorok)
                      return;
                    estateMngr.Add(apart);
                    break;
                  }
              }

              //Then Update the GUI
              UpdateResults();
            }
        }