public void AddFeatured(Building building, List<DateTime> days)
        {
            var tzi = TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time");
            var today = DateTime.UtcNow.AddHours(tzi.GetUtcOffset(DateTime.Now).Hours);

            //make sure the featured days are scheduled to exactly midnight
            //of the day they've been purchased.
            for (int i = 0; i < days.Count; i++)
                days[i] = days[i].Date.AddHours(-tzi.GetUtcOffset(days[i].Date).Hours);

            using (var context = new RentlerContext())
            {
                foreach (var item in days)
                {
                    context.FeaturedListings.Add(new FeaturedListing
                    {
                        BuildingId = building.BuildingId,
                        ScheduledDate = item,
                        Zip = building.Zip
                    });
                }

                context.SaveChanges();
            }
        }
        public static List<Building> ConvertToBuildingsLight(
			IEnumerable<Home> homes, IEnumerable<Classified> classifieds)
        {
            Console.WriteLine("Scribbling down important information from Ksl...");

            var places = (from c in classifieds
                          join h in homes on c.sid equals h.aid
                          where c.status == "a" &&			//available
                                c.market_type == "sale" &&	//we want 'sale' types
                                int.Parse(c.nid) != 526
                          select new
                          {
                              UserId = c.userid,
                              Address1 = c.address1,
                              Address2 = c.address2,
                              City = c.city,
                              State = c.state,
                              Zip = c.zip,
                              Latitude = c.lat,
                              Longitude = c.lon,
                              Title = c.title,
                              Description = c.description,
                              Price = c.price,
                              Acres = GetAcres(h.acres),
                              Sqft = h.sqft,
                              Bedrooms = h.bed,
                              Bathrooms = h.bath,
                              Garage = h.garage,
                              Cooling = h.cooling,
                              Heating = h.heating,
                              sid = c.sid,
                              C = c,
                              H = h
                          }).DistinctBy(a => a.H.aid).ToList();

            Console.WriteLine("Converting scribbles to Rentler Buildings...");
            var buildings = new List<Building>();
            foreach(var item in places)
            {
                var b = new Building()
                {
                    AddressLine1 = item.Address1,
                    AddressLine2 = item.Address2,
                    City = item.City,
                    State = item.State,
                    Zip = item.Zip,
                    CreateDate = DateTime.UtcNow,
                    CreatedBy = "ksl import",
                    Latitude = item.Latitude,
                    Longitude = item.Longitude,
                    sid = item.sid,

                    //add the property info
                    PropertyInfo = new PropertyInfo()
                    {
                        Acres = double.Parse(item.Acres),
                        Bathrooms = (int)double.Parse(item.Bathrooms),
                        Bedrooms = int.Parse(item.Bedrooms),
                        CreateDate = DateTime.UtcNow,
                        CreatedBy = "ksl import",
                        DateAvailableUtc = DateTime.UtcNow,
                        IsAvailable = true,
                        Price = decimal.Parse(item.Price),
                        SquareFootage = (int)double.Parse(item.Sqft),
                        Type = GetPropertyType(int.Parse(item.C.nid))
                    }
                };

                //if there is already a listing with the same
                //address, skip it, it's probably a dupe
                //(people like to post dupes a lot here for some reason).
                if(buildings.Any(bu => bu.AddressLine1.Equals(b.AddressLine1) &&
                    bu.AddressLine2.Equals(b.AddressLine2)))
                {
                    Console.WriteLine("Ignoring duplicate listing: {0}", b.AddressLine1);
                    continue;
                }

                //add the listing
                b.Listings.Add(new Listing()
                {
                    CreateDate = DateTime.UtcNow,
                    CreatedBy = "ksl import",
                    DateListedUtc = DateTime.UtcNow,
                    Description = item.Description.Truncate(4000),
                    IsActive = true
                });

                //rooms!
                for(int i = 0; i < int.Parse(item.Bedrooms); i++)
                {
                    b.PropertyInfo.Rooms.Add(new Room()
                    {
                        CreateDate = DateTime.UtcNow,
                        CreatedBy = "ksl import",
                        FloorName = "Main Floor",
                        Name = "Bedroom"
                    });
                }
                for(int i = 0; i < (int)double.Parse(item.Bathrooms); i++)
                {
                    b.PropertyInfo.Rooms.Add(new Room()
                    {
                        CreateDate = DateTime.UtcNow,
                        CreatedBy = "ksl import",
                        FloorName = "Main Floor",
                        Name = "Bathroom"
                    });
                }

                buildings.Add(b);
            }

            //Remove html formatting from descriptions.
            Console.WriteLine("Removing Html formatting from descriptions...");
            foreach(var b in buildings)
                foreach(var item in b.Listings)
                    item.Description = Regex.Replace(item.Description, "<[^>]*>", string.Empty);

            return buildings;
        }
        /// <summary>
        /// Geocodes the specified full address, using the Google Maps Api.
        /// </summary>
        /// <param name="fullAddress">The full address.</param>
        /// <returns></returns>
        public void Geocode(Building building)
        {
            var fullAddress = string.Format("{0} {1}, {2}, {3} {4}",
                                building.Address1, building.Address2, building.City,
                                building.State, building.Zip);

            fullAddress = HttpUtility.UrlEncode(fullAddress);

            string url = string.Format(
                "http://maps.googleapis.com/maps/api/geocode/xml?address={0}&sensor=false",
                fullAddress);

            WebClient client = new WebClient();
            var result = XElement.Parse(client.DownloadString(url));

            if (result.Element("status").Value == "OK")
            {
                building.Latitude = float.Parse(result.Element("result").Element("geometry").Element("location").Element("lat").Value);
                building.Longitude = float.Parse(result.Element("result").Element("geometry").Element("location").Element("lng").Value);
            }
        }
        /// <summary>
        /// Gets basic building information for use with creating
        /// a new property within the application.
        /// </summary>
        /// <param name="username">The username of the user to generate
        /// property information from.</param>
        /// <returns>
        /// A building with pre-populated information based on the user.
        /// </returns>
        public Status<Building> GetInfoForNewProperty(string username)
        {
            if (string.IsNullOrWhiteSpace(username))
                return Status.ValidationError<Building>(null, "username", "The username is required");

            using (var context = new RentlerContext())
            {
                // get the user contact info
                var user = (from i in context.Users.Include("ContactInfos")
                            where i.Username.ToLower() == username.ToLower() &&
                            !i.IsDeleted
                            select i).FirstOrDefault();

                if (user == null)
                    return Status.NotFound<Building>();

                Building b = new Building();
                b.User = user;
                b.BuildingAmenities = new List<BuildingAmenity>();
                b.CustomAmenities = new List<CustomAmenity>();

                // Give them a contact info to work with
                if (user.ContactInfos.Count < 1)
                    b.ContactInfo = new ContactInfo();
                else
                    b.ContactInfo = user.ContactInfos.First();

                return Status.OK<Building>(b);
            }
        }
        /// <summary>
        /// Creates the building.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="building">The building.</param>
        /// <returns></returns>
        public Status<Building> CreateBuilding(string username, Building building)
        {
            // validate the input
            if (string.IsNullOrWhiteSpace(username))
                return Status.ValidationError<Building>(null, "username", "username is required");
            if (building == null)
                return Status.ValidationError<Building>(null, "building", "building is null");

            // validate the building
            var validation = Status.Validatate<Building>(building);
            if (validation.StatusCode != 200)
                return validation;

            // normalize standard amenities
            if (building.BuildingAmenities != null)
            {
                var amenities = building.BuildingAmenities.Distinct().ToList();
                for (int x = 0; x < amenities.Count; ++x)
                {
                    if (!Amenities.Current.IsValidAmenity(amenities[x].AmenityId))
                    {
                        amenities.RemoveAt(x);
                        --x;
                    }
                }
                building.BuildingAmenities = amenities;
            }

            // normalize custom amenities
            if (building.CustomAmenities != null)
            {
                var custom = building.CustomAmenities.Distinct().ToList();
                // pascal case custom amenities
                for (int x = 0; x < custom.Count; ++x)
                {
                    if (string.IsNullOrEmpty(custom[x].Name))
                    {
                        custom.RemoveAt(x);
                        --x;
                        continue;
                    }
                    custom[x].Name = char.ToUpper(custom[x].Name[0]) + custom[x].Name.Substring(1);
                }
                building.CustomAmenities = custom;
            }

            //get the lat/lng location of the building
            Geocode(building);

            // add it
            using (RentlerContext context = new RentlerContext())
            {
                var user = (from u in context.Users.Include("ContactInfos")
                            where u.Username == username && !u.IsDeleted
                            select u).FirstOrDefault();

                if (user == null)
                    return Status.ValidationError<Building>(null, "username", "User doesn't exist");

                // try to make one
                if (building.ContactInfo == null)
                    return Status.ValidationError<Building>(null, "contactinfo", "No contact information specified");

                // validate the contactinfo
                var contactValidation = Status.Validatate<ContactInfo>(building.ContactInfo);
                if (contactValidation.StatusCode != 200)
                    return Status.ValidationError<Building>(null, "contactinfo", "The contact information is not valid");

                // if the contactinfoid isn't set
                if (building.ContactInfoId == 0)
                {
                    // add it
                    ContactInfo finalContact = building.ContactInfo;
                    user.ContactInfos.Add(finalContact);
                    context.SaveChanges();

                    // add it to the building
                    building.ContactInfoId = finalContact.ContactInfoId;
                }
                else
                {
                    var contact = user.ContactInfos.Where(u => u.ContactInfoId == building.ContactInfoId).FirstOrDefault();
                    if (contact == null)
                        return Status.ValidationError<Building>(null, "contactinfoid", "ContactInfoId is invalid");

                    // update the contact info
                    contact.CompanyName = building.ContactInfo.CompanyName;
                    contact.ContactInfoTypeCode = building.ContactInfo.ContactInfoTypeCode;
                    contact.Email = building.ContactInfo.Email;
                    contact.Name = building.ContactInfo.Name;
                    contact.PhoneNumber = building.ContactInfo.PhoneNumber;
                    contact.ShowEmailAddress = building.ContactInfo.ShowEmailAddress;
                    contact.ShowPhoneNumber = building.ContactInfo.ShowPhoneNumber;
                }

                // don't allow them to pass complex object. We handled it above.
                building.ContactInfo = null;

                // set defaults
                building.CreateDateUtc = DateTime.UtcNow;
                building.CreatedBy = "propertyadapter";
                building.UpdateDateUtc = DateTime.UtcNow;
                building.UpdatedBy = "propertyadapter";

                user.Buildings.Add(building);

                try
                {
                    context.SaveChanges();
                }
                catch (Exception e)
                {
                    // log exception
                    return Status.Error<Building>(
                        "An unexpected error occurred while trying to save the listing information. Contact Rentler support for assistance.",
                        building
                    );
                }

                return Status.OK<Building>(building);
            }
        }
        public Status<Building> CreateProperty(Building building)
        {
            var identity = CustomAuthentication.GetIdentity();

            if (!identity.IsAuthenticated)
                return Status.UnAuthorized<Building>();

            if (building == null)
                return Status.ValidationError<Building>(null, "building", "building is null");

            //get the lat/lng location of the building
            Geocode(building);

            using (RentlerContext context = new RentlerContext())
            {
                try
                {
                    building.UserId = identity.UserId;

                    // set defaults
                    building.CreateDateUtc = DateTime.UtcNow;
                    building.CreatedBy = "propertyadapter.createproperty";

                    context.Buildings.Add(building);
                    context.SaveChanges();

                    return Status.OK<Building>(building);
                }
                catch (Exception ex)
                {
                    // TODO: log exception

                    return Status.Error<Building>("An unexpected error occurred so the property was not created. Contact Rentler Support for assistance.", building);
                }
            }
        }
        /// <summary>
        /// Activates the building.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="building">The building.</param>
        /// <returns></returns>
        private Status<Building> ActivateBuilding(RentlerContext context, Building building)
        {
            if (building == null)
                return Status.NotFound<Building>();

            if (!building.Bedrooms.HasValue)
                return Status.Error("Listing is not complete", building);
            ////confirm this is a valid listing
            //var listing = new Listing(building);
            //if (!listing.IsValidListing)
            //    return Status.Error("Listing is not complete", building);

            // set active
            building.IsActive = true;

            // if date activated is already set, only reset to now if it is more than 14 days old
            if (building.DateActivatedUtc.HasValue)
            {
                if (building.DateActivatedUtc <= DateTime.UtcNow.AddDays(-14))
                    building.DateActivatedUtc = DateTime.UtcNow;
            }
            else
                building.DateActivatedUtc = DateTime.UtcNow;

            try
            {
                context.SaveChanges();

                InvalidateCache(building.BuildingId);

                return Status.OK<Building>(building);
            }
            catch (Exception ex)
            {
                return Status.Error<Building>(ex.Message, building);
            }
        }
        /// <summary>
        /// Deactivates the building.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="building">The building.</param>
        /// <returns></returns>
        private Status<Building> DeactivateBuilding(RentlerContext context, Building building)
        {
            if (building == null)
                return Status.NotFound<Building>();

            building.IsActive = false;

            try
            {
                context.SaveChanges();

                InvalidateCache(building.BuildingId);

                return Status.OK<Building>(building);
            }
            catch (Exception ex)
            {
                return Status.Error<Building>(ex.Message, building);
            }
        }
        /// <summary>
        /// Updates the promotional specific fields on Building
        /// </summary>
        /// <param name="username">owner of the building</param>
        /// <param name="building">the building</param>
        /// <returns>
        /// Status with the updated building
        /// </returns>
        public Status<Building> UpdatePropertyPromotions(string username, Building building,
			string ribbonId, IEnumerable<DateTime> featuredDates, string priorityListing)
        {
            if (building == null)
                return Status.ValidationError<Building>(null, "building", "building is null");

            using (RentlerContext context = new RentlerContext())
            {
                try
                {
                    Building current = (from b in context.Buildings
                                            .Include("User")
                                            .Include("TemporaryOrder")
                                        where b.IsDeleted == false &&
                                        b.BuildingId == building.BuildingId &&
                                        b.User.Username == username
                                        select b).SingleOrDefault();

                    if (current == null)
                        return Status.NotFound<Building>();

                    current.Title = building.Title;
                    current.Description = building.Description;

                    // validate the building
                    var validation = Status.Validatate<Building>(current);
                    if (validation.StatusCode != 200)
                        return validation;

                    // delete any old order
                    if (current.TemporaryOrder != null)
                        context.Orders.Remove(current.TemporaryOrder);

                    // add order with ribbon if items
                    if (!string.IsNullOrWhiteSpace(ribbonId) || featuredDates != null || !string.IsNullOrWhiteSpace(priorityListing))
                    {
                        Order order = new Order();
                        order.UserId = current.UserId;
                        order.BuildingId = current.BuildingId;
                        order.CreateDate = DateTime.UtcNow;
                        order.CreatedBy = "propertyAdapter";
                        order.OrderStatus = OrderStatus.New;

                        //calculate order total here
                        if (!string.IsNullOrWhiteSpace(ribbonId))
                            order.OrderTotal += Configuration.Products.GetProduct("ribbon")
                                .ToOrderItem(ribbonId, 1).Price;

                        if (featuredDates != null)
                            order.OrderTotal += Configuration.Products
                                .GetProduct("featureddate").ToOrderItem(
                                    DateTime.UtcNow.ToString("G"), 1).Price * featuredDates.Count();

                        if (!string.IsNullOrWhiteSpace(priorityListing))
                            order.OrderTotal += Configuration.Products
                                .GetProduct("prioritylisting").ToOrderItem(
                                    DateTime.UtcNow.ToString("G"), 1).Price;

                        context.Orders.Add(order);
                        context.SaveChanges();

                        current.TemporaryOrder = order;
                        current.TemporaryOrderId = order.OrderId;

                        // add ribbon
                        if (!string.IsNullOrWhiteSpace(ribbonId))
                        {
                            var ribbonItem = Configuration.Products.GetProduct("ribbon").ToOrderItem(ribbonId, 1);
                            ribbonItem.OrderId = order.OrderId;
                            context.OrderItems.Add(ribbonItem);
                        }

                        // add featured dates
                        if (featuredDates != null)
                        {
                            for (int i = 0; i < featuredDates.Count(); ++i)
                            {
                                // featured dates come through with no time, we we have to add it
                                DateTime date = featuredDates.ElementAt(i);
                                date = date.Add(DateTime.Now.TimeOfDay);

                                DateTime dateUtc = date.ToUniversalTime();
                                var featuredItem = Configuration.Products.GetProduct("featureddate").ToOrderItem(dateUtc.ToString("G"), 1);
                                featuredItem.OrderId = order.OrderId;
                                context.OrderItems.Add(featuredItem);
                            }
                        }

                        // add priority listing
                        if (!string.IsNullOrWhiteSpace(priorityListing))
                        {
                            var priorityItem =
                                Configuration.Products.GetProduct("prioritylisting")
                                .ToOrderItem(true.ToString(), 1);
                            priorityItem.OrderId = order.OrderId;
                            context.OrderItems.Add(priorityItem);
                        }
                    }

                    context.SaveChanges();

                    InvalidateCache(building.BuildingId);

                    return Status.OK<Building>(current);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    // log exception
                    return Status.Error<Building>(
                        "An unexpected error occurred while trying to save promotions. Contact Rentler support for assistance.",
                        building
                    );
                }
            }
        }
        /// <summary>
        /// Updates the terms specific fields on Building
        /// </summary>
        /// <param name="username">owner of the building</param>
        /// <param name="building">the building</param>
        /// <returns>
        /// Status with the updated building
        /// </returns>
        public Status<Building> UpdatePropertyTerms(string username, Building building)
        {
            if (string.IsNullOrWhiteSpace(username))
                return Status.ValidationError<Building>(null, "username", "username is required");

            if (building == null)
                return Status.ValidationError<Building>(null, "building", "building is null");

            using (RentlerContext context = new RentlerContext())
            {
                try
                {
                    Building current = (from b in context.Buildings.Include("User")
                                        where b.IsDeleted == false &&
                                        b.BuildingId == building.BuildingId &&
                                        b.User.Username == username
                                        select b).SingleOrDefault();

                    if (current == null)
                        return Status.NotFound<Building>();

                    current.IsBackgroundCheckRequired = building.IsBackgroundCheckRequired;
                    current.IsCreditCheckRequired = building.IsCreditCheckRequired;
                    current.Price = building.Price;
                    current.Deposit = building.Deposit;
                    current.RefundableDeposit = building.RefundableDeposit;
                    current.DateAvailableUtc = building.DateAvailableUtc;
                    current.LeaseLengthCode = building.LeaseLengthCode;
                    current.IsSmokingAllowed = building.IsSmokingAllowed;
                    current.ArePetsAllowed = building.ArePetsAllowed;

                    // pets are not allowed so no fee can be charged
                    if (!building.ArePetsAllowed)
                        current.PetFee = decimal.Zero;
                    else
                        current.PetFee = building.PetFee;

                    // validate the building
                    var validation = Status.Validatate<Building>(current);
                    if (validation.StatusCode != 200)
                        return validation;

                    context.SaveChanges();

                    InvalidateCache(building.BuildingId);

                    return Status.OK<Building>(current);
                }
                catch (Exception ex)
                {
                    // log exception
                    return Status.Error<Building>(
                        "An unexpected error occurred while trying to update rental terms. Contact Rentler support for assistance.",
                        building
                    );
                }
            }
        }
        public Status<Building> UpdateProperty(Building building)
        {
            var identity = CustomAuthentication.GetIdentity();

            if (!identity.IsAuthenticated)
                return Status.UnAuthorized<Building>();

            if (building == null)
                return Status.ValidationError<Building>(null, "building", "building is null");

            // address could have changed, if so we need to get new lat lon
            Geocode(building);

            using (RentlerContext context = new RentlerContext())
            {
                try
                {
                    var presentBuilding = (from b in context.Buildings
                                           where b.UserId == identity.UserId &&
                                           b.BuildingId == building.BuildingId
                                           select b).SingleOrDefault();

                    presentBuilding.PropertyTypeCode = building.PropertyTypeCode;
                    presentBuilding.Address1 = building.Address1;
                    presentBuilding.Address2 = building.Address2;
                    presentBuilding.City = building.City;
                    presentBuilding.State = building.State;
                    presentBuilding.Zip = building.Zip;
                    presentBuilding.Latitude = building.Latitude;
                    presentBuilding.Longitude = building.Longitude;

                    presentBuilding.UpdateDateUtc = DateTime.UtcNow;
                    presentBuilding.UpdatedBy = "propertyadapter.updateproperty";

                    context.SaveChanges();
                    InvalidateCache(presentBuilding.BuildingId);

                    return Status.OK<Building>(presentBuilding);
                }
                catch (Exception)
                {
                    // log exception
                    return Status.Error<Building>("An unexpected error occurred so the requested property changes were not completed. Contact Rentler Support for assistance.", building);
                }
            }
        }
        public Status<BuildingPreview> GenerateBuildingPreview(Building building)
        {
            if (building == null)
                return Status.ValidationError<BuildingPreview>(null, "building", "The building cannot be null");

            var preview = new BuildingPreview()
            {
                Address1 = building.Address1,
                Address2 = building.Address2,
                Bathrooms = building.Bathrooms.Value,
                Bedrooms = building.Bedrooms.Value,
                BuildingId = building.BuildingId,
                City = building.City,
                IsActive = building.IsActive,
                IsRemovedByAdmin = building.IsRemovedByAdmin,
                Latitude = building.Latitude,
                Longitude = building.Longitude,
                Price = building.Price,
                PrimaryPhotoExtension = building.PrimaryPhotoExtension,
                PrimaryPhotoId = building.PrimaryPhotoId,
                RibbonId = building.RibbonId,
                State = building.State,
                Title = building.Title,
                Zip = building.Zip
            };

            return Status.OK<BuildingPreview>(preview);
        }
 /// <summary>
 /// Create a new Building object.
 /// </summary>
 /// <param name="buildingId">Initial value of the BuildingId property.</param>
 /// <param name="userId">Initial value of the UserId property.</param>
 /// <param name="address1">Initial value of the Address1 property.</param>
 /// <param name="city">Initial value of the City property.</param>
 /// <param name="state">Initial value of the State property.</param>
 /// <param name="zip">Initial value of the Zip property.</param>
 /// <param name="latitude">Initial value of the Latitude property.</param>
 /// <param name="longitude">Initial value of the Longitude property.</param>
 /// <param name="propertyTypeCode">Initial value of the PropertyTypeCode property.</param>
 /// <param name="price">Initial value of the Price property.</param>
 /// <param name="isActive">Initial value of the IsActive property.</param>
 /// <param name="isCreditCheckRequired">Initial value of the IsCreditCheckRequired property.</param>
 /// <param name="isBackgroundCheckRequired">Initial value of the IsBackgroundCheckRequired property.</param>
 /// <param name="deposit">Initial value of the Deposit property.</param>
 /// <param name="refundableDeposit">Initial value of the RefundableDeposit property.</param>
 /// <param name="leaseLengthCode">Initial value of the LeaseLengthCode property.</param>
 /// <param name="isSmokingAllowed">Initial value of the IsSmokingAllowed property.</param>
 /// <param name="arePetsAllowed">Initial value of the ArePetsAllowed property.</param>
 /// <param name="isRemovedByAdmin">Initial value of the IsRemovedByAdmin property.</param>
 /// <param name="isReported">Initial value of the IsReported property.</param>
 /// <param name="isDeleted">Initial value of the IsDeleted property.</param>
 /// <param name="hasPriority">Initial value of the HasPriority property.</param>
 /// <param name="petFee">Initial value of the PetFee property.</param>
 public static Building CreateBuilding(global::System.Int64 buildingId, global::System.Int32 userId, global::System.String address1, global::System.String city, global::System.String state, global::System.String zip, global::System.Single latitude, global::System.Single longitude, global::System.Int32 propertyTypeCode, global::System.Decimal price, global::System.Boolean isActive, global::System.Boolean isCreditCheckRequired, global::System.Boolean isBackgroundCheckRequired, global::System.Decimal deposit, global::System.Decimal refundableDeposit, global::System.Int32 leaseLengthCode, global::System.Boolean isSmokingAllowed, global::System.Boolean arePetsAllowed, global::System.Boolean isRemovedByAdmin, global::System.Boolean isReported, global::System.Boolean isDeleted, global::System.Boolean hasPriority, global::System.Decimal petFee)
 {
     Building building = new Building();
     building.BuildingId = buildingId;
     building.UserId = userId;
     building.Address1 = address1;
     building.City = city;
     building.State = state;
     building.Zip = zip;
     building.Latitude = latitude;
     building.Longitude = longitude;
     building.PropertyTypeCode = propertyTypeCode;
     building.Price = price;
     building.IsActive = isActive;
     building.IsCreditCheckRequired = isCreditCheckRequired;
     building.IsBackgroundCheckRequired = isBackgroundCheckRequired;
     building.Deposit = deposit;
     building.RefundableDeposit = refundableDeposit;
     building.LeaseLengthCode = leaseLengthCode;
     building.IsSmokingAllowed = isSmokingAllowed;
     building.ArePetsAllowed = arePetsAllowed;
     building.IsRemovedByAdmin = isRemovedByAdmin;
     building.IsReported = isReported;
     building.IsDeleted = isDeleted;
     building.HasPriority = hasPriority;
     building.PetFee = petFee;
     return building;
 }
 /// <summary>
 /// Deprecated Method for adding a new object to the Buildings EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.
 /// </summary>
 public void AddToBuildings(Building building)
 {
     base.AddObject("Buildings", building);
 }
        public static List<Building> ConvertToBuildings(
			IEnumerable<Home> homes, IEnumerable<Classified> classifieds, IEnumerable<HomeCooling> homeCoolings,
			IEnumerable<HomeHeating> homeHeatings, IEnumerable<HomeProperty> homeProperties, IEnumerable<User> users)
        {
            Console.WriteLine("Scribbling down important information from Ksl...");

            var places = (from c in classifieds
                          join h in homes on c.sid equals h.aid
                          where c.status == "a" &&			//available
                                c.market_type == "sale" &&	//we want 'sale' types
                                int.Parse(c.nid) != 526
                          select new
                          {
                              UserId = c.userid,
                              Address1 = c.address1,
                              Address2 = c.address2,
                              City = c.city,
                              State = c.state,
                              Zip = c.zip,
                              Latitude = c.lat,
                              Longitude = c.lon,
                              Title = c.title,
                              Description = c.description,
                              Price = c.price,
                              Acres = GetAcres(h.acres),
                              Sqft = h.sqft,
                              Bedrooms = h.bed,
                              Bathrooms = h.bath,
                              Garage = h.garage,
                              Cooling = h.cooling,
                              Heating = h.heating,
                              sid = c.sid,
                              C = c,
                              H = h
                          }).DistinctBy(a => a.H.aid).ToList();

            Console.WriteLine("Converting scribbles to Rentler Buildings...");
            var buildings = new List<Building>();
            foreach(var item in places)
            {
                var b = new Building()
                {
                    AddressLine1 = item.Address1,
                    AddressLine2 = item.Address2,
                    City = item.City,
                    State = item.State,
                    Zip = item.Zip,
                    CreateDate = DateTime.UtcNow,
                    CreatedBy = "ksl import",
                    Latitude = item.Latitude,
                    Longitude = item.Longitude,
                    sid = item.sid,

                    //add the property info
                    PropertyInfo = new PropertyInfo()
                    {
                        Acres = double.Parse(item.Acres),
                        Bathrooms = (int)double.Parse(item.Bathrooms),
                        Bedrooms = int.Parse(item.Bedrooms),
                        CreateDate = DateTime.UtcNow,
                        CreatedBy = "ksl import",
                        DateAvailableUtc = DateTime.UtcNow,
                        IsAvailable = true,
                        Price = decimal.Parse(item.Price),
                        SquareFootage = (int)double.Parse(item.Sqft),
                        Type = GetPropertyType(int.Parse(item.C.nid))
                    }
                };

                //if there is already a listing with the same
                //address, skip it, it's probably a dupe
                //(people like to post dupes a lot here for some reason).
                if(buildings.Any(bu => bu.AddressLine1.Equals(b.AddressLine1) &&
                    bu.AddressLine2.Equals(b.AddressLine2)))
                {
                    Console.WriteLine("Ignoring duplicate listing: {0}", b.AddressLine1);
                    continue;
                }

                //add the listing
                b.Listings.Add(new Listing()
                {
                    CreateDate = DateTime.UtcNow,
                    CreatedBy = "ksl import",
                    DateListedUtc = DateTime.UtcNow,
                    Description = item.Description.TruncateElipsed(500),
                    IsActive = true
                });

                ////heating!
                //var heatingAmenity = new Dictionary<int, string>();
                //heatingAmenity[6] = "Other";
                //heatingAmenity[5] = "Hydronic";
                //heatingAmenity[4] = "Steam Radiant";
                //heatingAmenity[3] = "Geothermal";
                //heatingAmenity[2] = "Radiant Heat";
                //heatingAmenity[1] = "Forced Air";
                //heatingAmenity[0] = null;

                //if(heatingAmenity[int.Parse(item.Heating)] != null)
                //    b.PropertyInfo.PropertyInfoAmenitiesWithOptions.Add(new PropertyInfoAmenitiesWithOption()
                //    {
                //        AmenityId = 3,
                //        Option = heatingAmenity[int.Parse(item.Heating)],
                //        CreateDate = DateTime.UtcNow,
                //        CreatedBy = "ksl import"
                //    });

                ////cooling!
                //var coolingAmenity = new Dictionary<int, string>();
                //coolingAmenity[0] = null;
                //coolingAmenity[1] = "Central Air";
                //coolingAmenity[2] = "Evaporative Cooler";
                //coolingAmenity[3] = null;
                //coolingAmenity[4] = null;

                //if(coolingAmenity[int.Parse(item.Cooling)] != null)
                //    b.PropertyInfo.PropertyInfoAmenitiesWithOptions.Add(new PropertyInfoAmenitiesWithOption()
                //    {
                //        AmenityId = 4,
                //        Option = coolingAmenity[int.Parse(item.Cooling)],
                //        CreateDate = DateTime.UtcNow,
                //        CreatedBy = "ksl import"
                //    });

                //todo: garage? Not sure I can translate this one.

                //rooms!
                for(int i = 0; i < int.Parse(item.Bedrooms); i++)
                {
                    b.PropertyInfo.Rooms.Add(new Room()
                    {
                        CreateDate = DateTime.UtcNow,
                        CreatedBy = "ksl import",
                        FloorName = "Main Floor",
                        Name = "Bedroom"
                    });
                }
                for(int i = 0; i < (int)double.Parse(item.Bathrooms); i++)
                {
                    b.PropertyInfo.Rooms.Add(new Room()
                    {
                        CreateDate = DateTime.UtcNow,
                        CreatedBy = "ksl import",
                        FloorName = "Main Floor",
                        Name = "Bathroom"
                    });
                }

                //attach user
                var user = users.SingleOrDefault(u => u.AffiliateUser.AffiliateUserKey.Equals(item.UserId));
                if(user == null)
                    continue;

                b.UserId = user.UserId;
                buildings.Add(b);
            }

            //Remove html formatting from descriptions.
            Console.WriteLine("Removing Html formatting from descriptions...");
            foreach(var b in buildings)
                foreach(var item in b.Listings)
                    item.Description = Regex.Replace(item.Description, "<[^>]*>", string.Empty);

            return buildings;
        }