/// <summary>
        /// Method to update user detail
        /// </summary>
        /// <param name="userMl"></param>
        /// <returns></returns>
        public int UpdateUserDetails(UsersModel userMl)
        {
            // Creating instance of the string builder class to hold the tracing data
            StringBuilder objStringBuilderTrace = new StringBuilder();
            var userId = 0;
            // Append tracing into string builder
            objStringBuilderTrace.AppendLine("Start method : UpdateUserDetails(UsersModel userML) :: JetstreamLaunchpad.DAL.Users class : DBUsers.cs");
            // Writing trace log into the log file 
            SaveLogger.SaveLoggerTrace(objStringBuilderTrace.ToString());
            // Clear StringBuilder object
            objStringBuilderTrace.Clear();

            user objUserDetail = ObjTersoDataContext.users.FirstOrDefault(x => x.UserId == userMl.UserId);
            if (objUserDetail != null)
            {
                objUserDetail.FirstName = userMl.FirstName;
                objUserDetail.LastName = userMl.LastName;
                objUserDetail.EmailAddress = userMl.EmailAddress;
                objUserDetail.PassNumber = userMl.PassNumber;
                objUserDetail.PassRFID = userMl.PassRFID != null ? userMl.PassRFID.ToUpper() : userMl.PassRFID;
                objUserDetail.Status = userMl.Status;
                ObjTersoDataContext.SaveChanges();
                userId = objUserDetail.UserId;
            }
            // Append tracing into string builder
            objStringBuilderTrace.AppendLine("End method : UpdateUserDetails(UsersModel userML) :: JetstreamLaunchpad.DAL.Users class : DBUsers.cs");
            // Writing trace log into the log file 
            SaveLogger.SaveLoggerTrace(objStringBuilderTrace.ToString());
            objStringBuilderTrace.Clear();
            return userId;

        }
        public ActionResult UserLogin(UsersModel userMl, string command)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                if (string.Equals(command, JetstreamResource.LoginCommand))
                {
                    if (userMl != null)
                    {
                        userMl.Password = CryptoManager.Encrypt(userMl.Password, true);
                        UsersModel objUser;
                        using (JetstreamClient objMainServiceClient = new JetstreamClient())
                        {
                            objUser = objMainServiceClient.LogOn(userMl);
                        }
                        if (objUser != null && objUser.UserId != 0)
                        {
                            Session["UserName"] = string.Format("{0} {1}", objUser.FirstName, objUser.LastName);
                            Session["UserId"] = objUser.UserId.ToString();
                            return RedirectToAction("InventoryDetail", "Inventory");
                        }
                        else
                        {
                            Danger(JetstreamResource.LoginFailed, true);
                            return RedirectToAction("UserLogin", "Login");
                        }
                    }
                }
                else if (command == JetstreamResource.ForgetPasswordCommand)
                {
                    return RedirectToAction("ForgetPassword", "Login");
                }
                return RedirectToAction("UserLogin", "Login");
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : UserLogin() :: LoginController");
                objStringBuilderError.AppendFormat("ErrorMessage::{0} {1}", fex.Detail.ErrorMessage, Environment.NewLine);
                objStringBuilderError.AppendFormat("ErrorDetails::{0} {1}", Environment.NewLine, fex.Detail.ErrorDetails);

                SaveLogger.SaveLoggerError(objStringBuilderError.ToString());
                return View("Error");
            }
            catch (Exception ex)
            {
                objStringBuilderError.AppendLine("In method : UserLogin() :: LoginController");
                objStringBuilderError.AppendFormat("ErrorMessage::{0} {1}", ex.Message, Environment.NewLine);
                objStringBuilderError.AppendFormat("ErrorDetails::{0} {1}", Environment.NewLine, ex.ToString());

                SaveLogger.SaveLoggerError(objStringBuilderError.ToString());
                return View("Error");
            }
        }
        public void UserLogin_OnPost_WithUserMode_ExpectRedirectToUserLogin()
        {
            //Arrange
            String expectedController = "Login";
            String expectedAction = "UserLogin";
            UsersModel usersML = new UsersModel { EmailAddress = "*****@*****.**", Password = "******" };

            //Act
            var redirectToRouteResult = _loginController.UserLogin(usersML, string.Empty) as RedirectToRouteResult;

            // Assert
            Assert.IsNotNull(redirectToRouteResult, "Not a redirect result");
            Assert.IsFalse(redirectToRouteResult.Permanent); // Or IsTrue if you use RedirectToActionPermanent
            Assert.AreEqual(expectedAction, redirectToRouteResult.RouteValues["Action"]);
            Assert.AreEqual(expectedController, redirectToRouteResult.RouteValues["Controller"]);
        }
        public void UserLogin_OnPost_WithUserModelAndLoginCommand_ExpectOk()
        {
            //Arrange
            String expectedController = "Inventory";
            String expectedAction = "InventoryDetail";
            _controllerContext.Setup(cc => cc.HttpContext.Session["UserName"]).Returns(string.Empty);
            _controllerContext.Setup(cc => cc.HttpContext.Session["UserId"]).Returns(string.Empty);
            _loginController.ControllerContext = _controllerContext.Object;
            UsersModel usersML = new UsersModel { EmailAddress = "*****@*****.**", Password = "******" };

            //Act
            var redirectToRouteResult = _loginController.UserLogin(usersML, "Login") as RedirectToRouteResult;

            // Assert
            Assert.IsNotNull(redirectToRouteResult, "Not a redirect result");
            Assert.IsFalse(redirectToRouteResult.Permanent); // Or IsTrue if you use RedirectToActionPermanent
            Assert.AreEqual(expectedAction, redirectToRouteResult.RouteValues["Action"]);
            Assert.AreEqual(expectedController, redirectToRouteResult.RouteValues["Controller"]);
        }
        /// <summary>
        /// Method to send mail
        /// </summary>
        /// <param name="userMl"></param>
        /// <param name="mailToDisplayName"></param>
        /// <param name="subject"></param>
        /// <param name="message"></param>
        public static void SendEmail(UsersModel userMl, string mailToDisplayName, string subject, string message)
        {
            if (userMl != null)
            {
                using (System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient())
                {
                    var smtpSection = (SmtpSection)ConfigurationManager.GetSection(JetstreamResource.SmtpSection);

                    using (System.Net.Mail.MailMessage mMessage = new System.Net.Mail.MailMessage(
                        new System.Net.Mail.MailAddress(smtpSection.Network.UserName, mailToDisplayName),
                        new System.Net.Mail.MailAddress(userMl.EmailAddress)))
                    {
                        mMessage.Subject = subject;
                        mMessage.Body = message;
                        mMessage.IsBodyHtml = true;
                        smtp.Send(mMessage);
                    }
                }
            }
        }
 /// <summary>
 /// Method to update user detail
 /// </summary>
 /// <param name="userMl"></param>
 /// <returns></returns>
 public int UpdateUserDetails(UsersModel userMl)
 {
     ServiceData serviceData = new ServiceData();
     try
     {
         int result;
         using (DBUsers objDbUsers = new DBUsers())
         {
             result = objDbUsers.UpdateUserDetails(userMl);
         }
         return result;
     }
     catch (Exception ex)
     {
         serviceData.Result = false;
         serviceData.ErrorMessage = ex.Message;
         serviceData.ErrorDetails = ex.ToString();
         throw new FaultException<ServiceData>(serviceData);
     }
 }
        public ActionResult ForgetPassword(UsersModel userMl, string command)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                if (command == JetstreamResource.SendEmailCommand)
                {
                    if (userMl != null)
                    {
                        UsersModel objUser;
                        using (JetstreamClient objMainServiceClient = new JetstreamClient())
                        {
                            objUser = objMainServiceClient.GetUserModelListByEmail(userMl.EmailAddress);
                        }
                        Email.SendEmail(userMl, JetstreamResource.ForgetPasswordDisplayName, JetstreamResource.ForgetPasswordSubject,
                                                string.Format(JetstreamResource.ForgetPasswordMessage,
                                                                objUser.FirstName, objUser.LastName,
                                                                objUser.EmailAddress, CryptoManager.Decrypt(objUser.Password, true)));
                        Success(JetstreamResource.PasswordSendSuccess, true);
                    }
                }
                return RedirectToAction("UserLogin", "Login");
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : ForgetPassword(UsersModel userMl, string command) :: LoginController");
                objStringBuilderError.AppendFormat("ErrorMessage::{0} {1}", fex.Detail.ErrorMessage, Environment.NewLine);
                objStringBuilderError.AppendFormat("ErrorDetails::{0} {1}", Environment.NewLine, fex.Detail.ErrorDetails);

                SaveLogger.SaveLoggerError(objStringBuilderError.ToString());
                return View("Error");
            }
            catch (Exception ex)
            {
                objStringBuilderError.AppendLine("In method : ForgetPassword(UsersModel userMl, string command) :: LoginController");
                objStringBuilderError.AppendFormat("ErrorMessage::{0} {1}", ex.Message, Environment.NewLine);
                objStringBuilderError.AppendFormat("ErrorDetails::{0} {1}", Environment.NewLine, ex.ToString());

                SaveLogger.SaveLoggerError(objStringBuilderError.ToString());
                return View("Error");
            }
        }
        /// <summary>
        /// Check for user with same email id and pass ref id
        /// </summary>
        /// <param name="userMl"></param>
        /// <returns></returns>
        static int CheckForDuplicate(UsersModel userMl)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            int duplicateDevice = 0;        //Cannot remove initialization of variable to zero.giving error "Use of unassigned local variable 'duplicateDevice'"
            try
            {
                using (JetstreamClient objMainServiceClient = new JetstreamClient())
                {
                    if (objMainServiceClient.GetUserModelByPassRfId(userMl) > 0)
                    {
                        duplicateDevice = 1;
                    }
                    else if (objMainServiceClient.GetUserModelByEmailId(userMl) > 0)
                    {
                        duplicateDevice = 2;
                    }
                }
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : CheckForDuplicate(UsersModel userMl) :: UserController");
                objStringBuilderError.AppendFormat("ErrorMessage::{0} {1}", fex.Detail.ErrorMessage, Environment.NewLine);
                objStringBuilderError.AppendFormat("ErrorDetails::{0} {1}", Environment.NewLine, fex.Detail.ErrorDetails);
                SaveLogger.SaveLoggerError(objStringBuilderError.ToString());
            }
            catch (Exception ex)
            {
                objStringBuilderError.AppendLine("In method : CheckForDuplicate(UsersModel userMl) :: UserController");
                objStringBuilderError.AppendFormat("ErrorMessage::{0} {1}", ex.Message, Environment.NewLine);
                objStringBuilderError.AppendFormat("ErrorDetails::{0} {1}", Environment.NewLine, ex.ToString());

                SaveLogger.SaveLoggerError(objStringBuilderError.ToString());
            }
            return duplicateDevice;
        }
 /// <summary>
 /// Redirect to Edit user screen
 /// </summary>
 /// <param name="userDetail"></param>
 /// <returns></returns>
 public ActionResult RedirectToEditUser(UsersModel userDetail)
 {
     var statusList = Enum.GetValues(typeof(Enums.Status)).Cast<object>().ToDictionary(item => Convert.ToBoolean(Enum.Parse(typeof(Enums.Status), item.ToString())), item => Enum.GetName(typeof(Enums.Status), item));
     ViewBag.StatusModelList = new SelectList(statusList.OrderBy(x => x.Value), "Key", "Value");
     if (userDetail != null)
     {
         ViewBag.Name = userDetail.FirstName + " " + userDetail.LastName;
     }
     return View("EditUser", userDetail);
 }
        /// <summary>
        /// Method to update passes to all the device
        /// </summary>
        /// <param name="userMl"></param>
        private static void UpdatePasses(UsersModel userMl)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                if (!string.IsNullOrEmpty(userMl.PassRFID))
                {
                    // construct a Jetstream service client
                    JetstreamServiceClient client = new JetstreamServiceClient(JetstreamConfiguration.Url,
                        JetstreamConfiguration.ApplicationAccessKey);

                    // create the GetDeviceDefinitions request
                    GetDeviceDefinitionsRequest deviceRequest = new GetDeviceDefinitionsRequest();

                    // call the Jetstream GetDeviceDefinitions ReST endpoint
                    GetDeviceDefinitionsResponse deviceResponse = client.GetDeviceDefinitions(deviceRequest);

                    //List the user passRFId
                    List<string> passes = new List<string> { userMl.PassRFID.ToUpper() };

                    //Get the list of Devices from local database
                    IEnumerable<DeviceModel> devices;
                    using (JetstreamClient objMainServiceClient = new JetstreamClient())
                    {
                        devices = objMainServiceClient.GetDeviceList();
                    }

                    //Itterate through the list of devices
                    foreach (var device in devices)
                    {
                        //get the device defination list for checking if device allow pass update
                        var deviceModel =
                            deviceResponse.DeviceDefinitionList.Where(x => x.Id == device.DeviceGuid).ToList();

                        if (deviceModel.Count > 0)
                        {
                            //Check if device allow pass update
                            var jetstreamGetDeviceDefinitionsResponseDeviceDefinition = deviceModel.FirstOrDefault();
                            bool updatePass = jetstreamGetDeviceDefinitionsResponseDeviceDefinition != null &&
                                              jetstreamGetDeviceDefinitionsResponseDeviceDefinition.CommandList
                                                  .DeviceSpecificCommandList.DeviceSpecificCommand.ToList()
                                                  .Select(x => x.CommandName)
                                                  .Contains("UpdatePasses");

                            if (updatePass)
                            {
                                //Update Pass to device
                                UpdatePassesRequest updateRequest = new UpdatePassesRequest
                                {
                                    LogicalDeviceId = device.LogicalDeviceId
                                };
                                if (userMl.Status != null && userMl.Status.Value)
                                {
                                    updateRequest.Add = passes;
                                }
                                else
                                {
                                    updateRequest.Remove = passes;
                                }

                                client.DeviceSpecificCommand(updateRequest);
                            }
                        }
                    }
                }
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : UpdatePasses(UsersModel userMl) :: UserController");
                objStringBuilderError.AppendFormat("ErrorMessage::{0} {1}", fex.Detail.ErrorMessage, Environment.NewLine);
                objStringBuilderError.AppendFormat("ErrorDetails::{0} {1}", Environment.NewLine, fex.Detail.ErrorDetails);
                SaveLogger.SaveLoggerError(objStringBuilderError.ToString());
            }
            catch (Exception ex)
            {
                objStringBuilderError.AppendLine("In method : UpdatePasses(UsersModel userMl) :: UserController");
                objStringBuilderError.AppendFormat("ErrorMessage::{0} {1}", ex.Message, Environment.NewLine);
                objStringBuilderError.AppendFormat("ErrorDetails::{0} {1}", Environment.NewLine, ex.ToString());

                SaveLogger.SaveLoggerError(objStringBuilderError.ToString());
            }
        }
        public void UpdateUserDetail_WithSessionIsNullAndUserModel_ExpectUserLogin()
        {
            //Arrange
            String expectedController = "Login";
            String expectedAction = "UserLogin";

            _controllerContext.Setup(cc => cc.HttpContext.Session["UserName"]).Returns(null);
            _userController.ControllerContext = _controllerContext.Object;

            var userModel = new UsersModel()
            {
                UserId = 23,
                FirstName = "FName",
                LastName = "LName",
                EmailAddress = "*****@*****.**",
                Status = true,
                PassRFID = "BBCDEF1234",
                PassNumber = "1234"
            };

            //Act
            var redirectToRouteResult = _userController.UpdateUserDetail(userModel) as RedirectToRouteResult;

            // Assert
            Assert.IsNotNull(redirectToRouteResult, "Not a redirect result");
            Assert.IsFalse(redirectToRouteResult.Permanent); // Or IsTrue if you use RedirectToActionPermanent
            Assert.AreEqual(expectedAction, redirectToRouteResult.RouteValues["Action"]);
            Assert.AreEqual(expectedController, redirectToRouteResult.RouteValues["Controller"]);
        }
        /// <summary>
        /// Check duplicate user for emailid
        /// </summary>
        /// <param name="userMl"></param>
        /// <returns></returns>
        public int GetUserModelByEmailId(UsersModel userMl)
        {
            // Creating instance of the string builder class to hold the tracing data
            StringBuilder objStringBuilderTrace = new StringBuilder();

            // Append tracing into string builder
            objStringBuilderTrace.AppendLine("Start method : GetUserModelByEmailId(UsersModel userML) :: JetstreamLaunchpad.DAL.Users class : DBUsers.cs");
            // Writing trace log into the log file 
            SaveLogger.SaveLoggerTrace(objStringBuilderTrace.ToString());
            // Clear StringBuilder object
            objStringBuilderTrace.Clear();

            var user = ObjTersoDataContext.users.Where(x => !string.IsNullOrEmpty(userMl.EmailAddress) && x.EmailAddress.Equals(userMl.EmailAddress) && x.UserId != userMl.UserId).ToList();
            var result = user.Count > 0 ? user.Count : 0;

            // Append tracing into string builder
            objStringBuilderTrace.AppendLine("End method : GetUserModelByEmailId(UsersModel userML) :: JetstreamLaunchpad.DAL.Users class : DBUsers.cs");
            // Writing trace log into the log file 
            SaveLogger.SaveLoggerTrace(objStringBuilderTrace.ToString());
            objStringBuilderTrace.Clear();
            return result;
        }
        /// <summary>
        /// Method to setup password for user 
        /// </summary>
        /// <param name="userMl"></param>
        /// <returns></returns>
        public int SetupPassword(UsersModel userMl)
        {
            // Creating instance of the string builder class to hold the tracing data
            StringBuilder objStringBuilderTrace = new StringBuilder();

            // Append tracing into string builder
            objStringBuilderTrace.AppendLine("Start method : SetupPassword(UsersModel userML) :: JetstreamLaunchpad.DAL.Users class : DBUsers.cs");
            // Writing trace log into the log file 
            SaveLogger.SaveLoggerTrace(objStringBuilderTrace.ToString());
            // Clear StringBuilder object
            objStringBuilderTrace.Clear();

            var objUserDetail = ObjTersoDataContext.users.FirstOrDefault(x => x.UserId == userMl.UserId);
            if (objUserDetail != null) objUserDetail.Password = userMl.Password;
            ObjTersoDataContext.SaveChanges();
            var userId = userMl.UserId;

            // Append tracing into string builder
            objStringBuilderTrace.AppendLine("End method : SetupPassword(UsersModel userML) :: JetstreamLaunchpad.DAL.Users class : DBUsers.cs");
            // Writing trace log into the log file 
            SaveLogger.SaveLoggerTrace(objStringBuilderTrace.ToString());
            objStringBuilderTrace.Clear();
            return userId;

        }
        public void EditUser_WithSessionNotNull_ExpectOk()
        {
            //Arrange
            int userId = 23;
            String expectedView = "EditUser";
            _controllerContext.Setup(cc => cc.HttpContext.Session["UserName"]).Returns(string.Format("{0} {1}", "FName", "LName"));
            _userController.ControllerContext = _controllerContext.Object;

            var expectedUserModel = new UsersModel()
            {
                UserId = 23,
                FirstName = "FName",
                LastName = "LName",
                EmailAddress = "*****@*****.**",
                Status = true,
                PassRFID = "BBCDEF1234",
                PassNumber = "1234",
                Password = "******"
            };


            //Act
            var actionResult = _userController.EditUser(userId) as ViewResult;
            var actualUserModel = actionResult.Model as UsersModel;

            //Assert
            Assert.IsNotNull(actionResult, "AddUserDetails action result should not be null");
            Assert.IsNotNull(actionResult.ViewBag.StatusModelList, "ViewBag StatusModelList should not be null");
            Assert.AreEqual(actionResult.ViewName, expectedView, "View name should be EditUser");


            Assert.AreEqual(expectedUserModel.UserId, actualUserModel.UserId);
            Assert.AreEqual(expectedUserModel.FirstName, actualUserModel.FirstName);
            Assert.AreEqual(expectedUserModel.LastName, actualUserModel.LastName);
            Assert.AreEqual(expectedUserModel.EmailAddress, actualUserModel.EmailAddress);
            Assert.AreEqual(expectedUserModel.Status, actualUserModel.Status);
            Assert.AreEqual(expectedUserModel.PassRFID, actualUserModel.PassRFID);
            Assert.AreEqual(expectedUserModel.PassNumber, actualUserModel.PassNumber);
            Assert.AreEqual(expectedUserModel.Password, actualUserModel.Password);

        }
        public void RedirectToEditUser_ExpectOk()
        {
            //Arrange
            String expectedView = "EditUser";
            _controllerContext.Setup(cc => cc.HttpContext.Session["UserName"]).Returns(string.Format("{0} {1}", "FName", "LName"));
            _userController.ControllerContext = _controllerContext.Object;
            UsersModel userDetail = new UsersModel();

            //Act
            var actionResult = _userController.RedirectToEditUser(userDetail) as ViewResult;

            //Assert
            Assert.IsNotNull(actionResult, "AddUserDetails action result should not be null");
            Assert.IsNotNull(actionResult.ViewBag.StatusModelList, "ViewBag StatusModelList should not be null");
            Assert.AreEqual(actionResult.ViewName, expectedView, "View name should be AddUser");
        }
        public void AddUserDetails_OnPost_WithSessionIsNullAndUserModel_ExpectUserLogin()
        {
            //Arrange
            String expectedController = "Login";
            String expectedAction = "UserLogin";

            _controllerContext.Setup(cc => cc.HttpContext.Session["UserName"]).Returns(null);
            _userController.ControllerContext = _controllerContext.Object;

            var userModel = new UsersModel();

            //Act
            var redirectToRouteResult = _userController.AddUserDetails(userModel, string.Empty) as RedirectToRouteResult;

            // Assert
            Assert.IsNotNull(redirectToRouteResult, "Not a redirect result");
            Assert.IsFalse(redirectToRouteResult.Permanent); // Or IsTrue if you use RedirectToActionPermanent
            Assert.AreEqual(expectedAction, redirectToRouteResult.RouteValues["Action"]);
            Assert.AreEqual(expectedController, redirectToRouteResult.RouteValues["Controller"]);
        }
        public void AddUserDetails_OnPost_WithSessionNotNullUserModelAndCancelCommand_ExpectGetUserDetails()
        {
            //Arrange
            String expectedAction = "GetUserDetails";

            _controllerContext.Setup(cc => cc.HttpContext.Session["UserName"]).Returns(string.Format("{0} {1}", "FName", "LName"));
            _userController.ControllerContext = _controllerContext.Object;

            var userModel = new UsersModel();

            //Act
            var redirectToRouteResult = _userController.AddUserDetails(userModel, "Cancel") as RedirectToRouteResult;

            // Assert
            Assert.IsNotNull(redirectToRouteResult, "Not a redirect result");
            Assert.IsFalse(redirectToRouteResult.Permanent); // Or IsTrue if you use RedirectToActionPermanent
            Assert.AreEqual(expectedAction, redirectToRouteResult.RouteValues["Action"]);
        }
        public void AddUserDetails_OnPost_WithSessionNotNullUserModelAndAddCommand_ExpectOk()
        {
            //Arrange
            String expectedAction = "GetUserDetails";

            _controllerContext.Setup(cc => cc.HttpContext.Session["UserName"]).Returns(string.Format("{0} {1}", "FName", "LName"));
            _userController.ControllerContext = _controllerContext.Object;
            var context = new Mock<System.Web.HttpContextBase>().Object;
            _userController.Url = new UrlHelper(
                new RequestContext(context, new RouteData()),
                new RouteCollection()
            );
            Random rNo = new Random();
            string randomNumber = rNo.Next().ToString();
            var userModel = new UsersModel()
            {
                FirstName = "FirstName",
                LastName = "LastName",
                EmailAddress = string.Format("testemail{0}@chetu.com", randomNumber),
                Status = true,
                PassRFID = null,
                PassNumber = null
            };

            //Act
            var redirectToRouteResult = _userController.AddUserDetails(userModel, "Add") as RedirectToRouteResult;

            // Assert
            Assert.IsNotNull(redirectToRouteResult, "Not a redirect result");
            Assert.IsFalse(redirectToRouteResult.Permanent); // Or IsTrue if you use RedirectToActionPermanent
            Assert.AreEqual(expectedAction, redirectToRouteResult.RouteValues["Action"]);
        }
        public void AddUserDetails_OnPost_WithSessionNotNullUserModelAndAddCommand_DuplicateUser_ExpectRedirectToAddUser()
        {
            //Arrange
            String expectedAction = "RedirectToAddUser";

            _controllerContext.Setup(cc => cc.HttpContext.Session["UserName"]).Returns(string.Format("{0} {1}", "FName", "LName"));
            _userController.ControllerContext = _controllerContext.Object;

            var userModel = new UsersModel()
            {
                FirstName = "FirstName",
                LastName = "LastName",
                EmailAddress = "*****@*****.**",
                Status = true,
                PassRFID = "FACDEF1234",
                PassNumber = "1234"
            };

            //Act
            var redirectToRouteResult = _userController.AddUserDetails(userModel, "Add") as RedirectToRouteResult;

            // Assert
            Assert.IsNotNull(redirectToRouteResult, "Not a redirect result");
            Assert.IsFalse(redirectToRouteResult.Permanent); // Or IsTrue if you use RedirectToActionPermanent
            Assert.AreEqual(expectedAction, redirectToRouteResult.RouteValues["Action"]);
        }
        public ActionResult SetupPassword(UsersModel userMl, string command)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                if (command == JetstreamResource.SetupPasswordCommand)
                {
                    if (userMl != null)
                    {
                        int result;
                        userMl.Password = CryptoManager.Encrypt(userMl.Password, true);
                        using (JetstreamClient objMainServiceClient = new JetstreamClient())
                        {
                            result = objMainServiceClient.SetupPassword(userMl);
                        }
                        if (result > 0)
                        {
                            Session["UserId"] = result;
                        }
                        Success(JetstreamResource.PasswordSetupSuccess, true);
                    }
                }
                return RedirectToAction("UserLogin");
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : SetupPassword(UsersModel userMl, string command) :: LoginController");
                objStringBuilderError.AppendFormat("ErrorMessage::{0} {1}", fex.Detail.ErrorMessage, Environment.NewLine);
                objStringBuilderError.AppendFormat("ErrorDetails::{0} {1}", Environment.NewLine, fex.Detail.ErrorDetails);

                SaveLogger.SaveLoggerError(objStringBuilderError.ToString());
                return View("Error");
            }
            catch (Exception ex)
            {
                objStringBuilderError.AppendLine("In method : SetupPassword(UsersModel userMl, string command) :: LoginController");
                objStringBuilderError.AppendFormat("ErrorMessage::{0} {1}", ex.Message, Environment.NewLine);
                objStringBuilderError.AppendFormat("ErrorDetails::{0} {1}", Environment.NewLine, ex.ToString());

                SaveLogger.SaveLoggerError(objStringBuilderError.ToString());
                return View("Error");
            }
        }
 /// <summary>
 /// Method to Logon user by entering email id and password
 /// </summary>
 /// <param name="userMl"></param>
 /// <returns></returns>
 public UsersModel LogOn(UsersModel userMl)
 {
     ServiceData serviceData = new ServiceData();
     try
     {
         UsersModel lstUser;
         using (DBUsers objUser = new DBUsers())
         {
             lstUser = objUser.LogOn(userMl);
         }
         return lstUser;
     }
     catch (Exception ex)
     {
         serviceData.Result = false;
         serviceData.ErrorMessage = ex.Message;
         serviceData.ErrorDetails = ex.ToString();
         throw new FaultException<ServiceData>(serviceData);
     }
 }
        /// <summary>
        /// Update User Detail
        /// </summary>
        /// <param name="userDetail"></param>
        /// <returns></returns>
        public ActionResult UpdateUserDetail(UsersModel userDetail)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                if (Session["UserName"] != null)
                {
                    if (!string.IsNullOrEmpty(userDetail.PassRFID))
                    {
                        bool isValid = IsHex(userDetail.PassRFID);
                        if (!isValid || userDetail.PassRFID.Length != 10)
                        {
                            Warning(JetstreamResource.PassRfIdHexadecimalValidationMessage, true);
                            return RedirectToAction("RedirectToEditUser", new RouteValueDictionary(userDetail));
                        }
                    }

                    var duplicateDevice = CheckForDuplicate(userDetail);
                    if (duplicateDevice > 0)
                    {
                        if (duplicateDevice == 1)
                        {
                            Warning(JetstreamResource.UserDuplicatePassRfIdMessage, true);
                        }
                        if (duplicateDevice == 2)
                        {
                            Warning(JetstreamResource.UserDuplicateEmailMessage, true);
                        }
                        return RedirectToAction("RedirectToEditUser", new RouteValueDictionary(userDetail));
                    }
                    else
                    {
                        if (ModelState.IsValid)
                        {
                            int result;
                            using (JetstreamClient objMainServiceClient = new JetstreamClient())
                            {
                                result = objMainServiceClient.UpdateUserDetails(userDetail);
                            }
                            if (result > 0)
                            {
                                UpdatePasses(userDetail);
                                Session["UserId"] = result;
                            }
                            Success(JetstreamResource.UserUpdateMessage, true);
                            return RedirectToAction("GetUserDetails");
                        }
                        else
                        {
                            return RedirectToAction("RedirectToEditUser", new RouteValueDictionary(userDetail));
                        }
                    }
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : UpdateUserDetail(UsersModel userDetail) :: UserController");
                objStringBuilderError.AppendFormat("ErrorMessage::{0} {1}", fex.Detail.ErrorMessage, Environment.NewLine);
                objStringBuilderError.AppendFormat("ErrorDetails::{0} {1}", Environment.NewLine, fex.Detail.ErrorDetails);
                SaveLogger.SaveLoggerError(objStringBuilderError.ToString());
                return View("Error");
            }
            catch (Exception ex)
            {
                objStringBuilderError.AppendLine("In method : UpdateUserDetail(UsersModel userDetail) :: UserController");
                objStringBuilderError.AppendFormat("ErrorMessage::{0} {1}", ex.Message, Environment.NewLine);
                objStringBuilderError.AppendFormat("ErrorDetails::{0} {1}", Environment.NewLine, ex.ToString());

                SaveLogger.SaveLoggerError(objStringBuilderError.ToString());
                return View("Error");
            }
        }
        /// <summary>
        /// Get user by email id
        /// </summary>
        /// <param name="emailId"></param>
        /// <returns></returns>
        public UsersModel GetUserModelListByEmail(string emailId)
        {
            // Creating instance of the string builder class to hold the tracing data
            StringBuilder objStringBuilderTrace = new StringBuilder();
            UsersModel objUserMl = new UsersModel();

            // Append tracing into string builder
            objStringBuilderTrace.AppendLine("Start method : GetUserModelListByEmail(string emailId) :: JetstreamLaunchpad.DAL.Users class : DBUsers.cs");
            // Writing trace log into the log file 
            SaveLogger.SaveLoggerTrace(objStringBuilderTrace.ToString());
            // Clear StringBuilder object
            objStringBuilderTrace.Clear();

            var user = ObjTersoDataContext.users.Where(x => x.EmailAddress.Equals(emailId)).ToList();
            if (user.Count > 0)
            {
                objUserMl = (from modelInfo in user
                             select new UsersModel
                             {
                                 UserId = modelInfo.UserId,
                                 FirstName = modelInfo.FirstName,
                                 LastName = modelInfo.LastName,
                                 EmailAddress = modelInfo.EmailAddress,
                                 Password = modelInfo.Password,
                             }).FirstOrDefault();
            }
            // Append tracing into string builder
            objStringBuilderTrace.AppendLine("End method : GetUserModelListByEmail(string emailId) :: JetstreamLaunchpad.DAL.Users class : DBUsers.cs");
            // Writing trace log into the log file 
            SaveLogger.SaveLoggerTrace(objStringBuilderTrace.ToString());
            objStringBuilderTrace.Clear();
            return objUserMl;
        }
        public ActionResult AddUserDetails(UsersModel userMl, string command)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                if (Session["UserName"] != null && string.Equals(command, JetstreamResource.AddCommand))
                {
                    if (!string.IsNullOrEmpty(userMl.PassRFID))
                    {
                        bool isValid = IsHex(userMl.PassRFID);
                        if (!isValid || userMl.PassRFID.Length != 10)
                        {
                            Warning(JetstreamResource.PassRfIdHexadecimalValidationMessage, true);
                            return RedirectToAction("RedirectToAddUser", new RouteValueDictionary(userMl));
                        }
                    }

                    var duplicateDevice = CheckForDuplicate(userMl);
                    if (duplicateDevice > 0)
                    {
                        if (duplicateDevice == 1)
                        {
                            Warning(JetstreamResource.UserDuplicatePassRfIdMessage, true);
                        }
                        if (duplicateDevice == 2)
                        {
                            Warning(JetstreamResource.UserDuplicateEmailMessage, true);
                        }
                        return RedirectToAction("RedirectToAddUser", new RouteValueDictionary(userMl));
                    }
                    else
                    {
                        if (ModelState.IsValid)
                        {
                            int result;
                            using (JetstreamClient objMainServiceClient = new JetstreamClient())
                            {
                                result = objMainServiceClient.SaveUserDetails(userMl);
                            }
                            if (result > 0)
                            {
                                UpdatePasses(userMl);
                            }

                            Email.SendEmail(userMl, JetstreamResource.SetupPasswordDisplayName, JetstreamResource.SetupPasswordSubject,
                                string.Format(JetstreamResource.SetupPasswordMessage, userMl.FirstName, userMl.LastName,
                                  Url.Action(JetstreamResource.SetupPasswordCommand, JetstreamResource.LoginCommand,
                                    new
                                    {
                                        userIdEncode = CryptoManager.Encrypt(result.ToString(), true),
                                        strKey = JetstreamResource.SetupPasswordCommand
                                    }, "Http")));
                            Success(string.Format(JetstreamResource.UserSaveMessage, userMl.FirstName, userMl.LastName), true);
                            return RedirectToAction("GetUserDetails");
                        }
                        else
                        {
                            return RedirectToAction("RedirectToAddUser", new RouteValueDictionary(userMl));
                        }
                    }
                }
                else if (Session["UserName"] != null && command == "Cancel")
                {
                    return RedirectToAction("GetUserDetails");
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : AddUserDetails(UsersModel userMl, string command) :: UserController");
                objStringBuilderError.AppendFormat("ErrorMessage::{0} {1}", fex.Detail.ErrorMessage, Environment.NewLine);
                objStringBuilderError.AppendFormat("ErrorDetails::{0} {1}", Environment.NewLine, fex.Detail.ErrorDetails);
                SaveLogger.SaveLoggerError(objStringBuilderError.ToString());
                return View("Error");
            }
            catch (Exception ex)
            {
                objStringBuilderError.AppendLine("In method : AddUserDetails(UsersModel userMl, string command) :: UserController");
                objStringBuilderError.AppendFormat("ErrorMessage::{0} {1}", ex.Message, Environment.NewLine);
                objStringBuilderError.AppendFormat("ErrorDetails::{0} {1}", Environment.NewLine, ex.ToString());

                SaveLogger.SaveLoggerError(objStringBuilderError.ToString());
                return View("Error");
            }
        }
        public ActionResult EditUser(UsersModel userMl, string command)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                if (Session["UserName"] != null && userMl != null)
                {
                    if (string.Equals(command, JetstreamResource.UpdateCommand))
                    {
                        return RedirectToAction("UpdateUserDetail", new RouteValueDictionary(userMl));
                    }
                    else if (string.Equals(command, JetstreamResource.ResetPasswordCommand))
                    {
                        Email.SendEmail(userMl, JetstreamResource.ResetPasswordDisplayName, JetstreamResource.ResetPasswordSubject,
                            string.Format(JetstreamResource.ResetPasswordMessage,
                                userMl.FirstName, userMl.LastName, Url.Action(JetstreamResource.SetupPasswordCommand, JetstreamResource.LoginCommand,
                                    new { userIdEncode = CryptoManager.Encrypt(userMl.UserId.ToString(), true), strKey = "ResetPassword" }, "http")));
                        Success(JetstreamResource.PasswordResetMail, true);
                        return RedirectToAction("GetUserDetails");
                    }
                    else if (string.Equals(command, JetstreamResource.DeleteCommand))
                    {
                        return RedirectToAction("DeleteUser", new { userId = userMl.UserId });
                    }
                    else
                    {
                        return RedirectToAction("GetUserDetails");
                    }
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : EditUser(UsersModel userMl, string command) :: UserController");
                objStringBuilderError.AppendFormat("ErrorMessage::{0} {1}", fex.Detail.ErrorMessage, Environment.NewLine);
                objStringBuilderError.AppendFormat("ErrorDetails::{0} {1}", Environment.NewLine, fex.Detail.ErrorDetails);
                SaveLogger.SaveLoggerError(objStringBuilderError.ToString());
                return View("Error");
            }
            catch (Exception ex)
            {
                objStringBuilderError.AppendLine("In method : EditUser(UsersModel userMl, string command) :: UserController");
                objStringBuilderError.AppendFormat("ErrorMessage::{0} {1}", ex.Message, Environment.NewLine);
                objStringBuilderError.AppendFormat("ErrorDetails::{0} {1}", Environment.NewLine, ex.ToString());

                SaveLogger.SaveLoggerError(objStringBuilderError.ToString());
                return View("Error");
            }
        }
        public void EditUser_OnPost_WithSessionNotNull_UserModelAndResetPasswordCommand_ExpectGetUserDetails()
        {
            //Arrange
            String expectedAction = "GetUserDetails";

            var context = new Mock<System.Web.HttpContextBase>().Object;

            _userController.Url = new UrlHelper(
                new RequestContext(context, new RouteData()),
                new RouteCollection()
            );

            _controllerContext.Setup(cc => cc.HttpContext.Session["UserName"]).Returns(string.Format("{0} {1}", "FName", "LName"));
            _userController.ControllerContext = _controllerContext.Object;

            var userModel = new UsersModel()
            {
                UserId = 23,
                FirstName = "FName",
                LastName = "LName",
                EmailAddress = "*****@*****.**",
                Status = true,
                PassRFID = "BBCDEF1234",
                PassNumber = "1234"
            };

            //Act
            var redirectToRouteResult = _userController.EditUser(userModel, "ResetPassword") as RedirectToRouteResult;

            //Assert
            Assert.IsNotNull(redirectToRouteResult, "Not a redirect result");
            Assert.IsFalse(redirectToRouteResult.Permanent); // Or IsTrue if you use RedirectToActionPermanent
            Assert.AreEqual(expectedAction, redirectToRouteResult.RouteValues["Action"]);
        }