/// <summary>
 /// Gets all of the user's credit cards on file.
 /// </summary>
 /// <param name="userId">The user's id.</param>
 /// <returns>A lsit of the user's credit cards.</returns>
 public List <UserBank> GetUserBanks(int userId)
 {
     using (var context = new RentlerContext())
         return((from u in context.UserBanks
                 where u.UserId == userId
                 select u).ToList());
 }
 /// <summary>
 /// Get user by username
 /// </summary>
 /// <param name="username">the username</param>
 /// <returns>
 /// Status result with requested user
 /// </returns>
 public Status <User> GetUser(string username)
 {
     using (var context = new RentlerContext())
     {
         return(GetUser(username, context));
     }
 }
 /// <summary>
 /// Get a user's credit card information.
 /// </summary>
 /// <param name="userId">The user's id.</param>
 /// <param name="userCardId">The unique id of the user's credit card info.</param>
 /// <returns>A UserCreditCard.</returns>
 public UserCreditCard GetUserCreditCard(int userId, int userCardId)
 {
     using (var context = new RentlerContext())
         return((from u in context.UserCreditCards
                 where u.UserCreditCardId == userCardId && u.UserId == userId
                 select u).SingleOrDefault());
 }
        public Status <UserInterest> GetUserInterest(string username, int userInterestId)
        {
            if (string.IsNullOrWhiteSpace(username))
            {
                return(Status.ValidationError <UserInterest>(null, "username", "The username is required"));
            }

            using (RentlerContext context = new RentlerContext())
            {
                try
                {
                    var lead = (from i in context.UserInterests.Include("User.UserApplication").Include("Building.User")
                                where i.User.Username == username && i.UserInterestId == userInterestId
                                select i).SingleOrDefault();

                    if (lead == null)
                    {
                        return(Status.NotFound <UserInterest>());
                    }

                    return(Status.OK(lead));
                }
                catch (Exception ex)
                {
                    // log exception
                    return(Status.Error <UserInterest>("System was unable to get lead", null));
                }
            }
        }
 /// <summary>
 ///	Gets all of the user's bank accounts.
 /// </summary>
 /// <param name="userId">The user's id.</param>
 /// <returns>A List of the user's bank accounts.</returns>
 public UserBank GetUserBank(int userId, int userBankId)
 {
     using (var context = new RentlerContext())
         return((from u in context.UserBanks
                 where u.UserBankId == userBankId && u.UserId == userId
                 select u).SingleOrDefault());
 }
        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();
            }
        }
Exemple #7
0
        public Status <BuildingPreview> GetUserProperty(string username, long buildingId)
        {
            BuildingPreview building = null;

            using (var context = new RentlerContext())
                building = (from b in context.Buildings
                            where b.BuildingId == buildingId &&
                            (b.User.Username == username || b.User.Email == username)
                            select new BuildingPreview()
                {
                    Bathrooms = b.Bathrooms.Value,
                    Bedrooms = b.Bedrooms.Value,
                    BuildingId = b.BuildingId,
                    City = b.City,
                    IsFeatured = false,
                    Price = b.Price,
                    PrimaryPhotoExtension = b.PrimaryPhotoExtension,
                    PrimaryPhotoId = b.PrimaryPhotoId,
                    State = b.State,
                    Title = b.Title,
                    IsRemovedByAdmin = b.IsRemovedByAdmin,
                    Address1 = b.Address1,
                    IsActive = b.IsActive
                }).SingleOrDefault();

            if (building == null)
            {
                return(Status.NotFound <BuildingPreview>());
            }

            return(Status.OK(building));
        }
Exemple #8
0
        public override void ExecuteOnComplete(Order order)
        {
            var tzi   = TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time");
            var today = DateTime.UtcNow.AddHours(tzi.GetUtcOffset(DateTime.Now).Hours);

            var featuredDate = DateTime.Parse(
                this.Item.ProductOption, null,
                System.Globalization.DateTimeStyles.AssumeUniversal);

            //make sure the featured day is scheduled to exactly midnight.
            featuredDate = featuredDate.Date.AddHours(-tzi.GetUtcOffset(featuredDate.Date).Hours);

            using (var context = new RentlerContext())
            {
                var building = context.Buildings.FirstOrDefault(b => b.BuildingId == order.BuildingId);

                if (building == null)
                {
                    throw new ArgumentNullException("Building");
                }

                context.FeaturedListings.Add(new FeaturedListing
                {
                    BuildingId    = building.BuildingId,
                    ScheduledDate = featuredDate,
                    Zip           = building.Zip
                });

                context.SaveChanges();
            }
        }
Exemple #9
0
        public Status <bool> FulfillCompletedOrder(string username, int orderId)
        {
            using (var context = new RentlerContext())
            {
                var order = (from o in context.Orders
                             .Include("OrderItems")
                             .Include("Building")
                             where o.OrderId == orderId &&
                             (o.User.Username == username || o.User.Email == username)
                             select o).SingleOrDefault();

                if (order == null)
                {
                    Status.NotFound <bool>();
                }

                foreach (var item in order.OrderItems)
                {
                    var p = Rentler.Configuration.Products
                            .GetProduct(item.ProductId)
                            .FromOrderItem(item);

                    p.ExecuteOnComplete(order);
                }

                context.SaveChanges();

                return(Status.OK(true));
            }
        }
        /// <summary>
        /// Gets the building for the requested listing.
        /// </summary>
        /// <param name="listingId">The listing id.</param>
        /// <returns>
        /// A status with the building.
        /// </returns>
        public Status <List <Building> > GetListings()
        {
            //L3
            using (var context = new RentlerContext())
            {
                context.Configuration.ProxyCreationEnabled = false;

                var listing = (from b in context.Buildings
                               .Include("Photos")
                               .Include("BuildingAmenities")
                               .Include("CustomAmenities")
                               .Include("User")
                               .Include("ContactInfo")
                               where !b.IsDeleted &&
                               b.IsActive
                               select b).ToList();

                if (listing == null)
                {
                    return(Status.NotFound <List <Building> >());
                }

                return(Status.OK <List <Building> >(listing));
            }
        }
        /// <summary>
        /// Registers the specified user.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="password">The password.</param>
        /// <returns></returns>
        public Status <User> RegisterUser(User user, string password)
        {
            user.CreateDateUtc = DateTime.UtcNow;
            user.UpdateDateUtc = DateTime.UtcNow;
            user.UpdatedBy     = "AccountAdapter";

            // validate the object
            var result = Status.Validatate <User>(user);

            if (result.StatusCode != 200)
            {
                return(result);
            }

            if (string.IsNullOrWhiteSpace(password))
            {
                return(Status.ValidationError <User>(null, "Password", "The password was not specified"));
            }

            using (var context = new RentlerContext())
            {
                try
                {
                    // check for dup email
                    var dupEmail = context.Users.Where(u => !u.IsDeleted && u.Email.ToLower() == user.Email.ToLower()).Count();
                    if (dupEmail > 0)
                    {
                        return(Status.ValidationError <User>(null, "Email", "The email is already used"));
                    }

                    // check for dup username
                    var dupUser = context.Users.Where(u => !u.IsDeleted && u.Username.ToLower() == user.Username.ToLower()).Count();
                    if (dupUser > 0)
                    {
                        return(Status.ValidationError <User>(null, "Username", "The username is already used"));
                    }

                    user.PasswordHash = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "SHA1");

                    // create the user
                    context.Users.Add(user);
                    context.SaveChanges();

                    // notify user by email that their password was changed successfully.
                    EmailAccountRegisterModel model = new EmailAccountRegisterModel()
                    {
                        Name = string.Format("{0} {1}", user.FirstName, user.LastName),
                        To   = user.Email
                    };
                    mailer.Register(model);

                    return(Status <User> .OK(user));
                }
                catch (Exception ex)
                {
                    // TODO: log exception
                    return(Status.Error <User>("System was unable to create user", null));
                }
            }
        }
        /// <summary>
        /// Gets the application for user. If the application doesn't
        /// exist then one is created.
        /// </summary>
        /// <param name="username">The username of the user.</param>
        /// <returns>
        /// A user application.
        /// </returns>
        public Status <UserApplication> GetApplicationForUser(string username)
        {
            using (var context = new RentlerContext())
            {
                // get the user
                User result = (from u in context.Users.Include("UserApplication")
                               where u.Username == username
                               select u).SingleOrDefault();

                if (result == null)
                {
                    return(Status.NotFound <UserApplication>());
                }

                UserApplication application;

                if (result.UserApplication == null)
                {
                    application        = new UserApplication();
                    application.UserId = result.UserId;
                    context.UserApplications.Add(application);
                    context.SaveChanges();
                }
                else
                {
                    application = result.UserApplication;
                }

                return(Status.OK <UserApplication>(application));
            }
        }
Exemple #13
0
        public Status <string[]> ReorderPhotos(string username, Guid[] photoIds)
        {
            if (photoIds.Length == 0)
            {
                return(Status.ValidationError <string[]>(null, "photoIds", "photoIds cannot be empty"));
            }

            string[] existingPhotoIds = null;
            Guid     primaryPhotoId   = photoIds[0];

            using (RentlerContext context = new RentlerContext())
            {
                try
                {
                    var building = (from p in context.Photos
                                    .Include("Building.Photos")
                                    where p.PhotoId == primaryPhotoId &&
                                    p.Building.User.Username == username
                                    select p.Building).SingleOrDefault();

                    if (building == null)
                    {
                        return(Status.NotFound <string[]>());
                    }

                    // save order prior to changing in case we have to restore them
                    var photos = from p in building.Photos
                                 orderby p.SortOrder
                                 select p;

                    existingPhotoIds = photos.Select(p => p.PhotoId.ToString()).ToArray();

                    for (int i = 0; i < photoIds.Length; ++i)
                    {
                        var photo = photos.SingleOrDefault(p => p.PhotoId == photoIds[i]);
                        photo.SortOrder = i;

                        // primary photo
                        if (i == 0)
                        {
                            building.PrimaryPhotoId        = photo.PhotoId;
                            building.PrimaryPhotoExtension = photo.Extension;
                        }
                    }

                    context.SaveChanges();

                    string[] resultIds = photoIds.Select(i => i.ToString()).ToArray();

                    InvalidateCache(building.BuildingId);

                    return(Status.OK <string[]>(resultIds));
                }
                catch (Exception ex)
                {
                    return(Status.Error <string[]>(ex.Message, existingPhotoIds));
                }
            }
        }
Exemple #14
0
        public Status <UserCreditCard> UpdateUserCreditCard(string username, UserCreditCard card)
        {
            if (string.IsNullOrWhiteSpace(username))
            {
                return(Status.ValidationError <UserCreditCard>(null, "username", "The username is required"));
            }

            if (card == null)
            {
                return(Status.ValidationError <UserCreditCard>(null, "card", "card is null"));
            }

            card = manager.UpdateCustomerCard(card);

            if (card.UserCreditCardId == 0)
            {
                return(AddUserCreditCard(username, card));
            }

            using (RentlerContext context = new RentlerContext())
            {
                try
                {
                    var userCreditCard = (from uc in context.UserCreditCards
                                          where uc.User.IsDeleted == false &&
                                          uc.User.Username == username &&
                                          uc.UserCreditCardId == card.UserCreditCardId
                                          select uc).SingleOrDefault();

                    userCreditCard.Alias            = card.Alias;
                    userCreditCard.AccountReference = card.AccountReference;
                    userCreditCard.CardName         = card.CardName;
                    userCreditCard.CardNumber       = card.CardNumber;
                    userCreditCard.ExpirationMonth  = card.ExpirationMonth;
                    userCreditCard.ExpirationYear   = card.ExpirationYear;
                    userCreditCard.Address1         = card.Address1;
                    userCreditCard.Address2         = card.Address2;
                    userCreditCard.City             = card.City;
                    userCreditCard.Email            = card.Email;
                    userCreditCard.FirstName        = card.FirstName;
                    userCreditCard.LastName         = card.LastName;
                    userCreditCard.Phone            = card.Phone;
                    userCreditCard.State            = card.State;
                    userCreditCard.Zip        = card.Zip;
                    userCreditCard.IsDeleted  = card.IsDeleted;
                    userCreditCard.UpdatedBy  = "orderadapter";
                    userCreditCard.UpdateDate = DateTime.UtcNow;

                    context.SaveChanges();

                    return(Status.OK <UserCreditCard>(card));
                }
                catch (Exception ex)
                {
                    return(Status.Error <UserCreditCard>(ex.Message, card));
                }
            }
        }
Exemple #15
0
        List <ZipInfoPreview> GetZips()
        {
            var zips = new List <ZipInfoPreview>();

            //L1
            var cache = HttpContext.Current.Cache;

            zips = cache[CacheKeys.ZIP_INFOS] as List <ZipInfoPreview>;
            if (zips != null)
            {
                return(zips);
            }

            //L2
            //try to get from redis

            //leave this connection as is; it is rarely hit, thanks to the L1 cache,
            //and zip infos should be loaded as fast as possible, since it is vital for search.
            var connection = ConnectionGateway.Current.GetWriteConnection();
            var zipTask    = connection.Strings.Get(App.RedisDatabase, CacheKeys.ZIP_INFOS);
            var result     = connection.Wait(zipTask);

            if (result != null && result.Length > 0)
            {
                using (var stream = new MemoryStream(result))
                    zips = Serializer.Deserialize <List <ZipInfoPreview> >(stream);

                //add to L1
                cache[CacheKeys.ZIP_INFOS] = zips;

                return(zips);
            }


            using (var context = new RentlerContext())
            {
                //get from db
                zips = (from z in context.ZipInfos
                        select new ZipInfoPreview
                {
                    ZipCode = z.ZipCode,
                    FriendlyName = (z.City + " " + z.CityAliasName + " " + z.StateCode).ToLower(),
                    StateCode = z.StateCode.ToLower(),
                    Latitude = z.Latitude,
                    Longitude = z.Longitude
                }).ToList();
            }

            //add to L2
            var con = ConnectionGateway.Current.GetWriteConnection();

            con.Strings.Set(App.RedisDatabase, CacheKeys.ZIP_INFOS, zips.ToBinaryArray());

            //add to L1
            cache[CacheKeys.ZIP_INFOS] = zips;

            return(zips);
        }
        /// <summary>
        /// Saves a Listing for a particular User
        /// </summary>
        /// <param name="listingId">listing identifier</param>
        /// <param name="username">user identifier</param>
        /// <returns>
        /// A status with the saved building
        /// </returns>
        public Status <SavedBuilding> CreateSavedBuilding(long listingId, string username)
        {
            if (listingId == 0)
            {
                return(Status.ValidationError <SavedBuilding>(null, "listingId", "listingId is required"));
            }

            if (string.IsNullOrWhiteSpace(username))
            {
                return(Status.ValidationError <SavedBuilding>(null, "username", "username is required"));
            }

            using (var context = new RentlerContext())
            {
                var user = (from u in context.Users.Include("SavedBuildings")
                            where u.IsDeleted == false && (u.Username == username || u.Email == username)
                            select u).SingleOrDefault();

                if (user == null)
                {
                    return(Status.NotFound <SavedBuilding>());
                }

                // see if user already saved this building so we don't try to
                // save it again
                if (user.SavedBuildings.Any(s => s.BuildingId == listingId))
                {
                    return(Status.Error <SavedBuilding>("User already saved this building", null));
                }

                SavedBuilding newSave = new SavedBuilding()
                {
                    BuildingId    = listingId,
                    UserId        = user.UserId,
                    CreateDateUtc = DateTime.UtcNow,
                    CreatedBy     = "ListingAdapter"
                };

                user.SavedBuildings.Add(newSave);

                try
                {
                    context.SaveChanges();

                    InvalidateCache(newSave.BuildingId);

                    newSave.User = null;
                    return(Status.OK <SavedBuilding>(newSave));
                }
                catch (Exception ex)
                {
                    return(Status.Error <SavedBuilding>(
                               ex.Message,
                               null
                               ));
                }
            }
        }
        /// <summary>
        /// Gets the building for the requested listing.
        /// </summary>
        /// <param name="listingId">The listing id.</param>
        /// <returns>
        /// A status with the building.
        /// </returns>
        public Status <Building> GetListing(long listingId)
        {
            if (listingId == 0)
            {
                return(Status.ValidationError <Building>(null, "listingId", "Listing ID is required"));
            }

            Building listing = null;

            //L2
            var settings = new JsonSerializerSettings {
                PreserveReferencesHandling = PreserveReferencesHandling.Objects
            };
            var redisConnection = ConnectionGateway.Current.GetReadConnection();
            var listingTask     = redisConnection.Strings.GetString(App.RedisCacheDatabase, CacheKeys.LISTING + listingId);
            var result          = redisConnection.Wait(listingTask);

            if (!string.IsNullOrWhiteSpace(result))
            {
                listing = JsonConvert.DeserializeObject <Building>(result, settings);
            }

            if (listing != null)
            {
                return(Status.OK <Building>(listing));
            }

            //L3
            using (var context = new RentlerContext())
            {
                context.Configuration.ProxyCreationEnabled = false;

                listing = (from b in context.Buildings
                           .Include("Photos")
                           .Include("BuildingAmenities")
                           .Include("CustomAmenities")
                           .Include("User")
                           .Include("ContactInfo")
                           where b.IsDeleted == false &&
                           b.IsRemovedByAdmin == false &&
                           b.IsActive &&
                           b.BuildingId == listingId
                           select b).SingleOrDefault();

                if (listing == null)
                {
                    return(Status.NotFound <Building>());
                }

                //store in L2
                var connection = ConnectionGateway.Current.GetWriteConnection();
                connection.Strings.Set(App.RedisCacheDatabase, CacheKeys.LISTING + listingId,
                                       JsonConvert.SerializeObject(listing, settings), 14400);

                return(Status.OK <Building>(listing));
            }
        }
Exemple #18
0
        public Status <ListingCountModel> GetListingCounts()
        {
            var result = new ListingCountModel();

            using (var context = new RentlerContext())
            {
                var counts = (from b in context.Buildings
                              where b.IsActive && !b.IsDeleted
                              group b by b.PropertyTypeCode into grouped
                              select new
                {
                    PropertyTypeCode = grouped.Key,
                    Count = grouped.Count()
                }).ToList();

                foreach (var item in counts)
                {
                    switch ((PropertyType)item.PropertyTypeCode)
                    {
                    case PropertyType.SingleFamilyHome:
                        result.SingleFamilyHome = item.Count;
                        break;

                    case PropertyType.Apartment:
                        result.Apartment = item.Count;
                        break;

                    case PropertyType.CondoTownhome:
                        result.CondoTownhome = item.Count;
                        break;

                    case PropertyType.MultiFamilyHome:
                        result.MultiFamilyHome = item.Count;
                        break;

                    case PropertyType.ManufacturedHome:
                        result.ManufacturedHome = item.Count;
                        break;

                    case PropertyType.HorseLivestock:
                        result.HorseLivestock = item.Count;
                        break;

                    case PropertyType.SingleRoom:
                        result.SingleRoom = item.Count;
                        break;

                    default:
                        break;
                    }
                }
            }

            return(Status.OK(result));
        }
        /// <summary>
        /// Creates the interest in building from the user to the current
        /// listing.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="listingId">The listing id.</param>
        /// <returns>
        /// A status of whether or not the interest was created.
        /// </returns>
        public Status <UserInterest> CreateInterestInBuilding(string username, long listingId, string message)
        {
            if (listingId == 0)
            {
                return(Status.ValidationError <UserInterest>(null, "listingId", "listingId is required"));
            }

            if (string.IsNullOrWhiteSpace(username))
            {
                return(Status.ValidationError <UserInterest>(null, "username", "username is required"));
            }

            using (var context = new RentlerContext())
            {
                try
                {
                    User user = (from u in context.Users
                                 where u.Username == username
                                 select u).SingleOrDefault();

                    if (user == null)
                    {
                        return(Status.NotFound <UserInterest>());
                    }

                    UserInterest newInterest = new UserInterest()
                    {
                        BuildingId = listingId,
                        UserId     = user.UserId,
                        Message    = message
                    };

                    context.UserInterests.Add(newInterest);
                    context.SaveChanges();

                    // loads the building, which generated this interest, into newInterest
                    context.Entry(newInterest).Reference(e => e.Building).Load();

                    // notify landlord of interest
                    // TODO: if we are unable to send this email we need a way to allow the user
                    // to re-notify the Landlord without requiring them to continue to create
                    // interests
                    EmailListingInterestedModel model = new EmailListingInterestedModel(newInterest);
                    mailer.Interested(model);

                    return(Status.OK <UserInterest>(newInterest));
                }
                catch (Exception ex)
                {
                    // log exception
                    return(Status.Error <UserInterest>("System was unable to create interest", null));
                }
            }
        }
 public Status <IEnumerable <long> > GetAllListingIds()
 {
     using (var context = new RentlerContext())
     {
         var listings = (from b in context.Buildings
                         where b.IsActive && !b.IsDeleted &&
                         !b.IsRemovedByAdmin
                         select b.BuildingId).ToList();
         return(Status.OK <IEnumerable <long> >(listings));
     }
 }
        public Status <UserInterest> SendApplication(string username, int userInterestId, UserApplication application)
        {
            if (string.IsNullOrWhiteSpace(username))
            {
                return(Status.ValidationError <UserInterest>(null, "username", "The username is required"));
            }

            // validate UserApplication
            var appStatusValid = Status.Validatate <UserApplication>(application);

            if (appStatusValid.StatusCode != 200)
            {
                return(Status.ValidationError <UserInterest>(null, "application", "The application is not valid"));
            }

            // update user application
            var appStatusSave = SaveApplicationForUser(username, application);

            if (appStatusSave.StatusCode != 200)
            {
                return(Status.Error <UserInterest>("System was unable to update application", null));
            }

            using (RentlerContext context = new RentlerContext())
            {
                try
                {
                    // get lead
                    var lead = (from i in context.UserInterests
                                where i.User.Username == username && i.UserInterestId == userInterestId
                                select i).SingleOrDefault();

                    if (lead == null)
                    {
                        return(Status.NotFound <UserInterest>());
                    }

                    // update lead - ApplicationSubmitted = true
                    lead.ApplicationSubmitted = true;

                    context.SaveChanges();

                    EmailSendApplicationModel model = new EmailSendApplicationModel(lead);
                    mailer.SendApplication(model);

                    return(Status.OK(lead));
                }
                catch (Exception ex)
                {
                    // log exception
                    return(Status.Error <UserInterest>("System was unable to get lead", null));
                }
            }
        }
        /// <summary>
        /// Checks if there is a user with a given email/username
        /// that is associated with that apiKey.
        /// This method uses L1, L2, and L3 caching.
        /// </summary>
        /// <param name="usernameOrEmail">The username/email to check for</param>
        /// <param name="apiKey">An apiKey provided to a 3rd party</param>
        /// <returns>A Status result of the id of the user</returns>
        public Status <int> GetAffiliateUserIdByUsernameOrEmailAndApiKey(string usernameOrEmail, Guid apiKey)
        {
            int?userId;

            //L1
            var cache = HttpContext.Current.Cache;

            userId = cache[CacheKeys.AFFILIATE_USER_IDS + ":" + usernameOrEmail + ":" + apiKey.ToString()] as int?;

            if (userId.HasValue)
            {
                return(Status.OK(userId.Value));
            }

            //L2
            var redisConnection = ConnectionGateway.Current.GetReadConnection();

            var task   = redisConnection.Hashes.GetString(App.RedisDatabase, CacheKeys.AFFILIATE_USER_IDS, usernameOrEmail + ":" + apiKey.ToString());
            var result = redisConnection.Wait(task);

            if (result != null)
            {
                //store in L1
                cache[CacheKeys.AFFILIATE_USER_IDS + ":" + usernameOrEmail + ":" + apiKey.ToString()] = int.Parse(result);

                return(Status.OK(int.Parse(result)));
            }


            //L3
            using (var context = new RentlerContext())
            {
                userId = (from u in context.Users
                          where !u.IsDeleted &&
                          (u.Username.Equals(usernameOrEmail) ||
                           u.Email.Equals(usernameOrEmail)) &&
                          u.AffiliateUser.ApiKey.Equals(apiKey)
                          select u.UserId).FirstOrDefault();

                if (userId.HasValue && userId.Value != 0)
                {
                    //store in L2
                    var connection = ConnectionGateway.Current.GetWriteConnection();
                    var storeTask  = connection.Hashes.Set(App.RedisDatabase, CacheKeys.AFFILIATE_USER_IDS, usernameOrEmail + ":" + apiKey.ToString(), userId.Value.ToString());

                    //store in L1
                    cache[CacheKeys.AFFILIATE_USER_IDS + ":" + usernameOrEmail + ":" + apiKey.ToString()] = userId.Value;

                    return(Status.OK(userId.Value));
                }

                return(Status.NotFound <int>());
            }
        }
        /// <summary>
        /// Gets the saved listings for user.
        /// </summary>
        /// <param name="username">The username to get the saved listings for.</param>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <returns>
        /// A list of saved listings for a user.
        /// </returns>
        public Status <PaginatedList <BuildingPreview> > GetFavoritesForUser(
            string username, int?pageNumber, int?pageSize)
        {
            var identity = CustomAuthentication.GetIdentity();

            if (!identity.IsAuthenticated)
            {
                return(Status.UnAuthorized <PaginatedList <BuildingPreview> >());
            }

            if (!pageNumber.HasValue)
            {
                pageNumber = 0;
            }
            if (!pageSize.HasValue || pageSize.Value > 100)
            {
                pageSize = 25;
            }

            if (string.IsNullOrWhiteSpace(username))
            {
                return(Status.ValidationError <PaginatedList <BuildingPreview> >(null, "username", "username is required"));
            }

            using (var context = new RentlerContext())
            {
                var props = (from sb in context.SavedBuildings
                             join b in context.Buildings on sb.BuildingId equals b.BuildingId
                             where sb.UserId == identity.UserId &&
                             b.IsActive == true &&
                             b.IsRemovedByAdmin == false
                             orderby b.CreateDateUtc descending
                             select b).ToList();

                var queryableProps = props.Select(b => new BuildingPreview()
                {
                    Bathrooms             = b.Bathrooms.Value,
                    Bedrooms              = b.Bedrooms.Value,
                    BuildingId            = b.BuildingId,
                    City                  = b.City,
                    IsFeatured            = false,
                    Price                 = b.Price,
                    PrimaryPhotoExtension = b.PrimaryPhotoExtension,
                    PrimaryPhotoId        = b.PrimaryPhotoId,
                    State                 = b.State,
                    Title                 = string.IsNullOrWhiteSpace(b.Title) ? b.Address1 : b.Title,
                    Address1              = b.Address1
                }).AsQueryable <BuildingPreview>();

                return(Status.OK <PaginatedList <BuildingPreview> >(
                           new PaginatedList <BuildingPreview>(queryableProps, pageNumber.Value, pageSize.Value)));
            }
        }
Exemple #24
0
        public Status <BoundBoxSearch> SearchLocation(float lat, float lng, float miles)
        {
            var bounds = Haversine.GetBoundingBox(lat, lng, miles);
            PaginatedList <BuildingPreview> results = null;

            using (var context = new RentlerContext())
            {
                var final = from b in context.Buildings
                            where b.IsActive &&
                            !b.IsDeleted &&
                            !b.IsRemovedByAdmin &&
                            b.Latitude >= bounds.MinLat &&
                            b.Latitude <= bounds.MaxLat &&
                            b.Longitude >= bounds.MinLng &&
                            b.Longitude <= bounds.MaxLng
                            orderby b.BuildingId
                            select new BuildingPreview()
                {
                    Address1              = b.Address1,
                    Address2              = b.Address2,
                    Bathrooms             = b.Bathrooms.Value,
                    Bedrooms              = b.Bedrooms.Value,
                    BuildingId            = b.BuildingId,
                    RibbonId              = b.RibbonId,
                    City                  = b.City,
                    IsFeatured            = false,
                    Price                 = b.Price,
                    PrimaryPhotoExtension = b.PrimaryPhotoExtension,
                    PrimaryPhotoId        = b.PrimaryPhotoId,
                    State                 = b.State,
                    Title                 = b.Title,
                    IsActive              = b.IsActive,
                    Latitude              = b.Latitude,
                    Longitude             = b.Longitude,
                    Zip = b.Zip
                };
                // get the results to show
                results = new PaginatedList <BuildingPreview>(final, 1, int.MaxValue);
            }

            results = new PaginatedList <BuildingPreview>(results
                                                          .Select(z => new KeyValuePair <double, BuildingPreview>(
                                                                      Haversine.GetDistance(lat, lng, z.Latitude, z.Longitude), z))
                                                          .OrderBy(z => z.Key).Select(s => s.Value).AsQueryable(), 1, int.MaxValue);

            return(Status.OK(new BoundBoxSearch
            {
                Results = results,
                Bounds = bounds,
                ResultsPerPage = int.MaxValue,
                Page = 1
            }));
        }
Exemple #25
0
        ApiKey GetApiKey(Guid key)
        {
            ApiKey apiKey = null;

            //L1
            var cache = HttpContext.Current.Cache;

            apiKey = cache[CacheKeys.API_KEYS] as ApiKey;

            if (apiKey != null)
            {
                return(apiKey);
            }

            //L2
            var redisConnection = ConnectionGateway.Current.GetReadConnection();

            var task   = redisConnection.Hashes.Get(App.RedisDatabase, CacheKeys.API_KEYS, key.ToString());
            var result = redisConnection.Wait(task);

            if (result != null)
            {
                using (var stream = new MemoryStream(result))
                    apiKey = Serializer.Deserialize <ApiKey>(stream);

                return(apiKey);
            }


            //L3
            using (var context = new RentlerContext())
                apiKey = (from k in context.ApiKeys
                          where k.ApiKeyId == key
                          select k).SingleOrDefault();

            if (apiKey != null)
            {
                //store in L2
                var connection = ConnectionGateway.Current.GetWriteConnection();
                var storeTask  = connection.Hashes.Set(App.RedisDatabase,
                                                       CacheKeys.API_KEYS, apiKey.ApiKeyId.ToString(), apiKey.ToBinaryArray());

                //store in L1
                cache.Add(CacheKeys.API_KEYS,
                          apiKey, null,
                          DateTime.Now.AddMinutes(5),
                          System.Web.Caching.Cache.NoSlidingExpiration,
                          System.Web.Caching.CacheItemPriority.Normal, null);
            }

            return(apiKey);
        }
Exemple #26
0
        public Status <UserCreditCard> AddUserCreditCard(string username, UserCreditCard card)
        {
            if (string.IsNullOrWhiteSpace(username))
            {
                return(Status.ValidationError <UserCreditCard>(null, "username", "The username is required"));
            }

            if (card == null)
            {
                return(Status.ValidationError <UserCreditCard>(null, "card", "card is null"));
            }

            card.CreatedBy  = "orderadapter";
            card.CreateDate = DateTime.UtcNow;

            // validate the contactinfo
            var cardValidation = Status.Validatate <UserCreditCard>(card);

            if (cardValidation.StatusCode != 200)
            {
                return(Status.ValidationError <UserCreditCard>(card, "", "credit card is not valid"));
            }

            card.AccountReference = Guid.NewGuid();

            card = manager.CreateCustomerCard(card);

            if (card == null)
            {
                return(Status.Error("Problem creating card on payment service.", card));
            }

            using (RentlerContext context = new RentlerContext())
            {
                try
                {
                    var user = (from u in context.Users
                                where u.IsDeleted == false &&
                                u.Username == username
                                select u).SingleOrDefault();

                    user.UserCreditCards.Add(card);
                    context.SaveChanges();

                    return(Status.OK <UserCreditCard>(card));
                }
                catch (Exception ex)
                {
                    return(Status.Error <UserCreditCard>(ex.Message, card));
                }
            }
        }
Exemple #27
0
        public UserCreditCard GetUserCreditCard(string username, int cardId)
        {
            using (var context = new RentlerContext())
            {
                var result = (from u in context.UserCreditCards
                              where !u.IsDeleted &&
                              (u.User.Username == username ||
                               u.User.Email == username) &&
                              u.UserCreditCardId == cardId
                              select u).SingleOrDefault();

                return(result);
            }
        }
Exemple #28
0
        public Status <User> ValidateAuthToken(Guid token)
        {
            RedisPublisher.Publish("token", "Validating token: " + token.ToString());

            //L1
            var cache  = HttpContext.Current.Cache;
            int?userId = cache[CacheKeys.AUTH_TOKENS + ":" + token.ToString()] as int?;

            if (!userId.HasValue || userId == 0)
            {
                //L2
                var redisConnection = ConnectionGateway.Current.GetReadConnection();

                var task   = redisConnection.Hashes.GetString(App.RedisDatabase, CacheKeys.AUTH_TOKENS, token.ToString());
                var result = redisConnection.Wait(task);

                int userIdTryParse = 0;
                if (int.TryParse(result, out userIdTryParse))
                {
                    userId = userIdTryParse;
                }
            }

            if (userId.HasValue && userId != 0)
            {
                using (var context = new RentlerContext())
                {
                    var user = (from u in context.Users
                                where u.UserId == userId.Value
                                select u).SingleOrDefault();

                    if (user == null)
                    {
                        return(Status.NotFound <User>());
                    }

                    //otherwise we're good, clear cache and return
                    //L2
                    var connection = ConnectionGateway.Current.GetWriteConnection();
                    var task       = connection.Hashes.Remove(App.RedisDatabase, CacheKeys.AUTH_TOKENS, token.ToString());

                    //L1
                    cache.Remove(CacheKeys.AUTH_TOKENS + ":" + token.ToString());

                    return(Status.OK(user));
                }
            }

            return(Status.NotFound <User>());
        }
        /// <summary>
        /// Verifies a user for correct login
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <returns>
        /// Status result with the working user if successful.
        /// </returns>
        public Status <User> LoginUser(string username, string password)
        {
            if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
            {
                return(Status.ValidationError <User>(null, "UserName", "The username or password is incorrect"));
            }

            string hashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "SHA1");

            using (var context = new RentlerContext())
            {
                // find rentler user
                var user = (from u in context.Users
                            where u.Email == username ||
                            u.Username == username
                            select u).FirstOrDefault();

                // user not found, need a user record
                if (user == null)
                {
                    return(Status.ValidationError <User>(null, "UserName", "The username or password is incorrect"));
                }

                // user has rentler password and it matched
                if (user.PasswordHash == hashedPassword)
                {
                    return(Status.OK <User>(user));
                }

                // no password match on rentler user
                // don't worry though, could still be an affiliate user
                context.Entry(user).Reference("AffiliateUser").Load();

                // make sure the user has an affiliate user
                // make sure the affiliate user has a password to check
                //"$A" denotes a "Mode A" Ksl Md5 hashing algorithm
                if (user.AffiliateUser != null &&
                    user.AffiliateUser.PasswordHash != null &&
                    user.AffiliateUser.PasswordHash.StartsWith("$A"))
                {
                    if (CheckKslPassword(password, user.AffiliateUser.PasswordHash))
                    {
                        return(Status.OK <User>(user));
                    }
                }

                return(Status.ValidationError <User>(null, "Password", "The username or password is incorrect"));
            }
        }
        public Status <List <FeaturedListing> > GetFeaturedDates()
        {
            using (var context = new RentlerContext())
            {
                var tzi   = TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time");
                var today = DateTime.UtcNow.AddHours(tzi.GetUtcOffset(DateTime.Now).Hours);
                today = today.Date.ToUniversalTime().AddHours(-tzi.GetUtcOffset(today).Hours);

                var dates = (from f in context.FeaturedListings
                             where f.ScheduledDate >= today
                             select f).ToList();

                return(Status.OK(dates));
            }
        }