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;
            }
        }
        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;
            }
        }
        public ActionResult Create(HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                MemoryStream target = new MemoryStream();
                file.InputStream.CopyTo(target);
                byte[] data = target.ToArray();

                UploadModel model = new UploadModel
                {
                    ContentType = file.ContentType,
                    Contents = data
                };

                UploadModel upload = new UploadService().UploadFile(LayoutViewModel.ProviderUserKey, model);

            }

            return View();
        }
        public ActionResult Index(UpdateSupplierProfileViewModel viewModel)
        {
            LayoutViewModel.ActiveLink = Links.SupplierUpdateProfile;

            var membershipUser = Membership.GetUser();

            if (ModelState.IsValid)
            {
                UserModel userModel = new UserModel
                {
                    Id = LayoutViewModel.CurrentAccountId,
                    FirstName = viewModel.FirstName,
                    LastName = viewModel.LastName,
                    PhotoID = viewModel.PhotoID,
                    BusinessName = viewModel.BusinessName,
                    BusinessNumberABN = viewModel.BusinessNumberABN,
                    BusinessType = viewModel.BusinessType,
                    BussinesEmail = viewModel.BussinesEmail,
                    BussinesLocation = viewModel.BussinesLocation,
                    BussinesPhone = viewModel.BussinesPhone,
                    BussinesPhoneArea = viewModel.BussinesPhoneArea,
                    BussinesPhoneMobile = viewModel.BussinesPhoneMobile,
                    BussinesWebSite = viewModel.BussinesWebSite,
                    EmailBussinesOnVoucherRedeem = viewModel.EmailBussinesOnVoucherRedeem,
                    SendEmailUpdates = viewModel.SendEmailUpdates
                };

                var success = true;

                // change password
                if (!string.IsNullOrEmpty(viewModel.OldPassword) || !string.IsNullOrEmpty(viewModel.NewPassword)
                    || !string.IsNullOrEmpty(viewModel.ConfirmNewPassword))
                {
                    if (string.IsNullOrEmpty(viewModel.OldPassword))
                    {
                        ModelState.AddModelError("OldPassword", "The Old password field is required.");
                        success = false;
                    }

                    if (string.IsNullOrEmpty(viewModel.NewPassword))
                    {
                        ModelState.AddModelError("NewPassword", "The New password field is required.");
                        success = false;
                    }

                    if (string.IsNullOrEmpty(viewModel.ConfirmNewPassword))
                    {
                        ModelState.AddModelError("ConfirmNewPassword", "The Confirm new password field is required.");
                        success = false;
                    }

                    if (success && viewModel.NewPassword != viewModel.ConfirmNewPassword)
                    {
                        ModelState.AddModelError("ConfirmNewPassword", "New password and confirmation password do not match.");
                        success = false;
                    }

                    if (success && !membershipUser.ChangePassword(viewModel.OldPassword, viewModel.NewPassword))
                    {
                        ModelState.AddModelError("OldPassword", "Old password is incorrect.");
                        success = false;
                    }
                }

                if (viewModel.Photo != null && viewModel.Photo.ContentLength > 0)
                {
                    MemoryStream target = new MemoryStream();
                    viewModel.Photo.InputStream.CopyTo(target);
                    byte[] data = target.ToArray();

                    UploadModel model = new UploadModel
                    {
                        ContentType = viewModel.Photo.ContentType,
                        Contents = data,
                        FileName = viewModel.Photo.FileName
                    };

                    UploadModel upload = new UploadService().UploadFile(membershipUser.ProviderUserKey.ToString(), model, true);

                }

                if (success)
                {
                    var updated = new UserService().UpdateSupplierUser(userModel);

                    // change username COMPLICATED
                    if (membershipUser.UserName != viewModel.BussinesEmail)
                    {

                        var config = WebConfigurationManager.OpenWebConfiguration("~");
                        var section = config.SectionGroups["system.web"].Sections["membership"] as MembershipSection;
                        var defaultProvider = section.DefaultProvider;
                        var connectionStringName = section.Providers[defaultProvider].ElementInformation.Properties["connectionStringName"].Value.ToString();

                        string connectionString = config.ConnectionStrings.ConnectionStrings[connectionStringName].ConnectionString;

                        var changed = new ProfileService().ChangeUsername(membershipUser.UserName, viewModel.BussinesEmail, connectionString);

                        if (changed)
                        {
                            // change email as well
                            membershipUser.Email = viewModel.BussinesEmail;

                            // need to re-verify
                            membershipUser.IsApproved = false;
                            //SendVerifyEmail(membershipUser, user, false);
                            //instead I'm showing verifucation code in the view

                            Membership.UpdateUser(membershipUser);

                            // need to sign out to force verification
                            FormsAuthentication.SignOut();

                            TempData["VerifyCode"] = ZBase32.Encode(LayoutViewModel.CurrentAccountId.ToByteArray());

                            // redirect to screen which tells user to check email
                            return RedirectToAction("EmailChangeSuccess", "Account");
                        }
                        else
                        {
                            ModelState.AddModelError("", "A user for that email address already exists. Please enter a different email address.");
                        }
                    }

                    return RedirectToAction("Dashboard");
                }

                return View(viewModel);
            }

            return View(viewModel);
        }
        public ActionResult UpdateProfileAuspost(UpdateProfileAuspostViewModel viewModel)
        {
            LayoutViewModel.ActiveLink = Links.AccountUpdateProfile;

            var membershipUser = Membership.GetUser();

            if (ModelState.IsValid)
            {
                UpdateProfileModel updateModel = new UpdateProfileModel();

                updateModel.FirstName = viewModel.FirstName;
                updateModel.LastName = viewModel.LastName;
                updateModel.PhoneNumber = viewModel.PhoneNumber;
                updateModel.Sex = viewModel.Sex;
                updateModel.PushNotifications = viewModel.PushNotifications;
                updateModel.EmploymentType = viewModel.EmploymentType;

                if (viewModel.DateOfBirthDay != null && viewModel.DateOfBirthMonth != null && viewModel.DateOfBirthYear != null)
                {
                    updateModel.BirthDate =
                        new DateTime(year: viewModel.DateOfBirthYear.Value,
                            month: viewModel.DateOfBirthMonth.Value,
                            day: viewModel.DateOfBirthDay.Value);
                }

                // find new user's address
                //int? addressId = new UserService().FindMatchingAuspostAddressId(
                //    streetName: viewModel.StreetName,
                //    streetType: viewModel.StreetType,
                //    suburb: viewModel.Subrp,
                //    state: viewModel.State
                //    );

                //if (addressId != null)
                //{
                //    updateModel.AddressId = addressId;
                //}
                //else
                //{
                //    FillBaseViewModelData(viewModel);

                //    ModelState.AddModelError("", "Incomplete workplace details. Please update your details and save.");
                //    return View(viewModel);
                //}

                var success = true;

                // change password
                if (!string.IsNullOrEmpty(viewModel.OldPassword) || !string.IsNullOrEmpty(viewModel.NewPassword)
                    || !string.IsNullOrEmpty(viewModel.ConfirmNewPassword))
                {
                    if (string.IsNullOrEmpty(viewModel.OldPassword))
                    {
                        ModelState.AddModelError("OldPassword", "The Old password field is required.");
                        success = false;
                    }

                    if (string.IsNullOrEmpty(viewModel.NewPassword))
                    {
                        ModelState.AddModelError("NewPassword", "The New password field is required.");
                        success = false;
                    }

                    if (string.IsNullOrEmpty(viewModel.ConfirmNewPassword))
                    {
                        ModelState.AddModelError("ConfirmNewPassword", "The Confirm new password field is required.");
                        success = false;
                    }

                    if (success && viewModel.NewPassword != viewModel.ConfirmNewPassword)
                    {
                        ModelState.AddModelError("ConfirmNewPassword", "New password and confirmation password do not match.");
                        success = false;
                    }

                    if (success && !membershipUser.ChangePassword(viewModel.OldPassword, viewModel.NewPassword))
                    {
                        ModelState.AddModelError("OldPassword", "Old password is incorrect.");
                        success = false;
                    }
                }

                if (viewModel.Photo != null && viewModel.Photo.ContentLength > 0)
                {
                    MemoryStream target = new MemoryStream();
                    viewModel.Photo.InputStream.CopyTo(target);
                    byte[] data = target.ToArray();

                    UploadModel model = new UploadModel
                    {
                        ContentType = viewModel.Photo.ContentType,
                        Contents = data,
                        FileName = viewModel.Photo.FileName
                    };

                    UploadModel upload = new UploadService().UploadFile(LayoutViewModel.ProviderUserKey, model, true);

                }

                if (success)
                {

                    var updated =
                        new ProfileService().UpdateProfile(LayoutViewModel.ProviderUserKey, updateModel);

                    // change username COMPLICATED
                    if (membershipUser.UserName != viewModel.Email)
                    {

                        var config = WebConfigurationManager.OpenWebConfiguration("~");
                        var section = config.SectionGroups["system.web"].Sections["membership"] as MembershipSection;
                        var defaultProvider = section.DefaultProvider;
                        var connectionStringName = section.Providers[defaultProvider].ElementInformation.Properties["connectionStringName"].Value.ToString();

                        string connectionString = config.ConnectionStrings.ConnectionStrings[connectionStringName].ConnectionString;

                        string companyEmail = string.Join(viewModel.CompanyEmail, viewModel.CompanyEmailDomain);

                        var changed = new ProfileService().ChangeUsername(membershipUser.UserName, companyEmail, connectionString);

                        if (changed)
                        {
                            // change email as well
                            membershipUser.Email = companyEmail;

                            // need to re-verify
                            membershipUser.IsApproved = false;
                            SendVerifyEmail(membershipUser.Email, updateModel.FirstName, LayoutViewModel.CurrentAccountId, false);

                            //instead I'm showing verifucation code in the view
                            Membership.UpdateUser(membershipUser);

                            // need to sign out to force verification
                            FormsAuthentication.SignOut();

                            TempData["VerifyCode"] = ZBase32.Encode(LayoutViewModel.CurrentAccountId.ToByteArray());

                            // redirect to screen which tells user to check email
                            return RedirectToAction("EmailChangeSuccess");
                        }
                        else
                        {
                            ModelState.AddModelError("", "A user for that email address already exists. Please enter a different email address.");
                        }
                    }

                    return RedirectToAction("MyProfile");

                }

                //Something not valid, show errors
                viewModel.SupportEmail = ConfigurationManager.AppSettings["SupportEmail"];

                return View(viewModel);
            }

            FillBaseViewModelData(viewModel);

            return View(viewModel);
        }
 public UploadModel UploadFile(string providerUserKey, UploadModel model, bool isProfilePhoto = false)
 {
     return new UploadsRepository().UploadFile(providerUserKey, model, isProfilePhoto);
 }
        public ActionResult Create(CreateChallengeViewModel model, string saveAndPreviewButton, string saveAndExitButton)
        {
            LayoutViewModel.ActiveLink = Links.CreateChallenge;

            var membershipUser = Membership.GetUser();

            if (membershipUser != null && membershipUser.ProviderUserKey != null)
            {
                if (LayoutViewModel.IsCouncil)
                {

                    if (ModelState.IsValid)
                    {
                        ChallengeModel challengeModel = new ChallengeModel();

                        Utils.CopyProperties(model, challengeModel);

                        if (model.LogoPhoto != null && model.LogoPhoto.ContentLength > 0)
                        {
                            MemoryStream target = new MemoryStream();
                            model.LogoPhoto.InputStream.CopyTo(target);
                            byte[] data = target.ToArray();

                            UploadModel uploadModel = new UploadModel
                            {
                                ContentType = model.LogoPhoto.ContentType,
                                Contents = data,
                                FileName = model.LogoPhoto.FileName
                            };

                            UploadModel upload = new UploadService().UploadFile(membershipUser.ProviderUserKey.ToString(), uploadModel);
                            challengeModel.LogoImageId = upload.UploadId;
                        }

                        if (model.ProfileImage != null)
                        {
                            List<UploadModel> profileImages = new List<UploadModel>();

                            for (var i = 0; i < 4; i++)
                            {
                                var image = model.ProfileImage[i];
                                UploadModel uploadModel = new UploadModel();

                                if (image != null)
                                {
                                    MemoryStream target = new MemoryStream();
                                    image.InputStream.CopyTo(target);
                                    byte[] data = target.ToArray();

                                    uploadModel.ContentType = image.ContentType;
                                    uploadModel.Contents = data;
                                    uploadModel.FileName = image.FileName;
                                }

                                profileImages.Add(uploadModel);

                            }

                            challengeModel.ProfileImages = profileImages;
                        }

                        // rewardModel.PartnerEmail = model.PartnerEmail ?? membershipUser.Email;

                        if (model.StartDate == DateTime.MinValue)
                        {
                            challengeModel.StartDate = null;
                        }
                        if (model.EndDate == DateTime.MinValue)
                        {
                            challengeModel.EndDate = null;
                        }

                        if (model.Points == null)
                        {
                            challengeModel.Points = 0;
                        }

                        int? challengeId;
                        if (model.IsUpdate)
                        {
                            challengeId = new ChallengesAdminService().UpdateChallenge((Guid)membershipUser.ProviderUserKey, challengeModel);
                        }
                        else
                        {
                            challengeId = new ChallengesAdminService().CreateChallenge((Guid)membershipUser.ProviderUserKey, challengeModel);
                        }

                        if (challengeId != null)
                        {
                            //if (rewardModel.State == (int)RewardState.WaitingApproval)
                            //{
                            //    SendRewardSubmitEmail(rewardModel);
                            //}
                        }
                        else
                        {
                            ModelState.AddModelError("", "Unable to save changes to database");

                            ViewModelHelper.SetDefaultsForChallengeViewModel(model, membershipUser);

                            return View(model);
                        }

                        //if (saveAndApproveButton != null)
                        //{
                        //    return RedirectToAction("Create", new { id = rewardId, approve = true });
                        //}
                        if (saveAndExitButton != null)
                        {
                            return RedirectToAction("Index");
                        }
                        if (saveAndPreviewButton != null)
                        {
                            // redirect to Challenge page
                            return RedirectToAction("Details", "Challenges", new { id = challengeId });
                        }

                        return RedirectToAction("Create", new { id = challengeId });

                    }

                    ViewModelHelper.SetDefaultsForChallengeViewModel(model, membershipUser);

                    if (model.IsInitialRegistrationStep)
                    {
                        LayoutViewModel.HideTopWrapperMenu = true;
                    }

                    return View(model);
                }
                else
                    return RedirectToAction("Index", "Home");
            }
            else
                return RedirectToAction("Index", "Home");
        }