Exemplo n.º 1
0
        public async Task <bool> CreateAsync(ApplicationUser newUser, string password)
        {
            try
            {
                IdentityResult result = await UserManager.CreateAsync(newUser, password);

                return(Result_Helper(newUser, result));
            }
            catch (Exception e)
            {
                ErrorsGlobal.Add("User not created", MethodBase.GetCurrentMethod(), e);
                throw new Exception(ErrorsGlobal.ToString());
            }
        }
Exemplo n.º 2
0
        public void UpdateAndSaveDefaultAddress(string userId, string addressId, GlobalObject globalObject)
        {
            userId.IsNullOrWhiteSpaceThrowArgumentException("userId");
            addressId.IsNullOrWhiteSpaceThrowArgumentException("AddressId is null");

            AddressMain address = Find(addressId);

            address.IsNullThrowException("Address");

            //the default address must always be all three
            if (!address.AddressType.IsBillAddress || !address.AddressType.IsShipAddress || !address.AddressType.IsInformAddress)
            {
                if (!address.AddressType.IsBillAddress)
                {
                    ErrorsGlobal.AddMessage("Updated to Billing address.");
                }

                if (!address.AddressType.IsShipAddress)
                {
                    ErrorsGlobal.AddMessage("Updated to Shipping address.");
                }

                if (!address.AddressType.IsInformAddress)
                {
                    ErrorsGlobal.AddMessage("Updated to Inform To address.");
                }

                address.AddressType.IsBillAddress   = true;
                address.AddressType.IsShipAddress   = true;
                address.AddressType.IsInformAddress = true;
                Update(address);
            }

            Person person = UserBiz.GetPersonFor(userId);

            person.IsNullThrowException("Person not found");

            person.DefaultBillAddressId = addressId;

            ControllerCreateEditParameter param = new ControllerCreateEditParameter();

            param.Entity       = person as ICommonWithId;
            param.GlobalObject = globalObject;

            PersonBiz.UpdateAndSave(param);

            //PersonBiz.UpdateAndSave(person);
        }
Exemplo n.º 3
0
        public BuySellDocumentTypeENUM IsSaleOrPurchaseOrDelivery(BuySellDoc buySellDoc)
        {
            if (buySellDoc.BuySellDocumentTypeEnum == BuySellDocumentTypeENUM.Delivery)
            {
                return(BuySellDocumentTypeENUM.Delivery);
            }

            if (buySellDoc.CustomerId.IsNullOrWhiteSpace() && buySellDoc.OwnerId.IsNullOrWhiteSpace())
            {
                ErrorsGlobal.Add("Both Customer and Owner are empty.", "Event_CreateViewAndSetupSelectList");
                throw new Exception();
            }

            if (buySellDoc.CustomerId.IsNullOrWhiteSpace())
            {
                //this is a purchase order
                return(BuySellDocumentTypeENUM.Sale);
            }
            if (buySellDoc.OwnerId.IsNullOrWhiteSpace())
            {
                //this is a sale.
                return(BuySellDocumentTypeENUM.Purchase);
            }

            ApplicationUser ownerUser = OwnerBiz.GetUserForEntityrWhoIsNotAdminFor(buySellDoc.OwnerId);

            ownerUser.IsNullThrowException();

            if (UserId == ownerUser.Id)
            {
                return(BuySellDocumentTypeENUM.Sale);
            }



            //get the CustomerUser
            ApplicationUser customerUser = CustomerBiz.GetUserForEntityrWhoIsNotAdminFor(buySellDoc.CustomerId);

            customerUser.IsNullThrowException();
            if (UserId == customerUser.Id)
            {
                return(BuySellDocumentTypeENUM.Purchase);
            }

            //if(buySellDoc.)
            throw new Exception("Unknown type");
        }
Exemplo n.º 4
0
        private ApplicationUser Factory(string password, string userName, string phoneNumber, string countryAbbrev, string email = "")
        {
            RegisterViewModel rvm = new RegisterViewModel();

            rvm.Password = password;
            rvm.UserName = userName;
            //rvm.Phone = phoneNumber;
            //rvm.Email = email;

            if (countryAbbrev.IsNullOrWhiteSpace())
            {
                ErrorsGlobal.Add("No Country Abbreviation Received", MethodBase.GetCurrentMethod());
                throw new Exception(ErrorsGlobal.ToString());
            }

            return(Factory(rvm, countryAbbrev));
        }
Exemplo n.º 5
0
        //This is
        private ApplicationUser createUserEngine(string userName, string password)
        {
            ApplicationUser appUser = new ApplicationUser();

            appUser.UserName = userName;
            appUser.Name     = userName;

            try
            {
                IdentityResult result = UserManager.Create(appUser, password);

                if (result.Succeeded)
                {
                    return(appUser);
                }
                else
                {
                    if (!result.Errors.IsNull())
                    {
                        if (result.Errors.Count() > 0)
                        {
                            foreach (var item in result.Errors)
                            {
                                ErrorsGlobal.Add(item, "Creating User");
                            }
                        }
                        else
                        {
                            ErrorsGlobal.Add("Errors are 0 but no user created.", "Creating User");
                        }
                    }
                    else
                    {
                        ErrorsGlobal.Add("Errors are null, but no user created", "Creating User");
                    }
                }

                throw new Exception();
            }
            catch (Exception e)
            {
                ErrorsGlobal.Add("Unable to create user.", MethodBase.GetCurrentMethod(), e);
                throw new Exception(ErrorsGlobal.ToString());
            }
        }
Exemplo n.º 6
0
        public void CreateNewFeature(CreateNewFeatureModel model)
        {
            model.SelfCheck();
            MenuFeature menuFeature = MenuFeatureBiz.FindByName(model.FeatureName);

            if (menuFeature.IsNull())
            {
                menuFeature = MenuFeatureBiz.Factory() as MenuFeature;
                menuFeature.IsNullThrowException("menuFeature");

                menuFeature.Name = model.FeatureName;
                MenuFeatureBiz.CreateAndSave(menuFeature);
                return;
            }
            //if you are here then the feature already exists
            ErrorsGlobal.Add(string.Format("'{0}' already exists!", model.FeatureName), MethodBase.GetCurrentMethod());
            throw new Exception(ErrorsGlobal.ToString());
        }
Exemplo n.º 7
0
        public async Task <bool> VerifyPhoneNumberAsync(VerifyPhoneNumberViewModel model)
        {
            var result = await UserManager.ChangePhoneNumberAsync(UserId, model.PhoneNumber, model.Code);

            if (result.Succeeded)
            {
                var user = await UserManager.FindByIdAsync(UserId);

                if (user != null)
                {
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);
                }
                return(true);
            }
            // If we got this far, something failed, redisplay form
            ErrorsGlobal.Add("Failed to verify phone", MethodBase.GetCurrentMethod());
            return(false);
        }
Exemplo n.º 8
0
        //public override void Event_ModifyIndexList(IndexListVM indexListVM, ControllerIndexParams parameters)
        //{
        //    base.Event_ModifyIndexList(indexListVM, parameters);

        //    //indexListVM.Heading_Column = "All Files";
        //    indexListVM.Heading.Column = "All Files";

        //    indexListVM.Show.EditDeleteAndCreate = true;
        //    indexListVM.Show.Create = true;

        //    indexListVM.NameInput2 = "File Number";
        //    indexListVM.Show.ImageInList = false;


        //}

        //public override IList<ICommonWithId> GetListForIndex()
        //{

        //    try
        //    {


        //        //errIfNotLoggedIn();


        //        var lstAsFileDoc = base.GetListForIndex().ToList() as IList<FileDoc>;

        //        if (lstAsFileDoc.IsNullOrEmpty())
        //            return null;

        //        var lst = lstAsFileDoc.Where(x => x.UserId == UserId).ToList();

        //        if (lst.IsNullOrEmpty())
        //            return null;

        //        var lstIcommonwithId = lst as IList<ICommonWithId>;
        //        return lstIcommonwithId;
        //    }
        //    catch (Exception e)
        //    {
        //        ErrorsGlobal.Add("Unable to continue", MethodBase.GetCurrentMethod(), e);
        //        throw new Exception(ErrorsGlobal.ToString());
        //    }
        //}



        //public override async Task<IList<ICommonWithId>> GetListForIndexAsync(ControllerIndexParams parms)
        //{
        //    // errIfNotLoggedIn();

        //    var lst = (await base.GetListForIndexAsync(parms)).Cast<FileDoc>().ToList();

        //    if (lst.IsNullOrEmpty())
        //        return null;


        //    var lstIcommonwithId = (lst.Where(x => x.UserId == UserId)).Cast<ICommonWithId>().ToList();

        //    return lstIcommonwithId;
        //}

        //private void errIfNotLoggedIn()
        //{
        //    if (UserId.IsNullOrWhiteSpace())
        //    {
        //        ErrorsGlobal.Add("You must log in to continue", "");
        //    }
        //}

        public override void Event_ModifyIndexItem(IndexListVM indexListVM, IndexItemVM indexItem, ICommonWithId icommonWithid)
        {
            base.Event_ModifyIndexItem(indexListVM, indexItem, icommonWithid);
            FileDoc filedoc = icommonWithid as FileDoc;

            if (filedoc.IsNull())
            {
                ErrorsGlobal.Add("Unable to convert to File Doc", MethodBase.GetCurrentMethod());
                throw new Exception(ErrorsGlobal.ToString());
            }
            indexItem.Name = filedoc.FullNameWithFileNumber();

            indexItem.PrintLineNumber = filedoc.FileNumber.ToString();
            if (!filedoc.OldFileNumber.IsNullOrWhiteSpace())
            {
                indexItem.PrintLineNumber = filedoc.OldFileNumber.ToString();
            }
        }
Exemplo n.º 9
0
        private SelectList LoadDataIntoDbAndThenGetSelectListAndAddToCache()
        {
            ErrorsGlobal.AddMessage("Country Select List DAL has been refilled because it was NOT in CACHE.", MethodBase.GetCurrentMethod());
            LoadCountryFromArrayIntoDb();

            var selectListData = base.SelectList();

            if (selectListData.IsNull())
            {
                ErrorsGlobal.Add("No Data loaded. Please load country data.", MethodBase.GetCurrentMethod());
                //return null;
            }

            _memory.CacheMemory.Add(_key, selectListData, new System.TimeSpan(10, 0, 0, 0));
            object obj = _memory.CacheMemory.GetFrom(_key);

            return((SelectList)obj);
        }
Exemplo n.º 10
0
        private void LoadCountryFromArrayIntoDb()
        {
            //now make sure that country has been loaded.
            var allCountryDataInDb = FindAll().ToList();


            int noOfCountryRecInArray = CountryData.CountryDataArray().Length;

            if (noOfCountryRecInArray == 0)
            {
                ErrorsGlobal.Add("Country Data not loaded in Array. Please load country data.", MethodBase.GetCurrentMethod());
                return;
            }

            noOfCountryRecInArray = noOfCountryRecInArray / 3;

            //if there is no country data
            if (allCountryDataInDb.IsNullOrEmpty() || allCountryDataInDb.Count() < noOfCountryRecInArray)
            {
                //Load all of the data from array into database
                for (int i = 0; i < noOfCountryRecInArray; i++)
                {
                    try
                    {
                        Country c = Factory();
                        c.Abbreviation = CountryData.CountryDataArray()[i, 1];
                        c.Name         = CountryData.CountryDataArray()[i, 0];
                        Create(c);
                        SaveChanges();
                    }
                    catch (NoDuplicateException)
                    {
                        //ignore and continue...
                    }
                    catch (Exception e)
                    {
                        ErrorsGlobal.Add(string.Format("Something happened in record no '{0}' while creating Country records.", i), MethodBase.GetCurrentMethod(), e);
                        throw new Exception(ErrorsGlobal.ToString());
                    }
                }
            }
        }
Exemplo n.º 11
0
        public void PrepareEncashmentForUser(string userId, string userName, CashEncashmentTrx cet)
        {
            userId.IsNullOrWhiteSpaceThrowArgumentException("You must be logged in");
            cet.PaymentMethodId.IsNullOrWhiteSpaceThrowException("No method selected");


            decimal currBalanceForUser = BalanceFor_User(userId, CashTypeENUM.Refundable);

            if (currBalanceForUser != cet.CurrentBalance_Refundable)
            {
                throw new Exception("Something is wrong. Previous balance does not match current balance.");
            }

            if (currBalanceForUser >= cet.Amount)
            {
                cet.IsApproved.MarkTrue(UserName, UserId);
                RandomNoGenerator randomGen = new RandomNoGenerator(3);
                cet.SecretNumber = randomGen.GetRandomNumber(1);

                PaymentMethod paymentMethod = PaymentMethodBiz.Find(cet.PaymentMethodId);
                paymentMethod.IsNullThrowException();

                cet.SystemMessageToApplicant = paymentMethod.DetailInfoToDisplayOnWebsite;

                Person userPerson = UserBiz.GetPersonFor(userId);
                userPerson.IsNullThrowException("Person not found");
                cet.PersonRequestingPaymentId = userPerson.Id;

                if (userPerson.CashEncashmentTrxs.IsNull())
                {
                    userPerson.CashEncashmentTrxs = new List <CashEncashmentTrx>();
                }
                userPerson.CashEncashmentTrxs.Add(cet);
                CashEncashmentTrxBiz.CreateAndSave(cet);

                ErrorsGlobal.AddMessage("Encashment certificate created and approved.");
            }
            else
            {
                throw new Exception("Something went wrong. You do not have the balance");
            }
        }
Exemplo n.º 12
0
        public MenuPath1ENUM ChangeToEnum(MenuPath1 mp1)
        {
            string spacesRemovedName = mp1.Name.RemoveAllSpaces();

            try
            {
                MenuPath1ENUM mp1Enum = (MenuPath1ENUM)Enum.Parse(typeof(MenuPath1ENUM), spacesRemovedName, true);
                return(mp1Enum);
            }
            catch (ArgumentException a)
            {
                ErrorsGlobal.Add(string.Format("Unable to convert the enum: '{0}'", spacesRemovedName), MethodBase.GetCurrentMethod(), a);
                throw new ArgumentException(ErrorsGlobal.ToString());
            }
            catch (Exception e)
            {
                ErrorsGlobal.Add(string.Format("Error converting enum: '{0}'", spacesRemovedName), MethodBase.GetCurrentMethod(), e);
                throw new Exception(ErrorsGlobal.ToString());
            }
        }
Exemplo n.º 13
0
        ////private ApplicationSignInManager _signInManager;
        ////private ApplicationUserManager _userManager;
        //private IErrorSet _ierrorSet;
        //private IRepositry<Country> _icountryDAL;
        //private IRepositry<ApplicationUser> _iuserDAL;

        //private IAuthenticationManager _iAuthenticationManager;
        //private readonly RoleManager<IdentityRole> _roleManager;
        //private readonly IRoleStore<IdentityRole, string> _store;
        //private RightBiz _rightBiz;
        ////public AccountController()
        ////{
        ////}

        //public UserBiz(
        //    ApplicationDbContext db,
        //    ApplicationUserManager userManager,
        //    ApplicationSignInManager signInManager,
        //    IAuthenticationManager iAuthenticationManager,
        //    IErrorSet ierrSet,
        //    IRepositry<Country> icountryDAL,
        //    IRepositry<ApplicationUser> iuserDAL,
        //    IMemoryMain memoryMain,
        //    IErrorSet errorSet,
        //    ConfigManagerHelper configManagerHelper,
        //    RightBiz rightBiz)
        //    : base(iuserDAL, memoryMain, ierrSet, iuserDAL, db, configManagerHelper)
        //{
        //    UserManager = userManager;
        //    SignInManager = signInManager;
        //    _ierrorSet = ierrSet;
        //    _icountryDAL = icountryDAL;
        //    _iuserDAL = iuserDAL;
        //    _iAuthenticationManager = iAuthenticationManager;

        //    _store = new RoleStore<IdentityRole>();
        //    _roleManager = new RoleManager<IdentityRole>(_store);
        //    _rightBiz = rightBiz;

        //}

        //public ApplicationSignInManager SignInManager { get; set; }
        //public ApplicationUserManager UserManager { get; set; }
        //public RoleManager<IdentityRole> RoleManager { get { return _roleManager; } }
        //public IAuthenticationManager AuthenticationManager { get { return _iAuthenticationManager; } }

        //public IEnumerable<AuthenticationDescription> GetExternalAuthenticationTypes
        //{
        //    get
        //    {
        //        return AuthenticationManager.GetExternalAuthenticationTypes();
        //    }
        //}
        ////public string UserName { get; set; }
        ////public string UserId { get; set; }

        ////public ErrorSet ErrorsGlobal
        ////{
        ////    get
        ////    {
        ////        if (_ierrorSet.IsNull())
        ////            throw new Exception("ErrorSet is null. UserDAL. " + MethodBase.GetCurrentMethod().Name);

        ////        return (ErrorSet)_ierrorSet;

        ////    }
        ////}
        //private Repositry<Country> CountryDal
        //{
        //    get
        //    {
        //        if (_icountryDAL.IsNull())
        //        {
        //            ErrorsGlobal.Add("Country DAL is null.", MethodBase.GetCurrentMethod());
        //            throw new Exception(ErrorsGlobal.ToString());

        //        }

        //        return (Repositry<Country>)_icountryDAL;
        //    }
        //}

        ////private Repositry<ApplicationUser> UserDal
        ////{
        ////    get
        ////    {
        ////        if (_iuserDAL.IsNull())
        ////        {
        ////            ErrorsGlobal.Add("User DAL is null.", MethodBase.GetCurrentMethod());
        ////            throw new Exception(ErrorsGlobal.ToString());

        ////        }

        ////        return (Repositry<ApplicationUser>)_icountryDAL;
        ////    }
        ////}
        //public async Task<string> GenerateChangePhoneNumberTokenAsync(string userId, string phoneNumber)
        //{
        //    string code = await UserManager.GenerateChangePhoneNumberTokenAsync(userId, phoneNumber);
        //    return code;
        //}



        //public override SelectList SelectList()
        //{
        //    if (this.IsNull())
        //        return null;

        //    var allUsers = UserManager.Users.ToList();

        //    if (allUsers.IsNull() || allUsers.Count() == 0)
        //        return null;

        //    var sortedList = allUsers.OrderBy(x => x.UserName)
        //        .Select(x =>
        //        new
        //        {
        //            Text = x.UserName,
        //            Value = x.Id
        //        })
        //        .ToList();
        //    var selectList = new SelectList(sortedList, "Value", "Text");
        //    return selectList;
        //}



        //public ApplicationUser FindById_UserManager(string userId)
        //{
        //    ApplicationUser user = UserManager.FindById(userId);
        //    return user;
        //}

        //public async Task<bool> GetTwoFactorBrowserRememberedAsync(string userId)
        //{
        //    return await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId);
        //}


        //private void throwErrorUserIsNullOrWhiteSpace(string userName)
        //{
        //    if (userName.IsNullOrWhiteSpace())
        //    {
        //        ErrorsGlobal.Add("User name is empty", "Creating User.");
        //        throw new Exception(ErrorsGlobal.ToString());
        //    }
        //}

        public IdentityRole CreateRole_UserManager(string roleName)
        {
            try
            {
                //first check to see if role exists...
                if (RoleManager.RoleExists(roleName))
                {
                    return(RoleManager.FindByName(roleName));
                }

                IdentityRole role = new IdentityRole(roleName);
                RoleManager.Create(role);
                return(role);
            }
            catch (Exception e)
            {
                ErrorsGlobal.Add("Unable to create role.", MethodBase.GetCurrentMethod(), e);
                throw new Exception(ErrorsGlobal.ToString());
            }
        }
Exemplo n.º 14
0
        private void noDuplicateState(State entity)
        {
            //there should be one Blank state only for a country

            //Is the current one blank?
            bool isBlankState = entity.Name.IsNullOrWhiteSpace();

            if (isBlankState)
            {
                List <State> blankStates            = FindAll().Where(x => x.Name == "").ToList();
                State        blankCountryStateFound = blankStates.FirstOrDefault(x => x.CountryId == entity.CountryId);

                if (!blankCountryStateFound.IsNull())
                {
                    string err = string.Format("Blank state exists for {0}", entity.Country.FullName());
                    ErrorsGlobal.AddMessage(err);
                    throw new NoDuplicateException(err);
                }
            }
        }
Exemplo n.º 15
0
        public async Task <SendCodeViewModel> SendCodeAsync(string returnUrl, bool rememberMe)
        {
            var userId = await SignInManager.GetVerifiedUserIdAsync();

            if (userId == null)
            {
                ErrorsGlobal.Add("No user found.", MethodBase.GetCurrentMethod());
                throw new Exception(ErrorsGlobal.ToString());
            }

            var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId);

            var factorOptions = userFactors.Select(purpose => new SelectListItem {
                Text = purpose, Value = purpose
            }).ToList();

            return(new SendCodeViewModel {
                Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe
            });
        }
Exemplo n.º 16
0
        private void deliveryman_PicksUp_From_Seller(BuySellDoc bsd)
        {
            if (bsd.BuySellDocStateModifierEnum == BuySellDocStateModifierENUM.Cancel)
            {
                return;
            }


            if (bsd.PickupCode_Seller == bsd.PickupCode_Deliveryman)
            {
                string err = string.Format("Delivery code {0} Accepted!", bsd.PickupCode_Deliveryman);
                ErrorsGlobal.AddMessage(err);
                bsd.BuySellDocStateEnum = BuySellDocStateENUM.Enroute;
                bsd.Enroute.SetToTodaysDate(UserName, UserId);
            }
            else
            {
                string err = string.Format("The code {0} given by delivery man is incorrect!", bsd.PickupCode_Seller);
                throw new Exception(err);
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// This swaps the ranks of the two items
        /// </summary>
        /// <param name="FromId"></param>
        /// <param name="ToId"></param>
        public void SwapRanks(string fromIdstr, string toIdstr)
        {
            if (fromIdstr.IsNullOrWhiteSpace() || toIdstr.IsNullOrWhiteSpace())
            {
                ErrorsGlobal.AddMessage("Unable to swap ranks. One of the Params is empty.", MethodBase.GetCurrentMethod());
                return;
            }

            string fromId = fromIdstr;
            string toId   = toIdstr;

            if (fromId.IsNullOrEmpty() || toId.IsNullOrEmpty())
            {
                ErrorsGlobal.AddMessage("Unable to swap ranks. One of the Ids is empty.", MethodBase.GetCurrentMethod());
                return;
            }

            DiscountPrecedence dpFrom = Find(fromId);
            DiscountPrecedence dpTo   = Find(toId);

            if (dpTo.IsNull() || dpFrom.IsNull())
            {
                ErrorsGlobal.AddMessage("Unable to swap ranks. Unable to find one item", MethodBase.GetCurrentMethod());
                return;
            }

            int tempRank = dpFrom.Rank;

            dpFrom.Rank = dpTo.Rank;
            dpTo.Rank   = tempRank;
            ControllerCreateEditParameter parmFrom = new ControllerCreateEditParameter();

            parmFrom.Entity = dpFrom;
            Update(parmFrom);

            ControllerCreateEditParameter parmTo = new ControllerCreateEditParameter();

            parmTo.Entity = dpTo;
            UpdateAndSave(parmTo);
        }
Exemplo n.º 18
0
        public override void BusinessRulesFor(ControllerCreateEditParameter parm)
        {
            State state = parm.Entity as State;

            bool isBlankState = state.Name.IsNullOrWhiteSpace();

            if (isBlankState)
            {
                List <State> blankStates            = FindAll().Where(x => x.Name == "").ToList();
                State        blankCountryStateFound = blankStates.FirstOrDefault(x => x.CountryId == state.CountryId);

                if (!blankCountryStateFound.IsNull())
                {
                    string err = string.Format("Blank state exists for {0}", state.Country.FullName());
                    ErrorsGlobal.AddMessage(err);
                    throw new NoDuplicateException(err);
                }
            }
            else
            {
                base.BusinessRulesFor(parm);
            }
        }
Exemplo n.º 19
0
        private decimal getSalePriceFor(BuySellItem buySellItem)
        {
            string salePriceStr = buySellItem.SalePriceStr;

            salePriceStr = salePriceStr.ToNumericString();
            decimal salePriceOut;
            bool    success = decimal.TryParse(buySellItem.SalePriceStr, out salePriceOut);

            if (success)
            {
                buySellItem.SalePrice = buySellItem.SalePriceStr.ToDecimal();
            }
            else
            {
                throw new Exception("Unable to understand number: " + buySellItem.SalePriceStr);
            }

            if (buySellItem.SalePrice == 0)
            {
                ErrorsGlobal.AddMessage("The sale price is zero");
            }

            return(salePriceOut);
        }
Exemplo n.º 20
0
        /// <summary>
        /// This creates and saves a mailer. It makes sure that there is only one created.
        /// Also, it ensures that deposit/account are taken care of
        /// </summary>
        /// <param name="vm"></param>
        public void CreateAndSaveMailer(CreateMailerVM vm)
        {
            //ControllerCreateEditParameter para
            vm.UserId.IsNullOrWhiteSpaceThrowArgumentException("User is required!");
            ApplicationUser user = UserBiz.Find(vm.UserId);

            user.IsNullThrowException("User not found");
            user.PersonId.IsNullOrWhiteSpaceThrowException("No person attached to user");
            string personId = user.PersonId;

            //first check if a mailer exists for the mailer
            bool mailerExists = FindAll().Any(x => x.PersonId == personId);

            if (mailerExists)
            {
                ErrorsGlobal.Add("Mailer already exists for user!", MethodBase.GetCurrentMethod(), null);
                string error = ErrorsGlobal.ToString();
                throw new Exception(error);
            }


            //Make sure user has enough deposit etc to become a mailer
            //todo
            ErrorsGlobal.AddMessage("Financial checks need to be done!");

            Mailer mailer = new Mailer();

            mailer.Name           = user.UserName;
            mailer.PersonId       = user.PersonId;
            mailer.TrustLevelEnum = vm.TrustLevelEnum;
            //user.Mailers.Add(mailer);
            //user.MailerId = mailer.Id;

            CreateAndSave(mailer);
            ErrorsGlobal.AddMessage(string.Format("Mailer created for {0}", user.UserName));
        }
Exemplo n.º 21
0
        public override void BusinessRulesFor(ControllerCreateEditParameter parm)
        {
            //Item shipped amount cannot begreater than the order amount.
            //if it is, make them equal.
            BuySellItem buySellItem = parm.Entity as BuySellItem;

            buySellItem.IsNullThrowException();

            switch (buySellItem.BuySellDocumentTypeEnum)
            {
            case BuySellDocumentTypeENUM.Sale:                  //--------  SALE
                switch (buySellItem.BuySellDocStateEnum)
                {
                case BuySellDocStateENUM.InProccess:
                    break;

                case BuySellDocStateENUM.BackOrdered:
                    break;

                case BuySellDocStateENUM.All:
                    break;

                case BuySellDocStateENUM.RequestUnconfirmed:
                    break;

                case BuySellDocStateENUM.RequestConfirmed:
                    double order = getOrderAmount(buySellItem);

                    if (order <= buySellItem.Quantity.Order_Original)
                    {
                        buySellItem.Quantity.Order = order;
                    }
                    else
                    {
                        string errMsg = string.Format("Unable to update the amount. Your amount {0} is greater than the original amount. This is not allowed.",
                                                      order.ToString("N2"),
                                                      buySellItem.Quantity.Order_Original.ToString("N2"));

                        ErrorsGlobal.AddMessage(errMsg);
                    }
                    buySellItem.SalePrice = getSalePriceFor(buySellItem);
                    break;

                case BuySellDocStateENUM.BeingPreparedForShipmentBySeller:
                    break;

                case BuySellDocStateENUM.ReadyForPickup:
                    break;

                case BuySellDocStateENUM.CourierAcceptedByBuyerAndSeller:
                    break;

                case BuySellDocStateENUM.CourierComingToPickUp:
                    break;

                case BuySellDocStateENUM.PickedUp:
                    break;

                case BuySellDocStateENUM.Delivered:
                    break;

                case BuySellDocStateENUM.Rejected:
                    break;

                case BuySellDocStateENUM.Problem:
                    break;

                case BuySellDocStateENUM.Unknown:
                default:
                    break;
                }
                break;

            case BuySellDocumentTypeENUM.Purchase:                  //-------- PURCHASE
                switch (buySellItem.BuySellDocStateEnum)
                {
                case BuySellDocStateENUM.InProccess:
                    break;

                case BuySellDocStateENUM.BackOrdered:
                    break;

                case BuySellDocStateENUM.All:
                    break;

                case BuySellDocStateENUM.RequestUnconfirmed:
                    buySellItem.Quantity.Order = getOrderAmount(buySellItem);
                    buySellItem.SalePrice      = getSalePriceFor(buySellItem);
                    break;

                case BuySellDocStateENUM.RequestConfirmed:
                    break;

                case BuySellDocStateENUM.BeingPreparedForShipmentBySeller:
                    break;

                case BuySellDocStateENUM.ReadyForPickup:
                    break;

                case BuySellDocStateENUM.CourierAcceptedByBuyerAndSeller:
                    break;


                case BuySellDocStateENUM.CourierComingToPickUp:
                    break;

                case BuySellDocStateENUM.PickedUp:
                    break;

                case BuySellDocStateENUM.Delivered:
                    break;

                case BuySellDocStateENUM.Rejected:
                    break;

                case BuySellDocStateENUM.Problem:
                    break;

                case BuySellDocStateENUM.Unknown:
                default:
                    break;
                }
                break;

            case BuySellDocumentTypeENUM.Delivery:              //-------- DELIVERY
                switch (buySellItem.BuySellDocStateEnum)
                {
                case BuySellDocStateENUM.InProccess:
                    break;

                case BuySellDocStateENUM.BackOrdered:
                    break;

                case BuySellDocStateENUM.All:
                    break;

                case BuySellDocStateENUM.RequestUnconfirmed:
                    break;

                case BuySellDocStateENUM.RequestConfirmed:
                    break;

                case BuySellDocStateENUM.BeingPreparedForShipmentBySeller:
                    break;

                case BuySellDocStateENUM.ReadyForPickup:
                    break;

                case BuySellDocStateENUM.CourierAcceptedByBuyerAndSeller:
                    break;


                case BuySellDocStateENUM.CourierComingToPickUp:
                    break;

                case BuySellDocStateENUM.PickedUp:
                    break;

                case BuySellDocStateENUM.Enroute:
                case BuySellDocStateENUM.Delivered:
                    break;

                case BuySellDocStateENUM.Rejected:
                    break;

                case BuySellDocStateENUM.Problem:
                    break;

                case BuySellDocStateENUM.Unknown:
                default:
                    break;
                }
                break;

            case BuySellDocumentTypeENUM.Unknown:
            default:
                break;
            }
        }
Exemplo n.º 22
0
        IQueryable <BuySellDoc> getByDocumentType_For(string userId, IQueryable <BuySellDoc> iq_allOrders, BuySellDocumentTypeENUM buySellDocumentTypeEnum)
        {
            //userId.IsNullOrWhiteSpaceThrowArgumentException("You are not logged in.");


            switch (buySellDocumentTypeEnum)
            {
            case BuySellDocumentTypeENUM.Sale:
            {
                try
                {
                    //all orders are returned because this is the admin
                    //if (userId.IsNullOrWhiteSpace())
                    //    return iq_allOrders;
                    if (userId.IsNullOrWhiteSpace())
                    {
                        return(BuySellDoc.IQueryable_GetSaleDocs(iq_allOrders, ""));
                    }

                    Owner owner = OwnerBiz.GetPlayerFor(userId);
                    owner.IsNullThrowException("No Owner");
                    return(BuySellDoc.IQueryable_GetSaleDocs(iq_allOrders, owner.Id));
                }
                catch (Exception e)
                {
                    ErrorsGlobal.Add("Problem getting sales.", MethodBase.GetCurrentMethod(), e);
                    throw new Exception(ErrorsGlobal.ToString());
                }
            }

            case BuySellDocumentTypeENUM.Purchase:
            {
                try
                {
                    //all orders are returned because this is the admin
                    //if (userId.IsNullOrWhiteSpace())
                    //    return iq_allOrders;
                    if (userId.IsNullOrWhiteSpace())
                    {
                        return(BuySellDoc.IQueryable_GetPurchaseDocs(iq_allOrders, ""));
                    }

                    Customer customer = CustomerBiz.GetPlayerFor(userId);
                    customer.IsNullThrowException("Customer");
                    return(BuySellDoc.IQueryable_GetPurchaseDocs(iq_allOrders, customer.Id));
                }
                catch (Exception e)
                {
                    ErrorsGlobal.Add("Problem getting purchases", MethodBase.GetCurrentMethod(), e);
                    throw new Exception(ErrorsGlobal.ToString());
                }
            }

            case BuySellDocumentTypeENUM.Delivery:
            {
                try
                {
                    //all orders are returned because this is the admin
                    if (userId.IsNullOrWhiteSpace())
                    {
                        return(BuySellDoc.IQueryable_GetDeliveryDocs(iq_allOrders, ""));
                    }


                    Deliveryman deliveryMan = DeliverymanBiz.GetPlayerFor(userId);
                    deliveryMan.IsNullThrowException("deliveryMan");

                    return(BuySellDoc.IQueryable_GetDeliveryDocs(iq_allOrders, deliveryMan.Id));
                }
                catch (Exception e)
                {
                    ErrorsGlobal.Add("Problem getting purchases", MethodBase.GetCurrentMethod(), e);
                    throw new Exception(ErrorsGlobal.ToString());
                }
            }

            case BuySellDocumentTypeENUM.Salesman:
            {
                try
                {
                    if (userId.IsNullOrWhiteSpace())
                    {
                        return(BuySellDoc.IQueryable_GetSalesmanDocs(iq_allOrders, ""));
                    }

                    Salesman salesman = SalesmanBiz.GetPlayerFor(userId);
                    salesman.IsNullThrowException("Salesman");

                    return(BuySellDoc.IQueryable_GetSalesmanDocs(iq_allOrders, salesman.Id));
                }
                catch (Exception e)
                {
                    ErrorsGlobal.Add("Problem getting purchases", MethodBase.GetCurrentMethod(), e);
                    throw new Exception(ErrorsGlobal.ToString());
                }
            }

            case BuySellDocumentTypeENUM.Unknown:
            default:
                throw new Exception("Unknown document type");
            }
        }
Exemplo n.º 23
0
        //public override string[] GetDataForStringArrayFormat
        //{
        //    get
        //    {
        //        return ProductCategoryMainArray.DataArray();
        //    }
        //}


        public override void AddInitData()
        {
            //get the data
            List <MenuPathMainHelper> dataList = new DatastoreNS.MenuPathMainInitilizingDataList().DataList();

            if (!dataList.IsNullOrEmpty())
            {
                foreach (var item in dataList)
                {
                    if (item.MenuPath1.IsNullOrWhiteSpace())
                    {
                        ErrorsGlobal.Add(string.Format("Menu Path 1 '{0}' not found", item.MenuPath1), MethodBase.GetCurrentMethod());
                        throw new Exception(ErrorsGlobal.ToString());
                    }


                    MenuPath1 menu1 = _menupath1Biz.FindByName(item.MenuPath1);
                    MenuPath2 menu2 = _menupath2Biz.FindByName(item.MenuPath2);
                    MenuPath3 menu3 = _menupath3Biz.FindByName(item.MenuPath3);

                    MenuPathMain pcm = new MenuPathMain();

                    pcm.MenuPath1   = menu1;
                    pcm.MenuPath1Id = menu1.Id;

                    if (menu1.MenuPathMains.IsNull())
                    {
                        menu1.MenuPathMains = new List <MenuPathMain>();
                    }

                    menu1.MenuPathMains.Add(pcm);



                    if (menu2.IsNull())
                    {
                        continue;
                    }

                    pcm.MenuPath2   = menu2;
                    pcm.MenuPath2Id = menu2.Id;
                    if (menu2.MenuPathMains.IsNull())
                    {
                        menu2.MenuPathMains = new List <MenuPathMain>();
                    }
                    menu2.MenuPathMains.Add(pcm);

                    if (menu3.IsNull())
                    {
                        continue;
                    }

                    pcm.MenuPath3   = menu3;
                    pcm.MenuPath3Id = menu3.Id;
                    if (menu3.MenuPathMains.IsNull())
                    {
                        menu3.MenuPathMains = new List <MenuPathMain>();
                    }
                    menu3.MenuPathMains.Add(pcm);

                    CreateSave_ForInitializeOnly(pcm);
                }
            }
            //SaveChanges();
        }
Exemplo n.º 24
0
        public void SavePageView(ActionExecutedContext filterContext, System.Web.HttpRequestBase request)
        {
            string userId         = UserId ?? "";
            string userName       = UserName ?? "";
            string actionName     = filterContext.ActionDescriptor.ActionName;
            string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            string httpMethod     = request.HttpMethod;

            string urlRefererrerHost = "";
            string UserInfo          = "";

            if (!request.UrlReferrer.IsNull())
            {
                urlRefererrerHost = request.UrlReferrer.Host;
                UserInfo          = request.UrlReferrer.UserInfo;
            }
            string userHostName    = request.UserHostName;
            string userHostAddress = request.UserHostAddress;
            string userAgent       = request.UserAgent;
            string userLanguages   = request.UserLanguages.ConvertToSemiColanString();
            string browserType     = request.Browser.Type;

            bool isAjaxRequest      = request.IsAjaxRequest();
            bool isCrawler          = request.Browser.Crawler;
            bool isMobileDevice     = request.Browser.IsMobileDevice;
            bool isClientWin16Based = request.Browser.Win16;
            bool isClientWin32Based = request.Browser.Win32;

            PageView pv = Factory() as PageView;

            pv.UserId            = userId;
            pv.UserName          = userName;
            pv.ActionName        = actionName;
            pv.ControllerName    = controllerName;
            pv.HttpMethod        = httpMethod;
            pv.UrlRefererrerHost = urlRefererrerHost;
            pv.UserHostName      = userHostName;
            pv.UserHostAddress   = userHostAddress;
            pv.UserInfo          = UserInfo;
            pv.UserAgent         = userAgent;
            pv.UserLanguages     = userLanguages;
            pv.BrowserType       = browserType;

            pv.IsAjaxRequest      = isAjaxRequest;
            pv.IsCrawler          = isCrawler;
            pv.IsMobileDevice     = isMobileDevice;
            pv.IsClientWin16Based = isClientWin16Based;
            pv.IsClientWin32Based = isClientWin32Based;

            pv.Name = pv.MakeName();

            ControllerCreateEditParameter ccep = new ControllerCreateEditParameter();

            ccep.Entity = pv as ICommonWithId;

            try
            {
                CreateAndSave(ccep);
            }
            catch (Exception e)
            {
                ErrorsGlobal.Add("The PageView save failed!", System.Reflection.MethodBase.GetCurrentMethod(), e);
            }
        }
Exemplo n.º 25
0
        private void addProducts()
        {
            //get the data
            List <ProductInitializerHelper> dataList = GetDataListForProduct;

            if (!dataList.IsNullOrEmpty())
            {
                foreach (ProductInitializerHelper prodInitHelper in dataList)
                {
                    //check to see if the product exists... if it does continue.
                    Product p = FindByName(prodInitHelper.Name);

                    if (!p.IsNull())
                    {
                        continue;
                    }

                    p              = new Product();
                    p.Name         = prodInitHelper.Name;
                    p.IsUnApproved = false;
                    //p.UomVolume = UomVolumeBiz.FindByName(prodInitHelper.UomVolumeName);
                    //p.UomVolume.IsNullThrowException();

                    //p.UomDimensions = UomLengthBiz.FindByName(prodInitHelper.UomLengthName);
                    //p.UomDimensions.IsNullThrowException();

                    //p.UomWeightActual = UomWeightBiz.FindByName(prodInitHelper.UomShipWeightName);


                    //p.UomWeightListed = UomWeightBiz.FindByName(prodInitHelper.UomWeightListedName);
                    //p.UomWeightListed.IsNullThrowException();

                    //p.UomPurchase = UomQuantityBiz.FindByName(prodInitHelper.UomPurchaseName);
                    //p.UomPurchase.IsNullThrowException();

                    //p.UomSale = UomQuantityBiz.FindByName(prodInitHelper.UomSaleName);
                    //p.UomSale.IsNullThrowException();

                    //p.Dimensions.Height = prodInitHelper.Height;
                    //p.Dimensions.Width = prodInitHelper.Width;
                    //p.Dimensions.Length = prodInitHelper.Length;
                    //p.UomDimensionsId = p.UomDimensions.Id;
                    //p.UomVolumeId = p.UomVolume.Id;
                    //p.UomDimensionsId = p.UomDimensions.Id;
                    //p.WeightActual = prodInitHelper.ShipWeight;
                    //p.UomWeightActualId = p.UomWeightActual.Id;

                    //p.UomWeightListedId = p.UomWeightListed.Id;
                    //p.UomPurchaseId = p.UomPurchase.Id;
                    //p.UomSaleId = p.UomSale.Id;

                    //p.WeightListed = prodInitHelper.WeightListed;
                    //p.Volume = prodInitHelper.ShipVolume;

                    if (ErrorsGlobal.HasErrors)
                    {
                        throw new Exception(ErrorsGlobal.ToString());
                    }



                    #region Menu Path

                    if (prodInitHelper.Menupaths.IsNull())
                    {
                    }
                    else
                    {
                        foreach (MenuPathHelper mph in prodInitHelper.Menupaths)
                        {
                            MenuPathMain mpm = MenuPathMainBiz.FindAll().FirstOrDefault(x =>
                                                                                        x.MenuPath1.Name.ToLower() == mph.MenuPath1Name.ToLower() &&
                                                                                        x.MenuPath2.Name.ToLower() == mph.MenuPath2Name.ToLower() &&
                                                                                        x.MenuPath3.Name.ToLower() == mph.MenuPath3Name.ToLower());

                            if (mpm.IsNull())
                            {
                                continue;
                            }

                            if (p.MenuPathMains.IsNull())
                            {
                                p.MenuPathMains = new List <MenuPathMain>();
                            }

                            p.MenuPathMains.Add(mpm);

                            if (mpm.Products.IsNull())
                            {
                                mpm.Products = new List <Product>();
                            }

                            mpm.Products.Add(p);
                        }
                    }
                    #endregion



                    #region ProductIdentifier
                    if (prodInitHelper.ProductIdentifiers.IsNull())
                    {
                    }
                    else
                    {
                        foreach (string piStr in prodInitHelper.ProductIdentifiers)
                        {
                            ProductIdentifier pi = ProductIdentifierBiz.Find(piStr);

                            if (!pi.IsNull())
                            {
                                throw new Exception(string.Format("Duplicate product Identifier: '{0}'", piStr));
                            }

                            pi = ProductIdentifierBiz.Factory() as ProductIdentifier;

                            pi.Name      = piStr;
                            pi.Product   = p;
                            pi.ProductId = p.Id;

                            if (p.ProductIdentifiers.IsNull())
                            {
                                p.ProductIdentifiers = new List <ProductIdentifier>();
                            }

                            p.ProductIdentifiers.Add(pi);
                        }
                    }
                    #endregion
                    CreateSave_ForInitializeOnly(p);
                }
            }

            AddInitData_ProductChild();
        }
Exemplo n.º 26
0
        public ApplicationUser Factory(RegisterViewModel r, string countryAbbrev = "")
        {
            #region Error CHecking

            if (r.UserName.IsNullOrWhiteSpace())
            {
                ErrorsGlobal.Add("No User Name", MethodBase.GetCurrentMethod());
                throw new Exception(ErrorsGlobal.ToString());
            }
            //Check the incoming phone number and fix it.
            //string phone

            ////Load the country
            //if (r.Phone.IsNullOrWhiteSpace())
            //{
            //    ErrorsGlobal.Add("No Phone", MethodBase.GetCurrentMethod());
            //    throw new Exception(ErrorsGlobal.ToString());
            //}


            //string _countryAbbrev = "";

            //if (countryAbbrev.IsNullOrWhiteSpace())
            //{
            //    if (r.CountryID.IsNullOrEmpty())
            //    {
            //        ErrorsGlobal.Add("No Country Received", MethodBase.GetCurrentMethod());
            //        throw new Exception(ErrorsGlobal.ToString());
            //    }
            //    Country country = CountryBiz.Find(r.CountryID);
            //    if (country.IsNull())
            //    {
            //        ErrorsGlobal.Add("Country not found", MethodBase.GetCurrentMethod());
            //        throw new Exception(ErrorsGlobal.ToString());
            //    }

            //    _countryAbbrev = country.Abbreviation;

            //}
            //else
            //{
            //    _countryAbbrev = countryAbbrev;
            //}
            #endregion

            //fix phone number
            //string fixedPhoneNumber = PhoneNumberFixer(
            //    r.Phone,
            //    _countryAbbrev);

            //PersonComplex p = new PersonComplex
            //{
            //    FName = r.FName,
            //    MName = r.MName,
            //    LName = r.LName,
            //    IdentificationNo = r.CountryIdCardNumber,
            //    NameOfFatherOrHusband = r.NameOfFatherOrHusband,
            //    Sex = r.Sex,
            //    SonOfOrWifeOf = r.SonOfOrWifeOf
            //};

            //AddressComplex a = new AddressComplex
            //{
            //    Address2 = r.Address.Address2,
            //    Attention = r.Address.Attention,
            //    HouseNo = r.Address.HouseNo,
            //    //Phone = r.Phone,
            //    Road = r.Address.Road,
            //    WebAddress = r.Address.WebAddress,
            //    Zip = r.Address.Zip

            //    //CityName = r.CityName,
            //    //CountryName = r.CountryName,
            //    //StateName = r.StateName,
            //    //TownName = r.TownName,
            //};

            ApplicationUser u = new ApplicationUser
            {
                UserName = r.UserName,  //This will be the Login
                //PhoneNumber = fixedPhoneNumber,
                //PhoneNumberAsEntered = r.Phone,
                //Email = r.Email,
                //PersonComplex = r.Person,
                //AddressComplex = r.Address
            };

            //Misc
            //u.IsEncrypted = ConfigManagerHelper.IsEncrypted;


            return(u);
        }
Exemplo n.º 27
0
        //public override string SelectListCacheKey
        //{
        //    get { return "EmailAddressesSelectListData"; }

        //}


        /// <summary>
        /// This sends the user an email verification code to their email address to verify their email
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="emailAddressId"></param>
        public void SendEmailConfirmation(string emailAddressId, GlobalObject globalObject)
        {
            UserId.IsNullThrowException("You are not logged in");
            emailAddressId.IsNullOrWhiteSpaceThrowArgumentException("emailAddressId");

            //get the email address.
            EmailAddress emailAddress = Find(emailAddressId);

            emailAddress.IsNullThrowException("Email Not found");

            RandomNoGenerator randomGen          = new RandomNoGenerator(5);
            string            verificationNumber = randomGen.GetRandomNumber(1000);

            verificationNumber.IsNullOrWhiteSpaceThrowArgumentException("Random number not generated");

            emailAddress.VerificationNumber = verificationNumber.ToString();
            emailAddress.VerificationDateComplex.SetToTodaysDate(UserName, UserId);
            //time allowed for verification is 60 min.



            string body       = string.Format("Your verification Id is: {0}", verificationNumber);
            string subject    = string.Format("Verification for email: {0}", emailAddress.Name);
            string smtpServer = ConfigManagerHelper.SmtpServer;

            string portStr = ConfigManagerHelper.SmtpPort;

            portStr.IsNullOrWhiteSpaceThrowArgumentException("No port has been listed.");
            int  portInt;
            bool success = int.TryParse(portStr, out portInt);

            if (!success)
            {
                throw new Exception("The port number is not a number.");
            }


            string userName = ConfigManagerHelper.SmtpUser;
            string from     = ConfigManagerHelper.SmtpFromEmailAddress;
            string password = ConfigManagerHelper.SmtpPassword;

            List <string> sendToList = new List <string>();

            sendToList.Add(emailAddress.Name);
            Emails emailClient = new Emails(smtpServer, portInt, userName, password, true);

            try
            {
                emailClient.SendEmailMsg(from, subject, body, sendToList, null);

                emailAddress.VerificationStatusEnum = VerificaionStatusENUM.Mailed;

                ControllerCreateEditParameter param = new ControllerCreateEditParameter();
                param.Entity       = emailAddress as ICommonWithId;
                param.GlobalObject = globalObject;

                PersonBiz.UpdateAndSave(param);

                //UpdateAndSave(emailAddress);
                ErrorsGlobal.AddMessage(string.Format("Verification Email Sent to: '{0}'", emailAddress.Name));
            }
            catch (Exception e)
            {
                ErrorsGlobal.Add(string.Format("Unable to send Email to: '{0}'", emailAddress.Name), MethodBase.GetCurrentMethod(), e);
            }
        }