/// <summary> /// This method saves a new list in the bd if not id is gived, or update an existing list if is gived /// </summary> /// <param name="formData"></param> /// <param name="id"></param> /// <author> /// Luis Gonzalo Quijada Romero /// </author> /// <returns> /// Returns the saved document's id /// </returns> public String saveList(FormCollection formData) { String dataPermissions = Session["Permissions"].ToString(); String dataPermissionsClient = Session["PermissionsClient"].ToString(); bool access = false; bool accessClient = false; // access = getpermissions("users", "r"); access = validatepermissions.getpermissions("lists", "u", dataPermissions); accessClient = validatepermissions.getpermissions("lists", "u", dataPermissionsClient); if (access == true && accessClient == true) { if (this.Request.IsAjaxRequest()) { try //trying to unserialize the formcollection gived { formData = CustomForm.unserialize(formData); } catch (Exception e) { return(null); } String listID = (formData["listID"] == "null") ? null : formData["listID"]; //is this an insert or an update?, converting null in javascript to null in c# if (listID != null) { char[] delimiters = { ',', '[', ']' }; string[] changedElements = formData["changedElements"].Split(delimiters); foreach (string element in changedElements) { removeElement(formData["listID"], element); } } BsonDocument list = listTable.getRow(listID); //validating listName if (!Regex.IsMatch(formData["listName"], "[A-Za-z_]+[A-Za-z0-9.-_]*")) { return("El nombre de la lista tiene un formato incorrecto"); } //validating listDisplayName else if (!Regex.IsMatch(formData["listDisplayName"], "")) { return("El nombre para mostrar de la lista tiene un formato incorrecto"); } else if (listNameUsed(formData["listName"]) && (list == null || formData["listName"] != list.GetElement("name").Value.ToString())) { return("El nombre de la lista ya está siendo utilizado"); } JObject jsonData = new JObject(); try { jsonData.Add("name", formData["listName"]); jsonData.Add("displayName", formData["listDisplayName"]); } catch (Exception e) { return(null); } try //trying to set the creator's id { if (listID == null) { jsonData.Add("creatorId", this.Session["_id"].ToString()); } else { try { jsonData.Add("creatorId", list["creatorId"].ToString()); } catch (Exception e) { /*Ignored*/ } } } catch (Exception e) { /*Ignored*/ } /*setting dependency*/ try { String dependency = formData["dependency"]; //checking dependency of this list BsonDocument dependencyDocument = BsonDocument.Parse(dependency); if (listHasElement(dependencyDocument.GetElement("listID").Value.ToString(), dependencyDocument.GetElement("elementName").Value.ToString())) { jsonData.Add("dependency", formData["dependency"]); } } catch (Exception e) { /*Ignored*/ } /*** Creating elements ***/ JObject listElements = new JObject(); JArray unorderElements = new JArray(); try //trying to create the unorder elements { BsonDocument uoElements = BsonDocument.Parse(formData["unorderElements"]); foreach (BsonElement element in uoElements) { if (Regex.IsMatch(element.Name.ToString(), "[A-Za-z0-9.-_]+") && Regex.IsMatch(element.Value.ToString(), "[A-Za-z0-9._-áéíóúÁÉÍÓÚñÑ]*")) { JObject newElement = new JObject(); newElement.Add(element.Name.ToString(), element.Value.ToString()); unorderElements.Add(newElement); } } if (listID != null) { BsonDocument oldElements = list.GetElement("elements").Value.ToBsonDocument(); foreach (BsonDocument document in (BsonArray)oldElements.GetElement("unorder").Value) { BsonElement element = document.First(); JObject newElement = new JObject(); newElement.Add(element.Name.ToString(), element.Value.ToString()); unorderElements.Add(newElement); } } } catch (Exception e) { /*Ignored*/ } listElements.Add("unorder", unorderElements); JArray orderElements = new JArray(); try //trying to create the unorder elements { BsonDocument uoElements = BsonDocument.Parse(formData["orderElements"]); int index = 0; foreach (BsonElement element in uoElements) { if (Regex.IsMatch(element.Name.ToString(), "[A-Za-z0-9.-_]+") && Regex.IsMatch(element.Value.ToString(), "[A-Za-z0-9._-áéíóúÁÉÍÓÚñÑ]*")) { JObject orderElement = new JObject(); orderElement.Add(element.Name.ToString(), element.Value.ToString()); orderElement.Add("position", index); orderElements.Add(orderElement); ++index; } } } catch (Exception e) { /*Ignored*/ } listElements.Add("order", orderElements); jsonData.Add("elements", listElements); String jsonString = JsonConvert.SerializeObject(jsonData); String savedID = listTable.saveRow(jsonString, listID); _logTable.SaveLog(Session["_id"].ToString(), "Listas", "Insert: guardar lista", "List", DateTime.Now.ToString()); jsonData.Add("client-name", "cinepolis"); jsonData.Add("innerCollection", "list"); jsonData.Add("auxId", listID); jsonData.Add("idInClient", savedID); jsonString = JsonConvert.SerializeObject(jsonData); jsonString = jsonString.Replace("\"", "'"); String jsonAgent = "{'action':'spreadToFather','collection':'ObjectReference','document':" + jsonString + ",'Source':'cinepolis'}"; // initAgent(); // agent.sendMessage(jsonAgent); return(savedID); } return(null); } return(null); }
public String saveObject(FormCollection data, HttpPostedFileBase file, IEnumerable <HttpPostedFileBase> files, String parentCategory = "null", String id = null) { if (id == "null" || id == "") //differents ways to receive null from javascript { id = null; } bool access = getpermissions("objects", "u"); if (access == true) { data = CustomForm.unserialize(data); JObject objectArray = new JObject(); try //name must be gived { if (data["txtserie"] == null || data["txtserie"] == "") { return("ingrese un numero de serie"); //name is wrong } objectArray.Add("serie", data["txtserie"].ToString()); data.Remove("txtserie"); } catch (Exception e) { //what to do if name is wrong return("Ha ocurrido un error"); } try //name must be gived { if (data["name"] == null || data["name"] == "") { return("ingrese un nombre"); //name is wrong } objectArray.Add("name", data["name"].ToString()); data.Remove("name"); } catch (Exception e) { //what to do if name is wrong return("Ha ocurrido un error"); } objectArray.Add("hardware_reference", parentCategory); JObject profileFields = new JObject(); //foreach element in the formData, let's append it to the jsonData in the profileFields foreach (String key in data.Keys) { profileFields.Add(key, data[key]); } objectArray.Add("profileFields", profileFields); String jsonData = JsonConvert.SerializeObject(objectArray); String auxid = id; id = _hardwareTable.SaveRow(jsonData, id); return("Guardado Correctamente"); } else { return(null); } }
public String saveEmployee(FormCollection formData, HttpPostedFileBase file) { bool access = false; String dataPermissions = Session["Permissions"].ToString(); String dataPermissionsClient = Session["PermissionsClient"].ToString(); bool accessClient = false; access = validatepermissions.getpermissions("employee", "u", dataPermissions); accessClient = validatepermissions.getpermissions("employee", "u", dataPermissionsClient); //if (access == true && accessClient == true) if (true) { if (this.Request.IsAjaxRequest()) { formData = CustomForm.unserialize(formData); //use the method serialize to parse the string into an array String employeeID = (formData["employeeID"] == "null") ? null : formData["employeeID"]; //check insert new or update existing String EmployeeName = ""; JObject employee = new JObject(); //get employee if update if (employeeID != null) { String employeestring = employeetable.GetRow(employeeID); employee = JsonConvert.DeserializeObject <JObject>(employeestring); } /*check when update , employee exist or not*/ if (employeeID != null && (employee == null)) { return("{\"msg\":\"El id especificado no existe\", \"status\":\"error\"}"); } /*The selected emoloyee Id is already in use and is not the employee who has it*/ if (employeeExists(formData["employee"]) == "true" && (employeeID == null || employeetable.get("employee", formData["employee"])[0].GetElement("_id").Value.ToString() != employeeID)) { return("{\"msg\":\"El empleado ya está siendo utilizado\", \"status\":\"error\"}"); } //due that the Employee's id is unique we use it has the image's name, so we store only the extension in the db string ext = null; if (file != null) { ext = file.FileName.Split('.').Last(); //getting the extension } else if (employeeID != null) { try { ext = employee["imgext"].ToString(); } catch (Exception e) { } } //JArray listp = new JArray(); /* Format validations */ if (!Regex.IsMatch(formData["name"], "[A-ZÁÉÍÓÚÑa-záéíóúñ]+( [A-ZÁÉÍÓÚÑa-záéíóúñ]+){0,2}")) { return("{\"msg\":\"Formato incorrecto para: name\", \"status\":\"error\"}"); } else if (!Regex.IsMatch(formData["lastname"], "[A-ZÁÉÍÓÚÑa-záéíóúñ]+( [A-ZÁÉÍÓÚÑa-záéíóúñ]+){0,1}")) { return("{\"msg\":\"Formato incorrecto para: Apellido Paterno\", \"status\":\"error\"}"); } else if (!Regex.IsMatch(formData["motherlastname"], "[A-ZÁÉÍÓÚÑa-záéíóúñ]+( [A-ZÁÉÍÓÚÑa-záéíóúñ]+){0,1}")) { return("{\"msg\":\"Formato incorrecto para: Apellido Materno\", \"status\":\"error\"}"); } else if (!Regex.IsMatch(formData["employee"], "([a-zA-Z0-9-_.]){4,}")) { return("{\"msg\":\"Formato incorrecto para: ID Empleado\", \"status\":\"error\"}"); } ///check selected profile id exist or not /// else if (formData["profileId"] == "null") { return("{\"msg\":\"Elija El perfil\", \"status\":\"error\"}"); } else if (employeeprofileTable.getRow(formData["profileId"]) == null) { return("{\"msg\":\"El perfil especificado no existe\", \"status\":\"error\"}"); } else if (formData["type"] == "null") { return("{\"msg\":\"Elija El Tipo de Empleado\", \"status\":\"error\"}"); } else if (formData["area"] == "null") { return("{\"msg\":\"Elija El Área\", \"status\":\"error\"}"); } else { EmployeeName = formData["employee"]; } /* Format validations */ //Change name representation formData["name"] = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(formData["name"].ToString().ToLower().Trim()); formData["lastname"] = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(formData["lastname"].ToString().ToLower().Trim()); //there are fields that we know that exists so we set them into the json String jsonData = "{'employee':'" + formData["employee"] + "','name':'" + formData["name"].Replace("+", " ") + "','imgext':'" + ext + "','lastname':'" + formData["lastname"].Replace("+", " ") + "','motherlastname':'" + formData["motherlastname"].Replace("+", " ") + "','type':'" + formData["type"] + "','profileId':'" + formData["profileId"] + "','area':'" + formData["area"]; try //trying to set the creator's id { jsonData += "','creatorId':'"; jsonData += this.Session["_id"]; jsonData += "'"; } catch (Exception e) { /*Ignored*/ } //remove the setted data in the json from the formData formData.Remove("employeeID"); formData.Remove("employee"); formData.Remove("name"); formData.Remove("lastname"); formData.Remove("motherlastname"); formData.Remove("type"); formData.Remove("profileId"); formData.Remove("area"); jsonData += ", 'profileFields':{"; //foreach element in the formData, let's append it to the jsonData in the profileFields int cont = 0; foreach (String key in formData.Keys) { jsonData += "'" + key + "':'" + formData[key] + "'"; cont++; if (cont < formData.Keys.Count) { jsonData += ", "; } } jsonData += "}}"; //now that we have the json and we know the data is ok, let's save it string id = employeetable.saveRow(jsonData, employeeID); //Notify this action if (employeeID == null) { Notificate.saveNotification("Employees", "Create", "El empleado '" + EmployeeName + "' ha sido creado"); _logTable.SaveLog(Session["_id"].ToString(), "empleados", "Insert: " + EmployeeName, "Employee", DateTime.Now.ToString()); } else { Notificate.saveNotification("Employees", "Update", "El empleado '" + EmployeeName + "' ha sido modificado"); _logTable.SaveLog(Session["_id"].ToString(), "empleados", "Update: " + EmployeeName, "Employee", DateTime.Now.ToString()); } //TODO:Aqui se guarda la imagen if (file != null) { string relativepath = "\\Uploads\\Images\\"; string absolutepath = Server.MapPath(relativepath); if (!System.IO.Directory.Exists(absolutepath)) { System.IO.Directory.CreateDirectory(absolutepath); } file.SaveAs(absolutepath + "\\" + id + "." + ext); Images resizeImage = new Images(absolutepath + "\\" + id + "." + ext, absolutepath, id + "." + ext); // If image bigger than 1MB, resize to 1024px max if (file.ContentLength > 1024 * 1024) { resizeImage.resizeImage(new System.Drawing.Size(1024, 1024)); } // Create the thumbnail of the image resizeImage.createThumb(); } return("{\"msg\":\"" + id + "\", \"status\":\"success\"}"); //returns the saved user's id } return(null); } else { return(null); } }