public void AddDevice_OnPost_WithSessionNotNullDeviceModelAndAddCommand_DuplicateDevice_ExpectRedirectToAddDevice()
        {
            //Arrange
            String expectedAction = "RedirectToAddDevice";

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

            var deviceModel = new DeviceModel()
            {
                DeviceName = "TS001, Freezer, US, 2.4GHz, MF, 5.0 cu ft",
                DeviceGuid = "7e904df7-8215-4752-bb46-7131ff867240",
                LogicalDeviceId = "TestChetuId1",
                SerialNumber = "TestSerial1",
                Region = "US"
            };

            //Act
            var redirectToRouteResult = _deviceController.AddDevice(deviceModel, "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"]);
        }
        /// <summary>
        /// Method to save device detail
        /// </summary>
        /// <param name="deviceMl"></param>
        /// <returns></returns>
        public int SaveDevice(DeviceModel deviceMl)
        {
            // Creating instance of the string builder class to hold the tracing data
            StringBuilder objStringBuilderTrace = new StringBuilder();
            device objDevice = new device();

            // Append tracing into string builder
            objStringBuilderTrace.AppendLine("Start method : SaveDevice(DeviceModel deviceML) :: JetstreamLaunchpad.DAL.Device class : DBDevice.cs");
            // Writing trace log into the log file 
            SaveLogger.SaveLoggerTrace(objStringBuilderTrace.ToString());
            // Clear StringBuilder object
            objStringBuilderTrace.Clear();

            objDevice.LogicalDeviceId = deviceMl.LogicalDeviceId;
            objDevice.DeviceName = deviceMl.DeviceName;
            objDevice.SerialNumber = deviceMl.SerialNumber;
            objDevice.DeviceGuid = deviceMl.DeviceGuid;
            objDevice.Region = deviceMl.Region;

            ObjTersoDataContext.devices.Add(objDevice);
            ObjTersoDataContext.SaveChanges();
            var deviceId = deviceMl.DeviceId;

            // Append tracing into string builder
            objStringBuilderTrace.AppendLine("End method : SaveDevice(DeviceModel deviceML) :: JetstreamLaunchpad.DAL.Device class : DBDevice.cs");
            // Writing trace log into the log file 
            SaveLogger.SaveLoggerTrace(objStringBuilderTrace.ToString());
            objStringBuilderTrace.Clear();
            return deviceId;
        }
        public ActionResult EditCurrentDevice(DeviceModel deviceMl, string command)
        {
            StringBuilder objStringBuilderError = new StringBuilder();
            try
            {
                if (Session["UserName"] != null && deviceMl != null)
                {
                    if (command == JetstreamResource.CancelCommand)
                    {
                        return RedirectToAction("EditDevice", new { deviceId = deviceMl.DeviceId });
                    }

                    else if (command == JetstreamResource.AddCommand)
                    {
                        return RedirectToAction("UpdateDevice", new RouteValueDictionary(deviceMl));
                    }
                    else
                    {
                        return RedirectToAction("DeviceDetail", "Device");
                    }
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            catch (FaultException<ServiceData> fex)
            {
                objStringBuilderError.AppendLine("In method : EditCurrentDevice(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 : EditCurrentDevice(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");
            }
        }
        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 void RedirectToAddDevice_WithDeviceModel_ExpectOk()
        {
            //Arrange
            String expectedView = "AddDevice";
            DeviceModel deviceML = new DeviceModel
            {
                LogicalDeviceId = "TestLogicalDeviceId",
                SerialNumber = "TestSerialNumber",
                Region = "US",
                DeviceGuid = "ca9c0cd6-a9e6-4cff-832f-f4acbe61ab64"
            };

            //Act
            var actionResult = _deviceController.RedirectToAddDevice(deviceML) as ViewResult;

            //Assert
            Assert.IsNotNull(actionResult, "RedirectToAddDevice action result should not be null");
            Assert.AreEqual(actionResult.ViewName, expectedView, "View name should be AddDevice");
        }
        public void RedirectToEditDevice_WithDeviceModel_ExpectOk()
        {
            //Arrange
            String expectedView = "EditCurrentDevice";
            var deviceModel = new DeviceModel()
            {
                DeviceId = 38,
                DeviceName = "TS001, Freezer, US, 2.4GHz, MF, 5.0 cu ft",
                DeviceGuid = "7e904df7-8215-4752-bb46-7131ff867240",
                LogicalDeviceId = "TestChetuId3",
                SerialNumber = "TestSerial3",
                Region = "US"
            };

            //Act
            var actionResult = _deviceController.RedirectToEditDevice(deviceModel) as ViewResult;

            //Assert
            Assert.IsNotNull(actionResult, "RedirectToEditDevice action result should not be null");
            Assert.AreEqual(actionResult.ViewName, expectedView, "View name should be EditCurrentDevice");
        }
        /// <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;
        }
        public void AddDevice_OnPost_WithSessionIsNullAndUserModel_ExpectUserLogin()
        {
            //Arrange
            String expectedController = "Login";
            String expectedAction = "UserLogin";

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

            var deviceModel = new DeviceModel();

            //Act
            var redirectToRouteResult = _deviceController.AddDevice(deviceModel, 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 EditCurrentDevice_OnPost_WithSessionNotNullAndEmptyCommand_ExpectRedirectToDeviceDetail()
        {
            //Arrange
            String expectedAction = "DeviceDetail";
            _controllerContext.Setup(cc => cc.HttpContext.Session["UserName"]).Returns(string.Format("{0} {1}", "FName", "LName"));
            _deviceController.ControllerContext = _controllerContext.Object;
            var deviceModel = new DeviceModel()
            {
                LogicalDeviceId = "DemoDevice01_L",
                DeviceGuid = "7e904df7-8215-4752-bb46-7131ff867240",
                DeviceName = "TS001, Freezer, US, 2.4GHz, MF, 5.0 cu ft",
                SerialNumber = "2134123132213"
            };

            //Act
            var redirectToRouteResult = _deviceController.EditCurrentDevice(deviceModel, 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"]);
        }
 /// <summary>
 /// Get device by logical device Id
 /// </summary>
 /// <param name="deviceMl"></param>
 /// <returns></returns>
 public int GetDeviceModelByLogicalDeviceId(DeviceModel deviceMl)
 {
     ServiceData serviceData = new ServiceData();
     try
     {
         int result;
         using (DBDevice objDbDevice = new DBDevice())
         {
             result = objDbDevice.GetDeviceModelByLogicalDeviceId(deviceMl);
         }
         return result;
     }
     catch (Exception ex)
     {
         serviceData.Result = false;
         serviceData.ErrorMessage = ex.Message;
         serviceData.ErrorDetails = ex.ToString();
         throw new FaultException<ServiceData>(serviceData);
     }
 }
        public void AddDevice_OnPost_WithSessionNotNullUserModelAndCancelCommand_ExpectGetUserDetails()
        {
            //Arrange
            String expectedAction = "DeviceDetail";

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

            var deviceModel = new DeviceModel();

            //Act
            var redirectToRouteResult = _deviceController.AddDevice(deviceModel, "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"]);
        }
        /// <summary>
        ///  Method to get device by deviceid
        /// </summary>
        /// <param name="logicalDeviceId"></param>
        /// <returns></returns>
        public DeviceModel GetDeviceInventoriesList(string logicalDeviceId)
        {
            // Creating instance of the string builder class to hold the tracing data
            StringBuilder objStringBuilderTrace = new StringBuilder();
            DeviceModel deviceMl = new DeviceModel();

            // Append tracing into string builder
            objStringBuilderTrace.AppendLine("Start method : GetDeviceInventoriesList(string logicalDeviceId) :: JetstreamLaunchpad.DAL.Device Class : DBDevice.cs");
            // Writing trace log into the log file 
            SaveLogger.SaveLoggerTrace(objStringBuilderTrace.ToString());
            // Clear StringBuilder object
            objStringBuilderTrace.Clear();

            deviceMl.Inventories = GetTotalInventory(logicalDeviceId);

            deviceMl.Inventories.ToList().ForEach(x =>
            {
                if (x.ExpirationDate != null) x.ExpirationDateString = x.ExpirationDate.Value.ToShortDateString();
            });

            // Append tracing into string builder
            objStringBuilderTrace.AppendLine("End method : GetDeviceInventoriesList(string logicalDeviceId) :: JetstreamLaunchpad.DAL.Device Class : DBDevice.cs");
            // Writing trace log into the log file 
            SaveLogger.SaveLoggerTrace(objStringBuilderTrace.ToString());
            objStringBuilderTrace.Clear();
            return deviceMl;
        }
        /// <summary>
        ///  Method to get device by logical deviceid
        /// </summary>
        /// <param name="deviceMl"></param>
        /// <returns></returns>
        public int GetDeviceModelByLogicalDeviceId(DeviceModel deviceMl)
        {
            // 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 :  GetDeviceModelByLogicalDeviceId(DeviceModel deviceML) :: JetstreamLaunchpad.DAL.Device Class : DBDevice.cs");
            // Writing trace log into the log file 
            SaveLogger.SaveLoggerTrace(objStringBuilderTrace.ToString());
            // Clear StringBuilder object
            objStringBuilderTrace.Clear();

            var device =
                ObjTersoDataContext.devices.Where(
                    x => x.LogicalDeviceId.Equals(deviceMl.LogicalDeviceId) && x.DeviceId != deviceMl.DeviceId).ToList();
            var result = device.Count > 0 ? device.Count : 0;

            // Append tracing into string builder
            objStringBuilderTrace.AppendLine("End method :  GetDeviceModelByLogicalDeviceId(DeviceModel deviceML) :: JetstreamLaunchpad.DAL.Device Class : DBDevice.cs");
            // Writing trace log into the log file 
            SaveLogger.SaveLoggerTrace(objStringBuilderTrace.ToString());
            objStringBuilderTrace.Clear();
            return result;
        }
        /// <summary>
        /// Method to update device
        /// </summary>
        /// <param name="deviceMl"></param>
        /// <returns></returns>
        public int UpdateDevice(DeviceModel deviceMl)
        {
            // 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 : UpdateDevice(DeviceModel deviceML) :: JetstreamLaunchpad.DAL.Device class : DBDevice.cs");
            // Writing trace log into the log file 
            SaveLogger.SaveLoggerTrace(objStringBuilderTrace.ToString());
            // Clear StringBuilder object
            objStringBuilderTrace.Clear();

            var objDevice = ObjTersoDataContext.devices.FirstOrDefault(x => x.DeviceId == deviceMl.DeviceId);
            if (objDevice != null)
            {
                objDevice.LogicalDeviceId = deviceMl.LogicalDeviceId;
                objDevice.DeviceGuid = deviceMl.DeviceGuid;
                objDevice.DeviceName = deviceMl.DeviceName;
                objDevice.SerialNumber = deviceMl.SerialNumber;
            }

            ObjTersoDataContext.SaveChanges();

            // Append tracing into string builder
            objStringBuilderTrace.AppendLine("End method : UpdateDevice(DeviceModel deviceML) :: JetstreamLaunchpad.DAL.Device class : DBDevice.cs");
            // Writing trace log into the log file 
            SaveLogger.SaveLoggerTrace(objStringBuilderTrace.ToString());
            objStringBuilderTrace.Clear();
            return objDevice != null ? objDevice.DeviceId : 0;
        }
        /// <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");
            }
        }
        public void UpdateDevice_WithSessionNotNullAndDeviceModel_ExpectOk()
        {
            //Arrange
            String expectedAction = "DeviceDetail";
            _controllerContext.Setup(cc => cc.HttpContext.Session["UserName"]).Returns(string.Format("{0} {1}", "FName", "LName"));
            _deviceController.ControllerContext = _controllerContext.Object;
            var deviceModel = new DeviceModel()
            {
                DeviceId = 23,
                LogicalDeviceId = "ChetuTestDeviceId2",
                DeviceGuid = "ca9c0cd6-a9e6-4cff-832f-f4acbe61ab64",
                DeviceName = "FalconAlpha",
                SerialNumber = "ChetuTestDeviceSLNO2",
                Region = "US",
            };

            //Act
            var redirectToRouteResult = _deviceController.UpdateDevice(deviceModel) 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 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");
            }
        }
        public void UpdateDevice_WithSessionIsNullAndDeviceModel_ExpectUserLogin()
        {
            //Arrange
            String expectedController = "Login";
            String expectedAction = "UserLogin";
            _controllerContext.Setup(cc => cc.HttpContext.Session["UserName"]).Returns(null);
            _deviceController.ControllerContext = _controllerContext.Object;

            var deviceModel = new DeviceModel()
            {
                DeviceId = 10,
                LogicalDeviceId = "DemoDevice01_L",
                DeviceGuid = "7e904df7-8215-4752-bb46-7131ff867240",
                DeviceName = "TS001, Freezer, US, 2.4GHz, MF, 5.0 cu ft",
                SerialNumber = "2134123132213"
            };

            //Act
            var redirectToRouteResult = _deviceController.UpdateDevice(deviceModel) 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>
        /// Redirect to add device screen
        /// </summary>
        /// <param name="deviceMl"></param>
        /// <returns></returns>
        public ActionResult RedirectToAddDevice(DeviceModel deviceMl)
        {
            // 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 (response.Body != null)
            {
                //Get the device defination for binding to model dropdown
                List<Models> 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");
            }

            return View("AddDevice", deviceMl);
        }
 /// <summary>
 /// Location
 /// </summary>
 /// <param name="latitude"></param>
 /// <param name="longitude"></param>
 /// <param name="range"></param>
 /// <returns></returns>
 public ActionResult Location(string latitude, string longitude, string range)
 {
     DeviceModel deviceMl = new DeviceModel();
     deviceMl.Latitude = latitude;
     deviceMl.Longitude = longitude;
     deviceMl.Range = range;
     return View(deviceMl);
 }