コード例 #1
0
ファイル: Save.cs プロジェクト: althera2004/OpenFrameworkV2
        /*/// <summary>
         * /// Inserts item data into database
         * /// </summary>
         * /// <param name="itemBuilder">Item instance</param>
         * /// <param name="fromImport">Indicates if insert is from import (not required)</param>
         * /// <returns>Result of action</returns>
         * public static ActionResult Insert(ItemBuilder itemBuilder,long userId, bool fromImport = false)
         * {
         *  return Insert(itemBuilder, Basics.ActualInstance.Config.ConnectionString, userId, fromImport);
         * }*/

        /// <summary>Inserts item data into database</summary>
        /// <param name="itemBuilder">Item instance</param>
        /// <param name="instanceName">String connection to database</param>
        /// <param name="userId">User identifier</param>
        /// <param name="fromImport">Indicates if insert is from import (not required)</param>
        /// <returns>Result of action</returns>
        public static ActionResult Insert(ItemBuilder itemBuilder, string instanceName, long userId, bool fromImport = false)
        {
            if (itemBuilder == null)
            {
                return(ActionResult.NoAction);
            }

            var    res   = ActionResult.NoAction;
            string query = SqlServerWrapper.InsertQuery(itemBuilder, userId);

            if (string.IsNullOrEmpty(query))
            {
                return(ActionResult.NoAction);
            }

            // Prepare code sequence

            /*if (itemBuilder.Definition.Fields.Any(f => !string.IsNullOrEmpty(f.CodeSequence)))
             * {
             *  foreach (ItemField field in itemBuilder.Definition.Fields.Where(f => !string.IsNullOrEmpty(f.CodeSequence)))
             *  {
             *      if (itemBuilder[field.Name] != null)
             *      {
             *          var codeSequence = CodeSequencePersistence.GetByName(itemBuilder.InstanceName, field.CodeSequence);
             *          itemBuilder[field.Name] = codeSequence.SetActualValue(userId, connectionString, itemBuilder.InstanceName);
             *      }
             *  }
             * }*/

            using (var cmd = new SqlCommand(query))
            {
                var instance = CustomerFramework.Load(instanceName);
                using (var cnn = new SqlConnection(instance.Config.ConnectionString))
                {
                    cmd.Connection = cnn;
                    try
                    {
                        cmd.Connection.Open();

                        // ExecuteScalar devuelve el Id del último insertado
                        var id = cmd.ExecuteScalar();

                        // PersistentData
                        if (itemBuilder.ContainsKey("Id"))
                        {
                            itemBuilder["Id"] = id;
                        }
                        else
                        {
                            itemBuilder.Add("Id", id);
                        }

                        itemBuilder["Active"] = true;
                        res.SetSuccess();
                        res.MessageError = itemBuilder.ItemName;
                        res.ReturnValue  = string.Format(CultureInfo.InvariantCulture, "INSERT|{0}", id);
                        ActionLog.Trace(itemBuilder.ItemName + "_", itemBuilder.Id, itemBuilder.Json, itemBuilder.InstanceName, instanceName);
                    }
                    catch (Exception ex)
                    {
                        ExceptionManager.LogException(ex as Exception, "Insert:" + query);
                        res.SetFail(ex);
                    }
                    finally
                    {
                        if (cmd.Connection.State != ConnectionState.Closed)
                        {
                            cmd.Connection.Close();
                        }
                    }
                }
            }

            return(res);
        }
コード例 #2
0
    private DataLine Parse(IRow data, int index, ItemDefinition definition, List <string> primaryKeys)
    {
        var d0  = DateTime.Now;
        var res = new DataLine()
        {
            Line = index, Data = string.Empty
        };

        if (data.Cells.Count > this.typeIndex.Count)
        {
            this.errors.Add(new Error()
            {
                Linea     = index,
                ErrorType = "Data",
                Message   = "El número de celdas no es correcto"
            });
        }
        else
        {
            var message  = new StringBuilder("[");
            int contCell = 0;
            var itemData = new ItemBuilder(this.Item.ItemName, definition, this.instance.Name);
            foreach (var field in itemFields)
            {
                var    cell      = data.GetCell(contCell);
                string cellValue = "null";
                string testValue = string.Empty;
                if (cell != null)
                {
                    cellValue = GetCellValueForJson(this.typeIndex[contCell], cell, field.Length);
                    testValue = cellValue;

                    // GES-129 Eliminar comillas del inicio y final
                    if (testValue.StartsWith("\"", StringComparison.OrdinalIgnoreCase))
                    {
                        testValue = testValue.Substring(1);
                    }

                    if (testValue.EndsWith("\"", StringComparison.OrdinalIgnoreCase))
                    {
                        testValue = testValue.Substring(0, testValue.Length - 1);
                    }

                    // GES-238 los mails y urls deben cumplir el formato
                    if (field.DataType == FieldDataType.Email)
                    {
                        if (field.Required || !string.IsNullOrEmpty(testValue))
                        {
                            if (!Basics.EmailIsValid(testValue))
                            {
                                this.errors.Add(new Error()
                                {
                                    Linea     = index,
                                    ErrorType = "Data",
                                    Message   = string.Format(
                                        CultureInfo.InvariantCulture,
                                        "El email del campo {0} no es valido ({1}).",
                                        field.Label,
                                        testValue)
                                });
                            }
                        }
                    }

                    if (field.DataType == FieldDataType.Url)
                    {
                        if (field.Required || !string.IsNullOrEmpty(testValue))
                        {
                            Uri  uriResult;
                            bool result = Uri.TryCreate(testValue, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
                            if (!result)
                            {
                                testValue = "http://" + testValue;
                                result    = Uri.TryCreate(testValue, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
                                if (!result)
                                {
                                    this.errors.Add(new Error()
                                    {
                                        Linea     = index,
                                        ErrorType = "Data",
                                        Message   = string.Format(
                                            CultureInfo.InvariantCulture,
                                            "La dirección URL del campo {0} no es valida ({1}).",
                                            field.Label,
                                            testValue)
                                    });
                                }
                            }
                        }
                    }

                    if (this.typeIndex[contCell] == FieldDataType.Text || this.typeIndex[contCell] == FieldDataType.Textarea)
                    {
                        if (field.Length.HasValue)
                        {
                            if (testValue.Length > field.Length)
                            {
                                this.errors.Add(new Error()
                                {
                                    Linea     = index,
                                    ErrorType = "Data",
                                    Message   = string.Format(
                                        CultureInfo.InvariantCulture,
                                        "El campo {0} tiene una longitud superior a {1}.",
                                        field.Label,
                                        field.Length.Value)
                                });
                            }
                        }
                    }
                    //// END GES-129

                    // Sólo se comprueba el FK si el campo está informado
                    if (!string.IsNullOrEmpty(testValue))
                    {
                        // GES-130 Se comprueba que si es un foreignlist haya valor en la tabla referenciada

                        /*if (definition.ForeignValues.Any(fv => fv.LocalName == field.Name))
                         * {
                         *  ForeignList fl = definition.ForeignValues.Where(fv =>  fv.LocalName.Equals(field.Name, StringComparison.OrdinalIgnoreCase)).First();
                         *  if (DataPersistence.GetAllByField(Item.InstanceName, fl.ItemName, fl.ImportReference, testValue).Count == 0)
                         *  {
                         *      errors.Add(new Error()
                         *      {
                         *          ErrorType = "Data",
                         *          Linea = index,
                         *          Message = string.Format(
                         *              CultureInfo.InvariantCulture,
                         *              "El campo <strong>{0}</strong> no encuentra referencia sobre el valor &quot;<strong>{1}</strong>&quot;",
                         *              field.Label,
                         *              testValue)
                         *      });
                         *  }
                         * }*/
                    }

                    if (cellValue.Equals("\"FixedList\"", StringComparison.OrdinalIgnoreCase))
                    {
                        string dataCell  = cell.StringCellValue;
                        var    fixedItem = new FixedListItem();// DataPersistence.FixedListItemGetById(itemData.InstanceName, field.FixedListId, dataCell);

                        if (!string.IsNullOrEmpty(cell.StringCellValue) && fixedItem == null)
                        {
                            errors.Add(new Error()
                            {
                                ErrorType = "Data",
                                Linea     = index,
                                Message   = string.Format(
                                    CultureInfo.InvariantCulture,
                                    "El campo <strong>{0}</strong> tiene el valor &quot;<strong>{1}</strong>&quot; que no está en la lista de valores aceptados",
                                    field.Label,
                                    dataCell)
                            });
                        }
                        else
                        {
                            itemData[field.Name] = fixedItem.Id;
                            cellValue            = string.Format(CultureInfo.InvariantCulture, @"""{0}""", fixedItem.Description);
                            testValue            = cellValue.Replace("\"", string.Empty);
                        }
                    }
                    else
                    {
                        if (this.typeIndex[contCell] == FieldDataType.ImageGallery)
                        {
                            itemData.Add(field.Name, string.Empty);
                            testValue = string.Empty;
                        }
                        else if (field.DataType == FieldDataType.Boolean || field.DataType == FieldDataType.NullableBoolean)
                        {
                            if (!string.IsNullOrEmpty(testValue))
                            {
                                itemData.Add(field.Name, Convert.ToBoolean(testValue));
                            }
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(testValue))
                            {
                                itemData.Add(field.Name, testValue.Replace(@"\""", @""""));
                            }
                            else
                            {
                                itemData.Add(field.Name, cellValue);
                            }
                        }
                    }
                }

                message.AppendFormat(CultureInfo.InvariantCulture, @"{0}""{1}""", contCell > 0 ? "," : string.Empty, testValue);
                contCell++;
            }

            // Juan Castilla - Comprobar que la PK no esté ya en la carga
            string primaryKeyData = itemData.PrimaryKeyData;
            if (primaryKeys.Contains(primaryKeyData))
            {
                this.errors.Add(new Error()
                {
                    Linea     = index,
                    ErrorType = "Data",
                    Message   = "La clave ya aparece en otro registro de esta carga"
                });
            }
            else
            {
                primaryKeys.Add(primaryKeyData);
            }

            // Cofirmar que los campos obligatorios están rellenados
            foreach (var field in Item.Definition.Fields.Where(f => f.Required))
            {
                if (field.Name != "Id" && field.Name != "CompanyId")
                {
                    if (!itemData.ContainsKey(field.Name))
                    {
                        this.errors.Add(new Error()
                        {
                            Linea     = index,
                            ErrorType = "Data",
                            Message   = string.Format(CultureInfo.InvariantCulture, "El campo {0} es obligatorio", field.Label)
                        });
                    }
                    else if (itemData[field.Name] == null)
                    {
                        this.errors.Add(new Error()
                        {
                            Linea     = index,
                            ErrorType = "Data",
                            Message   = "El campo " + field.Label + " es obligatorio"
                        });
                    }
                }
            }

            if (itemData.Definition.ItemRules.Count > 0)
            {
                foreach (var rule in itemData.Definition.ItemRules)
                {
                    var complains = new SpecialRule(itemData, rule).Complains;
                    if (!complains.Success)
                    {
                        this.errors.Add(new Error()
                        {
                            Linea     = index,
                            ErrorType = "Data",
                            Message   = complains.MessageError
                        });
                    }
                }
            }

            message.Append("]");

            if (res.Data.Count() < 21)
            {
                res.Data = message.ToString();
            }

            this.dataFile.Add(res);
            this.itemsReaded.Add(itemData);
        }

        return(res);
    }