Esempio n. 1
0
        EntityCommandModel IGetModAddDelEntityService.AddEntity(EntityCommandModel entity)
        {
            var newEntity = new Data.Entity()
            {
                Name = entity.Name, EntityTypeId = entity.EntityTypeId, IsValid = true
            };

            var dbEntity = _unitWork.GetRepository <Data.Entity>().Get(x => x.Name == entity.Name);

            if (dbEntity != null)
            {
                // Duplicate entity found/ Entity exist
            }
            else
            {
                try
                {
                    _unitWork.GetRepository <Data.Entity>().Insert(newEntity);
                    _unitWork.Save();
                }
                catch
                {
                    // Database operation exception
                }
            }
            return(GetEntityById(newEntity.Id));
        }
        private DataClass TransformToDataClass(Data.Entity entityConfig, CodeGenerationModel genModel, EntityClass entityClass)
        {
            var data = new DataClass
            {
                Name               = $"{entityClass.Name}Data",
                Namespace          = $"{genModel.BaseNamespace}.Business.Data",
                Partial            = entityConfig.PartialData,
                PrivateConstructor = entityConfig.PrivateDataConstructor
            };

            data.Usings.Add("System");
            data.Usings.Add("System.Threading.Tasks");
            data.Usings.Add(entityClass.Namespace);

            if (entityConfig.Operations != null)
            {
                data.Operations = entityConfig.Operations.Select(o =>
                {
                    var op = CreateOperation <OperationModelBase>(o, entityClass);

                    if (op.IsGetColl && o.PagingArgs)
                    {
                        data.Usings.Add("Beef.Entities");
                        op.Parameters.Add(new OperationParameter {
                            Name = "pagingArgs", Type = "PagingArgs?"
                        });
                    }

                    return(op);
                }).ToList();
            }

            return(data);
        }
Esempio n. 3
0
 void IGetModAddDelEntityService.DeleteEntity(int id)
 {
     Data.Entity currentEntity = null;
     try
     {
         currentEntity = _unitWork.GetRepository <Data.Entity>().Get(x => x.Id == id).SingleOrDefault();
     }
     catch (Exception ex)
     {
         if (ex is InvalidOperationException)
         {
             throw new InvalidOperationException(); // Duplicate entity found
         }
         throw;
     }
     if (currentEntity == null)
     {
         // Entity not found
     }
     else
     {
         try
         {
             _unitWork.GetRepository <Data.Entity>().Delete(currentEntity);
             _unitWork.Save();
         }
         catch
         {
             // Database operation exception
         }
     }
 }
 public IEntity AppResources()
 {
     var vals = new Dictionary<string, object>()
     {
         {"Title", "Resources"},
         {"Greeting", "Hello there!"},
         {"Introduction", "Welcome to this"}
     };
     var ent = new Data.Entity(305200, "AppResources", vals, "Title");
     return ent;
 }
        public IEntity AppSettings()
        {
            var vals = new Dictionary<string, object>()
            {
                {"Title", "App Settings"},
                {"DefaultCategoryName", DefaultCategory},
                {"MaxPictures", MaxPictures},
                {"PicsPerRow", "3"}
            };

            var ent = new Data.Entity(305200, "AppSettings", vals, "Title");
            return ent;
        }
        private ControllerClass TransformToControllerClass(Data.Entity entityConfig, CodeGenerationModel genModel, EntityClass entityClass, ManagerInterface managerInterface)
        {
            var data = new ControllerClass();

            data.Name               = $"{entityClass.Name}Controller";
            data.Namespace          = $"{genModel.BaseNamespace}.Api.Controllers";
            data.Partial            = entityConfig.PartialWebApi;
            data.PrivateConstructor = entityConfig.PrivateWebApiConstructor;

            data.WebApiRoutePrefix = entityConfig.WebApiRoutePrefix;

            data.Usings.Add("Microsoft.AspNetCore.Mvc");
            data.Usings.Add("System");
            data.Usings.Add("System.Net");
            data.Usings.Add("Beef");
            data.Usings.Add("Beef.AspNetCore.WebApi");
            data.Usings.Add(entityClass.Namespace);
            data.Usings.Add(managerInterface.Namespace);

            data.Operations = entityConfig.Operations.Select(o =>
            {
                var op         = CreateOperation <ControllerOperationModel>(o, entityClass);
                op.WebApiRoute = o.WebApiRoute;

                if (op.IsGet || op.IsDelete)
                {
                    op.WebApiRoute = op.WebApiRoute ?? String.Join('/', op.Parameters.Select(o => $"{{{o.Name}}}"));
                }

                if (op.IsGetColl)
                {
                    op.WebApiRoute   = op.WebApiRoute ?? "";
                    op.HasPagingArgs = o.PagingArgs;
                }

                if (op.IsUpdate)
                {
                    op.Parameters.AddRange(entityClass.Properties.Where(o => o.UnqiueKey).Select(o => new OperationParameter {
                        Name = o.Name.ToCamelCase(), Type = o.Type, EntityProperty = o.Name
                    }));
                    op.WebApiRoute = op.WebApiRoute ?? String.Join('/', op.Parameters.Skip(1).Select(o => $"{{{o.Name}}}"));
                }

                return(op);
            }).ToList();

            return(data);
        }
        private Entity TransformToEntityModel(CodeGenerationModel genModel, Data.Entity entityConfig)
        {
            var model = new Entity
            {
                Name = entityConfig.Name
            };

            if (entityConfig.ExcludeEntity == false)
            {
                model.EntityClass = TransformToEntityClass(entityConfig, genModel);
            }

            if (entityConfig.Operations != null && entityConfig.Operations.Count > 0 && entityConfig.ExcludeAll == false)
            {
                if (entityConfig.ExcludeIData == false)
                {
                    model.DataInterface = TransformToDataInterface(entityConfig, genModel, model.EntityClass);
                }
                if (entityConfig.ExcludeData == false)
                {
                    model.DataClass = TransformToDataClass(entityConfig, genModel, model.EntityClass);
                }
                if (entityConfig.ExcludeIDataSvc == false)
                {
                    model.DataServiceInterface = TransformToDataServiceInterface(entityConfig, genModel, model.EntityClass);
                }
                if (entityConfig.ExcludeDataSvc == false)
                {
                    model.DataServiceClass = TransformToDataServiceClass(entityConfig, genModel, model.EntityClass, model.DataInterface);
                }
                if (entityConfig.ExcludeIManager == false)
                {
                    model.ManagerInterface = TransformToManagerInterface(entityConfig, genModel, model.EntityClass);
                }
                if (entityConfig.ExcludeManager == false)
                {
                    model.Manager = TransformToManagerClass(entityConfig, genModel, model.EntityClass, model.DataServiceInterface);
                }
                if (entityConfig.ExcludeWebApi == false)
                {
                    model.ControllerClass   = TransformToControllerClass(entityConfig, genModel, model.EntityClass, model.ManagerInterface);
                    model.ServiceAgentClass = TransformToServiceAgentClass(entityConfig, genModel, model.EntityClass, model.ControllerClass);
                }
            }

            return(model);
        }
        private ManagerClass TransformToManagerClass(Data.Entity entityConfig, CodeGenerationModel genModel, EntityClass entityClass, DataServiceInterface dataServiceInterface)
        {
            var data = new ManagerClass
            {
                Name               = $"{entityClass.Name}Manager",
                Namespace          = $"{genModel.BaseNamespace}.Business",
                Partial            = entityConfig.PartialManager,
                PrivateConstructor = entityConfig.PrivateManagerConstructor
            };

            data.Usings.Add("Beef");
            data.Usings.Add("Beef.Business");
            data.Usings.Add("Beef.Entities");
            data.Usings.Add("Beef.Validation");
            data.Usings.Add("System");
            data.Usings.Add("System.Threading.Tasks");
            data.Usings.Add(entityClass.Namespace);
            data.Usings.Add(dataServiceInterface.Namespace);

            if (entityConfig.Operations != null)
            {
                data.Operations = entityConfig.Operations.Select(o =>
                {
                    var op = CreateOperation <OperationModelBase>(o, entityClass);

                    if (op.IsGetColl && o.PagingArgs)
                    {
                        op.Parameters.Add(new OperationParameter {
                            Name = "pagingArgs", Type = "PagingArgs?"
                        });
                    }

                    return(op);
                }).ToList();
            }

            if (data.Operations.SelectMany(o => o.Parameters ?? new List <OperationParameter>()).Any(o => o.Validator != null))
            {
                data.Usings.Add($"{data.Namespace}.Validation");
            }

            return(data);
        }
        private ManagerInterface TransformToManagerInterface(Data.Entity entityConfig, CodeGenerationModel genModel, EntityClass entityClass)
        {
            var data = new ManagerInterface
            {
                Name      = $"I{entityClass.Name}Manager",
                Namespace = $"{genModel.BaseNamespace}.Business"
            };

            data.Usings.Add("System");
            data.Usings.Add("System.Threading.Tasks");
            data.Usings.Add(entityClass.Namespace);

            if (entityConfig.Operations?.Any(o => o.PagingArgs) == true)
            {
                data.Usings.Add("Beef.Entities");
            }

            return(data);
        }
        private DataServiceClass TransformToDataServiceClass(Data.Entity entityConfig, CodeGenerationModel genModel, EntityClass entityClass, DataInterface dataInterface)
        {
            var data = new DataServiceClass
            {
                Name               = $"{entityClass.Name}DataSvc",
                Namespace          = $"{genModel.BaseNamespace}.Business.DataSvc",
                HasCaching         = entityConfig.DataSvcCaching,
                Partial            = entityConfig.PartialDataSvc,
                PrivateConstructor = entityConfig.PrivateDataSvcConstructor
            };

            data.Usings.Add("Beef");
            data.Usings.Add("Beef.Business");
            data.Usings.Add("Beef.Entities");
            data.Usings.Add("System");
            data.Usings.Add("System.Threading.Tasks");
            data.Usings.Add(entityClass.Namespace);
            data.Usings.Add(dataInterface.Namespace);

            if (entityConfig.Operations != null)
            {
                data.Operations = entityConfig.Operations.Select(o =>
                {
                    var op          = CreateOperation <DataServiceOperationModel>(o, entityClass);
                    op.EventSubject = entityClass.Name;
                    op.EventAction  = o.EventPublish ?? entityConfig.EventPublish ?? true ? (op.IsCreate ? "Created" : op.IsUpdate ? "Updated" : op.IsDelete ? "Deleted" : null) : null;

                    if (op.IsGetColl && o.PagingArgs)
                    {
                        op.Parameters.Add(new OperationParameter {
                            Name = "pagingArgs", Type = "PagingArgs?"
                        });
                    }

                    return(op);
                }).ToList();
            }

            return(data);
        }
Esempio n. 11
0
        EntityCommandModel IGetModAddDelEntityService.ModifyEntity(EntityCommandModel entity)
        {
            Data.Entity currentEntity = null;
            try
            {
                currentEntity = _unitWork.GetRepository <Data.Entity>().Get(x => x.Id == entity.Id).SingleOrDefault();
            }
            catch (Exception ex)
            {
                if (ex is InvalidOperationException)
                {
                    throw new InvalidOperationException(); // Duplicate entity found
                }
                throw;
            }
            if (currentEntity == null)
            {
                // Entity not found
            }
            else
            {
                currentEntity.Name         = entity.Name;
                currentEntity.EntityTypeId = entity.EntityTypeId;

                try
                {
                    _unitWork.GetRepository <Data.Entity>().Update(currentEntity);
                    _unitWork.Save();
                }
                catch
                {
                    // Database operation exception
                }
            }
            return(GetEntityById(currentEntity.Id));
        }
        private ServiceAgentClass TransformToServiceAgentClass(Data.Entity entityConfig, CodeGenerationModel genModel, EntityClass entityClass, ControllerClass controllerClass)
        {
            var data = new ServiceAgentClass();

            data.Name               = $"{entityClass.Name}ServiceAgent";
            data.Namespace          = $"{genModel.BaseNamespace}.Common.ServiceAgents";
            data.Partial            = false;
            data.PrivateConstructor = false;

            data.Usings.Add("Beef.WebApi");
            data.Usings.Add(entityClass.Namespace);
            data.Usings.Add("Microsoft.Extensions.Options");
            data.Usings.Add("System");
            data.Usings.Add("System.Threading.Tasks");

            data.Operations = entityConfig.Operations.Select(o =>
            {
                var op = CreateOperation <ControllerOperationModel>(o, entityClass);

                var webOp        = controllerClass.Operations.First(w => w.Name == op.Name);
                op.WebApiRoute   = string.Join("/", new string[] { controllerClass.WebApiRoutePrefix, webOp.WebApiRoute }.Where(o => o != null));
                op.HasPagingArgs = webOp.HasPagingArgs;

                if (op.IsGetColl && o.PagingArgs)
                {
                    op.Parameters.Add(new OperationParameter {
                        Name = "pagingArgs", Type = "PagingArgs?"
                    });
                    data.Usings.Add("Beef.Entities");
                }

                return(op);
            }).ToList();

            return(data);
        }
Esempio n. 13
0
        //private IDictionary<int, IEntity> GetEntities()
        //{
        //    return GetList().ToDictionary(e => e.EntityId, e => e);
        //}
        private IEnumerable<IEntity> GetList()
        {
            EnsureConfigurationIsLoaded();

            // Check if SQL contains forbidden terms
            if(ForbiddenTermsInSelect.IsMatch(SelectCommand))
                throw new System.InvalidOperationException("Found forbidden words in the select-command. Cannot continue.");

            var list = new List<IEntity>(); // Dictionary<int, IEntity>();

            // Load ConnectionString by Name (if specified)
            if (!string.IsNullOrEmpty(ConnectionStringName) && (string.IsNullOrEmpty(ConnectionString) || ConnectionString == ConnectionStringDefault))
                ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString;

            using (var connection = new SqlConnection(ConnectionString))
            {
                var command = new SqlCommand(SelectCommand, connection);

                // Add all items in Configuration starting with an @, as this should be an SQL parameter
                foreach (var sqlParameter in Configuration.Where(k => k.Key.StartsWith("@")))
                    command.Parameters.AddWithValue(sqlParameter.Key, sqlParameter.Value);

                connection.Open();
                var reader = command.ExecuteReader();

                try
                {
                    #region Get the SQL Column List and validate it
                    var columNames = new string[reader.FieldCount];
                    for (var i = 0; i < reader.FieldCount; i++)
                        columNames[i] = reader.GetName(i);

                    if (!columNames.Contains(EntityIdField))
                        throw new Exception(string.Format("SQL Result doesn't contain an EntityId Column with Name \"{0}\". Ideally use something like Select ID As EntityId...", EntityIdField));
                    if (!columNames.Contains(TitleField))
                        throw new Exception(string.Format("SQL Result doesn't contain an EntityTitle Column with Name \"{0}\". Ideally use something like Select FullName As EntityTitle...", TitleField));
                    #endregion

                    #region Read all Rows from SQL Server
                    while (reader.Read())
                    {
                        var entityId = Convert.ToInt32(reader[EntityIdField]);
                        var values = columNames.Where(c => c != EntityIdField).ToDictionary(c => c, c => reader[c]);
                        var entity = new Data.Entity(entityId, ContentType, values, TitleField);
                        list.Add(entity);
                        //_entities.Add(entityId, entity);
                    }
                    #endregion
                }
                finally
                {
                    reader.Close();
                }
            }

            return list;
        }
        public void Wildcard(WebRequest request, WebResponse response, string name)
        {
            var wddEntity = UMC.Data.Database.Instance().ObjectEntity <UMC.Data.Entities.Wildcard>();
            var wdk       = wddEntity.Where.And().Equal(new Data.Entities.Wildcard {
                WildcardKey = name
            }).Entities.Single();

            var auths = new List <UMC.Security.Authorize>();

            if (wdk != null)
            {
                var data = new Data.Entity <Data.Entities.Wildcard, List <Security.Authorize> >(wdk, wdk.Authorizes);

                auths.AddRange(data.Config);
            }
            var Type = this.AsyncDialog("WType", gg =>
            {
                var form = request.SendValues ?? new UMC.Web.WebMeta();
                if (form.ContainsKey("limit") == false)
                {
                    this.Context.Send(new UISectionBuilder(request.Model, request.Command, new WebMeta(request.Arguments.GetDictionary()))
                                      .RefreshEvent("Wildcard")
                                      .Builder(), true);
                }
                var ui = UMC.Web.UISection.Create(new UITitle("权限设置"));
                ui.AddCell('\uf084', "标识", name);


                var ui3   = ui.NewSection().AddCell('\uf007', "许可用户", "", new Web.UIClick(new WebMeta(request.Arguments.GetDictionary()).Put(gg, "User")).Send(request.Model, request.Command));
                var users = auths.FindAll(g => g.Type == Security.AuthorizeType.UserAllow);
                var uids  = new List <String>();
                foreach (var u in users)
                {
                    uids.Add(u.Value);
                }

                var dusers = UMC.Security.Membership.Instance().Identity(uids.ToArray());


                foreach (var u in users)
                {
                    var text = u.Value;
                    var u1   = dusers.Find(d => d.Name == u.Value);
                    if (u1 != null)
                    {
                        text = u1.Alias;
                    }
                    var cell = UICell.Create("Cell", new WebMeta().Put("value", u.Value).Put("text", text));//.Put("Icon", '\uf007'));

                    ui3.Delete(cell, new UIEventText().Click(new Web.UIClick(new WebMeta(request.Arguments.GetDictionary()).Put(gg, u.Value)).Send(request.Model, request.Command)));
                }
                if (users.Count == 0)
                {
                    ui3.Add("Desc", new UMC.Web.WebMeta().Put("desc", "未设置许可用户").Put("icon", "\uEA05"), new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"),
                            new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));//.Name
                }

                var ui2 = ui.NewSection().AddCell('\uf0c0', "许可角色", "", new Web.UIClick(new WebMeta(request.Arguments.GetDictionary()).Put(gg, "Role")).Send(request.Model, request.Command));

                var roles = auths.FindAll(g => g.Type == Security.AuthorizeType.RoleAllow);

                foreach (var u in roles)
                {
                    var cell = UICell.Create("Cell", new WebMeta().Put("text", u.Value));//.Put("Icon", '\uf0c0'));

                    ui2.Delete(cell, new UIEventText().Click(new Web.UIClick(new WebMeta(request.Arguments.GetDictionary()).Put(gg, u.Value)).Send(request.Model, request.Command)));
                }
                if (roles.Count == 0)
                {
                    ui2.Add("Desc", new UMC.Web.WebMeta().Put("desc", "未设置许可角色").Put("icon", "\uEA05"), new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"), new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));//.Name
                }
                response.Redirect(ui);
                return(this.DialogValue("none"));
            });

            switch (Type)
            {
            case "Role":
                var role = this.AsyncDialog("SelectRole", request.Model, "SelectRole");
                auths.RemoveAll(k => String.Equals(k.Value, role));
                auths.Add(new Security.Authorize {
                    Type = UMC.Security.AuthorizeType.RoleAllow, Value = role
                });
                wddEntity.IFF(e => e.Update(new Data.Entities.Wildcard {
                    Authorizes = UMC.Data.JSON.Serialize(auths)
                }) == 0
                              , e => e.Insert(new Data.Entities.Wildcard {
                    WildcardKey = name, Authorizes = UMC.Data.JSON.Serialize(auths)
                }));
                this.Context.Send("Wildcard", true);
                break;

            case "User":

                var user = this.AsyncDialog("SelectUser", request.Model, "SelectUser");
                auths.RemoveAll(k => String.Equals(k.Value, user));
                auths.Add(new Security.Authorize {
                    Type = UMC.Security.AuthorizeType.UserAllow, Value = user
                });
                wddEntity.IFF(e => e.Update(new Data.Entities.Wildcard {
                    Authorizes = UMC.Data.JSON.Serialize(auths)
                }) == 0
                              , e => e.Insert(new Data.Entities.Wildcard {
                    WildcardKey = name, Authorizes = UMC.Data.JSON.Serialize(auths)
                }));
                this.Context.Send("Wildcard", true);
                break;

            default:
                var a = auths.Find(k => String.Equals(Type, k.Value));
                if (a != null)
                {
                    auths.Remove(a);
                    wddEntity.Update(new Data.Entities.Wildcard {
                        Authorizes = UMC.Data.JSON.Serialize(auths)
                    });
                    if (auths.Exists(k => k.Type == a.Type) == false)
                    {
                        this.Context.Send("Wildcard", true);
                    }
                }
                break;
            }
            //var acc =
        }
Esempio n. 15
0
        public static Entity LoadXml(XmlNode node)
        {
            Entity ent = null;

            if (node.Name == "Entity")
            {
                ent = new Data.Entity();
                if (node.Attributes["type"] != null)
                {
                    ent = (Entity)Utilities.Reflection.newType(node.Attributes["type"].Value);
                }
                foreach (XmlNode cNode in node.ChildNodes)
                {
                    bool val = false;
                    switch (cNode.Name)
                    {
                    case "SaveAuthGroups":
                        ent.SaveAuthGroups.Clear();
                        foreach (XmlNode child in cNode.ChildNodes)
                        {
                            ent.SaveAuthGroups.Add(child.InnerText);
                        }
                        break;

                    case "SaveAuth":
                        val = false;
                        bool.TryParse(cNode.InnerText, out val);
                        ent.SaveAuth = val;
                        break;

                    case "SaveVisible":
                        val = false;
                        bool.TryParse(cNode.InnerText, out val);
                        ent.SaveVisible = val;
                        break;

                    case "GetAuthGroups":
                        ent.GetAuthGroups.Clear();
                        foreach (XmlNode child in cNode.ChildNodes)
                        {
                            ent.GetAuthGroups.Add(child.InnerText);
                        }
                        break;

                    case "GetAuth":
                        val = false;
                        bool.TryParse(cNode.InnerText, out val);
                        ent.GetAuth = val;
                        break;

                    case "GetVisible":
                        val = false;
                        bool.TryParse(cNode.InnerText, out val);
                        ent.GetVisible = val;
                        break;

                    case "Description":
                        ent.Description = cNode.InnerText;
                        break;

                    case "Name":
                        ent.Name = cNode.InnerText;
                        break;
                    }
                }
            }
            return(ent);
        }
        /// <summary>Get Data to populate ICache</summary>
        /// <param name="entityIds">null or a List of EntitiIds</param>
        /// <param name="appId">AppId (can be different than the appId on current context (e.g. if something is needed from the default appId, like MetaData)</param>
        /// <param name="source">DataSource to get child entities</param>
        /// <param name="entitiesOnly">If only the CachItem.Entities is needed, this can be set to true to imporove performance</param>
        /// <returns>Item1: EntityModels, Item2: all ContentTypes, Item3: Assignment Object Types</returns>
        internal AppDataPackage GetAppDataPackage(int[] entityIds, int appId, IDeferredEntitiesList source, bool entitiesOnly = false)
        {
            var contentTypes = GetEavContentTypes(appId);

            var metadataForGuid = new Dictionary<int, Dictionary<Guid, IEnumerable<IEntity>>>();
            var metadataForNumber = new Dictionary<int, Dictionary<int, IEnumerable<IEntity>>>();
            var metadataForString = new Dictionary<int, Dictionary<string, IEnumerable<IEntity>>>();

            var relationships = new List<EntityRelationshipItem>();

            #region Prepare & Extend EntityIds
            if (entityIds == null)
                entityIds = new int[0];

            var filterByEntityIds = entityIds.Any();

            // Ensure published Versions of Drafts are also loaded (if filtered by EntityId, otherwise all Entities from the app are loaded anyway)
            if (filterByEntityIds)
                entityIds = entityIds.Union(from e in Context.SqlDb.Entities
                                            where e.PublishedEntityId.HasValue && !e.IsPublished && entityIds.Contains(e.EntityID) && !entityIds.Contains(e.PublishedEntityId.Value) && e.ChangeLogDeleted == null
                                            select e.PublishedEntityId.Value).ToArray();
            #endregion

            #region Get Entities with Attribute-Values from Database

            var entitiesWithAandVfromDb = from e in Context.SqlDb.Entities
                                 where
                                     !e.ChangeLogIDDeleted.HasValue &&
                                     e.Set.AppID == appId &&
                                     e.Set.ChangeLogIDDeleted == null &&
                                     (	// filter by EntityIds (if set)
                                         !filterByEntityIds ||
                                         entityIds.Contains(e.EntityID) ||
                                         (e.PublishedEntityId.HasValue && entityIds.Contains(e.PublishedEntityId.Value))	// also load Drafts
                                         )
                                 orderby
                                     e.EntityID	// guarantees Published appear before draft
                                 select new
                                 {
                                     e.EntityID,
                                     e.EntityGUID,
                                     e.AttributeSetID,
                                     Metadata = new Metadata
                                     {
                                         TargetType = e.AssignmentObjectTypeID,
                                         KeyGuid = e.KeyGuid,
                                         KeyNumber = e.KeyNumber,
                                         KeyString = e.KeyString
                                     },
                                     e.IsPublished,
                                     e.PublishedEntityId,
                                     e.Owner, // new 2016-03-01
                                     Modified = e.ChangeLogModified.Timestamp,
                                     RelatedEntities = from r in e.EntityParentRelationships
                                                       group r by r.AttributeID
                                                           into rg
                                                           select new
                                                           {
                                                               AttributeID = rg.Key,
                                                               Childs = rg.OrderBy(c => c.SortOrder).Select(c => c.ChildEntityID)
                                                           },
                                     Attributes = from v in e.Values
                                                  where !v.ChangeLogIDDeleted.HasValue
                                                  group v by v.AttributeID
                                                      into vg
                                                      select new
                                                      {
                                                          AttributeID = vg.Key,
                                                          Values = from v2 in vg
                                                                   orderby v2.ChangeLogIDCreated
                                                                   select new
                                                                   {
                                                                       v2.ValueID,
                                                                       v2.Value,
                                                                       Languages = from l in v2.ValuesDimensions
                                                                                   select new Data.Dimension
                                                                                   {
                                                                                       DimensionId = l.DimensionID,
                                                                                       ReadOnly = l.ReadOnly,
                                                                                       Key = l.Dimension.ExternalKey.ToLower()
                                                                                   },
                                                                       v2.ChangeLogIDCreated
                                                                   }
                                                      }
                                 };
            #endregion

            #region Build EntityModels
            var entities = new Dictionary<int, IEntity>();
            var entList = new List<IEntity>();

            foreach (var e in entitiesWithAandVfromDb)
            {
                var contentType = (ContentType)contentTypes[e.AttributeSetID];
                var newEntity = new Data.Entity(e.EntityGUID, e.EntityID, e.EntityID, e.Metadata /* e.AssignmentObjectTypeID */, contentType, e.IsPublished, relationships, e.Modified, e.Owner);

                var allAttribsOfThisType = new Dictionary<int, IAttributeManagement>();	// temporary Dictionary to set values later more performant by Dictionary-Key (AttributeId)
                IAttributeManagement titleAttrib = null;

                // Add all Attributes from that Content-Type
                foreach (var definition in contentType.AttributeDefinitions.Values)
                {
                    var newAttribute = AttributeHelperTools.GetAttributeManagementModel(definition);
                    newEntity.Attributes.Add(((IAttributeBase)newAttribute).Name, newAttribute);
                    allAttribsOfThisType.Add(definition.AttributeId, newAttribute);
                    if (newAttribute.IsTitle)
                        titleAttrib = newAttribute;
                }

                // If entity is a draft, add references to Published Entity
                if (!e.IsPublished && e.PublishedEntityId.HasValue)
                {
                    // Published Entity is already in the Entities-List as EntityIds is validated/extended before and Draft-EntityID is always higher as Published EntityId
                    newEntity.PublishedEntity = entities[e.PublishedEntityId.Value];
                    ((Data.Entity)newEntity.PublishedEntity).DraftEntity = newEntity;
                    newEntity.EntityId = e.PublishedEntityId.Value;
                }

                #region Add metadata-lists based on AssignmentObjectTypes

                // unclear why #1 is handled in a special way - why should this not be cached? I believe 1 means no specific assignment
                if (e.Metadata.HasMetadata && !entitiesOnly)
                {
                    // Try guid first. Note that an item can be assigned to both a guid, string and an int if necessary, though not commonly used
                    if (e.Metadata.KeyGuid.HasValue)
                    {
                        // Ensure that this assignment-Type (like 4 = entity-assignment) already has a dictionary for storage
                        if (!metadataForGuid.ContainsKey(e.Metadata.TargetType)) // ensure AssignmentObjectTypeID
                            metadataForGuid.Add(e.Metadata.TargetType, new Dictionary<Guid, IEnumerable<IEntity>>());

                        // Ensure that the assignment type (like 4) the target guid (like a350320-3502-afg0-...) has an empty list of items
                        if (!metadataForGuid[e.Metadata.TargetType].ContainsKey(e.Metadata.KeyGuid.Value)) // ensure Guid
                            metadataForGuid[e.Metadata.TargetType][e.Metadata.KeyGuid.Value] = new List<IEntity>();

                        // Now all containers must exist, add this item
                        ((List<IEntity>)metadataForGuid[e.Metadata.TargetType][e.Metadata.KeyGuid.Value]).Add(newEntity);
                    }
                    if (e.Metadata.KeyNumber.HasValue)
                    {
                        if (!metadataForNumber.ContainsKey(e.Metadata.TargetType)) // ensure AssignmentObjectTypeID
                            metadataForNumber.Add(e.Metadata.TargetType, new Dictionary<int, IEnumerable<IEntity>>());

                        if (!metadataForNumber[e.Metadata.TargetType].ContainsKey(e.Metadata.KeyNumber.Value)) // ensure Guid
                            metadataForNumber[e.Metadata.TargetType][e.Metadata.KeyNumber.Value] = new List<IEntity>();

                        ((List<IEntity>)metadataForNumber[e.Metadata.TargetType][e.Metadata.KeyNumber.Value]).Add(newEntity);
                    }
                    if (!string.IsNullOrEmpty(e.Metadata.KeyString))
                    {
                        if (!metadataForString.ContainsKey(e.Metadata.TargetType)) // ensure AssignmentObjectTypeID
                            metadataForString.Add(e.Metadata.TargetType, new Dictionary<string, IEnumerable<IEntity>>());

                        if (!metadataForString[e.Metadata.TargetType].ContainsKey(e.Metadata.KeyString)) // ensure Guid
                            metadataForString[e.Metadata.TargetType][e.Metadata.KeyString] = new List<IEntity>();

                        ((List<IEntity>)metadataForString[e.Metadata.TargetType][e.Metadata.KeyString]).Add(newEntity);
                    }
                }

                #endregion

                #region add Related-Entities Attributes
                foreach (var r in e.RelatedEntities)
                {
                    var attributeModel = allAttribsOfThisType[r.AttributeID];
                    var valueModel = Value.GetValueModel(((IAttributeBase)attributeModel).Type, r.Childs, source);
                    var valuesModelList = new List<IValue> { valueModel };
                    attributeModel.Values = valuesModelList;
                    attributeModel.DefaultValue = (IValueManagement)valuesModelList.FirstOrDefault();
                }
                #endregion

                #region Add "normal" Attributes (that are not Entity-Relations)
                foreach (var a in e.Attributes)
                {
                    IAttributeManagement attributeModel;
                    try
                    {
                        attributeModel = allAttribsOfThisType[a.AttributeID];
                    }
                    catch (KeyNotFoundException)
                    {
                        continue;
                    }
                    if (attributeModel.IsTitle)
                        newEntity.Title = attributeModel;
                    var valuesModelList = new List<IValue>();

                    #region Add all Values
                    foreach (var v in a.Values)
                    {
                        var valueModel = Value.GetValueModel(((IAttributeBase)attributeModel).Type, v.Value, v.Languages, v.ValueID, v.ChangeLogIDCreated);
                        valuesModelList.Add(valueModel);
                    }
                    #endregion

                    attributeModel.Values = valuesModelList;
                    attributeModel.DefaultValue = (IValueManagement)valuesModelList.FirstOrDefault();
                }

                // Special treatment in case there is no title - sometimes happens if the title-field is re-defined and ol data might no have this
                //if(newEntity.Title == null)
                //    newEntity.Title = titleAttrib;
                #endregion

                entities.Add(e.EntityID, newEntity);
                entList.Add(newEntity);
            }
            #endregion

            #region Populate Entity-Relationships (after all EntityModels are created)
            var relationshipsRaw = from r in Context.SqlDb.EntityRelationships
                                   where r.Attribute.AttributesInSets.Any(s => s.Set.AppID == appId && (!filterByEntityIds || (!r.ChildEntityID.HasValue || entityIds.Contains(r.ChildEntityID.Value)) || entityIds.Contains(r.ParentEntityID)))
                                   orderby r.ParentEntityID, r.AttributeID, r.ChildEntityID
                                   select new { r.ParentEntityID, r.Attribute.StaticName, r.ChildEntityID };
            foreach (var relationship in relationshipsRaw)
            {
                try
                {
                    if(entities.ContainsKey(relationship.ParentEntityID) && (!relationship.ChildEntityID.HasValue || entities.ContainsKey(relationship.ChildEntityID.Value)))
                        relationships.Add(new EntityRelationshipItem(entities[relationship.ParentEntityID], relationship.ChildEntityID.HasValue ? entities[relationship.ChildEntityID.Value] : null));
                }
                catch (KeyNotFoundException) { } // may occour if not all entities are loaded - edited 2rm 2015-09-29: Should not occur anymore
            }
            #endregion

            return new AppDataPackage(entities, entList, contentTypes, metadataForGuid, metadataForNumber, metadataForString, relationships);
        }
Esempio n. 17
0
        private IEnumerable<IEntity> GetPaging()
        {
            EnsureConfigurationIsLoaded();

            // Calculate any additional stuff
            var itemCount = In["Default"].LightList.Count();
            var pageCount = Math.Ceiling((decimal) itemCount / PageSize);

            // Assemble the entity
            var paging = new Dictionary<string, object>();
            paging.Add("Title", "Paging Information");
            paging.Add("PageSize", PageSize);
            paging.Add("PageNumber", PageNumber);
            paging.Add("ItemCount", itemCount);
            paging.Add("PageCount", pageCount);

            var entity = new Data.Entity(0, "Paging", paging, "Title");

            // Assemble list of this for the stream
            var list = new List<IEntity>();
            list.Add(entity);
            return list;
        }
        private EntityClass TransformToEntityClass(Data.Entity entityConfig, CodeGenerationModel genModel)
        {
            var data = new EntityClass
            {
                Name             = entityConfig.Name,
                Namespace        = $"{genModel.BaseNamespace}.{entityConfig.EntityScope}.Entities",
                Abstract         = entityConfig.Abstract,
                Partial          = entityConfig.PartialEntity,
                Validator        = entityConfig.Validator,
                HasBeefBaseClass = !entityConfig.OmitEntityBase
            };

            // Usings
            data.Usings.Add($"System");
            data.Usings.Add($"System.ComponentModel.DataAnnotations");
            if (entityConfig.OmitEntityBase == false)
            {
                data.Usings.Add($"Beef.Entities");
            }
            if (entityConfig.EntityScope == "Business")
            {
                data.Usings.Add($"{genModel.BaseNamespace}.Common.Entities");
            }
            foreach (var item in String.IsNullOrWhiteSpace(entityConfig.Usings) ? new string[0] : entityConfig.Usings.Split(","))
            {
                data.Usings.Add(item);
            }

            // Implements
            if (!string.IsNullOrWhiteSpace(entityConfig.Inherits))
            {
                data.Implements.Add(entityConfig.Inherits);
            }
            else if (entityConfig.OmitEntityBase == false)
            {
                data.Implements.Add("EntityBase");
            }
            foreach (var item in String.IsNullOrWhiteSpace(entityConfig.Implements) ? new string[0] : entityConfig.Implements.Split(","))
            {
                data.Implements.Add(item);
            }

            data.Properties = entityConfig.Properties?.Select(o => TransformToProperty(o)).ToList() ?? new List <Property>();

            if (entityConfig.AutoInferImplements)
            {
                // Add IIdentifier
                if (data.Properties.Any(o => o.Name == "Id" && o.Type == "Guid" && o.Nullable == false))
                {
                    data.Usings.Add($"Beef.Entities");
                    data.Implements.Add("IGuidIdentifier");
                }

                // Add IETag
                if (data.Properties.Any(o => o.Name == "ETag" && o.Type == "string"))
                {
                    data.Usings.Add($"Beef.Entities");
                    data.Implements.Add("IETag");
                }

                // Add ChangeLog
                if (data.Properties.Any(o => o.Name == "ChangeLog" && o.Type == "ChangeLog"))
                {
                    data.Usings.Add($"Beef.Entities");
                    data.Implements.Add("IChangeLog");
                }
            }

            // Add IEquatable
            if (entityConfig.OmitEntityBase == false)
            {
                data.Implements.Add($"IEquatable<{data.Name}>");
            }

            // Add Newtonsoft serialisation
            data.NewtonsoftJsonSerialization = true;
            data.Usings.Add("Newtonsoft.Json");

            // Has collection?
            if (entityConfig.Collection)
            {
                data.CollectionName             = $"{data.Name}Collection";
                data.CollectionHasBeefBaseClass = entityConfig.OmitEntityBase == false && entityConfig.CollectionInherits.HasValue() == false;
                data.CollectionImplements.Add(entityConfig.CollectionInherits.HasValue() ? entityConfig.CollectionInherits : entityConfig.OmitEntityBase ? $"List<{data.Name}>" : entityConfig.CollectionKeyed ? $"EntityBaseKeyedCollection<UniqueKey, {data.Name}>" : $"EntityBaseCollection<{data.Name}>");
                data.Usings.Add("System.Collections.Generic");

                // Has collection result?
                if (entityConfig.CollectionResult)
                {
                    data.CollectionResultName = $"{data.Name}CollectionResult";
                    data.CollectionResultImplements.Add(entityConfig.CollectionResultInherits.HasValue() ? entityConfig.CollectionResultInherits : $"EntityCollectionResult<{data.CollectionName}, {data.Name}>");
                }
            }

            return(data);
        }