/// <summary>
        /// Displays the list of inventory 
        /// </summary>
        /// <returns></returns>
        public ActionResult InventoryDetail()
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                if (Session["UserName"] != null)
                {
                    InventorySearchModel inventorySearchModel = new InventorySearchModel();
                    IEnumerable<InventoryModel> lstInventoryDetails;
                    List<DeviceModel> devices;
                    using (JetstreamClient objMainServiceClient = new JetstreamClient())
                    {
                        lstInventoryDetails = objMainServiceClient.GetInventoryList(inventorySearchModel.LogicalDeviceId, inventorySearchModel.SearchString);
                        devices = objMainServiceClient.GetDeviceList();
                    }

                    List<SelectListItem> deviceList = new SelectList(devices.OrderBy(x => x.LogicalDeviceId), "LogicalDeviceId", "LogicalDeviceId").ToList();
                    deviceList.Insert(0, new SelectListItem { Text = JetstreamResource.All, Value = string.Empty });
                    ViewBag.DeviceList = deviceList;

                    SortingPagingInfo info = new SortingPagingInfo
                    {
                        SortField = Enums.InventorySortField.Material.ToString(),
                        SortDirection = Constants.Ascending,
                    };
                    lstInventoryDetails = lstInventoryDetails.OrderBy(x => x.Material).Take(Constants.PagingPageSize);
                    ViewBag.SortingPagingInfo = info;

                    if (lstInventoryDetails.Any())
                        inventorySearchModel.InventoryModels = lstInventoryDetails.ToList();

                    return View("InventoryDetail", inventorySearchModel);
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : InventoryDetail() :: InventoryController");
                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 : InventoryDetail() :: InventoryController");
                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 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 ActionResult EditUser(int userId)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                if (Session["UserName"] != null)
                {
                    UsersModel userMl;
                    using (JetstreamClient objMainServiceClient = new JetstreamClient())
                    {
                        userMl = objMainServiceClient.GetUserModelListByUserId(userId);
                    }
                    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");

                    ViewBag.Name = userMl.FirstName + " " + userMl.LastName;
                    return View("EditUser", userMl);
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : EditUser(int userId) :: 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(int userId) :: 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 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");
            }
        }
        public ActionResult SetupPassword(string userIdEncode, string strKey)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                if (userIdEncode != null)
                {
                    int userId = Convert.ToInt32(CryptoManager.Decrypt(userIdEncode, true));
                    UsersModel objUser;
                    using (JetstreamClient objMainServiceClient = new JetstreamClient())
                    {
                        objUser = objMainServiceClient.GetUserModelListByUserId(userId);
                    }
                    if (objUser != null)
                    {
                        if (string.Equals(strKey, JetstreamResource.ResetPasswordCommand))
                        {
                            objUser.Password = null;
                            return View("SetupPassword", objUser);
                        }
                        else if (string.Equals(strKey, JetstreamResource.SetupPasswordCommand))
                        {
                            if (!string.IsNullOrEmpty(objUser.Password))
                            {
                                Success(JetstreamResource.PasswordSetup, true);
                                return View("UserLogin");
                            }
                            else
                            {
                                return View("SetupPassword", objUser);
                            }
                        }
                    }
                    return View("UserLogin");
                }
                else
                {
                    return View("UserLogin");
                }
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : SetupPassword(string userIdEncode, string strKey) :: 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(string userIdEncode, string strKey) :: 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>
        /// Search Items for server side paging and searching
        /// </summary>
        /// <param name="searchText"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sortField"></param>
        /// <param name="sortDirection"></param>
        /// <returns></returns>
        public JsonResult GetItemsList(string searchText, int pageIndex, int pageSize, string sortField, string sortDirection)
        {
            List<ItemModel> itemsModel;
            using (JetstreamClient objMainServiceClient = new JetstreamClient())
            {
                var itemList = objMainServiceClient.GetFilterItemList(searchText);

                SortingPagingInfo info = new SortingPagingInfo
                {
                    SortField = sortField,
                    SortDirection = sortDirection,
                };
                itemsModel = ApplySorting(info, itemList).Skip(pageIndex * pageSize).Take(pageSize).ToList();

            }
            return Json(new { itemsModel }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult InventoryTransaction(TransactionSearchModel transactionSearchMl, SortingPagingInfo info, string command)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                if (Session["UserName"] != null)
                {
                    if (!string.IsNullOrEmpty(command) && command.Equals(JetstreamResource.SearchCommand) && !CheckDate(transactionSearchMl.StartDateFrom))
                    {
                        transactionSearchMl.TransactionModels = null;
                        Warning(JetstreamResource.FromDateValidation, true);
                        ViewBag.SortingPagingInfo = info;
                        return View("InventoryTransaction", transactionSearchMl);
                    }

                    if (!string.IsNullOrEmpty(command) && command.Equals(JetstreamResource.SearchCommand) && !CheckDate(transactionSearchMl.StartDateTo))
                    {
                        transactionSearchMl.TransactionModels = null;
                        Warning(JetstreamResource.ToDateValidation, true);
                        ViewBag.SortingPagingInfo = info;
                        return View("InventoryTransaction", transactionSearchMl);
                    }

                    DateTime? StartDateFrom = !string.IsNullOrEmpty(transactionSearchMl.StartDateFrom) ? Convert.ToDateTime(transactionSearchMl.StartDateFrom) : (DateTime?)null;
                    DateTime? StartDateTo = !string.IsNullOrEmpty(transactionSearchMl.StartDateTo) ? Convert.ToDateTime(transactionSearchMl.StartDateTo) : (DateTime?)null;

                    if (!string.IsNullOrEmpty(command) && command.Equals(JetstreamResource.SearchCommand) && StartDateFrom > StartDateTo)
                    {
                        transactionSearchMl.TransactionModels = null;
                        Warning(JetstreamResource.DateValidation, true);
                        ViewBag.SortingPagingInfo = info;
                        return View("InventoryTransaction", transactionSearchMl);
                    }

                    using (JetstreamClient objMainServiceClient = new JetstreamClient())
                    {
                        IEnumerable<TransactionModel> lstTransactionModel;
                        lstTransactionModel =
                            objMainServiceClient.GetInventoryTransaction(transactionSearchMl.SearchString,
                                transactionSearchMl.StartDateFrom, transactionSearchMl.StartDateTo);

                        lstTransactionModel.ToList().ForEach(x =>
                        {
                            x.Location = x.Latitude + (x.Longitude != null ? string.Format(":{0}", x.Longitude) : x.Longitude)
                                + (x.Range != null ? string.Format(":{0}", x.Range) : x.Range);
                        });
                        if (lstTransactionModel.Any())
                        {
                            transactionSearchMl.TransactionModels = ApplySorting(lstTransactionModel.ToList(), info).Take(Constants.PagingPageSize).ToList();
                        }
                    }
                    ViewBag.SortingPagingInfo = info;
                    return View("InventoryTransaction", transactionSearchMl);

                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : InventoryTransaction(TransactionSearchModel transactionSearchMl, SortingPagingInfo info, string command) :: TransactionController");
                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 : InventoryTransaction(TransactionSearchModel transactionSearchMl, SortingPagingInfo info, string command) :: TransactionController");
                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>
        /// Edit current Device
        /// </summary>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        public ActionResult EditCurrentDevice(int deviceId)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                DeviceModel deviceMl;
                using (JetstreamClient objMainServiceClient = new JetstreamClient())
                {
                    deviceMl = objMainServiceClient.GetDeviceByDeviceId(deviceId);
                }

                // construct a Jetstream service client
                JetstreamServiceClient client = new JetstreamServiceClient(JetstreamConfiguration.Url, JetstreamConfiguration.ApplicationAccessKey);

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

                // call the Jetstream GetDeviceDefinitions ReST endpoint
                GetDeviceDefinitionsResponse response = client.GetDeviceDefinitions(request);

                if (!string.IsNullOrEmpty(response.Body))
                {
                    //Get the device definations for binding to model dropdown
                    var modelList = response.DeviceDefinitionList.Select(model => new Models
                    {
                        ModelId = model.Id,
                        Name = model.Name
                    }).ToList();

                    ViewBag.ModelList = new SelectList(modelList.OrderBy(x => x.Name), "ModelId", "Name", deviceMl.DeviceGuid);
                }

                return View("EditCurrentDevice", deviceMl);
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : EditCurrentDevice(int deviceId) :: DeviceController");
                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 : EditCurrentDevice(int deviceId) :: DeviceController");
                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>
        /// Delete device from database
        /// </summary>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        public ActionResult DeleteDevice(int deviceId)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                if (Session["UserName"] != null)
                {
                    using (JetstreamClient objMainServiceClient = new JetstreamClient())
                    {
                        var device = objMainServiceClient.GetDeviceById(deviceId);
                        objMainServiceClient.DeleteDevice(deviceId);

                        // construct a Jetstream service client
                        JetstreamServiceClient client = new JetstreamServiceClient(JetstreamConfiguration.Url, JetstreamConfiguration.ApplicationAccessKey);

                        RemoveLogicalDeviceRequest removeRequest = new RemoveLogicalDeviceRequest
                        {
                            LogicalDeviceId = device.LogicalDeviceId
                        };

                        //Remove device from jetstream
                        client.RemoveLogicalDevice(removeRequest);

                    }
                    Success(JetstreamResource.DeviceDeleteMessage, true);
                    return RedirectToAction("DeviceDetail", "Device");
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : DeleteDevice(int deviceId) :: DeviceController");
                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 : DeleteDevice(int deviceId) :: DeviceController");
                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 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 DeviceDetail(SortingPagingInfo info)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                if (Session["UserName"] != null)
                {
                    IEnumerable<DeviceModel> lstDeviceDetail;
                    using (JetstreamClient objMainServiceClient = new JetstreamClient())
                    {
                        lstDeviceDetail = objMainServiceClient.GetFilterDeviceList(info.SearchText);
                    }
                    SetDeviceLocation(lstDeviceDetail);

                    lstDeviceDetail = ApplySorting(info, lstDeviceDetail).Take(Constants.PagingPageSize);

                    ViewBag.SortingPagingInfo = info;
                    ViewBag.SortField = info.SortField;
                    return View("DeviceDetail", lstDeviceDetail);
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : DeviceDetail(SortingPagingInfo info) :: DeviceController");
                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 : DeviceDetail(SortingPagingInfo info) :: DeviceController");
                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>
        /// 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>
        /// Delete user
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ActionResult DeleteUser(int userId)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                if (Session["UserName"] != null)
                {
                    UsersModel userML;
                    using (JetstreamClient objMainServiceClient = new JetstreamClient())
                    {
                        userML = objMainServiceClient.GetUserModelListByUserId(userId);
                        objMainServiceClient.DeleteUserDetails(userId);
                    }
                    UpdatePasses(userML);
                    Success(JetstreamResource.UserDeleteMessage, true);
                    return RedirectToAction("GetUserDetails");
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : DeleteUser(int userId) :: 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 : DeleteUser(int userId) :: 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>
        /// Method to Show the Temperature Graph
        /// </summary>
        /// <param name="temperatureSearchMl"></param>
        private void ShowTemperatureGraph(TemperatureSearchModel temperatureSearchMl)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                BindDevices();

                using (JetstreamClient objMainServiceClient = new JetstreamClient())
                {
                    var lstTemperatureModel = objMainServiceClient.GetTemperatureList(temperatureSearchMl.LogicalDeviceId, temperatureSearchMl.ReadingTimeFrom, temperatureSearchMl.ReadingTimeTo);
                    TempData["TemperatureModels"] = lstTemperatureModel;
                    if (lstTemperatureModel.Any())
                    {
                        BindTemperatureChart(lstTemperatureModel);
                        temperatureSearchMl.TemperatureModels = lstTemperatureModel;
                    }
                    else
                    {
                        //Create the empty highchart which will be shown when the Temperature screen is loaded
                        var chart = new Highcharts(JetstreamResource.HighChartName)
                            .InitChart(new Chart { DefaultSeriesType = ChartTypes.Line })
                            .SetTitle(new Title { Text = JetstreamResource.HighChartTitleText, Style = JetstreamResource.HighChartStyle })
                            .SetSubtitle(new Subtitle { Text = "" })
                            .SetXAxis(new XAxis { Categories = null, EndOnTick = true })
                            .SetYAxis(new YAxis { Title = new YAxisTitle { Text = JetstreamResource.HighChartYAxisText, Style = JetstreamResource.HighChartStyle } })
                            .SetTooltip(new Tooltip
                            {
                                Enabled = true,
                                Formatter = @"function() {return '<b>' + this .series.name + '<br/><br/>'+this.x+': '+this.y; }"
                            })
                            .SetPlotOptions(new PlotOptions { Line = new PlotOptionsLine { DataLabels = new PlotOptionsLineDataLabels { Enabled = true }, EnableMouseTracking = false } })
                            .SetSeries(new[] { new Series { Name = JetstreamResource.ProbeA }, new Series { Name = JetstreamResource.ProbeB } });
                        ViewData["chart"] = chart;
                    }
                }
            }
            catch (Exception ex)
            {
                objStringBuilderError.AppendLine("In method : ShowTemperatureGraph(TemperatureSearchModel temperatureSearchMl) :: TemperatureController");
                objStringBuilderError.AppendFormat("ErrorMessage::{0} {1}", ex.Message, Environment.NewLine);
                objStringBuilderError.AppendFormat("ErrorDetails::{0} {1}", Environment.NewLine, ex.ToString());

                SaveLogger.SaveLoggerError(objStringBuilderError.ToString());                
            }
        }
        /// <summary>
        /// Method to bind the devices to device dropdown
        /// </summary>
        private void BindDevices()
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                List<DeviceModel> devices;
                using (JetstreamClient objMainServiceClient = new JetstreamClient())
                {
                    devices = objMainServiceClient.GetDeviceList();
                }

                List<SelectListItem> deviceList = new SelectList(devices.OrderBy(x => x.LogicalDeviceId), "DeviceId", "LogicalDeviceId").ToList();
                deviceList.Insert(0, new SelectListItem { Text = JetstreamResource.Device, Value = JetstreamResource.Zero });
                ViewBag.DeviceList = deviceList;
            }
            catch (Exception ex)
            {
                objStringBuilderError.AppendLine("In method : BindDevices() :: TemperatureController");
                objStringBuilderError.AppendFormat("ErrorMessage::{0} {1}", ex.Message, Environment.NewLine);
                objStringBuilderError.AppendFormat("ErrorDetails::{0} {1}", Environment.NewLine, ex.ToString());

                SaveLogger.SaveLoggerError(objStringBuilderError.ToString());                
            }
        }
        public ActionResult AddItem(ItemModel itemMl, string command)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                if (Session["UserName"] != null)
                {
                    if (string.Equals(command, JetstreamResource.AddCommand))
                    {
                        var duplicateItem = CheckForDuplicate(itemMl);
                        if (duplicateItem > 0)
                        {
                            if (duplicateItem == 1)
                            {
                                Warning(JetstreamResource.DuplicateItemMessage, true);
                            }
                            return RedirectToAction("RedirectToAddItem", new RouteValueDictionary(itemMl));
                        }
                        else
                        {
                            if (ModelState.IsValid)
                            {
                                itemMl.ExpirationDate = itemMl.ExpirationDate + DateTime.Now.TimeOfDay;

                                using (JetstreamClient objMainServiceClient = new JetstreamClient())
                                {
                                    objMainServiceClient.SaveItem(itemMl);
                                }
                                Success(string.Format(JetstreamResource.ItemSaveMessage, itemMl.EPC), true);
                                return RedirectToAction("ItemDetail", "Item");
                            }
                            else
                            {
                                return RedirectToAction("RedirectToAddItem", new RouteValueDictionary(itemMl));
                            }
                        }
                    }
                    else
                    {
                        return RedirectToAction("ItemDetail", "Item");
                    }
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : AddItem(ItemModel itemMl, string command) :: ItemController");
                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 : AddItem(ItemModel itemMl, string command) :: ItemController");
                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 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 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 ActionResult EditItem(int itemId)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                if (Session["UserName"] != null)
                {
                    ItemModel itemMl;
                    using (JetstreamClient objMainServiceClient = new JetstreamClient())
                    {
                        itemMl = objMainServiceClient.GetItemByItemId(itemId);
                    }
                    ViewBag.Name = itemMl.Material;
                    return View("EditItem", itemMl);
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : EditItem(int itemId) :: ItemController");
                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 : EditItem(int itemId) :: ItemController");
                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 detail
        /// </summary>
        /// <returns></returns>
        public ActionResult GetUserDetails()
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                if (Session["UserName"] != null)
                {
                    IEnumerable<UsersModel> lstUserDetails;
                    using (JetstreamClient objMainServiceClient = new JetstreamClient())
                    {
                        lstUserDetails = objMainServiceClient.GetFilterUserModelList(string.Empty);
                    }

                    SortingPagingInfo info = new SortingPagingInfo
                    {
                        SortField = Enums.UserSortField.FirstName.ToString(),
                        SortDirection = Constants.Ascending,
                    };

                    lstUserDetails = lstUserDetails.OrderBy(x => x.FirstName).Take(Constants.PagingPageSize);
                    ViewBag.SortingPagingInfo = info;
                    return View("UserDetails", lstUserDetails);
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : GetUserDetails() :: 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 : GetUserDetails() :: 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 EditDevice(DeviceModel deviceMl, string command, SortingPagingInfo info)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                if (Session["UserName"] != null && deviceMl != null)
                {
                    if (string.Equals(command, JetstreamResource.UpdateCommand))
                    {
                        return RedirectToAction("EditCurrentDevice", new { deviceId = deviceMl.DeviceId });
                    }
                    else if (string.Equals(command, JetstreamResource.CancelCommand))
                    {
                        return RedirectToAction("DeviceDetail", "Device");
                    }
                    else if (string.Equals(command, JetstreamResource.DeleteCommand))
                    {
                        return RedirectToAction("DeleteDevice", new { deviceId = deviceMl.DeviceId });
                    }
                    else
                    {
                        using (JetstreamClient objMainServiceClient = new JetstreamClient())
                        {
                            deviceMl = objMainServiceClient.GetDeviceByDeviceId(deviceMl.DeviceId);
                        }

                        deviceMl.Inventories = ApplySortingInventory(info, deviceMl.Inventories).Take(Constants.PagingPageSize).ToList();

                        ViewBag.SortingPagingInfo = info;
                        return View("EditDevice", deviceMl);
                    }
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : EditDevice(DeviceModel deviceMl, string command, SortingPagingInfo info) :: DeviceController");
                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 : EditDevice(DeviceModel deviceMl, string command, SortingPagingInfo info) :: DeviceController");
                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 AddDevice(DeviceModel deviceMl, string command)
        {
            StringBuilder objStringBuilderError = new StringBuilder();

            try
            {
                if (Session["UserName"] != null && string.Equals(command, JetstreamResource.AddCommand) && deviceMl != null)
                {
                    var duplicateLogicalDeviceId = CheckForDuplicateId(deviceMl);
                    var duplicateSerial = CheckForDuplicateSerial(deviceMl);

                    if (duplicateLogicalDeviceId == 1 || duplicateSerial == 1)
                    {
                        Warning(JetstreamResource.DuplicateAddDeviceMessage, true);
                        return RedirectToAction("RedirectToAddDevice", new RouteValueDictionary(deviceMl));
                    }
                    else
                    {
                        if (ModelState.IsValid)
                        {
                            // construct a Jetstream service client
                            JetstreamServiceClient client = new JetstreamServiceClient(JetstreamConfiguration.Url, JetstreamConfiguration.ApplicationAccessKey);

                            //Make logical device request object
                            AddLogicalDeviceRequest request = new AddLogicalDeviceRequest
                            {
                                DeviceDefinitionId = deviceMl.DeviceGuid,
                                DeviceSerialNumber = deviceMl.SerialNumber,
                                LogicalDeviceId = deviceMl.LogicalDeviceId,
                                Region = (Regions)Enum.Parse(typeof(Regions), deviceMl.Region)
                            };

                            // Add device to jetstream cloud
                            AddLogicalDeviceResponse response = client.AddLogicalDevice(request);

                            using (JetstreamClient objMainServiceClient = new JetstreamClient())
                            {
                                objMainServiceClient.SaveDevice(deviceMl);
                            }
                            Success(string.Format(JetstreamResource.DeviceSaveMessage, deviceMl.LogicalDeviceId, response.Id), true);
                            return RedirectToAction("DeviceDetail", "Device");
                        }
                        else
                        {
                            return RedirectToAction("RedirectToAddDevice", new RouteValueDictionary(deviceMl));
                        }
                    }
                }
                else if (string.Equals(command, JetstreamResource.CancelCommand))
                {
                    return RedirectToAction("DeviceDetail", "Device");
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : AddDevice(DeviceModel deviceMl, string command) :: DeviceController");
                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 : AddDevice(DeviceModel deviceMl, string command) :: DeviceController");
                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>
        /// Update devices to database
        /// </summary>
        /// <param name="deviceMl"></param>
        /// <returns></returns>
        public ActionResult UpdateDevice(DeviceModel deviceMl)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                if (Session["UserName"] != null)
                {
                    var duplicateLogicalDeviceId = CheckForDuplicateId(deviceMl);
                    var duplicateSerial = CheckForDuplicateSerial(deviceMl);

                    if (duplicateLogicalDeviceId == 1 || duplicateSerial == 1)
                    {
                        Warning(JetstreamResource.DuplicateAddDeviceMessage, true);
                        return RedirectToAction("RedirectToEditDevice", new RouteValueDictionary(deviceMl));
                    }
                    else
                    {
                        if (ModelState.IsValid)
                        {
                            string oldLogicalDeviceId;
                            using (JetstreamClient objMainServiceClient = new JetstreamClient())
                            {
                                DeviceModel dm = objMainServiceClient.GetDeviceByDeviceId(deviceMl.DeviceId);
                                oldLogicalDeviceId = dm.LogicalDeviceId;
                            }

                            // construct a Jetstream service client
                            JetstreamServiceClient client = new JetstreamServiceClient(JetstreamConfiguration.Url, JetstreamConfiguration.ApplicationAccessKey);

                            RemoveLogicalDeviceRequest removeRequest = new RemoveLogicalDeviceRequest
                            {
                                LogicalDeviceId = oldLogicalDeviceId
                            };

                            //Remove device from jetstream
                            client.RemoveLogicalDevice(removeRequest);

                            using (JetstreamClient objMainServiceClient = new JetstreamClient())
                            {
                                objMainServiceClient.UpdateDevice(deviceMl);
                            }

                            AddLogicalDeviceRequest addRequest = new AddLogicalDeviceRequest
                            {
                                DeviceDefinitionId = deviceMl.DeviceGuid,
                                DeviceSerialNumber = deviceMl.SerialNumber,
                                LogicalDeviceId = deviceMl.LogicalDeviceId,
                                Region = (Regions)Enum.Parse(typeof(Regions), deviceMl.Region)
                            };

                            // call the Jetstream GetDeviceDefinitions ReST endpoint
                            AddLogicalDeviceResponse addResponse = client.AddLogicalDevice(addRequest);

                            Success(string.Format(JetstreamResource.DeviceSaveMessage, deviceMl.LogicalDeviceId, addResponse.Id), true);
                            return RedirectToAction("DeviceDetail", "Device");
                        }
                        else
                        {
                            return RedirectToAction("RedirectToEditDevice", new RouteValueDictionary(deviceMl));
                        }
                    }
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : UpdateDevice(DeviceModel deviceMl) :: DeviceController");
                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 : UpdateDevice(DeviceModel deviceMl) :: DeviceController");
                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 get the device list with search text
        /// </summary>
        /// <param name="searchText"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sortField"></param>
        /// <param name="sortDirection"></param>
        /// <returns></returns>
        public JsonResult GetDeviceList(string searchText, int pageIndex, int pageSize, string sortField, string sortDirection)
        {
            List<DeviceModel> deviceModels;
            using (JetstreamClient objMainServiceClient = new JetstreamClient())
            {
                var deviceList = objMainServiceClient.GetFilterDeviceList(searchText);

                SetDeviceLocation(deviceList);

                SortingPagingInfo info = new SortingPagingInfo
                {
                    SortField = sortField,
                    SortDirection = sortDirection,
                };
                deviceModels = ApplySorting(info, deviceList).Skip(pageIndex * pageSize).Take(pageSize).ToList();
            }
            return Json(new { deviceModels }, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// Displays view to edit device
        /// </summary>
        /// <param name="logicalDeviceId"></param>
        /// <returns></returns>
        public ActionResult GetDevice(string logicalDeviceId)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                if (Session["UserName"] != null)
                {
                    DeviceModel deviceMl;
                    using (JetstreamClient objMainServiceClient = new JetstreamClient())
                    {
                        deviceMl = objMainServiceClient.GetDeviceByLogicalDeviceId(logicalDeviceId);
                    }
                    SortingPagingInfo info = new SortingPagingInfo
                    {
                        SortField = Enums.InventorySortField.Material.ToString(),
                        SortDirection = Constants.Ascending,
                        SearchText = string.Empty
                    };
                    if (deviceMl != null)
                        deviceMl.Inventories = deviceMl.Inventories.OrderBy(x => x.Material).Take(Constants.PagingPageSize).ToList();
                    ViewBag.SortingPagingInfo = info;
                    return View("EditDevice", deviceMl);
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : GetDevice(string logicalDeviceId) :: DeviceController");
                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 : GetDevice(string logicalDeviceId) :: DeviceController");
                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>
        /// Delete item from database
        /// </summary>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public ActionResult DeleteItem(int itemId)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                if (Session["UserName"] != null)
                {
                    using (JetstreamClient objMainServiceClient = new JetstreamClient())
                    {
                        objMainServiceClient.DeleteItem(itemId);
                    }
                    Success(JetstreamResource.ItemDeleteMessage, true);
                    return RedirectToAction("ItemDetail", "Item");
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : DeleteItem(int itemId) :: ItemController");
                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 : DeleteItem(int itemId) :: ItemController");
                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 duplicate serial number
        /// </summary>
        /// <param name="deviceMl"></param>
        /// <returns></returns>
        static int CheckForDuplicateSerial(DeviceModel deviceMl)
        {
            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.CheckForDuplicateSerial(deviceMl.DeviceId, deviceMl.SerialNumber) > 0)
                    {
                        duplicateDevice = 1;
                    }
                }
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : CheckForDuplicateSerial(DeviceModel deviceMl) :: DeviceController");
                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 : CheckForDuplicateSerial(DeviceModel deviceMl) :: DeviceController");
                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>
 /// Method to get the Inventory list by page number and page size for server side paging
 /// </summary>
 /// <param name="logicalDeviceId"></param>
 /// <param name="searchText"></param>
 /// <param name="pageIndex"></param>
 /// <param name="pageSize"></param>
 /// <param name="sortField"></param>
 /// <param name="sortDirection"></param>
 /// <returns></returns>
 public JsonResult GetInventoryList(string logicalDeviceId, string SearchString, int pageIndex, int pageSize, string sortField, string sortDirection)
 {
     List<InventoryModel> inventoriesModel;
     using (JetstreamClient objMainServiceClient = new JetstreamClient())
     {
         var inventoryList = objMainServiceClient.GetInventoryList(logicalDeviceId, SearchString);
         SortingPagingInfo info = new SortingPagingInfo
            {
                SortField = sortField,
                SortDirection = sortDirection,
            };
         inventoriesModel = ApplySorting(info, inventoryList).Skip(pageIndex * pageSize).Take(pageSize).ToList();
     }
     return Json(new { inventoriesModel }, JsonRequestBehavior.AllowGet);
 }
        /// <summary>
        ///  Method to get the inventory lists
        /// </summary>
        /// <param name="logicalDeviceId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sortField"></param>
        /// <param name="sortDirection"></param>
        /// <returns></returns>
        public JsonResult GetDeviceInventoriesList(string logicalDeviceId, int pageIndex, int pageSize, string sortField, string sortDirection)
        {
            DeviceModel deviceModel;
            using (JetstreamClient objMainServiceClient = new JetstreamClient())
            {
                deviceModel = objMainServiceClient.GetDeviceInventoriesList(logicalDeviceId);

                SortingPagingInfo info = new SortingPagingInfo
                {
                    SortField = sortField,
                    SortDirection = sortDirection,
                };
                deviceModel.Inventories = ApplySortingInventory(info, deviceModel.Inventories).Skip(pageIndex * pageSize).Take(pageSize).ToList();
            }
            return Json(new { deviceModel }, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// return json for server side paging
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sortField"></param>
        /// <param name="sortDirection"></param>
        /// <param name="searchString"></param>
        /// <param name="startDateFrom"></param>
        /// <param name="startDateTo"></param>
        /// <returns></returns>
        public JsonResult GetTransactionsList(int pageIndex, int pageSize, string sortField, string sortDirection, string searchString, string startDateFrom, string startDateTo)
        {
            List<TransactionModel> transactionModels;
            using (JetstreamClient objMainServiceClient = new JetstreamClient())
            {
                List<TransactionModel> transactionList;
                transactionList = objMainServiceClient.GetInventoryTransaction(searchString, startDateFrom,
                     startDateTo);

                transactionList.ForEach(x =>
                {
                    x.Location = x.Latitude +
                                 (x.Longitude != null ? string.Format(":{0}", x.Longitude) : x.Longitude)
                                 + (x.Range != null ? string.Format(":{0}", x.Range) : x.Range);
                });

                SortingPagingInfo info = new SortingPagingInfo
                {
                    SortField = sortField,
                    SortDirection = sortDirection,
                };
                transactionModels = ApplySorting(transactionList, info).Skip(pageIndex * pageSize).Take(pageSize).ToList();
            }
            return Json(new { transactionModels }, JsonRequestBehavior.AllowGet);
        }