Beispiel #1
0
        public ActionResult AddDevice(string name, string address, string userName, string password, int cameraId)
        {
            AddDeviceResult result = null;

            //Calling the SurveillanceCloudSampleService's AddDevice method with the parameters filled by the user
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://*****:*****@"application/json";

            using (Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
            }

            try
            {
                WebResponse response = request.GetResponse();
                using (Stream responseStream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                    //Deserializing the response
                    result = JsonConvert.DeserializeObject <AddDeviceResult>(reader.ReadToEnd());
                }
            }
            catch (Exception ex)
            {
                try
                {
                    if (ex is WebException && (ex as WebException).Response != null && (ex as WebException).Response is HttpWebResponse && (((ex as WebException).Response as HttpWebResponse).StatusCode == HttpStatusCode.BadRequest || ((ex as WebException).Response as HttpWebResponse).StatusCode == HttpStatusCode.InternalServerError))
                    {
                        //Getting the error message and setting it in the TempData object for later visualization
                        string description = JsonConvert.DeserializeObject <string>(new StreamReader(((ex as WebException).Response as HttpWebResponse).GetResponseStream()).ReadToEnd());
                        TempData["Error"] = HttpUtility.HtmlEncode(description);
                        return(RedirectToAction("Index", "Dashboard", new { cameraId = cameraId }));
                    }
                }
                finally
                {
                }

                TempData["Error"] = HttpUtility.HtmlEncode("Invalid or no response from the service");
                return(RedirectToAction("Index", "Dashboard", new { cameraId = cameraId }));
            }

            return(RedirectToAction("Index", "Dashboard"));
        }
        public IHttpActionResult AddDevice([FromBody] JObject parameters)
        {
            List <JProperty> properties = null;
            int?   userId;
            string userName;
            string password;
            string ipAddress;
            int?   cameraId;
            string cameraName;

            try
            {
                //Getting parameters values
                properties = parameters.Children().Cast <JProperty>().ToList();
                userId     = (properties.Where(p => p.Name == "userId").FirstOrDefault().Value as JValue).Value <int>();
                userName   = properties.Where(p => p.Name == "userName").FirstOrDefault()?.Value?.ToString();
                password   = properties.Where(p => p.Name == "password").FirstOrDefault()?.Value?.ToString();
                ipAddress  = properties.Where(p => p.Name == "ipAddress").FirstOrDefault()?.Value?.ToString();
                cameraId   = (properties.Where(p => p.Name == "cameraId").FirstOrDefault().Value as JValue).Value <int>();
                cameraName = properties.Where(p => p.Name == "name").FirstOrDefault()?.Value?.ToString();

                //Checking if userId and cameraId parameters are entered
                if (userId == null || cameraId == null)
                {
                    //returning error response
                    return(Content(HttpStatusCode.BadRequest, "Invalid input parameters"));
                }
            }
            catch
            {
                //returning error response
                return(Content(HttpStatusCode.BadRequest, "Invalid input parameters"));
            }

            try
            {
                //Creating response object
                AddDeviceResult o = new AddDeviceResult();
                //Setting the default response status to Problem
                o.Status = AddDeviceStatus.Problem;

                User tmpUser;
                ConfigurationItem tmpConfigurationItem;
                ConfigurationItem resultConfigurationItem;

                //Getting the user object
                if ((tmpUser = users?.Where(u => u.Id == userId).FirstOrDefault()) != null)
                {
                    string cameraAddress;

                    //Checking if there is a camera on the selected slot or not. If a camera exists on the selected slot, we will remove it before adding the new one.
                    bool cameraReplace = !string.IsNullOrWhiteSpace((cameraAddress = tmpUser.Cameras[cameraId.Value].Address));

                    //If a camera exists on the selected slot and we don't provide a new address that is considered as only remove the camera,
                    //but if we don't provide address and there is no camera on the selected slot - this is not correct.
                    if (string.IsNullOrWhiteSpace(ipAddress) && !cameraReplace)
                    {
                        //returning error response
                        return(Content(HttpStatusCode.BadRequest, "The address field cannot be empty"));
                    }

                    if (cameraReplace)
                    {
                        #region Removing camera
                        tmpConfigurationItem = configApiClient.InvokeMethod(configApiClient.GetItem(configApiClient.GetChildItems(configApiClient.GetItem("/" + ItemTypes.RecordingServerFolder).Path)[0].Path + "/" + ItemTypes.HardwareFolder), "DeleteHardware");
                        tmpConfigurationItem.Properties.Where(p => p.Key == "ItemSelection").FirstOrDefault().Value = configApiClient.GetChildItems(configApiClient.GetItem(configApiClient.GetChildItems(configApiClient.GetItem("/" + ItemTypes.RecordingServerFolder).Path)[0].Path + "/" + ItemTypes.HardwareFolder).Path).Where(h => h.Properties.Where(p => p.Key == "Address" && p.Value.Contains(cameraAddress)).FirstOrDefault() != null).FirstOrDefault().Path;
                        resultConfigurationItem = configApiClient.InvokeMethod(tmpConfigurationItem, "DeleteHardware");
                        if (resultConfigurationItem.Properties.FirstOrDefault(p => p.Key == InvokeInfoProperty.State).Value != InvokeInfoStates.Error)
                        {
                            do
                            {
                                tmpConfigurationItem = configApiClient.GetItem(resultConfigurationItem.Properties.Where(p => p.Key == "Path").FirstOrDefault().Value);
                            }while ((tmpConfigurationItem.Properties.FirstOrDefault(p => p.Key == "Progress")?.Value ?? "0") != "100");
                            if (tmpConfigurationItem.Properties.FirstOrDefault(p => p.Key == InvokeInfoProperty.State).Value != InvokeInfoStates.Success)
                            {
                                //returning error response
                                return(Content(HttpStatusCode.BadRequest, "Error removing the old camera"));
                            }
                        }
                        else
                        {
                            //returning error response
                            return(Content(HttpStatusCode.BadRequest, "Error removing the old camera"));
                        }
                        #endregion
                    }

                    //If deleting the camera is the only thing we need to do, we just updating the User object and serializing it in the file
                    if (string.IsNullOrWhiteSpace(ipAddress))
                    {
                        tmpUser.Cameras[cameraId.Value].Address  = null;
                        tmpUser.Cameras[cameraId.Value].Name     = null;
                        tmpUser.Cameras[cameraId.Value].Password = null;
                        tmpUser.Cameras[cameraId.Value].Username = null;
                        File.WriteAllText(HttpContext.Current.Server.MapPath("~/data.txt"), JsonConvert.SerializeObject(users, new JsonSerializerSettings()
                        {
                            ContractResolver = new ExcludeCameraUsernameAndPasswordResolver()
                        }));
                        o.Status = AddDeviceStatus.Success;
                        //returning success response
                        return(Ok(o));
                    }

                    #region Searching for hardware driver
                    //Trying the default credentials, if we don't provide such
                    bool useDefaultCredentials = string.IsNullOrWhiteSpace(userName) && string.IsNullOrWhiteSpace(password);
                    tmpConfigurationItem = configApiClient.InvokeMethod(configApiClient.GetChildItems(configApiClient.GetItem("/" + ItemTypes.RecordingServerFolder).Path)[0], "HardwareScan");
                    tmpConfigurationItem.Properties.Where(p => p.Key == "HardwareAddress").FirstOrDefault().Value       = ipAddress;
                    tmpConfigurationItem.Properties.Where(p => p.Key == "UseDefaultCredentials").FirstOrDefault().Value = useDefaultCredentials.ToString();
                    if (!useDefaultCredentials)
                    {
                        tmpConfigurationItem.Properties.Where(p => p.Key == "UserName").FirstOrDefault().Value = userName;
                        tmpConfigurationItem.Properties.Where(p => p.Key == "Password").FirstOrDefault().Value = password;
                    }
                    resultConfigurationItem = configApiClient.InvokeMethod(tmpConfigurationItem, "HardwareScan");
                    #endregion
                    if (resultConfigurationItem.Properties.FirstOrDefault(p => p.Key == InvokeInfoProperty.State).Value != InvokeInfoStates.Error)
                    {
                        do
                        {
                            tmpConfigurationItem = configApiClient.GetItem(resultConfigurationItem.Properties.Where(p => p.Key == "Path").FirstOrDefault().Value);
                        }while ((tmpConfigurationItem.Properties.FirstOrDefault(p => p.Key == "Progress")?.Value ?? "0") != "100");

                        if (tmpConfigurationItem.Properties.FirstOrDefault(p => p.Key == InvokeInfoProperty.State).Value == InvokeInfoStates.Success)
                        {
                            #region Adding Hardware
                            resultConfigurationItem = configApiClient.InvokeMethod(configApiClient.GetChildItems(configApiClient.GetItem("/" + ItemTypes.RecordingServerFolder).Path)[0], "AddHardware");

                            resultConfigurationItem.Properties.Where(p => p.Key == "HardwareAddress").FirstOrDefault().Value    = tmpConfigurationItem.Properties.FirstOrDefault(p => p.Key == "HardwareAddress").Value;
                            resultConfigurationItem.Properties.Where(p => p.Key == "UserName").FirstOrDefault().Value           = tmpConfigurationItem.Properties.FirstOrDefault(p => p.Key == "UserName").Value;
                            resultConfigurationItem.Properties.Where(p => p.Key == "Password").FirstOrDefault().Value           = tmpConfigurationItem.Properties.FirstOrDefault(p => p.Key == "Password").Value;
                            resultConfigurationItem.Properties.Where(p => p.Key == "HardwareDriverPath").FirstOrDefault().Value = tmpConfigurationItem.Properties.FirstOrDefault(p => p.Key == "HardwareDriverPath").Value;
                            tmpConfigurationItem = configApiClient.InvokeMethod(resultConfigurationItem, "AddHardware");
                            #endregion

                            do
                            {
                                resultConfigurationItem = configApiClient.GetItem(tmpConfigurationItem.Properties.Where(p => p.Key == "Path").FirstOrDefault().Value);
                            }while ((resultConfigurationItem.Properties.FirstOrDefault(p => p.Key == "Progress")?.Value ?? "0") != "100");

                            if (resultConfigurationItem.Properties.FirstOrDefault(p => p.Key == InvokeInfoProperty.State).Value == InvokeInfoStates.Success)
                            {
                                #region Enable Hardware
                                resultConfigurationItem = configApiClient.GetItem(resultConfigurationItem.Properties.FirstOrDefault(p => p.Key == "Path").Value);
                                resultConfigurationItem.EnableProperty.Enabled = true;
                                var result = configApiClient.SetItem(resultConfigurationItem);
                                #endregion
                                if (result.ValidatedOk)
                                {
                                    //If there is no camera-group already then create one
                                    if (configApiClient.GetChildItems("/" + ItemTypes.CameraGroupFolder).Length == 0)
                                    {
                                        var cameraGroupItem = configApiClient.GetItem("/" + ItemTypes.CameraGroupFolder);
                                        cameraGroupItem.Properties = new Property[] { new Property {
                                                                                          Key = "GroupName", DisplayName = "SurveillanceCloud", IsSettable = true, Value = "SurveillanceCloud"
                                                                                      }, new Property {
                                                                                          Key = "GroupDescription", DisplayName = "Camera(s) for SurveillanceCloud", IsSettable = true, Value = "Camera(s) for SurveillanceCloud"
                                                                                      } };
                                        cameraGroupItem.ItemCategory = ItemCategories.Item;
                                        cameraGroupItem.ItemType     = ItemTypes.InvokeInfo;
                                        configApiClient.InvokeMethod(cameraGroupItem, "AddDeviceGroup");
                                    }

                                    #region Enable the cameras, adding to first available camera group and adding to role
                                    foreach (var configItem in configApiClient.GetChildItems(resultConfigurationItem.Path + "/" + ItemTypes.CameraFolder))
                                    {
                                        #region Enable camera
                                        configItem.EnableProperty.Enabled = true;
                                        configItem.Properties.FirstOrDefault(p => p.Key == "Name").Value = string.IsNullOrWhiteSpace(cameraName) ? configItem.DisplayName : cameraName;
                                        result = configApiClient.SetItem(configItem);
                                        #endregion
                                        if (result.ValidatedOk)
                                        {
                                            #region Adding the camera to the first available camera group
                                            tmpConfigurationItem = configApiClient.InvokeMethod(configApiClient.GetItem(configApiClient.GetChildItems("/" + ItemTypes.CameraGroupFolder)[0].Path + "/" + ItemTypes.CameraFolder), "AddDeviceGroupMember");
                                            tmpConfigurationItem.Properties.Where(p => p.Key == "ItemSelection").FirstOrDefault().Value = configItem.Path;
                                            tmpConfigurationItem = configApiClient.InvokeMethod(tmpConfigurationItem, "AddDeviceGroupMember");
                                            #endregion
                                            if (tmpConfigurationItem.Properties.FirstOrDefault(p => p.Key == InvokeInfoProperty.State).Value == InvokeInfoStates.Success)
                                            {
                                                #region Adding the camera to the role
                                                tmpConfigurationItem = configApiClient.InvokeMethod(configItem, "ChangeSecurityPermissions");
                                                tmpConfigurationItem.Properties.Where(p => p.Key == "UserPath").FirstOrDefault().Value = configApiClient.GetChildItems("/" + ItemTypes.RoleFolder).Where(i => i.ItemType == ItemTypes.Role && i.Properties.Where(p => p.Key == "Name" && p.Value == tmpUser.Username).FirstOrDefault() != null).FirstOrDefault().Path;
                                                resultConfigurationItem = configApiClient.InvokeMethod(tmpConfigurationItem, "ChangeSecurityPermissions");
                                                resultConfigurationItem.Properties.Where(p => p.Key == "GENERIC_READ").FirstOrDefault().Value = true.ToString();
                                                resultConfigurationItem.Properties.Where(p => p.Key == "VIEW_LIVE").FirstOrDefault().Value    = true.ToString();
                                                resultConfigurationItem.Properties.Where(p => p.Key == "PLAYBACK").FirstOrDefault().Value     = true.ToString();
                                                resultConfigurationItem = configApiClient.InvokeMethod(resultConfigurationItem, "ChangeSecurityPermissions");
                                                #endregion
                                            }
                                            else
                                            {
                                                //returning error response
                                                return(Content(HttpStatusCode.BadRequest, "Error adding the camera to a group"));
                                            }
                                        }
                                        else
                                        {
                                            //returning error response
                                            return(Content(HttpStatusCode.BadRequest, "Error enabling the camera"));
                                        }
                                    }
                                    #endregion

                                    //Updating User data and serializing the collection to the file
                                    tmpUser.Cameras[cameraId.Value].Address = ipAddress;
                                    tmpUser.Cameras[cameraId.Value].Name    = cameraName;
                                    File.WriteAllText(HttpContext.Current.Server.MapPath("~/data.txt"), JsonConvert.SerializeObject(users, new JsonSerializerSettings()
                                    {
                                        ContractResolver = new ExcludeCameraUsernameAndPasswordResolver()
                                    }));

                                    //setting the status of the response object to success
                                    o.Status = AddDeviceStatus.Success;
                                }
                                else
                                {
                                    //returning error response
                                    return(Content(HttpStatusCode.BadRequest, "Error enabling the device"));
                                }
                            }
                            else
                            {
                                //returning error response
                                return(Content(HttpStatusCode.BadRequest, "Camera already added to the system"));
                            }
                        }
                        else
                        {
                            //returning error response
                            return(Content(HttpStatusCode.BadRequest, "Invalid address, camera connection problem or unsupported camera."));
                        }
                    }
                    else
                    {
                        //returning error response
                        return(Content(HttpStatusCode.BadRequest, "Invalid address or camera connection problem"));
                    }
                }
                else
                {
                    //returning error response
                    return(Content(HttpStatusCode.BadRequest, "Invalid input parameters"));
                }

                //returning success response
                return(Ok(o));
            }
            catch (Exception)
            {
                //returning error response
                return(Content(HttpStatusCode.InternalServerError, "Unknown error"));
            }
        }