public ActionResult Add(CustomerAccountWithEmployeeModel m, string command, FormCollection fc )
        {
            
            if (command.ToLower() == "cancel") return RedirectToAction("Index");


            SemplestModel.Semplest dbcontext = new SemplestModel.Semplest();

            


            //check if userid has been taken by other users

            var userIDSs = from c in dbcontext.Credentials
                        where c.Username.Equals(m.CustomerAccount.UserID) 
                        select c;
            if (userIDSs.Count() > 0)
                      ModelState.AddModelError("CustomerAccount.UserID", "This UserID is already taken!!");

               
                  if (!ModelState.IsValid)
                  {
                      //repopulate 
                   #region needs to repopulate lists to get the same view again

                      var roles = (from r in dbcontext.Roles select r).ToList().OrderBy(r => r.RoleName);

                      m.Roles = roles.Select(r => new SelectListItem
                      {
                          Value = r.RolePK.ToString(),
                          Text = r.RoleName.ToString()
                      });




                      //repopualte

                      var allreps = from e in dbcontext.Employees
                                    //join eca in dbcontext.EmployeeCustomerAssociations on e.EmployeePK equals eca.EmployeeFK
                                    join et in dbcontext.EmployeeTypes on e.EmployeeTypeFK equals et.EmployeeTypeID
                                    join u in dbcontext.Users on e.UsersFK equals u.UserPK
                                    where (et.EmployeeType1 == "Rep" && u.IsActive.Equals(true))
                                    select new EmployeeCustomerAssociaitionModel
                                    {
                                        //AccountNumber = eca.CustomerFK,
                                        employeePK = e.EmployeePK,
                                        EmployeeType = et.EmployeeType1,
                                        EmployeeUserPK = u.UserPK,
                                        FirstName = u.FirstName,
                                        MiddleInitial = u.MiddleInitial,
                                        LastName = u.LastName
                                    };



                      /////////////////////////////////////////////////////////////////////////////////
                      //for sales dropdown
                      /////////////////////////////////////////////////////////////////////////////////
                      var allsalespersons = from e in dbcontext.Employees
                                            //join eca in dbcontext.EmployeeCustomerAssociations on e.EmployeePK equals eca.EmployeeFK
                                            join et in dbcontext.EmployeeTypes on e.EmployeeTypeFK equals et.EmployeeTypeID
                                            join u in dbcontext.Users on e.UsersFK equals u.UserPK
                                            where (et.EmployeeType1 == "Sales" && u.IsActive.Equals(true))
                                            select new EmployeeCustomerAssociaitionModel
                                            {
                                                //AccountNumber = eca.CustomerFK,
                                                employeePK = e.EmployeePK,
                                                EmployeeType = et.EmployeeType1,
                                                EmployeeUserPK = u.UserPK,
                                                FirstName = u.FirstName,
                                                MiddleInitial = u.MiddleInitial,
                                                LastName = u.LastName
                                            };


                      var allparents =
              from c in dbcontext.Customers
              join chi in dbcontext.CustomerHierarchies.Where(p => p.CustomerParentFK == null) on c.CustomerPK equals chi.CustomerFK
              select c;

                      List<SelectListItem> sli = new List<SelectListItem>();


                      sli.Add(new SelectListItem { Value = (-1).ToString(), Text = "«« Parent »»" });
                      sli.Add(new SelectListItem { Value = (0).ToString(), Text = "«« Single User   »»" });

                      //x.SelectedParentID = -1;

                      m.Parents = allparents.ToList().Select(r => new SelectListItem
                      {
                          Value = r.CustomerPK.ToString(),
                          Text = r.Name.ToString()
                      }).Union(sli);



                      /////////////////////////////////////////////////////////////////////////////////
                      //for billtype dropdown
                      /////////////////////////////////////////////////////////////////////////////////
                      var allbilltypes = (from a in dbcontext.BillTypes select a).ToList();

                      
                      m.BillTypes = allbilltypes.Select(r => new SelectListItem
                      {
                          Value = r.BillTypePK.ToString(),
                          Text = r.BillType1.ToString()
                      });




                      //for state dropdown
                      /////////////////////////////////////////////////////////////////////////////////
                      var allstates = (from sc in dbcontext.StateCodes select sc).ToList();
                      
                      m.States = allstates.Select(r => new SelectListItem
                      {
                          Value = r.StateAbbrPK.ToString(),
                          Text = r.StateAbbr.ToString()
                      });


                      List<SelectListItem> slina = new List<SelectListItem>();
                      slina.Add(new SelectListItem { Value = (-1).ToString(), Text = "«« Not Assigned »»" });



                      List<EmployeeCustomerAssociaitionModel> ll1 = allreps.OrderBy(r => r.LastName).ThenBy(r => r.FirstName).ToList(); ;
                      List<SelectListItem> sl1 = new List<SelectListItem>();
                      foreach (EmployeeCustomerAssociaitionModel s in ll1)
                      {
                          SelectListItem mylistitem = new SelectListItem();
                          mylistitem.Text = s.FirstName + " " + s.LastName;
                          mylistitem.Value = s.employeePK.ToString();
                          sl1.Add(mylistitem);
                      }
                      m.Reps = sl1.Union(slina);


                      List<EmployeeCustomerAssociaitionModel> ll2 = allsalespersons.OrderBy(r => r.LastName).ThenBy(r => r.FirstName).ToList();
                      List<SelectListItem> sl2 = new List<SelectListItem>();
                      foreach (EmployeeCustomerAssociaitionModel s in ll2)
                      {
                          SelectListItem mylistitem = new SelectListItem();
                          mylistitem.Text = s.FirstName + " " + s.LastName;
                          mylistitem.Value = s.employeePK.ToString();
                          sl2.Add(mylistitem);
                      }
                      m.SalesPersons = sl2.Union(slina);
                      return View(m);     
   #endregion
                  }

             

            try
            {
                


                //BillType bt = dbcontext.BillTypes.First(p => p.BillType1 == "Flat Fee"); // --- feees --- !!!
                //revisit 
                ProductGroupCycleType pgct = dbcontext.ProductGroupCycleTypes.First(p => p.ProductGroupCycleType1 == "Product Group Cycle 30");

                var c = new Customer
                            { 
                                Name = m.CustomerAccount.Customer,
                                BillTypeFK = m.SelectedBillTypeID,
                                ProductGroupCycleType = pgct,
                                 PercentOfMedia=m.CustomerAccount.PercentMedia,
                                 ServiceFee= m.CustomerAccount.ServiceFee,
                                  InternalCustomerId= m.CustomerAccount.internalID,
                                PromotionFeeAmount = m.CustomerAccount.PromotionFeeAmount,
                                CreditLimit=m.CustomerAccount.CreditLimit,
                                PromotionFeeOverride=m.CustomerAccount.PromotionFeeOverride 
                            };

                dbcontext.Customers.Add(c);

                var u = new User
                            {
                                Customer = c,
                                Email = m.CustomerAccount.Email,
                                FirstName = m.CustomerAccount.FirstName,
                                LastName = m.CustomerAccount.LastName,
                                MiddleInitial = m.CustomerAccount.MiddleInitial,
                                IsActive = m.CustomerAccount.isActive
                            };
                dbcontext.Users.Add(u);

                var r = dbcontext.Roles.First(p => p.RolePK == m.SelectedRoleID);
                var ura = new UserRolesAssociation { Role = r, User = u };
                dbcontext.UserRolesAssociations.Add(ura);


                //
                var cr = new Credential
                             { 
                                 User = u,
                                 UsersFK = u.UserPK,
                                 Username = m.CustomerAccount.UserID,
                                 Password = m.CustomerAccount.UserPassword
                             };
                dbcontext.Credentials.Add(cr);


                PhoneType pt = dbcontext.PhoneTypes.First(p => p.PhoneType1 == "Business"); // --- phone types --- !!!!
                var ph = new Phone {Phone1 = m.CustomerAccount.Phone, PhoneType = pt};
                dbcontext.Phones.Add(ph);

                var cpa = new CustomerPhoneAssociation {Customer = c, Phone = ph};
                dbcontext.CustomerPhoneAssociations.Add(cpa);

                var sc = dbcontext.StateCodes.First(p => p.StateAbbrPK == m.SelectedStateID);
                var at = dbcontext.AddressTypes.First(p => p.AddressType1 == "H"); // --- address types --- !!!

                var a = new Address
                            {
                                Address1 = m.CustomerAccount.Address1,
                                Address2 = m.CustomerAccount.Address2,
                                City = m.CustomerAccount.City,
                                ZipCode = m.CustomerAccount.Zip,
                                StateCode = sc
                            };
                dbcontext.Addresses.Add(a);

                var caa = new CustomerAddressAssociation {Address = a, Customer = c, AddressType = at};
                dbcontext.CustomerAddressAssociations.Add(caa);

                var cn = new CustomerNote {Customer = c, Note = m.CustomerAccount.CustomerNote};
                dbcontext.CustomerNotes.Add(cn);

                
                //don't add if not assigned
                if (m.SelectedRepID != -1)
                {
                    var addrep = new EmployeeCustomerAssociation { Customer = c, EmployeeFK = m.SelectedRepID };
                    dbcontext.EmployeeCustomerAssociations.Add(addrep);
                }
                
                //don't add if not assigned
                if (m.SelectedSalesPersonID != -1)
                {
                    var addsales = new EmployeeCustomerAssociation { Customer = c, EmployeeFK = m.SelectedSalesPersonID };
                    dbcontext.EmployeeCustomerAssociations.Add(addsales);
                }

                CustomerHierarchy ch = null;
                if (m.SelectedParentID == -1) //set parent
                {
                    ch = new CustomerHierarchy {CustomerFK = c.CustomerPK, CustomerParentFK = null};
                    dbcontext.CustomerHierarchies.Add(ch);
                }
                else if (m.SelectedParentID == 0) //set self -- single user
                {
                    ch = new CustomerHierarchy {CustomerFK = c.CustomerPK, CustomerParentFK = c.CustomerPK};
                    dbcontext.CustomerHierarchies.Add(ch);
                }
                else //assign a parent
                {
                    ch = new CustomerHierarchy {CustomerFK = c.CustomerPK, CustomerParentFK = m.SelectedParentID};
                    dbcontext.CustomerHierarchies.Add(ch);
                }
                dbcontext.SaveChanges();

                /////////////////////////////////////////////////////////////////////////////
                ///// sending of emails
                AesEncyrption ae = AesEncyrption.getInstance();
                string encryptedToken = ae.GenerateToken(ch.CustomerParentFK.Value.ToString(), DateTime.Now.ToString(), cr.Username, cr.Password);
                string emailUrl = System.Configuration.ConfigurationManager.AppSettings["VerificationUrl"].ToString() + encryptedToken;
                if (fc["sendcustomeremail"] != null)
                {
                    string from, to, body, subject;

                    //send email to child customers
                    //if  child customer
                    if (m.SelectedParentID >0)
                    {
                        var emailtemplate = (
                                            from et in dbcontext.EmailTemplates
                                            join ey in dbcontext.EmailTypes on et.EmailTypeFK equals ey.EmailTypePK
                                            where ey.EmailType1.Equals("WelcomeEmailChild")
                                            select et).FirstOrDefault();

                        var parentdetails = from usr in dbcontext.Users
                                            join cus in dbcontext.Customers on usr.CustomerFK equals cus.CustomerPK
                                            where usr.CustomerFK == m.SelectedParentID
                                            select new { usr.CustomerFK, usr.Email, cus.Name };

                        //send mail //revisit
                        from = "*****@*****.**";
                        to = u.Email;
                        body = emailtemplate.EmailBody;
                        //parent name in subject line
                        subject = parentdetails.FirstOrDefault().Name + " " +emailtemplate.EmailSubject;
                        body = body.Replace("[ChildCustomerFirstLast]", u.FirstName.ToString() + " " + u.LastName.ToString());
                        body = body.Replace("[ParentCustomerName]", parentdetails.FirstOrDefault().Name.ToString());
                        body = body.Replace("[FAQs]", "http://faq");
                        body = body.Replace("[ChildCustomerUserID]", cr.Username.ToString());
                        body = body.Replace("[ChildCustomerPassword]", cr.Password.ToString());
                        body = body.Replace("[INSERT LINK]", emailUrl);
                        bool sent = false;
                        ServiceClientWrapper scw = new ServiceClientWrapper();
                        sent = scw.SendEmail(subject, from, to, body);
                    }


                    if (m.SelectedParentID == -1) ///set parent
                    {
                        var emailtemplate = (
                                            from et in dbcontext.EmailTemplates
                                            join ey in dbcontext.EmailTypes on et.EmailTypeFK equals ey.EmailTypePK
                                            where ey.EmailType1.Equals("WelcomeEmailParent")
                                            select et).FirstOrDefault();

                        
                        //send mail //revisit
                        from = "*****@*****.**";
                        to = u.Email;
                        body = emailtemplate.EmailBody;
                        subject = emailtemplate.EmailSubject;
                        

                        
                        body = body.Replace("[ParentCustomerName]", c.Name.FirstOrDefault().ToString());
                        body = body.Replace("[ParentCustomerUserID]", cr.Username.ToString());
                        body = body.Replace("[ParentCustomerPassword]", cr.Password.ToString());
                        body = body.Replace("[INSERT LINK]", emailUrl);
                        body = body.Replace("[DefaultEmailContactUS]", dbcontext.Configurations.First().DefaultEmailContactUs.ToString());
                        bool sent = false;
                        ServiceClientWrapper scw = new ServiceClientWrapper();
                        sent = scw.SendEmail(subject, from, to, body);
                    }



                    
                    if (m.SelectedParentID ==0) // non child parent customer - self
                    {

                        var emailtemplate = (
                                                from et in dbcontext.EmailTemplates
                                                join ey in dbcontext.EmailTypes on et.EmailTypeFK equals ey.EmailTypePK
                                                where ey.EmailType1.Equals("WelcomeEmailNonParentUser")
                                                select et).FirstOrDefault();

                        //send mail //revisit
                        from = "*****@*****.**";
                        to = u.Email;
                        body = emailtemplate.EmailBody;
                        subject = emailtemplate.EmailSubject;
                        body = body.Replace("[NonParentCustomer]", u.FirstName.ToString() + " " + u.LastName.ToString());
                        body = body.Replace("[NonParentCustomerUserID]", cr.Username.ToString());
                        body = body.Replace("[NonParentCustomerPassword]", cr.Password.ToString());
                        body = body.Replace("[INSERT LINK]", emailUrl);
                        bool sent = false;
                        ServiceClientWrapper scw = new ServiceClientWrapper();
                        sent = scw.SendEmail(subject, from, to, body);
                    }
                    //SendEmail


                }

            }
            catch (Exception ex)
            {
                Semplest.SharedResources.Helpers.ExceptionHelper.LogException(ex);
            }


            return RedirectToAction("Index");
        }
예제 #2
0
        public void AddCustomer(CustomerAccountWithEmployeeModel m)
        {
            try
            {
                SemplestModel.Semplest dbcontext = new SemplestModel.Semplest();
                //BillType bt = dbcontext.BillTypes.First(p => p.BillType1 == "Flat Fee"); // --- feees --- !!!
                //revisit 
                ProductGroupCycleType pgct = dbcontext.ProductGroupCycleTypes.First(p => p.ProductGroupCycleType1 == "Product Group Cycle 30");

                var c = new Customer
                            { 
                                Name = m.CustomerAccount.Customer,
                                BillTypeFK = m.SelectedBillTypeID,
                                ProductGroupCycleType = pgct,
                                 PercentOfMedia=m.CustomerAccount.PercentMedia,
                                 ServiceFee= m.CustomerAccount.ServiceFee,
                                  InternalCustomerId= m.CustomerAccount.internalID,
                                PromotionFeeAmount = m.CustomerAccount.PromotionFeeAmount,
                                CreditLimit=m.CustomerAccount.CreditLimit,
                                PromotionFeeOverride=m.CustomerAccount.PromotionFeeOverride,
                                CreatedDate = DateTime.Now,
                                AllowAutobid = m.CustomerAccount.AllowAutoBid
                            };

                dbcontext.Customers.Add(c);
                var ur = new UserRepository(dbcontext);
                var u = new User
                            {
                                Customer = c,
                                Email = m.CustomerAccount.Email,
                                FirstName = m.CustomerAccount.FirstName,
                                LastName = m.CustomerAccount.LastName,
                                MiddleInitial = m.CustomerAccount.MiddleInitial,
                                IsActive = m.CustomerAccount.isActive,
                                CreatedDate = DateTime.Now,
                                UserTypeFK = m.SelectedUserTypeID
                            };
                dbcontext.Users.Add(u);

                var r = dbcontext.Roles.First(p => p.RolePK == m.SelectedRoleID);
                var ura = new UserRolesAssociation { Role = r, User = u };
                dbcontext.UserRolesAssociations.Add(ura);
                AesEncyrption ae = AesEncyrption.getInstance();
                var encryptedPassword = ae.EncryptString(m.CustomerAccount.UserPassword);
                var cr = new Credential
                             { 
                                 User = u,
                                 UsersFK = u.UserPK,
                                 Username = m.CustomerAccount.UserID,
                                 Password = encryptedPassword
                             };
                dbcontext.Credentials.Add(cr);
                PhoneType pt = dbcontext.PhoneTypes.First(p => p.PhoneType1 == "Business"); // --- phone types --- !!!!
                var ph = new Phone {Phone1 = m.CustomerAccount.Phone, PhoneType = pt};
                dbcontext.Phones.Add(ph);
                var cpa = new CustomerPhoneAssociation {Customer = c, Phone = ph};
                dbcontext.CustomerPhoneAssociations.Add(cpa);
                var sc = dbcontext.StateCodes.First(p => p.StateAbbrPK == m.SelectedStateID);
                var at = dbcontext.AddressTypes.First(p => p.AddressType1 == "H"); // --- address types --- !!!
                var a = new Address
                            {
                                Address1 = m.CustomerAccount.Address1,
                                Address2 = m.CustomerAccount.Address2,
                                City = m.CustomerAccount.City,
                                ZipCode = m.CustomerAccount.Zip,
                                StateCode = sc
                            };
                dbcontext.Addresses.Add(a);
                var caa = new CustomerAddressAssociation {Address = a, Customer = c, AddressType = at};
                dbcontext.CustomerAddressAssociations.Add(caa);
                var cn = new CustomerNote {Customer = c, Note = m.CustomerAccount.CustomerNote};
                dbcontext.CustomerNotes.Add(cn);
                //don't add if not assigned
                if (m.SelectedRepID != -1)
                {
                    var addrep = new EmployeeCustomerAssociation { Customer = c, EmployeeFK = m.SelectedRepID };
                    dbcontext.EmployeeCustomerAssociations.Add(addrep);
                }
                //don't add if not assigned
                if (m.SelectedSalesPersonID != -1)
                {
                    var addsales = new EmployeeCustomerAssociation { Customer = c, EmployeeFK = m.SelectedSalesPersonID };
                    dbcontext.EmployeeCustomerAssociations.Add(addsales);
                }
                CustomerHierarchy ch = null;
                if (m.SelectedParentID == -1) //set parent
                {
                    ch = new CustomerHierarchy {CustomerFK = c.CustomerPK, CustomerParentFK = null};
                    dbcontext.CustomerHierarchies.Add(ch);
                }
                else if (m.SelectedParentID == 0) //set self -- single user
                {
                    ch = new CustomerHierarchy {CustomerFK = c.CustomerPK, CustomerParentFK = c.CustomerPK};
                    dbcontext.CustomerHierarchies.Add(ch);
                }
                else //assign a parent
                {
                    ch = new CustomerHierarchy {CustomerFK = c.CustomerPK, CustomerParentFK = m.SelectedParentID};
                    dbcontext.CustomerHierarchies.Add(ch);
                }
                dbcontext.SaveChanges();

                SendAccountActivationEmail(u.UserPK);

            }
            catch (Exception ex)
            {
                Semplest.SharedResources.Helpers.ExceptionHelper.LogException(ex);
            }
        }
        public ActionResult Upload(HttpPostedFileBase uploadFile, CustomerImport imp, FormCollection fc)
        {
            string importstatus;
            importstatus  = "The import was the successful..";
            SemplestModel.Semplest dbcontext = new SemplestModel.Semplest();
            

            {

                StringBuilder strValidations = new StringBuilder(string.Empty);
                try
                {
                    if (uploadFile.ContentLength > 0)
                    {
                        string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
                        Path.GetFileName(uploadFile.FileName));
                        uploadFile.SaveAs(filePath);
                        FileHelperEngine engine = new FileHelperEngine(typeof(CustomerImportData));
                        engine.ErrorManager.ErrorMode = ErrorMode.SaveAndContinue;

                        CustomerImportData[] customersimported = (CustomerImportData[])engine.ReadFile(filePath);


                        if (engine.ErrorManager.HasErrors)
                            foreach (ErrorInfo err in engine.ErrorManager.Errors)
                            {
                                string s;
                                s = err.LineNumber + " / " + err.RecordString + " / " + err.ExceptionInfo.ToString();

                                //Console.WriteLine(err.LineNumber);    
                                //Console.WriteLine(err.RecordString);   
                                //Console.WriteLine(err.ExceptionInfo.ToString());
                            }

                        if (customersimported.Count() < 1) throw new Exception("No customers could be imported from csv file");
                        ///////////
                        ///////////


                        foreach (CustomerImportData cust in customersimported)
                        {

                            CustomerAccount m = new CustomerAccount();


                            #region
                            //cust.ContactCompanyName;
                            //cust.ContactEmail;
                            //cust.ContactFirstName;
                            //cust.ContactLastName;
                            //cust.ContactMiddleInitial;
                            //cust.ContactPhoneNumber;
                            //cust.ContactAddressLine1;
                            //cust.ContactAddressLine2;
                            //cust.ContactCity;
                            //cust.ContactState;
                            //cust.ContactStatus;
                            //cust.ContactZip;
                            //cust.FixedMonthlybudget;
                            //cust.InternalCustomerID;
                            ///////
                            //cust.LocalTargetAddress1;
                            //cust.LocalTargetAddress2;
                            //cust.LocalTargetAddress3;
                            //cust.LocalTargetProximity1;
                            //cust.LocalTargetProximity1;
                            //cust.LocalTargetProximity2;
                            //cust.LocalTargetProximity3;
                            //cust.ParentCompanyName;

                            //ca.Address1;
                            //ca.Address2;
                            //ca.City;
                            //ca.Customer;
                            //ca.Email;
                            //ca.FirstName;
                            //ca.MiddleInitial;
                            //ca.Phone;
                            //ca.State;
                            //ca.UserID;
                            //ca.UserPassword;
                            //ca.Zip;
                            //ca.isActive;
                            #endregion

                            /*
                        //cust.ContactStatus;
                        cust.FixedMonthlybudget;
                        //cust.InternalCustomerID;
                        /////
                        cust.LocalTargetAddress1;
                        cust.LocalTargetAddress2;
                        cust.LocalTargetAddress3;
                        cust.LocalTargetProximity1;
                        cust.LocalTargetProximity2;
                        cust.LocalTargetProximity3;
                        cust.ParentCompanyName;
                        /////
                        */

                            m.internalID = cust.InternalCustomerID;
                            m.Address1 = cust.ContactAddressLine1;
                            m.Address2 = cust.ContactAddressLine2;
                            m.City = cust.ContactCity;
                            m.Customer = cust.ContactCompanyName;
                            m.Email = cust.ContactEmail;
                            m.FirstName = cust.ContactFirstName;
                            m.MiddleInitial = cust.ContactMiddleInitial;
                            m.LastName = cust.ContactLastName;
                            m.Phone = cust.ContactPhoneNumber;
                            m.State = cust.ContactState;
                            m.UserID = cust.ContactEmail;
                            m.UserPassword = Semplest.SharedResources.Helpers.RandomPassword.Generate(8, 10);
                            m.Zip = cust.ContactZip;
                            m.isActive = true;


                            var emailtemplate = (from et in dbcontext.EmailTemplates
                                                 where et.EmailTemplatePK.Equals(13)
                                                 select et).FirstOrDefault();
                                                        
                            try
                            {
                                var existing = (from ex in dbcontext.Customers
                                                where ex.InternalCustomerId.Equals(cust.InternalCustomerID) && ex.Name.Equals(m.Customer)
                                                select ex).ToList();

                                if (existing.Count() > 0) throw new Exception();


                                ProductGroupCycleType pgct = dbcontext.ProductGroupCycleTypes.First(p => p.ProductGroupCycleType1 == "Product Group Cycle 30");

                                //Customer c = dbcontext.Customers.Add(new Customer { Name = m.Customer, BillTypeFK = imp.SelectedBillTypeID, ProductGroupCycleType = pgct, InternalCustomerId = cust.InternalCustomerID });
                                var c = new Customer { Name = m.Customer, BillTypeFK = imp.SelectedBillTypeID, ProductGroupCycleType = pgct, InternalCustomerId = cust.InternalCustomerID };
                                dbcontext.Customers.Add(c);
                                var u = new User
                                {
                                    Customer = c,
                                    Email = m.Email,
                                    FirstName = m.FirstName,
                                    LastName = m.LastName,
                                    MiddleInitial = m.MiddleInitial,
                                    IsActive = m.isActive
                                };
                                dbcontext.Users.Add(u);

                                var cr = new Credential { User = u, UsersFK = u.UserPK, Username = m.UserID, Password = m.UserPassword };
                                dbcontext.Credentials.Add(cr);


                                PhoneType pt = dbcontext.PhoneTypes.First(p => p.PhoneType1 == "Business"); // --- phone types --- !!!!
                                Phone ph = new Phone { Phone1 = m.Phone, PhoneType = pt };
                                dbcontext.Phones.Add(ph);
                                
                                var cpa = new CustomerPhoneAssociation { Customer = c, Phone = ph };
                                dbcontext.CustomerPhoneAssociations.Add(cpa);

                                StateCode sc = dbcontext.StateCodes.First(p => p.StateAbbr == m.State);
                                AddressType at = dbcontext.AddressTypes.First(p => p.AddressType1 == "H"); // --- address types --- !!!
                                var a = new Address { Address1 = m.Address1, Address2 = m.Address2, City = m.City, ZipCode = m.Zip, StateCode = sc };
                                dbcontext.Addresses.Add(a);
                                var caa = new CustomerAddressAssociation { Address = a, Customer = c, AddressType = at };
                                dbcontext.CustomerAddressAssociations.Add(caa);

                                var cn = new CustomerNote { Customer = c, Note = m.CustomerNote };
                                dbcontext.CustomerNotes.Add(cn);

                                var r = dbcontext.Roles.First(p => p.RolePK == imp.SelectedRoleID);
                                var ura = new UserRolesAssociation { Role = r, User = u };
                                dbcontext.UserRolesAssociations.Add(ura);

                                //default to the parent's rep and salesperson

                                var parentrepandsales = (from prs in dbcontext.EmployeeCustomerAssociations
                                                         where prs.CustomerFK.Equals(imp.ParentID)
                                                         select prs).ToList();
                                foreach (EmployeeCustomerAssociation eca in parentrepandsales)
                                {
                                    var addrepandsales = new EmployeeCustomerAssociation { Customer = c, EmployeeFK = eca.EmployeeFK };
                                    dbcontext.EmployeeCustomerAssociations.Add(addrepandsales);
                                }

                                //add child to parent in customerhierarchy
                                var ch = new CustomerHierarchy { CustomerFK = c.CustomerPK, CustomerParentFK = imp.ParentID };
                                dbcontext.CustomerHierarchies.Add(ch);
                                dbcontext.SaveChanges();

                                if (fc["sendcustomeremail"] != null)
                                {

                                    ///////////////////////////////////////////////////////////////
                                    //FOR SENDING OUT EMAILS to child customers
                                    /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ///

                                    var parentdetails = from usr in dbcontext.Users
                                                        join cus in dbcontext.Customers on usr.CustomerFK equals cus.CustomerPK
                                                        where usr.CustomerFK == imp.ParentID
                                                        select new { usr.CustomerFK, usr.Email, cus.Name };

                                    //send mail //revisit
                                    string from = "*****@*****.**";
                                    string to = u.Email;
                                    string body = emailtemplate.EmailBody;
                                    string subject = emailtemplate.EmailSubject;
                                    body = body.Replace("[ChildCustomerFirstLast]", u.FirstName.ToString() + " " + u.LastName.ToString());
                                    body = body.Replace("[ParentCustomerName]", parentdetails.FirstOrDefault().Name.ToString());
                                    body = body.Replace("[FAQs]", "http://faq");
                                    body = body.Replace("[ChildCustomerUserID]", cr.Username.ToString());
                                    body = body.Replace("[ChildCustomerPassword]", cr.Password.ToString());
                                    body = body.Replace("[INSERT LINK]", "http://encrypto");

                                    //SendEmail
                                    bool sent = false;
                                    ServiceClientWrapper scw = new ServiceClientWrapper();
                                    sent = scw.SendEmail(subject, from, to, body);
                                }
                                                            
                            }
                            catch (Exception ex)
                            {
                                //Console.WriteLine(ex.TargetSite);
                                SemplestModel.Semplest _dbContext = new SemplestModel.Semplest();
                                SemplestModel.Error er = new SemplestModel.Error();
                                er.ErrorMessage = ex.Message+"  \r\n "+ex.InnerException  +"  \r\n "+ex.StackTrace +"  \r\n "+ex.Source+"  \r\n "+ex.TargetSite;
                                //filterContext.RequestContext.HttpContext.Session
                                //if (HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID] == null)
                                //    er.UsersFK = 1;
                                //else
                                //    er.UsersFK = ((Credential)HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]) == null ? 1 : ((Credential)HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]).UsersFK;
                                er.CreatedDate = DateTime.Now;
                                _dbContext.Errors.Add(er);
                                _dbContext.SaveChanges();
                                
                                var scw = new ServiceClientWrapper();
                                scw.SendEmail("WebSite Error Message", "*****@*****.**", _dbContext.Configurations.First().OnErrorEmail, er.ErrorMessage);
                            }
                        }//endforeach

                    }
                    else throw new Exception();

                }
                catch (Exception ex)
                {
                    importstatus = "An error has occured. Please check the file for errors and try again..";
                    //Console.WriteLine(ex.TargetSite);
                    SemplestModel.Semplest _dbContext = new SemplestModel.Semplest();
                    SemplestModel.Error er = new SemplestModel.Error();
                    er.ErrorMessage = ex.Message + "  \r\n " + ex.InnerException + "  \r\n " + ex.StackTrace + "  \r\n " + ex.Source + "  \r\n " + ex.TargetSite;
                    //filterContext.RequestContext.HttpContext.Session
                    //if (HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID] == null)
                    //    er.UsersFK = 1;
                    //else
                    //    er.UsersFK = ((Credential)HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]) == null ? 1 : ((Credential)HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]).UsersFK;
                    er.CreatedDate = DateTime.Now;
                    _dbContext.Errors.Add(er);
                    _dbContext.SaveChanges();
                    var scw = new ServiceClientWrapper();
                    scw.SendEmail("WebSite Error Message", "*****@*****.**", _dbContext.Configurations.First().OnErrorEmail, er.ErrorMessage);

                }


                /*
                 
                 *   public Boolean SendEmail(String subject, String from, String recipient, String msgTxt)
        {
            var jsonHash = new Dictionary<string, string>();
            jsonHash.Add("subject", subject);
            jsonHash.Add("from", from);
            jsonHash.Add("recipient", recipient);
            jsonHash.Add("msgTxt", msgTxt);
            string jsonstr = JsonConvert.SerializeObject(jsonHash);
            string returnData = runMethod(_baseURLTest, MAILSERVICEOFFERED, "SendEmail", jsonstr, timeoutMS);
            var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(returnData);
            string boolResult = dict.Values.First();
            return Convert.ToBoolean(boolResult);
        }
                 
                 */



                //scope.Complete();
            }

            //return View(m);

            ImportResultModel res = new ImportResultModel();
            res.Importresult = importstatus;
            return RedirectToAction("CustomerImportResult", "AccountService",   res );
        }
        public ActionResult Add(EmployeeSetupWithRolesModel m, string command)
        {

            if (command.ToLower() == "cancel") return RedirectToAction("Index");

            SemplestModel.Semplest dbcontext = new SemplestModel.Semplest();


            //check if userid has been taken by other users

                  var userIDSs = from c in dbcontext.Credentials
                        where c.Username.Equals(m.EmployeeSetup.UserID) //&& !c.UsersFK.Equals(m.EmployeeSetup.UserPK)
                        select c;
                  if (userIDSs.Count() > 0)
                      ModelState.AddModelError("EmployeeSetup.UserID", "This UserID is already taken!!");


                  if (!ModelState.IsValid)
                  {
                      //repopulate 


                      var roles = (from r in dbcontext.Roles select r).ToList().OrderBy(r => r.RoleName);
                      
                      m.Roles = roles.Select(r => new SelectListItem
                      {
                          Value = r.RolePK.ToString(),
                          Text = r.RoleName.ToString()
                      });



                      /////////////////////////////////////////////////////////////////////////////////
                      //for Reportingto dropdown
                      /////////////////////////////////////////////////////////////////////////////////
                      var reportingto = (
                          from e in dbcontext.Employees
                          join u in dbcontext.Users on e.UsersFK equals u.UserPK
                          where u.IsActive.Equals(true)
                          select new ReportingToModel
                          {
                              EmployeePK = e.EmployeePK,
                              FirstName = u.FirstName,
                              LastName = u.LastName
                          }
                          ).ToList().OrderBy(r => r.LastName).ThenBy(r => r.FirstName);
                      



                      //to add exception to dropdownlist - it can be optional, in this case the employee reporting to may be optional
                      List<SelectListItem> sli = new List<SelectListItem>();
                      sli.Add(new SelectListItem { Value = (-1).ToString(), Text = "«« Not Assigned »»" });


                      m.ReportingTo = reportingto.Select(r => new SelectListItem
                      {
                          Value = r.EmployeePK.ToString(),
                          Text = r.FirstName.ToString() + " " + r.LastName.ToString()
                      }).Union(sli);



                      /////////////////////////////////////////////////////////////////////////////////
                      // for employeetype dropdown
                      /////////////////////////////////////////////////////////////////////////////////
                      var employeetypes = (from r in dbcontext.EmployeeTypes select r).ToList();
                      m.EmployeeTypes = employeetypes.Select(r => new SelectListItem
                      {
                          Value = r.EmployeeTypeID.ToString(),
                          Text = r.EmployeeType1.ToString()
                      });


                      return View(m);
                  }


            try
            {

                var u = new User
                            {
                                Customer = null,
                                Email = m.EmployeeSetup.Email,
                                FirstName = m.EmployeeSetup.FirstName,
                                MiddleInitial = m.EmployeeSetup.MiddleInitial,
                                LastName = m.EmployeeSetup.LastName,
                                CustomerFK = null,
                                IsActive = m.EmployeeSetup.isActive,
                                IsRegistered = true //only for admin, force registered=true (Andre)

                            };
                dbcontext.Users.Add(u);
                

                var r= dbcontext.Roles.First(p => p.RolePK   == m.SelectedRoleID );
                var ura = new UserRolesAssociation {Role = r, User = u};
                dbcontext.UserRolesAssociations.Add(ura);

                var et = dbcontext.EmployeeTypes.First(p => p.EmployeeTypeID == m.SelectedEmployeeTypeID);
                var e = new Employee {EmployeeType = et, User = u, HireDate = m.EmployeeSetup.HireDate};
                dbcontext.Employees.Add(e);
                //Credential c = dbcontext.Credentials.Add(new Credential { User = u, Username = m.EmployeeSetup.Email, Password = "******" });

                var cr = new Credential
                             {
                                 User = u,
                                 UsersFK = u.UserPK,
                                 Username = m.EmployeeSetup.UserID,
                                 Password = m.EmployeeSetup.UserPassword
                             };
                dbcontext.Credentials.Add(cr); 


                //BillType bt = dbcontext.BillTypes.First(p => p.BillType1 == "Flat Fee"); // --- feees --- !!!

                //ProductGroupCycleType pgct = dbcontext.ProductGroupCycleTypes.First(p => p.ProductGroupCycleType1 == "Product Group Cycle 30");

                //Customer c = dbcontext.Customers.Add(new Customer { Name = m.CustomerAccount.Customer, BillType = bt, ProductGroupCycleType = pgct });
                //User u = dbcontext.Users.Add(new User
                //{
                //    Customer = c,
                //    Email = m.CustomerAccount.Email,
                //    FirstName = m.CustomerAccount.FirstName,
                //    LastName = m.CustomerAccount.LastName
                //});

                //Credential cr = dbcontext.Credentials.Add(new Credential { User = u, UsersFK = u.UserPK, Username = m.CustomerAccount.Email, Password = "******" }); //-- default password --- !!

                //PhoneType pt = dbcontext.PhoneTypes.First(p => p.PhoneType1 == "Business"); // --- phone types --- !!!!
                //Phone ph = dbcontext.Phones.Add(new Phone { Phone1 = m.CustomerAccount.Phone, PhoneType = pt });
                //CustomerPhoneAssociation cpa = dbcontext.CustomerPhoneAssociations.Add(new CustomerPhoneAssociation { Customer = c, Phone = ph });

                //StateCode sc = dbcontext.StateCodes.First(p => p.StateAbbrPK == m.SelectedStateID);
                //AddressType at = dbcontext.AddressTypes.First(p => p.AddressType1 == "H"); // --- address types --- !!!
                //Address a = dbcontext.Addresses.Add(new Address { Address1 = m.CustomerAccount.Address1, Address2 = m.CustomerAccount.Address2, City = m.CustomerAccount.City, ZipCode = m.CustomerAccount.Zip, StateCode = sc });
                //CustomerAddressAssociation caa = dbcontext.CustomerAddressAssociations.Add(new CustomerAddressAssociation { Address = a, Customer = c, AddressType = at });


                dbcontext.SaveChanges();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.TargetSite);
            }


            return RedirectToAction("Index");
        }