Example #1
0
        public UserModel AddUserToInInterestedPeople(UserModel userModel)
        {
            using (var context = new greenMoneyEntities())
            {
                var ip = new InterestedPeople
                {
                    FirstName = userModel.FirstName,
                    LastName = userModel.LastName,
                    SendEmailOffers = false,//registrationViewModel.SendEmailOffers, //Redesing
                    SendEmailUpdates = userModel.SendEmailOffers,
                    Email = userModel.Email,
                    Postcode = userModel.Postcode,
                    Gender = null, //model.Sex, //Redesing
                    DateOfBirth = userModel.DateOfBirth,
                    FreeStandingHome = true,
                    HasRfidTag = false,
                    StreetName = "N/A",
                    StreetNumber = "N/A",
                    StreetType = "N/A",
                    State = "N/A",
                    Suburb = "N/A",
                    UnitNumber = "N/A"
                };

                context.InterestedPeople.Add(ip);
                context.SaveChanges();

                return userModel;
            }
        }
        public bool AddPoints(int userChallengeId)
        {
            using (var context = new greenMoneyEntities())
            {
                var time = DateTime.Now;

                UserChallenges userChallenge = context.UserChallenges.Single(x => x.Id == userChallengeId);
                Users1 user = context.Users1.Single(x => x.Id == userChallenge.UserId);
                Challenges challenge = context.Challenges.Single(x => x.Id == userChallenge.ChallengeId);

                userChallenge.PointsClaimed = true;

                var transaction = new Transactions
                {
                    Address_Id = user.Address_Id,
                    User_Id = user.Id,
                    Time = time,
                    Description = "Challenge " + challenge.Name,
                    Points = Convert.ToInt64(challenge.Points),
                    TransactionTypeID = 2
                };

                context.Transactions.Add(transaction);
                context.SaveChanges();

                return true;
            }
        }
        public UploadModel UploadFile(string providerUserKey, UploadModel model, bool isProfilePhoto = false)
        {
            using (var context = new greenMoneyEntities())
            {

                var upload = context.Uploads.Create();

                var user = context.Users1.Find(new Guid(providerUserKey));

                upload.Contents = model.Contents;
                upload.ContentType = model.ContentType;
                upload.FileName = model.FileName;
                upload.UploadedBy_Id = user.Id;

                context.Uploads.Add(upload);

                context.SaveChanges();

                if (isProfilePhoto)
                {
                    user.PhotoID = upload.Id;
                }

                context.SaveChanges();

                model.UploadId = upload.Id;

                return model;
            }
        }
Example #4
0
        public SectionModel GetSection(int id)
        {
            using (var context = new greenMoneyEntities())
            {

                Pages page = context.Pages.SingleOrDefault(w => w.Id == id);

                SectionModel model = new SectionModel();

                SectionEntityModel sectionModel = new SectionEntityModel();

                Sections section = context.Sections.SingleOrDefault(x => x.Id == page.Sections.Id);

                Utils.CopyProperties(section, sectionModel);
                model.Section = sectionModel;

                List<Pages> pages = context.Pages
                                            .Where(x => x.Sections.Id == section.Id)
                                            .OrderBy(o => o.OrderId)
                                            .ToList();

                List<PageModel> pagesList = new List<PageModel>();
                foreach (var item in pages)
                {
                    PageModel pmodel = new PageModel();
                    Utils.CopyProperties(item, pmodel);

                    pagesList.Add(pmodel);
                }

                model.Pages = pagesList;

                return model;
            }
        }
        public bool CheckInInstance(int challengeId, Guid userId)
        {
            using (var context = new greenMoneyEntities())
            {
                var challenge = context.Challenges.SingleOrDefault(x => x.Id == challengeId);
                var user = context.Users1.Single(x => x.Id == userId);

                bool InInstance = (challenge.Instance_Id == user.Instance_Id);
                return InInstance;
            }
        }
 public bool CheckIfInMyChallenges(string providerUserKey, int id)
 {
     try
     {
         using (var context = new greenMoneyEntities())
         {
             var isInMyChallenges = context.UserChallenges.Any(c => c.UserId == new Guid(providerUserKey) && c.ChallengeId == id);
             return isInMyChallenges;
         }
     }
     catch (Exception e)
     {
         return false;
     }
 }
        public UploadModel GetUpload(int id)
        {
            using (var context = new greenMoneyEntities())
            {
                var upload = context.Uploads.Find(id);

                if (upload != null)
                {
                    UploadModel model = new UploadModel();
                    model.Contents = upload.Contents;
                    upload.ContentType = upload.ContentType;

                    return model;
                }
                return null;
            }
        }
 //add points to translactions
 public bool AddPoints(string providerUserKey, int id, string promoCode = "")
 {
     try
     {
         using (var context = new greenMoneyEntities())
         {
             var user = context.Users1.Find(new Guid(providerUserKey));
             var time = DateTime.Now;
             var userChallenge =
                 context.UserChallenges.FirstOrDefault(
                     x => x.ChallengeId == id && x.UserId == user.Id);
             if (userChallenge != null)
             {
                 userChallenge.PointsClaimed = true;
                 var challenge = context.Challenges.SingleOrDefault(x => x.Id.Equals(id));
                 if (challenge != null)
                 {
                     //just for challenge action
                     if (string.IsNullOrEmpty(promoCode) || challenge.PromoCode.Equals(promoCode))
                     {
                         var addPoints = challenge.Points.HasValue ? Convert.ToInt64(challenge.Points.Value) : 0;
                         var transaction = new Transactions
                         {
                             Addresses = user.Addresses,
                             Users1 = user,
                             Time = time,
                             Description = "Challenge " + challenge.Name,
                             Points = +addPoints,
                             TransactionTypeID = 2
                         };
                         context.Transactions.Add(transaction);
                         context.SaveChanges();
                         return true;
                     }
                 }
             }
         }
         return false;
     }
     catch
     {
         return false;
     }
 }
        public List<ChallengeCategory> GetChallengeCategories()
        {
            using (var context = new greenMoneyEntities())
            {
               var categories = context.ChallengeCategories
                   .OrderBy(c => c.Name);

                List<ChallengeCategory> list = new List<ChallengeCategory>();
                foreach (var category in categories)
                {
                    ChallengeCategory model = new ChallengeCategory();
                    Utils.CopyProperties(category, model);

                    list.Add(model);
                }

                return list;
            }
        }
        public List<ChallengeAwardPointsOption> GetChallengeAwardPointsOptions()
        {
            using (var context = new greenMoneyEntities())
            {
                var options = context.AwardPointsOptions
                    .OrderBy(c => c.Name);

                List<ChallengeAwardPointsOption> list = new List<ChallengeAwardPointsOption>();
                foreach (var option in options)
                {
                    ChallengeAwardPointsOption model = new ChallengeAwardPointsOption();
                    Utils.CopyProperties(option, model);

                    list.Add(model);
                }

                return list;
            }
        }
 public bool ClaimedPoints(string providerUserKey, int id)
 {
     try
     {
         using (var context = new greenMoneyEntities())
         {
             var userChallenge = context.UserChallenges.SingleOrDefault(c => c.UserId == new Guid(providerUserKey) && c.ChallengeId == id);
             if (userChallenge != null)
             {
                 return userChallenge.PointsClaimed.HasValue && userChallenge.PointsClaimed.Value;
             }
             return false;
         }
     }
     catch (Exception e)
     {
         return false;
     }
 }
        //challenge
        public int? CreateChallenge(Guid providerUserKey, ChallengeModel model)
        {
            using (var context = new greenMoneyEntities())
            {
                var user = context.Users1.FirstOrDefault(u => u.Id == providerUserKey);
                if (user != null)
                {
                    Challenges challenge = new Challenges();

                    Utils.CopyProperties(model, challenge);

                    challenge.DateAdded = DateTime.Now;

                    context.Challenges.Add(challenge);
                     try
                    {
                        context.SaveChanges();

                        return challenge.Id;

                    }
                     catch (DbEntityValidationException dbEx)
                     {
                         foreach (var validationErrors in dbEx.EntityValidationErrors)
                         {
                             foreach (var validationError in validationErrors.ValidationErrors)
                             {
                                 Trace.TraceInformation("Class: {0}, Property: {1}, Error: {2}",
                                     validationErrors.Entry.Entity.GetType().FullName,
                                     validationError.PropertyName,
                                     validationError.ErrorMessage);
                             }
                         }

                         return null;
                     }
                }
            }
            return null;
        }
        public string AddSupplierAddressDefault()
        {
            using (var context = new greenMoneyEntities())
            {

                var address = context.Addresses.Create();
                address.Id = 1;
                address.StreetNumber = "1";
                address.Instance_Id = 1;
                address.StreetName = "Supplier";
                address.Suburb = "Supplier";
                address.StreetType = "Supplier";
                address.UnitNumber = "Supplier";
                address.State = "000";
                address.Postcode = "0000";

                context.Addresses.Add(address);
                context.SaveChanges();

                return address.Id.ToString();
            }
        }
        public ChallengeModel CopyChallenge(int id)
        {
            using (var context = new greenMoneyEntities())
            {
                Challenges challenge = context.Challenges.Single(x => x.Id == id);
                challenge.DateAdded = DateTime.Now;
                context.Challenges.Add(challenge);

                try
                {
                    context.SaveChanges();

                    ChallengeModel challengeModel = new ChallengeModel();

                    Utils.CopyProperties(challenge, challengeModel);
                    //  challengeModel.AustraliaState = challenge.State;

                    return challengeModel;

                }
                catch (DbEntityValidationException dbEx)
                {
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            Trace.TraceInformation("Class: {0}, Property: {1}, Error: {2}",
                                validationErrors.Entry.Entity.GetType().FullName,
                                validationError.PropertyName,
                                validationError.ErrorMessage);
                        }
                    }

                    return null;
                }
            }
        }
        public int? UpdateReward(Guid providerUserKey, RewardModel model)
        {
            using (var context = new greenMoneyEntities())
            {
                var user = context.Users1.FirstOrDefault(u => u.Id == providerUserKey);
                var reward = context.Rewards.FirstOrDefault(r => r.Id == model.Id);

                if (user != null && reward != null)
                {
                    reward.PartnerEmail = model.PartnerEmail;
                    Utils.CopyProperties(model, reward);

                    //CopyProperties doesn't work for null values...
                    reward.ImageSmallId = model.ImageSmallId;
                    reward.VoucherBarcodeId = model.VoucherBarcodeId;

                    if (model.ProfileImages.Count > 0)
                    {
                        if (model.ProfileImages[0] != null && model.ProfileImages[0].FileName != null)
                        {
                            var upload = new UploadsRepository().UploadFile(providerUserKey.ToString(), model.ProfileImages[0]);
                            reward.ImageId = upload.UploadId;
                        }
                        else if (model.ImageId == null)
                        {
                            Uploads uploadOld = context.Uploads.SingleOrDefault(x => x.Id == reward.ImageId);
                            if (uploadOld != null)
                            {
                                context.Uploads.Remove(uploadOld);
                                reward.ImageId = null;
                            }
                        }

                        if (model.ProfileImages[1] != null && model.ProfileImages[1].FileName != null)
                        {
                            var upload = new UploadsRepository().UploadFile(providerUserKey.ToString(), model.ProfileImages[1]);
                            reward.Image2Id = upload.UploadId;
                        }
                        else if (model.Image2Id == null)
                        {
                            Uploads uploadOld = context.Uploads.SingleOrDefault(x => x.Id == reward.Image2Id);
                            if (uploadOld != null)
                            {
                                context.Uploads.Remove(uploadOld);
                                reward.Image2Id = null;
                            }
                        }

                        if (model.ProfileImages[2] != null && model.ProfileImages[2].FileName != null)
                        {
                            var upload = new UploadsRepository().UploadFile(providerUserKey.ToString(), model.ProfileImages[2]);
                            reward.Image3Id = upload.UploadId;
                        }
                        else if (model.Image3Id == null)
                        {
                            Uploads uploadOld = context.Uploads.SingleOrDefault(x => x.Id == reward.Image3Id);
                            if (uploadOld != null)
                            {
                                context.Uploads.Remove(uploadOld);
                                reward.Image3Id = null;
                            }
                        }

                        if (model.ProfileImages[3] != null && model.ProfileImages[3].FileName != null)
                        {
                            var upload = new UploadsRepository().UploadFile(providerUserKey.ToString(), model.ProfileImages[3]);
                            reward.Image4Id = upload.UploadId;
                        }
                        else if (model.Image4Id == null)
                        {
                            Uploads uploadOld = context.Uploads.SingleOrDefault(x => x.Id == reward.Image4Id);
                            if (uploadOld != null)
                            {
                                context.Uploads.Remove(uploadOld);
                                reward.Image4Id = null;
                            }
                        }
                    }

                    try
                    {

                        context.SaveChanges();

                        return reward.Id;
                    }
                    catch (DbEntityValidationException dbEx)
                    {
                        foreach (var validationErrors in dbEx.EntityValidationErrors)
                        {
                            foreach (var validationError in validationErrors.ValidationErrors)
                            {
                                Trace.TraceInformation("Class: {0}, Property: {1}, Error: {2}",
                                    validationErrors.Entry.Entity.GetType().FullName,
                                    validationError.PropertyName,
                                    validationError.ErrorMessage);
                            }
                        }

                        return null;
                    }
                }
            }

            return null;
        }
        public int? UpdateChallenge(Guid providerUserKey, ChallengeModel model)
        {
            using (var context = new greenMoneyEntities())
            {
                var user = context.Users1.FirstOrDefault(u => u.Id == providerUserKey);
                var challenge = context.Challenges.FirstOrDefault(r => r.Id == model.Id);

                if (user != null && challenge != null)
                {

                    Utils.CopyProperties(model, challenge);
                    // challenge.State = model.AustraliaState;

                    challenge.Owner_Id = user.Id;
                    challenge.Instance_Id = user.Instance_Id;
                    challenge.LogoImageId = model.LogoImageId;

                    if (model.ProfileImages.Count > 0)
                    {
                        if (model.ProfileImages[0] != null && model.ProfileImages[0].FileName != null)
                        {
                            var upload = new UploadsRepository().UploadFile(providerUserKey.ToString(), model.ProfileImages[0]);
                            challenge.ImageId1 = upload.UploadId;
                        }
                        else if (model.ImageId1 == null)
                        {
                            Uploads uploadOld = context.Uploads.SingleOrDefault(x => x.Id == challenge.ImageId1);
                            if (uploadOld != null)
                            {
                                context.Uploads.Remove(uploadOld);
                                challenge.ImageId1 = null;
                            }
                        }

                        if (model.ProfileImages[1] != null && model.ProfileImages[1].FileName != null)
                        {
                            var upload = new UploadsRepository().UploadFile(providerUserKey.ToString(), model.ProfileImages[1]);
                            challenge.ImageId2 = upload.UploadId;
                        }
                        else if (model.ImageId2 == null)
                        {
                            Uploads uploadOld = context.Uploads.SingleOrDefault(x => x.Id == challenge.ImageId2);
                            if (uploadOld != null)
                            {
                                context.Uploads.Remove(uploadOld);
                                challenge.ImageId2 = null;
                            }
                        }

                        if (model.ProfileImages[2] != null && model.ProfileImages[2].FileName != null)
                        {
                            var upload = new UploadsRepository().UploadFile(providerUserKey.ToString(), model.ProfileImages[2]);
                            challenge.ImageId3 = upload.UploadId;
                        }
                        else if (model.ImageId3 == null)
                        {
                            Uploads uploadOld = context.Uploads.SingleOrDefault(x => x.Id == challenge.ImageId3);
                            if (uploadOld != null)
                            {
                                context.Uploads.Remove(uploadOld);
                                challenge.ImageId3 = null;
                            }
                        }

                        if (model.ProfileImages[3] != null && model.ProfileImages[3].FileName != null)
                        {
                            var upload = new UploadsRepository().UploadFile(providerUserKey.ToString(), model.ProfileImages[3]);
                            challenge.ImageId4 = upload.UploadId;
                        }
                        else if (model.ImageId4 == null)
                        {
                            Uploads uploadOld = context.Uploads.SingleOrDefault(x => x.Id == challenge.ImageId4);
                            if (uploadOld != null)
                            {
                                context.Uploads.Remove(uploadOld);
                                challenge.ImageId4 = null;
                            }
                        }
                    }

                    try
                    {
                        context.SaveChanges();

                        return challenge.Id;
                    }
                    catch (DbEntityValidationException dbEx)
                    {
                        foreach (var validationErrors in dbEx.EntityValidationErrors)
                        {
                            foreach (var validationError in validationErrors.ValidationErrors)
                            {
                                Trace.TraceInformation("Class: {0}, Property: {1}, Error: {2}",
                                    validationErrors.Entry.Entity.GetType().FullName,
                                    validationError.PropertyName,
                                    validationError.ErrorMessage);
                            }
                        }

                        return null;
                    }
                }
            }

            return null;
        }
        public RewardsListModel GetRewards(int? instanceId, int? excludeInstanceId, string sortBy, string category, string filter, int page, int pageSize)
        {
            using (var context = new greenMoneyEntities())
            {

                if (pageSize == 0)
                {
                    pageSize = 10;
                }

                //Get all rewards
                var rewards = context.Rewards
                    .Where(r => r.AvailableFrom == null || r.AvailableFrom.Value <= DateTime.Now)
                    .Where(r => r.AvailableTo == null || r.AvailableTo.Value > DateTime.Now)
                    .Where(r => r.Display)
                    .Where(
                        r =>
                            r.State == null || (int)r.State == (int)RewardState.Approved ||
                            (int)r.State == (int)RewardState.NotModerated).ToList();

                if (instanceId != null && instanceId != 0)
                {
                    rewards = rewards.Where(r => r.Instance_Id == instanceId).ToList();
                }
                else if (excludeInstanceId != null)
                {
                    rewards = rewards.Where(r => r.Instance_Id != excludeInstanceId).ToList();
                }

                //Filter all by text query
                if (!string.IsNullOrEmpty(filter))
                    rewards =
                        rewards.Where(
                            r =>
                                r.Name.ToLower().IndexOf(filter.ToLower()) > -1 ||
                                r.Description.ToLower().IndexOf(filter.ToLower()) > -1).ToList();

                List<Rewards> selected = new List<Rewards>();

                //Filter all by selected category
                RewardCategories rewardCategory;
                if (category != null)
                {
                    rewardCategory =
                        context.RewardCategories.FirstOrDefault(
                            c => category.Equals(c.Slug, StringComparison.OrdinalIgnoreCase));
                    if (rewardCategory == null)
                    {
                        throw new Exception("reward category not found");
                    }

                    //get all items, for selected and for subcategories
                    if (rewardCategory.ParentId == 0)
                    {
                        var allAvailableCategories = context.RewardCategories
                            .Where(c => c.Rewards.Any(
                                r => (r.AvailableFrom == null || r.AvailableFrom.Value <= DateTime.Now)
                                     && (r.AvailableTo == null || r.AvailableTo.Value > DateTime.Now)));

                        List<int> subCategoriesIds = allAvailableCategories
                            .Where(c => c.ParentId == rewardCategory.Id).Select(c => c.Id).ToList();

                        subCategoriesIds.Add(rewardCategory.Id);

                        foreach (var subCategoriesId in subCategoriesIds)
                        {
                            selected.AddRange(rewards.Where(r => r.CategoryId == subCategoriesId).ToList());
                        }
                    }
                    else
                    {
                        selected = rewards.Where(r => r.CategoryId == rewardCategory.Id).ToList();
                    }
                }
                else
                {
                    selected = rewards.ToList();
                }

                switch (sortBy)
                {
                    case "newest":
                        selected = selected.OrderByDescending(r => r.AvailableFrom).ThenByDescending(r => r.Id).ToList();
                        break;
                    case "oldest":
                        selected = selected.OrderBy(r => r.AvailableFrom).ThenBy(r => r.Id).ToList();
                        break;
                    case "cheapest":
                        selected = selected.OrderBy(r => r.Price).ToList();
                        break;
                    case "expensive":
                        selected = selected.OrderByDescending(r => r.Price).ToList();
                        break;
                    case "popular":
                        selected = selected.OrderByDescending(r => r.Popularity).ToList();
                        break;
                    default:
                        selected = selected.OrderByDescending(r => r.Popularity).ToList();
                        break;
                }

                //Include pagination
                var list = selected.Skip((page - 1) * pageSize).Take(pageSize);

                List<RewardModel> models = new List<RewardModel>();

                foreach (var item in list)
                {
                    RewardModel m = new RewardModel();
                    Utils.CopyProperties(item, m);

                    models.Add(m);
                }

                RewardsListModel model = new RewardsListModel
                {
                    RewardsList = models,
                    NumPages = (int)Math.Ceiling((double)selected.Count() / pageSize),
                    NumRewards = selected.Count(),
                    Page = page
                };

                return model;
            }
        }
        public UserChallengeModel GetUserChallenge(int id)
        {
            using (var context = new greenMoneyEntities())
            {
                UserChallenges userChallenge = context.UserChallenges.Single(x => x.Id == id);
                UserChallengeModel ucModel = new UserChallengeModel();

                Utils.CopyProperties(userChallenge, ucModel);

                return ucModel;
            }
        }
        public UserChallengeListModel GetUserChallenges(int id, int? orderBy, bool? pointsClaimed, string suburb, string search, int? timeRange, int page, int pageSize)
        {
            using (var context = new greenMoneyEntities())
            {
                UserChallengeListModel listModel = new UserChallengeListModel();
                if (timeRange == 100 || timeRange == null)
                    timeRange = 0;
                int range = (-1) * Convert.ToInt32(timeRange);
                DateTime history = DateTime.Now.Date.AddDays(range);

                var userChallenges = from uc in context.UserChallenges
                                     join u in context.Users1 on uc.UserId equals u.Id //uc.UserId.Equals(u.Id)
                                     join a in context.Addresses on u.Address_Id equals a.Id
                                     where uc.ChallengeId == id && (uc.PointsClaimed == pointsClaimed || pointsClaimed == null) && (a.Suburb == suburb || suburb == "Suburb") && (u.FirstName.Contains(search) || u.LastName.Contains(search))
                                            && (uc.Issued > history || range == 0)
                                     orderby uc.Issued descending
                                     select new
                                     {
                                         Id = uc.Id,
                                         ChallengeId = uc.ChallengeId,
                                         Issued = uc.Issued,
                                         UserId = uc.UserId,
                                         UserName = (String.IsNullOrEmpty(u.FirstName) ? "" : u.FirstName) + " " + (String.IsNullOrEmpty(u.LastName) ? "" : u.LastName),
                                         Suburb = a.Suburb,
                                         Workplace = a.StreetName,
                                         PointsClaimed = uc.PointsClaimed
                                     };

                if (pageSize == 0)
                    pageSize = userChallenges.Count();

                switch (orderBy)
                {
                    case 0: userChallenges = userChallenges.OrderByDescending(x => x.Issued);
                        break;
                    case 1: userChallenges = userChallenges.OrderBy(x => x.Issued);
                        break;
                }

                listModel.NumChallenges = userChallenges.Count();
                listModel.Page = page;
                listModel.NumPages = (int)Math.Ceiling((double)userChallenges.Count() / pageSize);

                userChallenges = userChallenges.Skip((page - 1) * pageSize).Take(pageSize);

                //var userChallenges = context.UserChallenges.Where(x => x.ChallengeId == id).Include(p => p.Users1);

                List<UserChallengeModel> list = new List<UserChallengeModel>();

                foreach (var userChallenge in userChallenges)
                {
                    UserChallengeModel userChallengeModel = new UserChallengeModel();
                    Utils.CopyProperties(userChallenge, userChallengeModel);
                    list.Add(userChallengeModel);
                }
                listModel.UserChallengeList = list;
                return listModel;

            }
        }
        public ChallengesListModel GetChallenges(Guid providerUserKey, int page, int pageSize, int orderBy, int? status, int? category, string search)
        {
            using (var context = new greenMoneyEntities())
            {
                var user = new UserRepository().GetUserById(providerUserKey);
                ChallengesListModel model = new ChallengesListModel();

                var challenges = context.Challenges.Where(r => r.Instance_Id == user.Instance_Id)
                                                    .Where(r => (category == null || category == 0) || r.ChallengeCategoryId == category)
                                                    .Where(r => search == null || r.Name.Contains(search) || r.About.Contains(search));

                DateTime now = DateTime.Now.Date;

                DateTime inWeek = DateTime.Now.Date.AddDays(7);

                switch (status)
                {
                    case 1: challenges = challenges.Where(x => x.Display == false);
                        break;
                    case 2: challenges = challenges.Where(x => (x.Display == true) && (x.StartDate <= now || x.StartDate == null) && (x.EndDate >= now || x.EndDate == null));
                        break;
                    case 3: challenges = challenges.Where(x => (x.Display == false) || (x.StartDate > now) || (x.EndDate < now));
                        break;
                    case 4: challenges = challenges.Where(x => x.EndDate > now && x.EndDate <= inWeek);
                        break;

                }

                model.NumChallenges = challenges.Count();
                model.Page = page;
                model.NumPages = (int)Math.Ceiling((double)challenges.Count() / pageSize);

                if (pageSize == 0)
                    pageSize = model.NumChallenges;

                List<ChallengeModel> list = new List<ChallengeModel>();
                //IEnumerable<ChallengeModel> list = new IEnumerable<ChallengeModel>();
                foreach (var challenge in challenges)
                {
                    var challengeModel = new ChallengeModel();
                    Utils.CopyProperties(challenge, challengeModel);
                    challengeModel.Participants = challenge.UserChallenges.Count();
                    //  challengeModel.AustraliaState = challenge.State;
                    if (challenge.ChallengeCategoryId != null)
                    {
                        challengeModel.ChallengeCategory = challenge.ChallengeCategories.Name;
                    }
                    else
                    {
                        challengeModel.ChallengeCategory = "";
                    }

                    if ((challenge.StartDate <= DateTime.Now || challenge.StartDate == null) && (challenge.EndDate >= now || challenge.EndDate == null) && (challenge.Display == true))
                    {
                        challengeModel.ChallengeStatus = "Active";
                    }
                    else
                    {
                        challengeModel.ChallengeStatus = "Not active";
                    }

                    list.Add(challengeModel);
                }

                switch (orderBy)
                {
                    case 0: list = list.OrderByDescending(x => x.DateAdded).ToList();
                        break;
                    case 1: list = list.OrderBy(x => x.DateAdded).ToList();
                        break;
                    case 2: list = list.OrderByDescending(x => x.Participants).ToList();
                        break;
                    case 3: list = list.OrderBy(x => x.EndDate).ToList();
                        break;
                    case 4: list = list.OrderByDescending(x => x.Popularity).ToList();
                        break;

                }

                model.ChallengesList = list.AsEnumerable<ChallengeModel>().Skip((page - 1) * pageSize).Take(pageSize).ToList();

                return model;
            }
        }
 public DateTime GetLastActivityDate(Guid id)
 {
     using (var context = new greenMoneyEntities())
     {
         var user = context.Users.SingleOrDefault(x => x.UserId == id);
         DateTime lastActivity = user.LastActivityDate;
         return lastActivity;
     }
 }
        public ChallengeModel GetChallengeDetails(int id)
        {
            using (var context = new greenMoneyEntities())
            {
                var challenge = context.Challenges.SingleOrDefault(x => x.Id == id);

                ChallengeModel model = new ChallengeModel();

                Utils.CopyProperties(challenge, model);
                // model.AustraliaState = challenge.State;

                return model;
            }
        }
        public List<ChallengeParticipationFrequency> GetChallengeParticipationFrequency()
        {
            using (var context = new greenMoneyEntities())
            {
                var frequencies = context.ParticipationFrequency
                    .OrderBy(c => c.Name);

                List<ChallengeParticipationFrequency> list = new List<ChallengeParticipationFrequency>();
                foreach (var frequency in frequencies)
                {
                    ChallengeParticipationFrequency model = new ChallengeParticipationFrequency();
                    Utils.CopyProperties(frequency, model);

                    list.Add(model);
                }

                return list;
            }
        }
        public RewardsListModel GetSupplierRewards(Guid providerUserKey, int page, int pageSize)
        {
            using (var context = new greenMoneyEntities())
            {

                var rewards = context.Rewards.Where(r => r.Owner_Id == providerUserKey);
                //var uploads = context.Uploads.Where(u => u.UploadedBy_Id == providerUserKey);

                //Include pagination
                var rewardsList = rewards.OrderByDescending(r => r.DateAdded).Skip((page - 1) * pageSize).Take(pageSize);

                List<RewardModel> list = new List<RewardModel>();
                foreach (var reward in rewardsList)
                {
                    RewardModel rewardModel = new RewardModel();
                    Utils.CopyProperties(reward, rewardModel);

                    list.Add(rewardModel);
                }

                RewardsListModel model = new RewardsListModel();
                model.RewardsList = list;
                model.NumRewards = rewards.Count();
                model.Page = page;
                model.NumPages = (int)Math.Ceiling((double)rewards.Count() / pageSize);

                return model;
            }
        }
        public List<ChallengeCategory> GetChallengeCategories(int instance_Id)
        {
            using (var context = new greenMoneyEntities())
            {
                var categories = context.ChallengeCategories
                    .OrderBy(c => c.Name);

                List<ChallengeCategory> list = new List<ChallengeCategory>();
                foreach (var category in categories)
                {

                    ChallengeCategory model = new ChallengeCategory();
                    Utils.CopyProperties(category, model);

                    //if ((instance_Id != 5) || (instance_Id == 5 && category.Id != 4))
                    //for all instances Invite neighbour is not shown
                    if (category.Id != 4)
                    {
                        list.Add(model);
                    }
                }

                return list;
            }
        }
        public bool DeleteUserChallenge(int id)
        {
            using (var context = new greenMoneyEntities())
            {
                UserChallenges userChallenge = context.UserChallenges.Single(x => x.Id == id);
                context.UserChallenges.Remove(userChallenge);
                try
                {
                    context.SaveChanges();
                }
                catch (Exception)
                {

                    return false;
                }
                return true;
            }
        }
        //challenge
        public int? CreateChallenge(Guid providerUserKey, ChallengeModel model)
        {
            using (var context = new greenMoneyEntities())
            {
                var user = context.Users1.FirstOrDefault(u => u.Id == providerUserKey);
                if (user != null)
                {
                    Challenges challenge = new Challenges();

                    Utils.CopyProperties(model, challenge);

                    challenge.Owner_Id = user.Id;
                    challenge.Instance_Id = user.Instance_Id;

                    challenge.DateAdded = DateTime.Now;
                    challenge.Popularity = 0;
                    //  challenge.State = model.AustraliaState;

                    if (model.ProfileImages.Count > 0)
                    {
                        if (model.ProfileImages[0] != null && model.ProfileImages[0].FileName != null)
                        {
                            var upload = new UploadsRepository().UploadFile(providerUserKey.ToString(), model.ProfileImages[0]);
                            challenge.ImageId1 = upload.UploadId;
                        }

                        if (model.ProfileImages[1] != null && model.ProfileImages[1].FileName != null)
                        {
                            var upload = new UploadsRepository().UploadFile(providerUserKey.ToString(), model.ProfileImages[1]);
                            challenge.ImageId2 = upload.UploadId;
                        }

                        if (model.ProfileImages[2] != null && model.ProfileImages[2].FileName != null)
                        {
                            var upload = new UploadsRepository().UploadFile(providerUserKey.ToString(), model.ProfileImages[2]);
                            challenge.ImageId3 = upload.UploadId;
                        }

                        if (model.ProfileImages[3] != null && model.ProfileImages[3].FileName != null)
                        {
                            var upload = new UploadsRepository().UploadFile(providerUserKey.ToString(), model.ProfileImages[3]);
                            challenge.ImageId4 = upload.UploadId;
                        }

                    }

                    context.Challenges.Add(challenge);
                    try
                    {
                        context.SaveChanges();

                        return challenge.Id;

                    }
                    catch (DbEntityValidationException dbEx)
                    {
                        foreach (var validationErrors in dbEx.EntityValidationErrors)
                        {
                            foreach (var validationError in validationErrors.ValidationErrors)
                            {
                                Trace.TraceInformation("Class: {0}, Property: {1}, Error: {2}",
                                    validationErrors.Entry.Entity.GetType().FullName,
                                    validationError.PropertyName,
                                    validationError.ErrorMessage);
                            }
                        }

                        return null;
                    }
                }
            }
            return null;
        }
        public bool DeleteReward(int id)
        {
            using (var context = new greenMoneyEntities())
            {
                Rewards reward = context.Rewards.Single(x => x.Id == id);
                context.Rewards.Remove(reward);
                context.SaveChanges();

                return true;
            }
        }
        public RewardsSummaryListModel GetSupplierRewardsSummary(Guid providerUserKey, int page, int pageSize)
        {
            using (var context = new greenMoneyEntities())
            {
                var rewards = context.Rewards.Where(r => r.Owner_Id == providerUserKey);

                //Include pagination
                var rewardsList = rewards.OrderByDescending(r => r.DateAdded).Skip((page - 1) * pageSize).Take(pageSize);

                List<RewardSummaryModel> list = new List<RewardSummaryModel>();
                foreach (var reward in rewardsList)
                {
                    RewardSummaryModel rewardModel = new RewardSummaryModel();
                    rewardModel.Id = reward.Id;
                    rewardModel.ImageSmallId = reward.ImageSmallId;
                    rewardModel.Name = reward.Name;
                    rewardModel.PartnerName = reward.PartnerName;
                    rewardModel.State = reward.State;

                    var instance = context.Instance.Where(i => i.Id == reward.Instance_Id).FirstOrDefault();
                    if (instance != null)
                    {
                        rewardModel.City = instance.Name;
                    }

                    rewardModel.NumOfRedemptions = context.Vouchers
                                                    .Where(v => v.Reward_Id == reward.Id)
                                                    .Count();

                    RewardState status = RewardState.NotModerated;

                    if (reward.State != null)
                    {
                        if (reward.State == (int)RewardState.Approved && reward.Display == true)
                        {
                            status = RewardState.Approved;
                        }
                        else if (reward.Display == false)
                        {
                            status = RewardState.NotDisplayed;
                        }
                        else if (reward.State == (int)RewardState.WaitingApproval)
                        {
                            status = RewardState.WaitingApproval;
                        }
                    }

                    rewardModel.RewardState = status;

                    list.Add(rewardModel);
                }

                RewardsSummaryListModel model = new RewardsSummaryListModel();
                model.RewardsList = list;
                model.NumRewards = rewards.Count();
                model.Page = page;
                model.NumPages = (int)Math.Ceiling((double)rewards.Count() / pageSize);

                return model;
            }
        }
        public VoucherModel GetVoucher(Guid id)
        {
            using (var context = new greenMoneyEntities())
            {
                var voucher = context.Vouchers.Find(id);

                VoucherModel model = new VoucherModel();
                model.VoucherId = voucher.Id;
                model.Issued = voucher.Issued;
                model.UserFirstName = voucher.Users1.FirstName;
                model.UserLastName = voucher.Users1.LastName;

                RewardModel rewardModel = new RewardModel();
                Utils.CopyProperties(voucher.Rewards, rewardModel);

                model.RewardModel = rewardModel;

                return model;
            }
        }