public ResultOperation IsValid(FileUploadHtml fileUploadHtml, sysBpmsVariable variable, Guid?entityId, Guid?entitydefid, string currentUserName)
        {
            ResultOperation resultOperation = new ResultOperation();

            if (variable != null && !entityId.HasValue)
            {
                sysBpmsEntityDef entityDef = new EntityDefService(base.UnitOfWork).GetInfo(variable.EntityDefID.Value);
                entitydefid = variable.EntityDefID.Value;
                entityId    = new EntityDefEngine(base.EngineSharedModel, base.UnitOfWork).GetEntityID(entityDef, variable, base.EngineSharedModel.BaseQueryModel);
            }
            Dictionary <Guid, HttpPostedFileBase> files = fileUploadHtml.Value == null ? new Dictionary <Guid, HttpPostedFileBase>() : (((Dictionary <Guid, object>)fileUploadHtml.Value).ToDictionary(c => c.Key.ToGuidObj(), c => c.Value == null ? null : c.Value is HttpPostedFileBase ? (HttpPostedFileBase)c.Value : new HttpPostedFileWrapper((HttpPostedFile)c.Value)));

            if (files.Any())
            {
                foreach (var item in files)
                {
                    ResultOperation result = this.IsValid(entitydefid, entityId, item.Value?.InputStream, item.Value?.FileName, item.Key);
                    if (!result.IsSuccess)
                    {
                        resultOperation.AddError(result.GetErrors());
                    }
                }
            }
            else
            {
                resultOperation = this.IsValid(entitydefid, entityId, null, null, fileUploadHtml.DocumentdefId.ToGuidObjNull().Value);
            }

            return(resultOperation);
        }
 public List <sysBpmsDocument> GetList(Guid?documentDefId, Guid?VariableId, Guid?documentFolderId)
 {
     if (VariableId.HasValue)
     {
         sysBpmsVariable  variable  = new VariableService(base.UnitOfWork).GetInfo(VariableId.Value);
         sysBpmsEntityDef entityDef = new EntityDefService(base.UnitOfWork).GetInfo(variable.EntityDefID.Value);
         Guid?            entityId  = new EntityDefEngine(base.EngineSharedModel, base.UnitOfWork).GetEntityID(entityDef, variable, base.EngineSharedModel.BaseQueryModel);
         if (entityId.HasValue)
         {
             return(new DocumentService(base.UnitOfWork).GetList(documentDefId, variable.EntityDefID, entityId, "", false, documentFolderId, null));
         }
         else
         {
             return(new List <sysBpmsDocument>());
         }
     }
     else
     {
         if (documentDefId.HasValue || documentFolderId.HasValue)
         {
             return(new DocumentService(base.UnitOfWork).GetList(documentDefId, null, null, "", false, documentFolderId, base.EngineSharedModel.CurrentThreadID));
         }
         else
         {
             return(new List <sysBpmsDocument>());
         }
     }
 }
        /// <param name="containerQuery">It is generally used in combosearch which add a parent query that filter table's rows according to query parameter and text field</param>
        /// <param name="includes">It is used in List variable in DataGrid and chart is each item in array is like (Product.Name,Order.Name)</param>
        public DataTable GetEntity(sysBpmsEntityDef entityDef, sysBpmsVariable variable, List <QueryModel> additionalParams, PagingProperties currentPaging, string containerQuery = null, string[] includes = null)
        {
            string columnName    = string.Empty;
            string includesQuery = string.Empty;

            switch ((sysBpmsVariable.e_VarTypeLU)variable.VarTypeLU)
            {
            case sysBpmsVariable.e_VarTypeLU.Integer:
            case sysBpmsVariable.e_VarTypeLU.String:
            case sysBpmsVariable.e_VarTypeLU.Uniqueidentifier:
            case sysBpmsVariable.e_VarTypeLU.Decimal:
            case sysBpmsVariable.e_VarTypeLU.DateTime:
            case sysBpmsVariable.e_VarTypeLU.Boolean:
                columnName = variable.FieldName;
                break;

            case sysBpmsVariable.e_VarTypeLU.List when variable.RelationTypeLU == (int)sysBpmsVariable.e_RelationTypeLU.Entity && includes?.Any() == true:
            case sysBpmsVariable.e_VarTypeLU.Object when includes?.Any() == true:

                EntityDefService entityDefService = new EntityDefService(base.UnitOfWork);

                foreach (var p in entityDef.Properties.Where(c => c.DbType == EntityPropertyModel.e_dbType.Entity && includes.Any(d => d.Contains(c.Name))))
                {
                    string foreingName         = entityDefService.GetInfo(p.RelationToEntityID.Value).FormattedTableName;
                    string includesColumnNames = string.Join(",", includes.Where(d => d.Split('.')[0] == p.Name).Select(c => $"{c.Split('.')[1]} as {p.Name}__{c.Split('.')[1]}"));
                    if (!includesColumnNames.Contains($"{p.Name}__ID"))
                    {
                        includesColumnNames += "," + $"ID as {p.Name}__ID";
                    }

                    includesQuery += $" left join (select {includesColumnNames} from {foreingName}) {foreingName} on {entityDef.FormattedTableName}.{p.Name}={foreingName}.{p.Name}__ID " + Environment.NewLine;
                }
                break;
            }
            columnName = string.IsNullOrWhiteSpace(columnName) ? "*" : columnName;
            string whereClause = VariableEngine.GenerateWhereClause(variable);
            string orderClause = VariableEngine.GenerateOrderClause(variable);

            //get sql query parameter from additionalParams
            List <SqlParameter> queryParams = QueryModel.GetSqlParameter(base.GetAllQueryModels(additionalParams) ?? new List <QueryModel>()).ToList();

            //add variable dependies to whereclause which have relation with current variable.
            this.AddDependencyClause(variable, queryParams, null, ref whereClause, additionalParams);

            string sqlQuery = $" select {columnName} from {entityDef.FormattedTableName} {includesQuery} {whereClause} {orderClause} ";

            //If containerQuery  is not null
            if (!string.IsNullOrWhiteSpace(containerQuery))
            {
                sqlQuery = (sqlQuery.Contains("order") && (!sqlQuery.ToLower().Contains("top") && !sqlQuery.ToLower().Contains("offset"))) ? $"{sqlQuery} OFFSET 0 ROWS " : sqlQuery;
                sqlQuery = string.Format(containerQuery, sqlQuery);
            }

            this.AddDefaultParams(sqlQuery, queryParams);
            this.AddVariableParameters(ref sqlQuery, queryParams);
            queryParams = queryParams.Where(c => sqlQuery.Contains(c.ParameterName)).ToList();

            return(new DataBaseQueryService(this.UnitOfWork).GetBySqlQuery(sqlQuery, true, currentPaging, queryParams.ToArray()));
        }
        /// <summary>
        /// this method save entityDef using dynamic code.
        /// </summary>
        public Tuple <ResultOperation, Guid?> SaveIntoDataBase(VariableModel variableModel)
        {
            ResultOperation     resultOperation = new ResultOperation();
            sysBpmsEntityDef    entityDef       = new EntityDefService(base.UnitOfWork).GetInfo(variableModel.Name);
            List <SqlParameter> columnParams    = this.GetColumsAsParams(entityDef, variableModel.Items.FirstOrDefault().ToList(), (base.EngineSharedModel != null ? new VariableService(base.UnitOfWork).GetInfo(base.EngineSharedModel.CurrentProcessID, base.EngineSharedModel.CurrentApplicationPageID, variableModel.Name) : null));
            //get sql query parameter from additionalParams
            List <SqlParameter> queryParams = QueryModel.GetSqlParameter(base.GetAllQueryModels(null) ?? new List <QueryModel>()).ToList();

            string sqlQueryIsExist = $@"(select top(1) {entityDef.FormattedTableName}.ID from {entityDef.FormattedTableName} where ID='{variableModel["ID"]}' )";

            string sqlInsertQuery = $@"INSERT INTO {entityDef.FormattedTableName}
                                          ({string.Join(",", columnParams.Select(c => c.ParameterName.TrimStart('@')))})
                                    OUTPUT inserted.ID
                                    VALUES
                                          ({string.Join(",", columnParams.Select(c => c.ParameterName))})";

            this.AddDefaultParams((sqlInsertQuery + sqlQueryIsExist), queryParams);
            this.AddVariableParameters(ref sqlInsertQuery, queryParams);
            this.AddVariableParameters(ref sqlQueryIsExist, queryParams);
            queryParams = columnParams.Union(queryParams).Where(c => (sqlInsertQuery + sqlQueryIsExist).Contains(c.ParameterName)).GroupBy(c => c.ParameterName).Select(c => c.FirstOrDefault()).ToList();

            DataTable dataTableIsExist = new DataBaseQueryService(base.UnitOfWork).GetBySqlQuery(sqlQueryIsExist, true, null, queryParams.ToArray());
            Guid?     entityIsExistId  = dataTableIsExist != null && dataTableIsExist.Rows.Count > 0 ? dataTableIsExist.Rows[0][0].ToGuidObj() : (Guid?)null;

            if (entityIsExistId.HasValue)
            {
                string sqlUpdateQuery = $@"update {entityDef.FormattedTableName} set {string.Join(",", columnParams.Select(c => c.ParameterName.TrimStart('@') + "=" + c.ParameterName))} where ID='{entityIsExistId.ToStringObj()}' ";
                //update entity
                new DataBaseQueryService(base.UnitOfWork).ExecuteBySqlQuery(sqlUpdateQuery, true, queryParams.ToArray());
            }
            else
            {
                //insert entity
                this.CheckMandatory(resultOperation, entityDef, columnParams);
                if (resultOperation.IsSuccess)
                {
                    entityIsExistId = new DataBaseQueryService(base.UnitOfWork).ExecuteScalar <Guid>(sqlInsertQuery, true, queryParams.ToArray()).ToGuidObjNull();
                }
            }

            return(new Tuple <ResultOperation, Guid?>(resultOperation, entityIsExistId));
        }
        /// <summary>
        /// this method make a list of variables name and Entity.PropertyName from variables which are object.
        /// </summary>
        public List <ComboTreeModel> GetVariableAsComboTree(Guid?ProcessID, Guid?ApplicationPageID, sysBpmsVariable.e_RelationTypeLU?notRelationTypeLU, string template = "")
        {
            List <ComboTreeModel>  Items     = new List <ComboTreeModel>();
            List <sysBpmsVariable> Variables = new VariableService(this.UnitOfWork).GetList(ProcessID, ApplicationPageID, null, "", null, true, new string[] { nameof(sysBpmsVariable.EntityDef) }).Where(c => (!notRelationTypeLU.HasValue || c.RelationTypeLU != (int)notRelationTypeLU) && c.VarTypeLU != (int)sysBpmsVariable.e_VarTypeLU.List).ToList();

            foreach (sysBpmsVariable item in Variables)
            {
                if (item.VarTypeLU == (int)sysBpmsVariable.e_VarTypeLU.Object)
                {
                    sysBpmsEntityDef entityDef = new EntityDefService(this.UnitOfWork).GetInfo(item.EntityDefID.Value);
                    Items.Add(new ComboTreeModel()
                    {
                        title = item.Name, id = item.Name, state = "closed",
                    });
                    foreach (EntityPropertyModel Property in entityDef.Properties.Where(c => c.IsActive))
                    {
                        Items.LastOrDefault().subs.Add(new ComboTreeModel()
                        {
                            title = item.Name + "." + Property.Name,
                            id    = !string.IsNullOrWhiteSpace(template) ? string.Format(template, (item.Name + "." + Property.Name)) :
                                    (item.Name + "." + Property.Name),
                        });
                    }
                    Items.LastOrDefault().subs.Add(new ComboTreeModel()
                    {
                        title = item.Name + ".ID",
                        id    = !string.IsNullOrWhiteSpace(template) ? string.Format(template, (item.Name + ".ID")) :
                                (item.Name + ".ID"),
                    });
                }
                else
                {
                    Items.Add(new ComboTreeModel()
                    {
                        title = item.Name,
                        id    = !string.IsNullOrWhiteSpace(template) ? string.Format(template, (item.Name)) : item.Name
                    });
                }
            }
            return(Items);
        }
        public ResultOperation SaveFile(FileUploadHtml fileUploadHtml, sysBpmsVariable variable, Guid?entityId, Guid?entitydefid, string captionOf, string currentUserName)
        {
            ResultOperation resultOperation = new ResultOperation();

            if (variable != null && !entityId.HasValue)
            {
                sysBpmsEntityDef entityDef = new EntityDefService(base.UnitOfWork).GetInfo(variable.EntityDefID.Value);
                entitydefid = variable.EntityDefID.Value;
                entityId    = new EntityDefEngine(base.EngineSharedModel, base.UnitOfWork).GetEntityID(entityDef, variable, base.EngineSharedModel.BaseQueryModel);
            }

            Dictionary <Guid, HttpPostedFileBase> files = fileUploadHtml.Value == null ? new Dictionary <Guid, HttpPostedFileBase>() : (((Dictionary <Guid, object>)fileUploadHtml.Value).ToDictionary(c => c.Key.ToGuidObj(), c => c.Value == null ? null : c.Value is HttpPostedFileBase ? (HttpPostedFileBase)c.Value : new HttpPostedFileWrapper((HttpPostedFile)c.Value)));

            foreach (var item in files)
            {
                if (resultOperation.IsSuccess)
                {
                    resultOperation = this.SaveFile(item.Value?.InputStream, item.Value?.FileName, entityId, entitydefid, item.Key, captionOf, !fileUploadHtml.Multiple);
                }
            }

            return(resultOperation);
        }