/// <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));
                }
            }
        }
        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 #3
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 #4
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 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 #6
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));
                }
            }
        }
        /// <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
                               ));
                }
            }
        }
Exemple #8
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));
                }
            }
        }
        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>
        /// 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));
                }
            }
        }
Exemple #11
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));
                }
            }
        }
        /// <summary>
        /// Changes the password of the specified user
        /// </summary>
        /// <param name="username">the username of the user</param>
        /// <param name="oldPassword">old password for user</param>
        /// <param name="newPassword">new password for user</param>
        /// <param name="confirmPassword">confirmed new password for user</param>
        /// <returns></returns>
        public Status <User> ChangePassword(string username, string oldPassword, string newPassword, string confirmPassword)
        {
            if (confirmPassword != newPassword)
            {
                return(Status <User> .ValidationError <User>(null, "ConfirmPassword", "Passwords do not match"));
            }

            using (var context = new RentlerContext())
            {
                // get user whose password needs to be reset
                var userStatus = GetUser(username, context);

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

                var user = userStatus.Result;

                if (user.PasswordHash != FormsAuthentication.HashPasswordForStoringInConfigFile(oldPassword, "SHA1"))
                {
                    return(Status <User> .ValidationError <User>(null, "OldPassword", "Old Password is incorrect"));
                }

                try
                {
                    // reset password
                    user.PasswordHash = FormsAuthentication.HashPasswordForStoringInConfigFile(newPassword, "SHA1");
                    context.SaveChanges();

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

                    return(Status <User> .OK(user));
                }
                catch (Exception ex)
                {
                    // TODO: log exception
                    return(Status.Error <User>("System was unable to change password", null));
                }
            }
        }
        public UserCreditCard CreateCreditCardForUser(UserCreditCard card)
        {
            card = manager.CreateCustomerCard(card);

            if (card == null)
            {
                return(null);
            }

            using (var context = new RentlerContext())
            {
                context.UserCreditCards.Add(card);
                context.SaveChanges();
            }

            return(card);
        }
        /// <summary>
        /// Removes a Saved 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 <bool> DeleteSavedBuilding(long listingId, string username)
        {
            var identity = CustomAuthentication.GetIdentity();

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

            if (listingId == 0)
            {
                return(Status.ValidationError <bool>(false, "listingId", "listingId is required"));
            }

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

            using (var context = new RentlerContext())
            {
                try
                {
                    SavedBuilding save = (from s in context.SavedBuildings
                                          where s.BuildingId == listingId &&
                                          s.UserId == identity.UserId
                                          select s).SingleOrDefault();

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

                    context.SavedBuildings.Remove(save);
                    context.SaveChanges();

                    InvalidateCache(save.BuildingId);

                    return(Status.OK <bool>(true));
                }
                catch (Exception ex)
                {
                    return(Status.Error <bool>(ex.Message, false));
                }
            }
        }
        /// <summary>
        /// Takes care of storing the user's credit card information.
        /// If it is a new card, it will create a new entry in the payment system
        /// and in our own storage. If it is just an update (e.g. the user changing their
        /// address information), it will act accordingly.
        /// </summary>
        /// <param name="card">The user's credit card.</param>
        public void UpdateCreditCardForUser(UserCreditCard card)
        {
            card = manager.UpdateCustomerCard(card);

            if (card.UserCreditCardId == 0)
            {
                CreateCreditCardForUser(card);
            }
            else
            {
                UserCreditCard toUpdate = null;

                using (var context = new RentlerContext())
                {
                    toUpdate = (from u in context.UserCreditCards
                                where u.UserId == card.UserId &&
                                u.UserCreditCardId == card.UserCreditCardId
                                select u).SingleOrDefault();

                    if (toUpdate == null)
                    {
                        throw new ArgumentNullException();
                    }

                    toUpdate.Alias            = card.Alias;
                    toUpdate.AccountReference = card.AccountReference;
                    toUpdate.CardName         = card.CardName;
                    toUpdate.CardNumber       = card.CardNumber;
                    toUpdate.ExpirationMonth  = card.ExpirationMonth;
                    toUpdate.ExpirationYear   = card.ExpirationYear;
                    toUpdate.Address1         = card.Address1;
                    toUpdate.Address2         = card.Address2;
                    toUpdate.City             = card.City;
                    toUpdate.Email            = card.Email;
                    toUpdate.FirstName        = card.FirstName;
                    toUpdate.LastName         = card.LastName;
                    toUpdate.Phone            = card.Phone;
                    toUpdate.State            = card.State;
                    toUpdate.Zip       = card.Zip;
                    toUpdate.IsDeleted = card.IsDeleted;

                    context.SaveChanges();
                }
            }
        }
        /// <summary>
        /// Resets the password of the specified user
        /// </summary>
        /// <param name="email">user's email</param>
        /// <returns></returns>
        public Status <User> ResetPassword(string email)
        {
            using (var context = new RentlerContext())
            {
                try
                {
                    var user = (from u in context.Users
                                where !u.IsDeleted && u.Email == email
                                select u).FirstOrDefault();

                    if (user == null)
                    {
                        return(Status.ValidationError <User>(null, "Email", "No user with this email exists"));
                    }

                    // generate a random password 8 char long
                    string newPassword = FormsAuthentication
                                         .HashPasswordForStoringInConfigFile(
                        DateTime.Now.ToString() + user.Username,
                        "SHA1")
                                         .Substring(0, 8);

                    // hash the random password and update user with it
                    user.PasswordHash = FormsAuthentication
                                        .HashPasswordForStoringInConfigFile(newPassword, "SHA1");
                    context.SaveChanges();

                    EmailForgotPasswordModel model = new EmailForgotPasswordModel()
                    {
                        To          = user.Email,
                        Username    = user.Username,
                        NewPassword = newPassword
                    };
                    mailer.ForgotPassword(model);

                    return(Status.OK <User>(user));
                }
                catch (Exception ex)
                {
                    // TODO: log exception
                    return(Status.Error <User>("System was unable to reset password", null));
                }
            }
        }
        /// <summary>
        /// Takes care of storing the user's bank account information.
        /// If it is a new card, it will create a new entry in the payment system
        /// and in our own storage. If it is just an update (e.g. the user changing their
        /// address information), it will act accordingly.
        /// </summary>
        /// <param name="bank">The user's bank account.</param>
        public void UpdateBankForUser(UserBank bank)
        {
            bank = manager.UpdateCustomerBank(bank);

            if (bank.UserBankId == 0)
            {
                CreateBankForUser(bank);
            }
            else
            {
                using (var context = new RentlerContext())
                {
                    var toUpdate = (from u in context.UserBanks
                                    where u.UserId == bank.UserId &&
                                    u.UserBankId == bank.UserBankId
                                    select u).SingleOrDefault();

                    if (toUpdate == null)
                    {
                        throw new ArgumentNullException();
                    }

                    toUpdate.AccountName   = bank.AccountName;
                    toUpdate.AccountNumber = bank.AccountNumber;
                    toUpdate.AccountType   = bank.AccountType;
                    toUpdate.PayerAlias    = bank.PayerAlias;
                    toUpdate.PayeeAlias    = bank.PayeeAlias;
                    toUpdate.RoutingNumber = bank.RoutingNumber;
                    toUpdate.Address1      = bank.Address1;
                    toUpdate.Address2      = bank.Address2;
                    toUpdate.City          = bank.City;
                    toUpdate.Email         = bank.Email;
                    toUpdate.FirstName     = bank.FirstName;
                    toUpdate.LastName      = bank.LastName;
                    toUpdate.Phone         = bank.Phone;
                    toUpdate.State         = bank.State;
                    toUpdate.Zip           = bank.Zip;
                    toUpdate.IsDeleted     = bank.IsDeleted;

                    context.SaveChanges();
                }
            }
        }
Exemple #18
0
        public override void ExecuteOnComplete(Order order)
        {
            using (var context = new RentlerContext())
            {
                // get local date, to timestamp when the building was prioritized (so we can turn it off after 30 days)
                TimeZoneInfo mstTZ     = TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time");
                DateTime     dateLocal = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, mstTZ);

                var building = context.Buildings.FirstOrDefault(b => b.BuildingId == order.BuildingId);

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

                building.HasPriority     = true;
                building.DatePrioritized = dateLocal;

                context.SaveChanges();
            }
        }
        /// <summary>
        /// Updates the profile of the specified user
        /// </summary>
        /// <param name="username">the username of the user</param>
        /// <param name="firstName">first name of user</param>
        /// <param name="lastName">last name of user</param>
        /// <param name="email">email of user</param>
        /// <returns>
        /// status result with this updated user
        /// </returns>
        public Status <User> UpdateProfile(string username, string firstName, string lastName, string email)
        {
            using (var context = new RentlerContext())
            {
                // get user to update
                var userStatus = GetUser(username, context);

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

                var user = userStatus.Result;

                // email changed
                if (user.Email.ToLower() != email.ToLower())
                {
                    var dupEmail = context.Users
                                   .Where(u => !u.IsDeleted && u.Email.ToLower() == email.ToLower())
                                   .Count();

                    if (dupEmail > 0)
                    {
                        return(Status.ValidationError <User>(null, "Email", "The email is already used"));
                    }

                    // ok to update
                    user.Email = email;
                }

                user.FirstName     = firstName;
                user.LastName      = lastName;
                user.UpdatedBy     = "AccountAdapter";
                user.UpdateDateUtc = DateTime.UtcNow;

                context.SaveChanges();

                return(Status <User> .OK(user));
            }
        }
Exemple #20
0
        public Status <bool> RemoveUserCreditCard(int userCreditCardId)
        {
            UserCreditCard card;

            using (var context = new RentlerContext())
            {
                card = (from c in context.UserCreditCards
                        where c.UserCreditCardId == userCreditCardId
                        select c).FirstOrDefault();

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

                card.IsDeleted = true;
                manager.UpdateCustomerCard(card);

                context.SaveChanges();

                return(Status.OK(true));
            }
        }
        /// <summary>
        /// Reports a listing
        /// </summary>
        /// <param name="listingId">listing identifier</param>
        /// <param name="reportedText">reason for reporting this listing</param>
        /// <returns>
        /// status with reported listing
        /// </returns>
        public Status <bool> ReportListing(long listingId, string reportedText)
        {
            if (listingId == 0)
            {
                return(Status.ValidationError <bool>(false, "listingId", "listingId is required"));
            }
            if (string.IsNullOrWhiteSpace(reportedText))
            {
                return(Status.ValidationError <bool>(false, "reportedText", "reportedText is required"));
            }

            using (var context = new RentlerContext())
            {
                var building = (from b in context.Buildings
                                where b.IsDeleted == false && b.BuildingId == listingId
                                select b).SingleOrDefault();

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

                building.IsReported   = true;
                building.ReportedText = reportedText;

                try
                {
                    context.SaveChanges();
                    return(Status.OK <bool>(true));
                }
                catch (Exception ex)
                {
                    return(Status.Error <bool>(ex.Message, false));
                }
            }
        }
Exemple #22
0
        public Status <Photo> SetSortOrder(Guid photoId, int sortOrder)
        {
            using (RentlerContext context = new RentlerContext(false))
            {
                try
                {
                    var photo = (from p in context.Photos
                                 where p.PhotoId == photoId
                                 select p).SingleOrDefault();

                    photo.SortOrder = sortOrder;

                    context.SaveChanges();

                    InvalidateCache(photo.BuildingId);

                    return(Status.OK <Photo>(photo));
                }
                catch (Exception ex)
                {
                    return(Status.Error <Photo>(ex.Message, null));
                }
            }
        }
Exemple #23
0
 public void Save()
 {
     context.SaveChanges();
 }
Exemple #24
0
        public Status <Order> ProcessOrder(
            string username, int orderId, UserCreditCard card, bool saveCard)
        {
            bool isNewCard = card.UserCreditCardId == 0;

            if (isNewCard)
            {
                // we're adding the new card regardless but we don't know if its valid
                // if the user requested to save it we will make it active after the payment
                // is successful, otherwise it will remain inactive
                card.IsDeleted = true;

                var cardResult = AddUserCreditCard(username, card);

                if (cardResult.StatusCode != 200)
                {
                    var orderStatus = GetOrderForCheckout(username, orderId);

                    orderStatus.StatusCode = 500;
                    orderStatus.Errors     = new ValidationResult[] {
                        new ValidationResult("An unexpected failure occurred: payment was not processed", new string[] { "Order" })
                    };

                    return(orderStatus);
                }
            }
            else
            {
                //get the card
                var storedCard = GetUserCreditCard(username, card.UserCreditCardId);

                if (storedCard == null)
                {
                    var orderStatus = GetOrderForCheckout(username, orderId);

                    orderStatus.StatusCode = 500;
                    orderStatus.Errors     = new ValidationResult[] {
                        new ValidationResult("Failed to locate credit card on file: payment was not processed", new string[] { "Order" })
                    };

                    return(orderStatus);
                }

                //update the billing address if anything changed
                if (storedCard.Address1 != card.Address1 ||
                    storedCard.Address2 != card.Address2 ||
                    storedCard.City != card.City ||
                    storedCard.FirstName != card.FirstName ||
                    storedCard.LastName != card.LastName ||
                    storedCard.State != card.State ||
                    storedCard.Zip != card.Zip)
                {
                    storedCard.Address1  = card.Address1;
                    storedCard.Address2  = card.Address2;
                    storedCard.City      = card.City;
                    storedCard.FirstName = card.FirstName;
                    storedCard.LastName  = card.LastName;
                    storedCard.State     = card.State;
                    storedCard.Zip       = card.Zip;

                    var updateStatus = UpdateUserCreditCard(username, storedCard);

                    if (updateStatus.StatusCode != 200)
                    {
                        var orderStatus = GetOrderForCheckout(username, orderId);

                        orderStatus.StatusCode = 500;
                        orderStatus.Errors     = new ValidationResult[] {
                            new ValidationResult("Failed to update card address: payment was not processed", new string[] { "Order" })
                        };

                        return(orderStatus);
                    }
                }

                card = storedCard;
            }

            //grab the order
            var order = GetOrderForCheckout(username, orderId);

            //attach the credit card to the order for our records
            order.Result.UserCreditCardId = card.UserCreditCardId;

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

            //let's pay for stuff!

            CardPaymentResult result;

            if (App.StorePricing == "Penny")
            {
                result = manager.AuthorizeCreditCardPayment(card, 0.01m);
            }
            else
            {
                result = manager.AuthorizeCreditCardPayment(card, order.Result.OrderTotal);
            }

            //did it work?
            if (result.Approved)
            {
                order.Result.OrderStatus = OrderStatus.Succeeded;
            }
            else
            {
                order.StatusCode = 500;

                // the payment method used is not valid so it should not be attached to
                // the order. Clear it here and the change will be persisted later
                order.Result.UserCreditCardId = null;

                //gateway might be down
                if (result.ServiceUnavailable)
                {
                    order.Result.OrderStatus = OrderStatus.ServiceUnavailable;
                    order.Errors             = new ValidationResult[] {
                        new ValidationResult("Payment service is unavailable. Please try again later.", new string[] { "Order" })
                    };
                }
                //or it was declined
                else
                {
                    order.Result.OrderStatus = OrderStatus.CardDeclined;
                    order.Errors             = new ValidationResult[] {
                        new ValidationResult("Credit Card was declined", new string[] { "Order" })
                    };
                }
            }

            //update the order status
            using (var context = new RentlerContext())
            {
                var toUpdate = (from o in context.Orders
                                .Include("Building")
                                where o.OrderId == order.Result.OrderId
                                select o).SingleOrDefault();

                toUpdate.OrderStatus      = order.Result.OrderStatus;
                toUpdate.UserCreditCardId = order.Result.UserCreditCardId;

                //remove temporary order if we're good
                if (order.Result.OrderStatus == OrderStatus.Succeeded)
                {
                    toUpdate.Building.TemporaryOrderId = null;

                    // allow credit card to be used again if requested
                    if (isNewCard && saveCard)
                    {
                        context.Entry(toUpdate).Reference(o => o.UserCreditCard).Load();
                        toUpdate.UserCreditCard.IsDeleted = false;
                    }
                }

                context.SaveChanges();
            }

            // send receipt only if order was successful
            if (order.Result.OrderStatus == OrderStatus.Succeeded)
            {
                //send a receipt
                EmailOrderReceiptModel model = new EmailOrderReceiptModel()
                {
                    To         = order.Result.User.Email,
                    Name       = string.Format("{0} {1}", order.Result.User.FirstName, order.Result.User.LastName),
                    BuildingId = (order.Result.BuildingId.HasValue) ? order.Result.BuildingId.Value : 0,
                    OrderItems = order.Result.OrderItems.ToList(),
                    OrderTotal = order.Result.OrderTotal
                };
                mailer.Receipt(model);
            }

            return(order);
        }
Exemple #25
0
        public Status <Guid> GetAuthToken(ApiKey apiKey, string affiliateUserKey,
                                          string email, string passwordHash,
                                          string firstName, string lastName, string username)
        {
            RedisPublisher.Publish("token", "Getting token for api key: " + apiKey.ToString());

            //check if user exists
            var userId = accountAdapter.GetAffiliateUserIdByUsernameOrEmailAndApiKey(email, apiKey.ApiKeyId);

            //did we not find anything?
            if (userId.StatusCode == 404)
            {
                //try again, looking for regular rentler users this time
                userId = accountAdapter.GetUserIdByUsernameOrEmail(email);

                //still didn't find anything?
                if (userId.StatusCode == 404)
                {
                    //we've got a new one, make 'em
                    var user = new User();
                    user.Email         = email;
                    user.FirstName     = firstName;
                    user.LastName      = lastName ?? string.Empty;
                    user.Username      = username;
                    user.PasswordHash  = string.Empty;
                    user.CreateDateUtc = DateTime.UtcNow;
                    user.UpdatedBy     = "ksl auth";
                    user.UpdateDateUtc = DateTime.UtcNow;

                    var status = Status.Validatate <User>(user);

                    if (status.StatusCode != 200)
                    {
                        var result = Status.NotFound <Guid>();
                        result.Errors = status.Errors;

                        return(result);
                    }


                    using (var context = new RentlerContext())
                    {
                        context.Users.Add(user);
                        context.SaveChanges();
                        userId = Status.OK(user.UserId);
                    }
                }

                //Okay, now they're either already a Rentler user but are coming in from an affiliate,
                //or they just became one from an affiliate, so create an affiliate user for them.
                using (var context = new RentlerContext())
                {
                    var affiliate = new AffiliateUser();
                    affiliate.UserId           = userId.Result;
                    affiliate.AffiliateUserKey = affiliateUserKey;
                    affiliate.ApiKey           = apiKey.ApiKeyId;
                    affiliate.PasswordHash     = passwordHash;
                    context.AffiliateUsers.Add(affiliate);
                    context.SaveChanges();
                }
            }

            //generate auth token
            var token = CreateAuthToken(userId.Result);

            RedisPublisher.Publish("token", "Returning token: " + token.ToString());

            //return token
            return(Status.OK(token));
        }
Exemple #26
0
        public Status <Photo[]> UploadPhotos(string username, long buildingId, UploadFileStream[] files)
        {
            using (var context = new RentlerContext())
            {
                try
                {
                    // get the building
                    var building = (from b in context.Buildings
                                    where b.User.Username == username &&
                                    b.BuildingId == buildingId
                                    select b).SingleOrDefault();

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

                    int nextPosition = building.Photos.Count;

                    List <Photo> final = new List <Photo>();

                    foreach (var upload in files)
                    {
                        if (upload == null)
                        {
                            continue;
                        }

                        Photo photo = new Photo();
                        photo.Extension     = Path.GetExtension(upload.FileName).ToLower();
                        photo.BuildingId    = building.BuildingId;
                        photo.CreateDateUtc = DateTime.UtcNow;
                        photo.CreatedBy     = "photoadapter";
                        photo.UpdateDateUtc = DateTime.UtcNow;
                        photo.UpdatedBy     = "photoadapter";
                        photo.PhotoId       = Guid.NewGuid();
                        photo.SortOrder     = nextPosition;

                        if (!Rentler.Configuration.Photos.Current.SupportedExtensions.Contains(photo.Extension))
                        {
                            continue;
                        }

                        UploadPhotoToAzure(upload.Stream, photo, 800, 600);
                        UploadPhotoToAzure(upload.Stream, photo, 600, 395);
                        UploadPhotoToAzure(upload.Stream, photo, 280, 190);
                        UploadPhotoToAzure(upload.Stream, photo, 200, 150);
                        UploadPhotoToAzure(upload.Stream, photo, 115, 85);
                        UploadPhotoToAzure(upload.Stream, photo, 50, 50);

                        building.Photos.Add(photo);

                        // see if it's the first photo uploaded
                        if (nextPosition == 0)
                        {
                            building.PrimaryPhotoId        = photo.PhotoId;
                            building.PrimaryPhotoExtension = photo.Extension;
                        }

                        context.SaveChanges();

                        photo.Building = null;
                        final.Add(photo);

                        nextPosition++;
                    }

                    InvalidateCache(buildingId);

                    return(Status.OK <Photo[]>(final.ToArray()));
                }
                catch (Exception ex)
                {
                    return(Status.Error <Photo[]>(ex.Message, null));
                }
            }
        }
Exemple #27
0
        public Status <bool> RemovePhoto(string username, Guid photoId)
        {
            if (string.IsNullOrWhiteSpace(username))
            {
                return(Status.ValidationError <bool>(false, "username", "User not authenticated"));
            }

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

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

                    var photo = building.Photos.SingleOrDefault(p => p.PhotoId == photoId);

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

                    context.Photos.Remove(photo);

                    // primary photo is being removed
                    if (building.PrimaryPhotoId == photoId)
                    {
                        // get new primary photo (next in line)
                        var nextPhoto = (from p in building.Photos
                                         where p.PhotoId != photoId
                                         orderby p.SortOrder
                                         select p).FirstOrDefault();

                        // if there isn't one then it doesn't matter
                        if (nextPhoto == null)
                        {
                            building.PrimaryPhotoId        = null;
                            building.PrimaryPhotoExtension = null;
                        }
                        else
                        {
                            building.PrimaryPhotoId        = nextPhoto.PhotoId;
                            building.PrimaryPhotoExtension = nextPhoto.Extension;
                        }
                    }

                    context.SaveChanges();


                    InvalidateCache(building.BuildingId);

                    return(Status.OK <bool>(true));
                }
                catch (Exception ex)
                {
                    return(Status.Error <bool>(ex.Message, false));
                }
            }
        }
        /// <summary>
        /// Sets the application for user.
        /// </summary>
        /// <param name="username">The username of the user to set the application for.</param>
        /// <param name="userApplication">The user's application.</param>
        /// <returns>
        /// The user application that was saved.
        /// </returns>
        public Status <UserApplication> SaveApplicationForUser(
            string username, UserApplication userApplication)
        {
            var identity = CustomAuthentication.GetIdentity();

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

            using (var context = new RentlerContext())
            {
                try
                {
                    bool isNew = false;

                    var application = (from u in context.UserApplications
                                       where u.UserId == identity.UserId
                                       select u).SingleOrDefault();

                    if (application == null)
                    {
                        application = new UserApplication {
                            UserId = identity.UserId
                        };
                        isNew = true;
                    }

                    application.ConvictedExplaination        = userApplication.ConvictedExplaination;
                    application.EmergencyContact             = userApplication.EmergencyContact;
                    application.EmergencyContactAddressLine1 = userApplication.EmergencyContactAddressLine1;
                    application.EmergencyContactAddressLine2 = userApplication.EmergencyContactAddressLine2;
                    application.EmergencyContactCity         = userApplication.EmergencyContactCity;
                    application.EmergencyContactPhone        = userApplication.EmergencyContactPhone;
                    application.EmergencyContactState        = userApplication.EmergencyContactState;
                    application.EmergencyContactZip          = userApplication.EmergencyContactZip;
                    application.FirstName                   = userApplication.FirstName;
                    application.HasBeenConvicted            = userApplication.HasBeenConvicted;
                    application.HasEverBeenUnlawfulDetainer = userApplication.HasEverBeenUnlawfulDetainer;
                    application.LastName              = userApplication.LastName;
                    application.PresentAddressLine1   = userApplication.PresentAddressLine1;
                    application.PresentAddressLine2   = userApplication.PresentAddressLine2;
                    application.PresentCity           = userApplication.PresentCity;
                    application.PresentEmployer       = userApplication.PresentEmployer;
                    application.PresentEmployerPhone  = userApplication.PresentEmployerPhone;
                    application.PresentLandlord       = userApplication.PresentLandlord;
                    application.PresentLandlordPhone  = userApplication.PresentLandlordPhone;
                    application.PresentPhone          = userApplication.PresentPhone;
                    application.PresentState          = userApplication.PresentState;
                    application.PresentZip            = userApplication.PresentZip;
                    application.PreviousAddressLine1  = userApplication.PreviousAddressLine1;
                    application.PreviousAddressLine2  = userApplication.PreviousAddressLine2;
                    application.PreviousCity          = userApplication.PreviousCity;
                    application.PreviousEmployer      = userApplication.PreviousEmployer;
                    application.PreviousEmployerPhone = userApplication.PreviousEmployerPhone;
                    application.PreviousLandlord      = userApplication.PreviousLandlord;
                    application.PreviousLandlordPhone = userApplication.PreviousLandlordPhone;
                    application.PreviousState         = userApplication.PreviousState;
                    application.PreviousZip           = userApplication.PreviousZip;
                    application.Ssn                  = userApplication.Ssn;
                    application.UpdateDateUtc        = DateTime.UtcNow;
                    application.UpdatedBy            = "accountadapter";
                    application.VehicleColor         = userApplication.VehicleColor;
                    application.VehicleLicenseNumber = userApplication.VehicleLicenseNumber;
                    application.VehicleMake          = userApplication.VehicleMake;
                    application.VehicleModel         = userApplication.VehicleModel;
                    application.VehicleState         = userApplication.VehicleState;
                    application.VehicleYear          = userApplication.VehicleYear;

                    // new applications need to be added to the context
                    if (isNew)
                    {
                        context.UserApplications.Add(application);
                    }

                    context.SaveChanges();

                    return(Status.OK <UserApplication>(application));
                }
                catch (Exception ex)
                {
                    // TODO: log exception
                    return(Status.Error <UserApplication>("System was unable to create/update application", null));
                }
            }
        }