public void GenerateCode(IConceptInfo conceptInfo, ICodeBuilder codeBuilder)
        {
            ReferencePropertyInfo info = (ReferencePropertyInfo)conceptInfo;

            var referenceGuid = new PropertyInfo {
                DataStructure = info.DataStructure, Name = info.Name + "ID"
            };

            PropertyHelper.GenerateCodeForType(referenceGuid, codeBuilder, "Guid?");

            if (DslUtility.IsQueryable(info.DataStructure) && DslUtility.IsQueryable(info.Referenced))
            {
                DataStructureQueryableCodeGenerator.AddNavigationPropertyWithBackingField(codeBuilder, info.DataStructure,
                                                                                          csPropertyName: info.Name,
                                                                                          propertyType: "Common.Queryable." + info.Referenced.Module.Name + "_" + info.Referenced.Name,
                                                                                          additionalSetterCode: info.Name + "ID = value != null ? (Guid?)value.ID : null;");
            }

            if (info.DataStructure is IOrmDataStructure && info.Referenced is IOrmDataStructure)
            {
                codeBuilder.InsertCode(
                    string.Format("modelBuilder.Entity<Common.Queryable.{0}_{1}>().HasOptional(t => t.{2}).WithMany().HasForeignKey(t => t.{2}ID);\r\n            ",
                                  info.DataStructure.Module.Name, info.DataStructure.Name, info.Name),
                    DomInitializationCodeGenerator.EntityFrameworkOnModelCreatingTag);
            }
            else if (info.DataStructure is IOrmDataStructure)
            {
                codeBuilder.InsertCode(
                    string.Format("modelBuilder.Entity<Common.Queryable.{0}_{1}>().Ignore(t => t.{2});\r\n            ",
                                  info.DataStructure.Module.Name, info.DataStructure.Name, info.Name),
                    DomInitializationCodeGenerator.EntityFrameworkOnModelCreatingTag);
            }
        }
        public static void InsertCodeSnippet(ICodeBuilder codeBuilder, ReferencePropertyInfo reference, DataStructureInfo parent)
        {
            if (reference.DataStructure is IWritableOrmDataStructure && parent is IWritableOrmDataStructure)
            {
                string detailName = reference.DataStructure.Module.Name + "." + reference.DataStructure.Name;

                string snippetDeleteChildItems =
                    $@"if (deletedIds.Count() > 0)
            {{
                List<{detailName}> childItems = deletedIds
                    .SelectMany(parent => _executionContext.Repository.{detailName}.Query()
                        .Where(child => child.{reference.Name}ID == parent.ID)
                        .Select(child => child.ID)
                        .ToList())
                    .Select(childId => new {detailName} {{ ID = childId }})
                    .ToList();

                if (childItems.Count() > 0)
                    _domRepository.{detailName}.Delete(childItems);
            }}

            ";

                codeBuilder.InsertCode(snippetDeleteChildItems, WritableOrmDataStructureCodeGenerator.OldDataLoadedTag, parent);
            }
        }
 public static string GetConstraintName(ReferencePropertyInfo info)
 {
     return(SqlUtility.Identifier(Sql.Format("ReferencePropertyConstraintDatabaseDefinition_ConstraintName",
                                             info.DataStructure.Name,
                                             info.Referenced.Name,
                                             info.Name)));
 }
Example #4
0
        public void GenerateCode(IConceptInfo conceptInfo, ICodeBuilder codeBuilder)
        {
            ReferencePropertyInfo info = (ReferencePropertyInfo)conceptInfo;

            if (DataStructureCodeGenerator.IsTypeSupported(info.DataStructure))
            {
                var properties = GetReferenceProperties(_dslModel.Concepts, info);

                string lookupField   = "";
                var    lookupColumns = new List <string>();

                foreach (var prop in properties)
                {
                    lookupField = prop.Name;
                    lookupColumns.Add("\"" + prop.Name + "\"");
                }


                string lookupEntity = info.Referenced.Name;

                //string dodatniAtribut = string.Format(ReferenceFormat, _dslModel.Concepts.Count(), lookupEntity, String.Join(", ", lookupColumns));
                string dodatniAtribut = string.Format(ReferenceFormat, lookupField, lookupEntity, String.Join(", ", lookupColumns));



                MvcPropertyHelper.GenerateCodeForType(_dslModel, info, codeBuilder, "Guid?", "ID", dodatniAtribut);
            }
        }
        public void GenerateCode(IConceptInfo conceptInfo, ICodeBuilder codeBuilder)
        {
            ReferencePropertyInfo info = (ReferencePropertyInfo)conceptInfo;

            if (DataStructureCodeGenerator.IsTypeSupported(info.DataStructure))
            {
                ODataPropertyHelper.GenerateCodeForType(info, codeBuilder, "Guid?", "ID");
            }
        }
Example #6
0
        public void GenerateCode(IConceptInfo conceptInfo, ICodeBuilder codeBuilder)
        {
            ReferencePropertyInfo info = (ReferencePropertyInfo)conceptInfo;

            var referenceGuid = new PropertyInfo {
                DataStructure = info.DataStructure, Name = info.Name + "ID"
            };

            PropertyHelper.GenerateCodeForType(referenceGuid, codeBuilder, "Guid?");
            PropertyHelper.GenerateStorageMapping(referenceGuid, codeBuilder, "System.Data.SqlDbType.UniqueIdentifier");

            if (DslUtility.IsQueryable(info.DataStructure) && DslUtility.IsQueryable(info.Referenced))
            {
                DataStructureQueryableCodeGenerator.AddNavigationPropertyWithBackingField(codeBuilder, info.DataStructure,
                                                                                          csPropertyName: info.Name,
                                                                                          propertyType: "Common.Queryable." + info.Referenced.Module.Name + "_" + info.Referenced.Name,
                                                                                          additionalSetterCode: info.Name + "ID = value != null ? (Guid?)value.ID : null;");
            }

            if (ReferencePropertyDbConstraintInfo.IsSupported(info) &&
                info.DataStructure is IOrmDataStructure &&
                info.Referenced is IOrmDataStructure)
            {
                var    ormDataStructure           = (IOrmDataStructure)info.DataStructure;
                var    referencedOrmDataStructure = (IOrmDataStructure)info.Referenced;
                string systemMessage = $"DataStructure:{info.DataStructure.FullName},Property:{info.Name}ID,Referenced:{info.Referenced.FullName}";

                if (info.DataStructure is IWritableOrmDataStructure)
                {
                    string onEnterInterpretSqlError = @"if (interpretedException is Rhetos.UserException && Rhetos.Utilities.MsSqlUtility.IsReferenceErrorOnInsertUpdate(interpretedException, "
                                                      + CsUtility.QuotedString(referencedOrmDataStructure.GetOrmSchema() + "." + referencedOrmDataStructure.GetOrmDatabaseObject()) + @", "
                                                      + CsUtility.QuotedString("ID") + @", "
                                                      + CsUtility.QuotedString(ReferencePropertyConstraintDatabaseDefinition.GetConstraintName(info)) + @"))
                        ((Rhetos.UserException)interpretedException).SystemMessage = " + CsUtility.QuotedString(systemMessage) + @";
                    ";
                    codeBuilder.InsertCode(onEnterInterpretSqlError, WritableOrmDataStructureCodeGenerator.OnDatabaseErrorTag, info.DataStructure);

                    if (info.Referenced == info.DataStructure)
                    {
                        codeBuilder.InsertCode($@"if (entity.{info.Name}ID != null && entity.{info.Name}ID != entity.ID) yield return entity.{info.Name}ID.Value;
            ", WritableOrmDataStructureCodeGenerator.PersistenceStorageMapperDependencyResolutionTag, info.DataStructure);
                    }
                }

                if (info.Referenced is IWritableOrmDataStructure)
                {
                    string onDeleteInterpretSqlError = @"if (interpretedException is Rhetos.UserException && Rhetos.Utilities.MsSqlUtility.IsReferenceErrorOnDelete(interpretedException, "
                                                       + CsUtility.QuotedString(ormDataStructure.GetOrmSchema() + "." + ormDataStructure.GetOrmDatabaseObject()) + @", "
                                                       + CsUtility.QuotedString(info.GetSimplePropertyName()) + @", "
                                                       + CsUtility.QuotedString(ReferencePropertyConstraintDatabaseDefinition.GetConstraintName(info)) + @"))
                        ((Rhetos.UserException)interpretedException).SystemMessage = " + CsUtility.QuotedString(systemMessage) + @";
                    ";
                    codeBuilder.InsertCode(onDeleteInterpretSqlError, WritableOrmDataStructureCodeGenerator.OnDatabaseErrorTag, info.Referenced);
                }
            }
        }
        /// <summary>
        /// Вместо ссылки на удаляемого мастера проставляем <c>null</c> в соответствующие свойства объектов.
        /// </summary>
        /// <param name="masterDataObject">Удаляемый объект, ссылки на который необходимо почистить.</param>
        /// <param name="referenceObjectList">Список объектов, из которых нужно почистить ссылки на мастера, заменив их на <c>null</c>.</param>
        /// <param name="referencePropertyInfos">Набор информации о классах, для которых переданный объект может являться мастером, и соответствующие свойства, которыми они могут ссылаться на мастера.</param>
        public static void NullifyMasterReferences(DataObject masterDataObject, List <DataObject> referenceObjectList, List <ReferencePropertyInfo> referencePropertyInfos)
        {
            if (masterDataObject == null)
            {
                throw new ArgumentNullException("masterDataObject");
            }

            if (referenceObjectList == null)
            {
                throw new ArgumentNullException("referenceObjectList");
            }

            if (referencePropertyInfos == null)
            {
                throw new ArgumentNullException("referencePropertyInfos");
            }

            List <DataObject> referenceObjectListCopy = referenceObjectList.ToList();

            foreach (DataObject dataObject in referenceObjectListCopy)
            {
                // Зануляем ссылки.
                Type dataObjectType = dataObject.GetType();
                ReferencePropertyInfo referencePropertyInfo =
                    referencePropertyInfos.FirstOrDefault(x => x.TypeWithReference == dataObjectType);

                if (referencePropertyInfo == null)
                {
                    throw new ArgumentException("Список объектов, из которых нужно почистить ссылки на мастера, некорректен.");
                }

                DataObject    currentDataObject  = dataObject;
                List <string> filteredProperties = (from possibleProperty in referencePropertyInfo.ReferenceProperties
                                                    let propertyValue = Information.GetPropValueByName(currentDataObject, possibleProperty)
                                                                        where propertyValue is DataObject &&
                                                                        propertyValue != null &&
                                                                        ((DataObject)propertyValue).__PrimaryKey.Equals(masterDataObject.__PrimaryKey)
                                                                        select possibleProperty).ToList();

                foreach (string possibleProperty in filteredProperties)
                {
                    if (Information.GetPropertyNotNull(dataObjectType, possibleProperty))
                    {
                        throw new PropertyCouldnotBeNullException(possibleProperty, dataObject);
                    }

                    Information.SetPropValueByName(dataObject, possibleProperty, null);
                }
            }
        }
        /// <summary>
        /// Формируем представление, основываясь на информации о типе и необходимых в представлении свойств.
        /// </summary>
        /// <param name="referencePropertyInfo">Информации о типе и необходимых в представлении свойств.</param>
        /// <returns>Сформированное представление.</returns>
        public static View FormViewOnReferencePropertyInfo(ReferencePropertyInfo referencePropertyInfo)
        {
            if (referencePropertyInfo == null)
            {
                throw new ArgumentNullException("referencePropertyInfo");
            }

            var resultView = new View()
            {
                DefineClassType = referencePropertyInfo.TypeWithReference,
                Name            = referencePropertyInfo.TypeWithReference.FullName + "View"
            };

            foreach (string referenceProperty in referencePropertyInfo.ReferenceProperties)
            {
                resultView.AddProperty(referenceProperty);
            }

            return(resultView);
        }
        /// <summary>
        /// Определяем набор объектов, для которых переданный является мастером.
        /// </summary>
        /// <param name="masterObject">Объект, для которого мы будем искать набор объектов, чьим мастером он является.</param>
        /// <returns>Набор объектов, для которых переданный является мастером.</returns>
        public static List <ReferencePropertyInfo> GetReferencedDataObjectsInfo(DataObject masterObject)
        {
            var    referencePropertyInfos       = new List <ReferencePropertyInfo>();
            Type   realMasterObjectType         = masterObject.GetType();
            string masterObjectAssemblyLocation = realMasterObjectType.Assembly.Location;
            string directoryPath;

            if (!string.IsNullOrEmpty(masterObjectAssemblyLocation) &&
                !string.IsNullOrEmpty(directoryPath = Path.GetDirectoryName(masterObjectAssemblyLocation)) &&
                Directory.Exists(directoryPath))
            {
                List <Assembly> assembliesThatMayContainDataObjects = new List <Assembly>();
                foreach (FileInfo assemblyFileInfo in new DirectoryInfo(directoryPath).GetFiles("*.dll"))
                {
                    Assembly assembly = null;

                    try
                    {
                        assembly = Assembly.LoadFile(assemblyFileInfo.FullName);
                    }
                    catch (Exception ex)
                    {
                        LogService.LogError($"При попытке загрузить сборку \"{assemblyFileInfo.FullName}\" произошла ошибка.", ex);
                    }

                    if (assembly != null)
                    {
                        assembliesThatMayContainDataObjects.Add(assembly);
                    }
                }

                foreach (Assembly assembly in assembliesThatMayContainDataObjects)
                {
                    referencePropertyInfos.AddRange(ReferencePropertyInfo.FormList(assembly, realMasterObjectType));
                }
            }

            return(referencePropertyInfos);
        }
Example #10
0
        public void GenerateCode(IConceptInfo conceptInfo, ICodeBuilder codeBuilder)
        {
            ReferencePropertyInfo info = (ReferencePropertyInfo)conceptInfo;

            var referenceGuid = new PropertyInfo {
                DataStructure = info.DataStructure, Name = info.Name + "ID"
            };

            PropertyHelper.GenerateCodeForType(referenceGuid, codeBuilder, "Guid?");

            if (DslUtility.IsQueryable(info.DataStructure) && DslUtility.IsQueryable(info.Referenced))
            {
                DataStructureQueryableCodeGenerator.AddNavigationPropertyWithBackingField(codeBuilder, info.DataStructure,
                                                                                          csPropertyName: info.Name,
                                                                                          propertyType: "Common.Queryable." + info.Referenced.Module.Name + "_" + info.Referenced.Name,
                                                                                          additionalSetterCode: info.Name + "ID = value != null ? (Guid?)value.ID : null;");
            }

            if (info.DataStructure is IOrmDataStructure && info.Referenced is IOrmDataStructure)
            {
                codeBuilder.InsertCode(
                    info.OrmMappingSnippet(),
                    DomInitializationCodeGenerator.EntityFrameworkOnModelCreatingTag);
            }
            else if (info.DataStructure is IOrmDataStructure)
            {
                codeBuilder.InsertCode(
                    string.Format("modelBuilder.Entity<Common.Queryable.{0}_{1}>().Ignore(t => t.{2});\r\n            ",
                                  info.DataStructure.Module.Name, info.DataStructure.Name, info.Name),
                    DomInitializationCodeGenerator.EntityFrameworkOnModelCreatingTag);
            }

            if (ReferencePropertyConstraintDatabaseDefinition.IsSupported(info) &&
                info.DataStructure is IOrmDataStructure &&
                info.Referenced is IOrmDataStructure)
            {
                var    ormDataStructure           = (IOrmDataStructure)info.DataStructure;
                var    referencedOrmDataStructure = (IOrmDataStructure)info.Referenced;
                string systemMessage = "DataStructure:" + info.DataStructure + ",Property:" + info.Name + "ID,Referenced:" + info.Referenced;

                if (info.DataStructure is IWritableOrmDataStructure)
                {
                    string onEnterInterpretSqlError = @"if (interpretedException is Rhetos.UserException && Rhetos.Utilities.MsSqlUtility.IsReferenceErrorOnInsertUpdate(interpretedException, "
                                                      + CsUtility.QuotedString(referencedOrmDataStructure.GetOrmSchema() + "." + referencedOrmDataStructure.GetOrmDatabaseObject()) + @", "
                                                      + CsUtility.QuotedString("ID") + @", "
                                                      + CsUtility.QuotedString(ReferencePropertyConstraintDatabaseDefinition.GetConstraintName(info)) + @"))
                    ((Rhetos.UserException)interpretedException).SystemMessage = " + CsUtility.QuotedString(systemMessage) + @";
                ";
                    codeBuilder.InsertCode(onEnterInterpretSqlError, WritableOrmDataStructureCodeGenerator.OnDatabaseErrorTag, info.DataStructure);
                }

                if (info.Referenced is IWritableOrmDataStructure)
                {
                    string onDeleteInterpretSqlError = @"if (interpretedException is Rhetos.UserException && Rhetos.Utilities.MsSqlUtility.IsReferenceErrorOnDelete(interpretedException, "
                                                       + CsUtility.QuotedString(ormDataStructure.GetOrmSchema() + "." + ormDataStructure.GetOrmDatabaseObject()) + @", "
                                                       + CsUtility.QuotedString(info.Name + "ID") + @", "
                                                       + CsUtility.QuotedString(ReferencePropertyConstraintDatabaseDefinition.GetConstraintName(info)) + @"))
                    ((Rhetos.UserException)interpretedException).SystemMessage = " + CsUtility.QuotedString(systemMessage) + @";
                ";
                    codeBuilder.InsertCode(onDeleteInterpretSqlError, WritableOrmDataStructureCodeGenerator.OnDatabaseErrorTag, info.Referenced);
                }
            }
        }
Example #11
0
 public static string GetColumnName(this ReferencePropertyInfo info)
 {
     return(SqlUtility.Identifier(info.Name + "ID"));
 }
Example #12
0
        public void GenerateCode(IConceptInfo conceptInfo, ICodeBuilder codeBuilder)
        {
            ReferencePropertyInfo info = (ReferencePropertyInfo)conceptInfo;

            PropertyCodeGeneratorHelper.GenerateCodeForType(info, codeBuilder, "Guid?", "ID");
        }
 public static bool IsSupported(ReferencePropertyInfo info)
 {
     return(ReferencePropertyDatabaseDefinition.IsSupported(info) &&
            ForeignKeyUtility.GetSchemaTableForForeignKey(info.Referenced) != null);
 }
        public void GenerateCode(IConceptInfo conceptInfo, ICodeBuilder codeBuilder)
        {
            ReferencePropertyInfo info = (ReferencePropertyInfo)conceptInfo;

            PropertyCodeGeneratorHelper.GenerateCodeForType(info, codeBuilder, "string", "ID", info.Referenced.ToString());
        }
 public static bool IsSupported(ReferencePropertyInfo info)
 {
     return(info.DataStructure is EntityInfo);
 }
Example #16
0
        private string ImplementationDescriptionCodeSnippet(ReferencePropertyInfo info)
        {
            return(string.Format(
                       @"    ""lookupEntity"":""{0}.{1}"",
", info.Referenced.Module, info.Referenced.Name));
        }
Example #17
0
 private static IEnumerable <PropertyInfo> GetReferenceProperties(IEnumerable <IConceptInfo> existingConcepts, ReferencePropertyInfo property)
 {
     return(existingConcepts.OfType <LookupVisibleInfo>()
            .Where(r => r.Property.DataStructure == property.Referenced).ToList()
            .Select(r => r.Property));
 }