/// <exclude />
        public static void SetCustomForm(DataTypeDescriptor dataTypeDescriptor, string newFormMarkup)
        {
            string dynamicDataFormFolderPath = GetFolderPath(dataTypeDescriptor.Namespace);
            string dynamicDataFormFileName = GetFilename(dataTypeDescriptor.Name);

            // Parsing for assertion
            XDocument.Parse(newFormMarkup);

            IDynamicTypeFormDefinitionFile formDefinitionFile =
                DataFacade.GetData<IDynamicTypeFormDefinitionFile>()
                  .FirstOrDefault(f => f.FolderPath.Equals(dynamicDataFormFolderPath, StringComparison.OrdinalIgnoreCase) 
                                    && f.FileName.Equals(dynamicDataFormFileName, StringComparison.OrdinalIgnoreCase));

            if (formDefinitionFile == null)
            {
                var newFile = DataFacade.BuildNew<IDynamicTypeFormDefinitionFile>();
                newFile.FolderPath = dynamicDataFormFolderPath;
                newFile.FileName = dynamicDataFormFileName;
                newFile.SetNewContent(newFormMarkup);
                formDefinitionFile = DataFacade.AddNew<IDynamicTypeFormDefinitionFile>(newFile);
            }
            else
            {
                formDefinitionFile.SetNewContent(newFormMarkup);
                DataFacade.Update(formDefinitionFile);
            }
        }
        /// <summary>
        /// Returns custom form markup. 
        /// </summary>
        /// <param name="dataTypeDescriptor">A data type descriptor</param>
        /// <returns></returns>
        public static XDocument GetCustomFormMarkup(DataTypeDescriptor dataTypeDescriptor)
        {
            var file = GetCustomFormMarkupFile(dataTypeDescriptor.Namespace, dataTypeDescriptor.Name);

            if (file == null)
            {
                return null;
            }

            var markupFilePath = (file as FileSystemFile).SystemPath;

            return XDocumentUtils.Load(markupFilePath, LoadOptions.SetBaseUri | LoadOptions.SetLineInfo);
        }
 public DataIdClassGenerator(string className, DataTypeDescriptor dataTypeDescriptor)
 {
     _className          = className;
     _dataTypeDescriptor = dataTypeDescriptor;
 }
예제 #4
0
        private void ValidateDynamicAddedType(DataType dataType)
        {
            DataTypeDescriptor dataTypeDescriptor = this.InstallerContext.GetPendingDataTypeDescriptor(dataType.InterfaceTypeName);

            if (dataTypeDescriptor == null)
            {
                _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.MissingTypeDescriptor").FormatWith(dataType.InterfaceTypeName));
                return;
            }

            bool dataTypeLocalized = dataTypeDescriptor.SuperInterfaces.Contains(typeof(ILocalizedControlled));

            if (!ValidateTargetLocaleInfo(dataType, dataTypeLocalized))
            {
                return;
            }

            foreach (XElement addElement in dataType.Dataset)
            {
                var  dataKeyPropertyCollection = new DataKeyPropertyCollection();
                bool propertyValidationPassed  = true;
                var  fieldValues = new Dictionary <string, object>();

                foreach (XAttribute attribute in addElement.Attributes())
                {
                    string fieldName = attribute.Name.LocalName;

                    // A compatibility fix
                    if (IsObsoleteField(dataTypeDescriptor, fieldName))
                    {
                        continue;
                    }

                    DataFieldDescriptor dataFieldDescriptor = dataTypeDescriptor.Fields[fieldName];

                    if (dataFieldDescriptor == null)
                    {
                        _validationResult.AddFatal(Texts.DataPackageFragmentInstaller_MissingProperty(dataTypeDescriptor, fieldName));
                        propertyValidationPassed = false;
                        continue;
                    }

                    object fieldValue;
                    try
                    {
                        fieldValue = ValueTypeConverter.Convert(attribute.Value, dataFieldDescriptor.InstanceType);
                    }
                    catch (Exception)
                    {
                        _validationResult.AddFatal(Texts.DataPackageFragmentInstaller_ConversionFailed(attribute.Value, dataFieldDescriptor.InstanceType));
                        propertyValidationPassed = false;
                        continue;
                    }

                    if (dataTypeDescriptor.KeyPropertyNames.Contains(fieldName))
                    {
                        dataKeyPropertyCollection.AddKeyProperty(fieldName, fieldValue);
                    }

                    fieldValues.Add(fieldName, fieldValue);
                }

                if (!propertyValidationPassed)
                {
                    continue;
                }

                if (!dataType.AllowOverwrite && !dataType.OnlyUpdate)
                {
                    // TODO: implement check if the same key has already been added
                }

                RegisterKeyToBeAdded(dataType, dataTypeDescriptor, dataKeyPropertyCollection);

                // Checking foreign key references
                foreach (var referenceField in dataTypeDescriptor.Fields.Where(f => f.ForeignKeyReferenceTypeName != null))
                {
                    if (!fieldValues.TryGetValue(referenceField.Name, out object propertyValue) ||
                        propertyValue == null ||
                        (propertyValue is Guid guid && guid == Guid.Empty) ||
                        (propertyValue is string str && str == ""))
                    {
                        continue;
                    }

                    string referredTypeName = referenceField.ForeignKeyReferenceTypeName;
                    var    referredType     = TypeManager.TryGetType(referredTypeName);
                    if (referredType == null)
                    {
                        // TODO: implement reference check for dynamic types as well
                        continue;
                    }

                    string targetKeyPropertyName = referredType.GetKeyPropertyNames().SingleOrDefault();

                    CheckForBrokenReference(dataType, referredType, targetKeyPropertyName, propertyValue);
                }
            }
        }
예제 #5
0
        private void ValidateNonDynamicAddedType(DataType dataType)
        {
            if (dataType.InterfaceType == null)
            {
                _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.TypeNotConfigured").FormatWith(dataType.InterfaceTypeName));
                return;
            }


            if (!typeof(IData).IsAssignableFrom(dataType.InterfaceType))
            {
                _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.TypeNotInheriting").FormatWith(dataType.InterfaceType, typeof(IData)));
                return;
            }

            bool dataTypeLocalized = DataLocalizationFacade.IsLocalized(dataType.InterfaceType);

            if (!ValidateTargetLocaleInfo(dataType, dataTypeLocalized))
            {
                return;
            }

            int itemsAlreadyPresentInDatabase = 0;


            DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.BuildNewDataTypeDescriptor(dataType.InterfaceType);


            bool isVersionedDataType = typeof(IVersioned).IsAssignableFrom(dataType.InterfaceType);

            var requiredPropertyNames =
                (from dfd in dataTypeDescriptor.Fields
                 where !dfd.IsNullable && !(isVersionedDataType && dfd.Name == nameof(IVersioned.VersionId)) // Compatibility fix
                 select dfd.Name).ToList();

            var nonRequiredPropertyNames = dataTypeDescriptor.Fields.Select(f => f.Name)
                                           .Except(requiredPropertyNames).ToList();


            foreach (XElement addElement in dataType.Dataset)
            {
                var dataKeyPropertyCollection = new DataKeyPropertyCollection();

                bool propertyValidationPassed = true;
                var  assignedPropertyNames    = new List <string>();
                var  fieldValues = new Dictionary <string, object>();

                var properties = GetDataTypeProperties(dataType.InterfaceType);

                foreach (XAttribute attribute in addElement.Attributes())
                {
                    string fieldName = attribute.Name.LocalName;

                    PropertyInfo propertyInfo;
                    if (!properties.TryGetValue(fieldName, out propertyInfo))
                    {
                        // A compatibility fix
                        if (IsObsoleteField(dataType, fieldName))
                        {
                            continue;
                        }

                        _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.MissingProperty").FormatWith(dataType.InterfaceType, fieldName));
                        propertyValidationPassed = false;
                        continue;
                    }

                    if (!propertyInfo.CanWrite)
                    {
                        _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.MissingWritableProperty").FormatWith(dataType.InterfaceType, fieldName));
                        propertyValidationPassed = false;
                        continue;
                    }

                    object fieldValue;
                    try
                    {
                        fieldValue = ValueTypeConverter.Convert(attribute.Value, propertyInfo.PropertyType);
                    }
                    catch (Exception)
                    {
                        _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.ConversionFailed").FormatWith(attribute.Value, propertyInfo.PropertyType));
                        propertyValidationPassed = false;
                        continue;
                    }

                    if (dataType.InterfaceType.GetKeyPropertyNames().Contains(fieldName))
                    {
                        dataKeyPropertyCollection.AddKeyProperty(fieldName, fieldValue);
                    }

                    assignedPropertyNames.Add(fieldName);
                    fieldValues.Add(fieldName, fieldValue);
                }

                if (!propertyValidationPassed)
                {
                    continue;
                }


                var notAssignedRequiredProperties = requiredPropertyNames.Except(assignedPropertyNames.Except(nonRequiredPropertyNames)).ToArray();
                if (notAssignedRequiredProperties.Any())
                {
                    bool missingValues = false;
                    foreach (string propertyName in notAssignedRequiredProperties)
                    {
                        PropertyInfo propertyInfo = dataType.InterfaceType.GetPropertiesRecursively().Single(f => f.Name == propertyName);

                        if (propertyInfo.CanWrite)
                        {
                            var defaultValueAttribute = propertyInfo.GetCustomAttributesRecursively <NewInstanceDefaultFieldValueAttribute>().SingleOrDefault();
                            if (defaultValueAttribute == null || !defaultValueAttribute.HasValue)
                            {
                                _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.MissingPropertyVaule").FormatWith(propertyName, dataType.InterfaceType));
                                missingValues = true;
                            }
                        }
                    }
                    if (missingValues)
                    {
                        continue;
                    }
                }


                // Validating keys already present
                if (!dataType.AllowOverwrite && !dataType.OnlyUpdate)
                {
                    bool dataLocaleExists =
                        !DataLocalizationFacade.IsLocalized(dataType.InterfaceType) ||
                        (!dataType.AddToAllLocales && !dataType.AddToCurrentLocale) ||
                        (dataType.Locale != null && !this.InstallerContext.IsLocalePending(dataType.Locale));

                    if (dataLocaleExists)
                    {
                        using (new DataScope(dataType.DataScopeIdentifier, dataType.Locale))
                        {
                            IData data = DataFacade.TryGetDataByUniqueKey(dataType.InterfaceType, dataKeyPropertyCollection);

                            if (data != null)
                            {
                                itemsAlreadyPresentInDatabase++;
                            }
                        }
                    }
                }


                RegisterKeyToBeAdded(dataType, null, dataKeyPropertyCollection);

                // Checking foreign key references
                foreach (var foreignKeyProperty in DataAttributeFacade.GetDataReferenceProperties(dataType.InterfaceType))
                {
                    if (!fieldValues.ContainsKey(foreignKeyProperty.SourcePropertyName))
                    {
                        continue;
                    }

                    object propertyValue = fieldValues[foreignKeyProperty.SourcePropertyName];

                    if (propertyValue == null || propertyValue.Equals(foreignKeyProperty.NullReferenceValue))
                    {
                        continue;
                    }

                    CheckForBrokenReference(dataType, foreignKeyProperty.TargetType, foreignKeyProperty.TargetKeyPropertyName, propertyValue);
                }
            }

            if (itemsAlreadyPresentInDatabase > 0)
            {
                _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.DataExists").FormatWith(dataType.InterfaceType, itemsAlreadyPresentInDatabase));
            }
        }
예제 #6
0
 public DataIdClassGenerator(DataTypeDescriptor dataTypeDescriptor, string dataIdClassName)
 {
     _dataTypeDescriptor = dataTypeDescriptor;
     _dataIdClassName    = dataIdClassName;
 }
예제 #7
0
        public string CreatePackagePack()
        {
            using (new DataScope(DataScopeIdentifier.Public))
            {
                #region Init
                if (_packageName == string.Empty)
                {
                    return("");
                }

                _packageDirectoryPath = Path.Combine(_serviceDirectoryPath, _packageName);
                if (Directory.Exists(_packageDirectoryPath))
                {
                    Directory.Delete(_packageDirectoryPath, true);
                }

                var dataPackageDirectoryPath = Path.Combine(_serviceDirectoryPath, _packageName + "_Data");

                _zipDirectoryPath     = Path.Combine(_packageDirectoryPath, "Release");
                _packageDirectoryPath = Path.Combine(_packageDirectoryPath, "Package");

                Directory.CreateDirectory(_packageDirectoryPath);
                Directory.CreateDirectory(_zipDirectoryPath);

                if (Directory.Exists(dataPackageDirectoryPath))
                {
                    FileSystem.CopyDirectory(dataPackageDirectoryPath, _packageDirectoryPath);
                }

                string packageConfigFilePath = Path.Combine(_serviceDirectoryPath, _packageName + ".xml");

                XDocument config = XDocument.Load(packageConfigFilePath);

                var rootConfigElement = config.Element(pc + "PackageCreator");
                if (rootConfigElement == null)
                {
                    throw new InvalidOperationException("Root element of config PackageCreator 2.0 not found");
                }



                XElement blockElement;

                #endregion

                #region Init install.xml
                XDocument XPackage = new XDocument();
                XPackage.Declaration = new XDeclaration("1.0", "utf-8", "yes");

                XElement XPackageInstaller = new XElement(mi + "PackageInstaller");
                XPackageInstaller.Add(new XAttribute(XNamespace.Xmlns + "mi", mi));

                XElement XPackageRequirements = config.Descendants(mi + "PackageRequirements").FirstOrDefault();
                XPackageInstaller.Add(XPackageRequirements);


                XElement XPackageInformation = config.Descendants(mi + "PackageInformation").FirstOrDefault();
                AllowOverwriteDataOnInstall = XPackageInformation.AllowOverwriteAttributeValue();


                XPackageInstaller.Add(XPackageInformation);

                XElement XPackageFragmentInstallerBinaries = new XElement(mi + "PackageFragmentInstallerBinaries");
                try
                {
                    XPackageFragmentInstallerBinaries = config.Descendants(mi + "PackageFragmentInstallerBinaries").First();
                }
                catch
                {
                }

                XPackageFragmentInstallerBinaries.ReplaceNodes(XPackageFragmentInstallerBinaries.Elements().OrderBy(ReferencedAssemblies.AssemblyPosition));
                XPackageInstaller.Add(XPackageFragmentInstallerBinaries);


                XElement XPackageFragmentInstallers = new XElement(mi + "PackageFragmentInstallers");

                #endregion

                #region Init Categories
                foreach (var categoryType in PackageCreatorActionFacade.CategoryTypes)
                {
                    if (categoryType.Value.IsInitable())
                    {
                        foreach (var packageItem in PackageCreatorFacade.GetItems(categoryType.Value, config.Root))
                        {
                            (packageItem as IPackInit).Init(this);
                        }
                    }
                }
                #endregion

                #region XML PageTemplates
                XElement PageTemplates = config.Descendants(pc + "PageTemplates").FirstOrDefault();
                if (PageTemplates != null)
                {
                    foreach (XElement item in PageTemplates.Elements("Add"))
                    {
                        var pageTemplate = (from i in DataFacade.GetData <IXmlPageTemplate>()
                                            where i.Title == item.IndexAttributeValue()
                                            select i).FirstOrDefault();

                        if (pageTemplate != null)
                        {
                            var newPageTemplateFilePath = "\\" + pageTemplate.Title + ".xml";

                            AddFile("App_Data\\PageTemplates" + pageTemplate.PageTemplateFilePath, "App_Data\\PageTemplates" + newPageTemplateFilePath);
                            pageTemplate.PageTemplateFilePath = newPageTemplateFilePath;
                            AddData(pageTemplate);
                        }
                    }
                }

                #endregion

                #region Files
                XElement InstallFiles = config.Descendants(pc + "Files").FirstOrDefault();
                if (InstallFiles != null)
                {
                    foreach (XElement item in InstallFiles.Elements("Add"))
                    {
                        var filename = item.IndexAttributeValue();

                        if (string.IsNullOrEmpty(filename))
                        {
                            throw new InvalidOperationException("Files->Add attribute 'name' must be spesified");
                        }

                        AddFile(filename);
                    }
                }
                #endregion

                #region FilesInDirectory
                XElement InstallFilesInDirectory = config.Descendants(pc + "FilesInDirectories").FirstOrDefault();
                if (InstallFilesInDirectory != null)
                {
                    foreach (XElement item in InstallFilesInDirectory.Elements("Add"))
                    {
                        var path = item.IndexAttributeValue();
                        AddFilesInDirectory(path);
                    }
                }
                #endregion

                #region Directories
                XElement InstallDirectories = config.Descendants(pc + "Directories").FirstOrDefault();
                if (InstallDirectories != null)
                {
                    foreach (XElement item in InstallDirectories.Elements("Add"))
                    {
                        try
                        {
                            var filename = item.IndexAttributeValue();

                            AddDirectory(filename);
                        }
                        catch { }
                    }
                }
                #endregion

                #region Datas
                blockElement = rootConfigElement.Element(pc + "Datas");
                if (blockElement != null)
                {
                    foreach (XElement item in blockElement.Elements("Type"))
                    {
                        var dataTypeName        = item.Attribute("type").Value;
                        var dataScopeIdentifier = item.Element("Data").Attribute("dataScopeIdentifier").Value;
                        AddData(dataTypeName, dataScopeIdentifier);
                    }
                }
                #endregion

                #region DataItems
                blockElement = rootConfigElement.Element(pc + "DataItems");
                if (blockElement != null)
                {
                    foreach (XElement item in blockElement.Elements("Type"))
                    {
                        var dataTypeName = item.Attribute("type").Value;

                        Func <XElement, Func <IData, bool> > trueAttributes = e => e.Attributes().Where(x => x.Name.Namespace == XNamespace.None)
                                                                              .Aggregate(new Func <IData, bool>(d => true), (f, x) => new Func <IData, bool>(d => (d.GetProperty(x.Name.LocalName) == x.Value) && f(d)));
                        Func <IData, bool> where = item.Elements("Add")
                                                   .Aggregate(new Func <IData, bool>(d => false), (f, e) => new Func <IData, bool>(d => trueAttributes(e)(d) || f(d)));

                        AddData(dataTypeName, where);
                    }
                }
                #endregion

#warning TODO: Datatypes data format depends from datatype exists in package or not, thats why list of dtatype must created before adding data

                #region DynamicDataTypes
                XElement DynamicDataTypes = config.Descendants(pc + "DynamicDataTypes").FirstOrDefault();
                XElement DynamicDataTypePackageFragmentInstaller = null;
                if (DynamicDataTypes != null)
                {
                    List <XElement> dataTypes = new List <XElement>();
                    foreach (XElement item in DynamicDataTypes.Elements("Add").OrderBy(e => DataPosition(e.IndexAttributeValue())))
                    {
                        var dynamicDataType     = TypeManager.GetType(item.IndexAttributeValue());
                        var dynamicDataTypeName = TypeManager.SerializeType(dynamicDataType);

                        AddData <IGeneratedTypeWhiteList>(d => d.TypeManagerTypeName == dynamicDataTypeName);

                        installDataTypeNamesList.Add(dynamicDataTypeName);
                        var type = TypeManager.GetType(item.IndexAttributeValue());
                        DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(type);
                        dataTypes.Add(new XElement("Type",
                                                   new XAttribute("providerName", "GeneratedDataTypesElementProvider"),
                                                   new XAttribute("dataTypeDescriptor", dataTypeDescriptor.ToXml().ToString()),
                                                   new XAttribute("allowOverwrite", AllowOverwriteDataOnInstall))
                                      );

                        AddFileIfExists("App_Data\\Composite\\DynamicTypeForms\\" + item.IndexAttributeValue().Replace('.', '\\') + ".xml");
                    }


                    DynamicDataTypePackageFragmentInstaller = new XElement(mi + "Add",
                                                                           new XAttribute("installerType", "Composite.Core.PackageSystem.PackageFragmentInstallers.DynamicDataTypePackageFragmentInstaller, Composite"),
                                                                           new XAttribute("uninstallerType", "Composite.Core.PackageSystem.PackageFragmentInstallers.DynamicDataTypePackageFragmentUninstaller, Composite"),
                                                                           new XElement("Types",
                                                                                        dataTypes
                                                                                        )
                                                                           );
                }

                #endregion


                //Add only one MetaTypeTab
                using (new GuidReplacer(from cd in DataFacade.GetData <ICompositionContainer>()
                                        select new KeyValuePair <Guid, Guid>(cd.GetProperty <Guid>("Id"), GuidReplacer.CompositionContainerGuid)
                                        ))
                {
                    foreach (var categoryType in PackageCreatorActionFacade.CategoryTypes)
                    {
                        if (categoryType.Value.IsPackagable())
                        {
                            foreach (var packageItem in PackageCreatorFacade.GetItems(categoryType.Value, config.Root))
                            {
                                (packageItem as IPack).Pack(this);
                            }
                        }
                    }

                    #region DynamicDataTypesData

                    XElement element = config.Descendants(pc + "DynamicDataTypesData").FirstOrDefault();

                    if (element != null)
                    {
                        foreach (XElement item in element.Elements("Add"))
                        {
                            var indexAttrValue = item.IndexAttributeValue();
                            AddDataTypeData(TypeManager.TryGetType(indexAttrValue));
                        }
                    }
                }
                #endregion

                #region TransformationPackageFragmentInstallers

                XElement ConfigurationTransformationPackageFragmentInstallers = null;

                var sources = new HashSet <string>();
                sources.UnionWith(ConfigurationXPaths.Keys);
                sources.UnionWith(ConfigurationTemplates.Keys);

                foreach (var source in sources)
                {
                    XDocument installXsl   = XDocument.Parse(blankXsl);
                    XDocument uninstallXsl = XDocument.Parse(blankXsl);


                    HashSet <string> xpaths;
                    if (ConfigurationXPaths.TryGetValue(source, out xpaths))
                    {
                        var nodes = new Dictionary <string, Dictionary <string, XElement> >();
                        foreach (string xpath in xpaths)
                        {
                            var   configuration = PackageCreatorFacade.GetConfigurationDocument(source);
                            var   element       = configuration.XPathSelectElement(xpath);
                            Regex re            = new Regex(@"^(.*?)/([^/]*(\[[^\]]*\])?)$");
                            Match match         = re.Match(xpath);
                            if (match.Success)
                            {
                                var itemPath = match.Groups[1].Value;
                                var itemKey  = match.Groups[2].Value;

                                nodes.Add(itemPath, itemKey, element);

                                uninstallXsl.Root.Add(
                                    new XElement(xsl + "template",
                                                 new XAttribute("match", xpath)
                                                 )
                                    );
                            }
                        }
                        foreach (var node in nodes)
                        {
                            installXsl.Root.Add(
                                new XElement(xsl + "template",
                                             new XAttribute("match", node.Key),
                                             new XElement(xsl + "copy",
                                                          new XElement(xsl + "apply-templates",
                                                                       new XAttribute("select", "@* | node()")),
                                                          from e in node.Value
                                                          select
                                                          new XElement(xsl + "if",
                                                                       new XAttribute("test", string.Format("count({0})=0", e.Key)),
                                                                       e.Value
                                                                       )
                                                          )
                                             )
                                );
                        }
                    }

                    List <XElement> templates;
                    if (ConfigurationTemplates.TryGetValue(source, out templates))
                    {
                        installXsl.Root.Add(templates);
                    }

                    var configDirectory = Path.Combine(_packageDirectoryPath, source);
                    if (!Directory.Exists(configDirectory))
                    {
                        Directory.CreateDirectory(configDirectory);
                    }
                    installXsl.SaveTabbed(Path.Combine(configDirectory, configInstallFileName));
                    uninstallXsl.SaveTabbed(Path.Combine(configDirectory, configUninstallFileName));

                    if (PCCompositeConfig.Source == source)
                    {
                        ConfigurationTransformationPackageFragmentInstallers =
                            new XElement(mi + "Add",
                                         new XAttribute("installerType", "Composite.Core.PackageSystem.PackageFragmentInstallers.ConfigurationTransformationPackageFragmentInstaller, Composite"),
                                         new XAttribute("uninstallerType", "Composite.Core.PackageSystem.PackageFragmentInstallers.ConfigurationTransformationPackageFragmentUninstaller, Composite"),
                                         new XElement("Install",
                                                      new XAttribute("xsltFilePath", string.Format(@"~\{0}\{1}", source, configInstallFileName))
                                                      ),
                                         new XElement("Uninstall",
                                                      new XAttribute("xsltFilePath", string.Format(@"~\{0}\{1}", source, configUninstallFileName))
                                                      )
                                         );
                    }
                    else
                    {
                        XslFiles.Add(
                            new XElement("XslFile",
                                         new XAttribute("pathXml", PackageCreatorFacade.GetConfigurationPath(source)),
                                         new XAttribute("installXsl", string.Format(@"~\{0}\{1}", source, configInstallFileName)),
                                         new XAttribute("uninstallXsl", string.Format(@"~\{0}\{1}", source, configUninstallFileName))
                                         )
                            );
                    }
                }
                #endregion



                XElement XPackageFragments = config.Descendants(pc + "PackageFragmentInstallers").FirstOrDefault();
                if (XPackageFragments != null)
                {
                    XPackageFragmentInstallers.Add(XPackageFragments.Elements());
                }


                XPackageFragmentInstallers.Add(ConfigurationTransformationPackageFragmentInstallers);

                #region FilePackageFragmentInstaller
                if (Files.Count + Directories.Count > 0)
                {
                    XElement FilePackageFragmentInstaller = new XElement(mi + "Add",
                                                                         new XAttribute("installerType", "Composite.Core.PackageSystem.PackageFragmentInstallers.FilePackageFragmentInstaller, Composite"),
                                                                         new XAttribute("uninstallerType", "Composite.Core.PackageSystem.PackageFragmentInstallers.FilePackageFragmentUninstaller, Composite"),
                                                                         Files.Count == 0 ? null : new XElement("Files"
                                                                                                                , Files.OrderBy(d => ReferencedAssemblies.AssemblyPosition(d))
                                                                                                                ),
                                                                         Directories.Count == 0 ? null : new XElement("Directories"
                                                                                                                      , Directories
                                                                                                                      )
                                                                         );
                    XPackageFragmentInstallers.Add(FilePackageFragmentInstaller);
                }
                #endregion


                #region FileXslTransformationPackageFragmentInstaller
                if (XslFiles.Count > 0)
                {
                    XPackageFragmentInstallers.Add(new XElement(mi + "Add",
                                                                new XAttribute("installerType", "Composite.Core.PackageSystem.PackageFragmentInstallers.FileXslTransformationPackageFragmentInstaller, Composite"),
                                                                new XAttribute("uninstallerType", "Composite.Core.PackageSystem.PackageFragmentInstallers.FileXslTransformationPackageFragmentUninstaller, Composite"),
                                                                new XElement("XslFiles"
                                                                             , XslFiles
                                                                             )
                                                                )
                                                   );
                }
                #endregion

                XPackageFragmentInstallers.Add(DynamicDataTypePackageFragmentInstaller);

                #region DataPackageFragmentInstaller
                if (Datas.Count > 0)
                {
                    var DataPackageFragmentInstaller = new XElement(mi + "Add",
                                                                    new XAttribute("installerType", "Composite.Core.PackageSystem.PackageFragmentInstallers.DataPackageFragmentInstaller, Composite"),
                                                                    new XAttribute("uninstallerType", "Composite.Core.PackageSystem.PackageFragmentInstallers.DataPackageFragmentUninstaller, Composite"),
                                                                    new XElement("Types",
                                                                                 from t in Datas
                                                                                 orderby t.Key
                                                                                 orderby DataPosition(t.Value.AttributeValue("type"))
                                                                                 select t.Value
                                                                                 )
                                                                    );
                    XPackageFragmentInstallers.Add(DataPackageFragmentInstaller);
                }
                #endregion

                DataFiles.Save();

                XPackageFragmentInstallers.ReplaceNodes(XPackageFragmentInstallers.Elements().OrderBy(FragmentPosition).Select(DeleteOrderingMark));
                XPackageInstaller.Add(XPackageFragmentInstallers);

                XPackage.Add(XPackageInstaller);

                XPackage.SaveTabbed(Path.Combine(_packageDirectoryPath, InstallFilename));

                var zipFilename = _packageName + ".zip";


                #region Zipping
                var filenames   = Directory.GetFiles(_packageDirectoryPath, "*", SearchOption.AllDirectories);
                var directories = Directory.GetDirectories(_packageDirectoryPath, "*", SearchOption.AllDirectories);


                using (var archiveFileStream = File.Create(Path.Combine(_zipDirectoryPath, zipFilename)))
                    using (var archive = new ZipArchive(archiveFileStream, ZipArchiveMode.Create))
                    {
                        foreach (string directory in directories)
                        {
                            string directoryEntryName = directory.Replace(_packageDirectoryPath + "\\", "").Replace("\\", "/") + "/";

                            var dirEntry = archive.CreateEntry(directoryEntryName);
                            dirEntry.LastWriteTime = Directory.GetLastWriteTime(directory);
                        }

                        foreach (string file in filenames)
                        {
                            string fileEntryName = file.Replace(_packageDirectoryPath + "\\", "").Replace("\\", "/");

                            var entry = archive.CreateEntry(fileEntryName, PackageCompressionLevel);

                            using (var fileStream = File.OpenRead(file))
                                using (var entryStream = entry.Open())
                                {
                                    fileStream.CopyTo(entryStream);
                                }
                        }
                    }
                #endregion

                var packageCreatorDirectory = Path.Combine(_packageDirectoryPath, "../_" + CREATOR_DRECTORY);
                try
                {
                    Directory.CreateDirectory(packageCreatorDirectory);

                    var packageCopyFilePath = packageCreatorDirectory + @"\" + _packageName + ".xml";
                    File.Copy(packageConfigFilePath, packageCopyFilePath);
                    SetFileReadAccess(packageCopyFilePath, false);
                }
                catch { }

                try
                {
                    if (Directory.Exists(dataPackageDirectoryPath))
                    {
                        FileSystem.CopyDirectory(dataPackageDirectoryPath, packageCreatorDirectory + @"\" + _packageName + "_Data");
                    }
                }
                catch { }

                return(Path.Combine(_packageName, "Release", zipFilename));
            }
        }
예제 #8
0
 internal bool ContainsInterfaceType(DataTypeDescriptor dataTypeDescriptor)
 {
     return(ContainsInterfaceType(dataTypeDescriptor.DataTypeId));
 }
        private static void AddInterfaceProperties(CodeTypeDeclaration codeTypeDeclaratoin, DataTypeDescriptor dataTypeDescriptor, List <string> propertyNamesToSkip)
        {
            foreach (DataFieldDescriptor dataFieldDescriptor in dataTypeDescriptor.Fields.Where(dfd => dfd.Inherited == false))
            {
                if (propertyNamesToSkip.Contains(dataFieldDescriptor.Name))
                {
                    continue;
                }

                var codeMemberProperty = new CodeMemberProperty
                {
                    Name   = dataFieldDescriptor.Name,
                    Type   = new CodeTypeReference(dataFieldDescriptor.InstanceType),
                    HasGet = true,
                    HasSet = true
                };

                AddPropertyAttributes(codeMemberProperty, dataFieldDescriptor, dataTypeDescriptor.KeyPropertyNames.Contains(dataFieldDescriptor.Name));

                codeTypeDeclaratoin.Members.Add(codeMemberProperty);
            }
        }
        /// <summary>
        /// Checks that tables related to specified data type included in current DataContext class, if not - compiles a new version of DataContext that contains them
        /// </summary>
        private HelperClassesGenerationInfo EnsureNeededTypes(
            DataTypeDescriptor dataTypeDescriptor,
            IEnumerable <SqlDataTypeStoreDataScope> sqlDataTypeStoreDataScopes,
            Dictionary <DataTypeDescriptor, IEnumerable <SqlDataTypeStoreDataScope> > allSqlDataTypeStoreDataScopes,
            Type dataContextClassType,
            out Dictionary <SqlDataTypeStoreTableKey, StoreTypeInfo> fields,
            ref bool dataContextRecompileNeeded, bool forceCompile = false)
        {
            lock (_lock)
            {
                // Getting the interface (ensuring that it exists)
                Type interfaceType = DataTypeTypesManager.GetDataType(dataTypeDescriptor);

                var storeDataScopesToCompile       = new List <SqlDataTypeStoreDataScope>();
                var storeDataScopesAlreadyCompiled = new List <SqlDataTypeStoreDataScope>();

                fields = new Dictionary <SqlDataTypeStoreTableKey, StoreTypeInfo>();

                foreach (SqlDataTypeStoreDataScope storeDataScope in sqlDataTypeStoreDataScopes)
                {
                    string dataContextFieldName = NamesCreator.MakeDataContextFieldName(storeDataScope.TableName);

                    FieldInfo dataContextFieldInfo = null;
                    if (dataContextClassType != null)
                    {
                        dataContextFieldInfo = dataContextClassType.GetFields(BindingFlags.Public | BindingFlags.Instance)
                                               .SingleOrDefault(f => f.Name == dataContextFieldName);
                    }


                    string sqlDataProviderHelperClassFullName = NamesCreator.MakeSqlDataProviderHelperClassFullName(dataTypeDescriptor, storeDataScope.DataScopeName, storeDataScope.CultureName, _dataProviderContext.ProviderName);

                    string entityClassName = NamesCreator.MakeEntityClassFullName(dataTypeDescriptor, storeDataScope.DataScopeName, storeDataScope.CultureName, _dataProviderContext.ProviderName);

                    Type sqlDataProviderHelperClass = null, entityClass = null;

                    try
                    {
                        sqlDataProviderHelperClass = TryGetGeneratedType(sqlDataProviderHelperClassFullName);
                        entityClass = TryGetGeneratedType(entityClassName);

                        forceCompile = forceCompile ||
                                       CodeGenerationManager.IsRecompileNeeded(interfaceType, new[] { sqlDataProviderHelperClass, entityClass });
                    }
                    catch (TypeLoadException)
                    {
                        forceCompile = true;
                    }

                    if (!forceCompile)
                    {
                        var storeTypeInfo = new StoreTypeInfo(dataContextFieldName, entityClass, sqlDataProviderHelperClass)
                        {
                            DataContextField = dataContextFieldInfo
                        };

                        fields.Add(new SqlDataTypeStoreTableKey(storeDataScope.DataScopeName, storeDataScope.CultureName), storeTypeInfo);
                    }

                    if (dataContextFieldInfo == null)
                    {
                        dataContextRecompileNeeded = true;
                    }

                    if (forceCompile)
                    {
                        storeDataScopesToCompile.Add(storeDataScope);
                    }
                    else
                    {
                        storeDataScopesAlreadyCompiled.Add(storeDataScope);
                    }
                }


                if (storeDataScopesToCompile.Any())
                {
                    dataContextRecompileNeeded = true;

                    if (!dataTypeDescriptor.IsCodeGenerated)
                    {
                        // Building a new descriptor so generated classes take in account field changes
                        dataTypeDescriptor = DynamicTypeManager.BuildNewDataTypeDescriptor(interfaceType);
                    }

                    return(CompileMissingClasses(dataTypeDescriptor, allSqlDataTypeStoreDataScopes, fields,
                                                 storeDataScopesToCompile, storeDataScopesAlreadyCompiled));
                }
            }

            return(null);
        }
예제 #11
0
 private void UpdateDataTypeStore(DataTypeDescriptor dataTypeDescriptor, Type interfaceType, XmlDataTypeStore xmlDateTypeStore)
 {
     _xmlDataTypeStoresContainer.UpdateSupportedDataTypeStore(interfaceType, xmlDateTypeStore);
 }
예제 #12
0
 private static string CreateFilename(DataTypeDescriptor dataTypeDescriptor)
 {
     return(Path.Combine(_metaDataPath, string.Format("{0} {1}.xml", dataTypeDescriptor.Name, dataTypeDescriptor.DataTypeId)));
 }
        internal static IEnumerable <Assembly> GetReferencedAssemblies(DataTypeDescriptor dataTypeDescriptor)
        {
            yield return(typeof(ImmutableTypeIdAttribute).Assembly);

            yield return(typeof(Microsoft.Practices.EnterpriseLibrary.Validation.Validators.NotNullValidatorAttribute).Assembly);
        }
        /// <summary>
        /// Adds the source code defined by <see cref="DataTypeDescriptor"/> to the supplied  <see cref="CodeGenerationBuilder"/>
        /// </summary>
        /// <param name="codeGenerationBuilder">Source code is added to this builder</param>
        /// <param name="dataTypeDescriptor">Data type descriptor to convert into source code</param>
        public static void AddInterfaceTypeCode(CodeGenerationBuilder codeGenerationBuilder, DataTypeDescriptor dataTypeDescriptor)
        {
            var codeTypeDeclaration = CreateCodeTypeDeclaration(dataTypeDescriptor);

            var codeNamespace = new CodeNamespace(dataTypeDescriptor.Namespace);

            codeNamespace.Types.Add(codeTypeDeclaration);
            codeGenerationBuilder.AddNamespace(codeNamespace);
        }
 /// <summary>
 /// Adds the assembly references required by the supplied <see cref="DataTypeDescriptor"/> to the supplied  <see cref="CodeGenerationBuilder"/>
 /// </summary>
 /// <param name="codeGenerationBuilder">Assembly refences is added to this builder</param>
 /// <param name="dataTypeDescriptor">Data type descriptor which may contain references to assemblies</param>
 public static void AddAssemblyReferences(CodeGenerationBuilder codeGenerationBuilder, DataTypeDescriptor dataTypeDescriptor)
 {
     foreach (Assembly assembly in GetReferencedAssemblies(dataTypeDescriptor))
     {
         codeGenerationBuilder.AddReference(assembly);
     }
 }
        /// <exclude />
        public static DataTypeDescriptor Build(Type type)
        {
            Verify.ArgumentNotNull(type, "type");
            Verify.ArgumentCondition(typeof(IData).IsAssignableFrom(type), "type", "{0} does not implement {1}".FormatWith(type.FullName, typeof(IData).FullName));

            Guid dataTypeId = DynamicTypeReflectionFacade.GetImmutableTypeId(type);

            bool isCodeGenerated = type.GetCustomInterfaceAttributes<CodeGeneratedAttribute>().Any();

            var typeDescriptor = new DataTypeDescriptor(dataTypeId, type.Namespace, type.Name, TypeManager.SerializeType(type), isCodeGenerated)
            {
                Title = DynamicTypeReflectionFacade.GetTitle(type),
                LabelFieldName = DynamicTypeReflectionFacade.GetLabelPropertyName(type),
                InternalUrlPrefix = DynamicTypeReflectionFacade.GetInternalUrlPrefix(type),
                DataAssociations = DynamicTypeReflectionFacade.GetDataTypeAssociationDescriptors(type)
            };
            
            List<Type> superInterfaces = type.GetInterfacesRecursively(t => typeof(IData).IsAssignableFrom(t) && t != typeof(IData));
            typeDescriptor.SetSuperInterfaces(superInterfaces);
            
            Type buildNewHandlerType = DynamicTypeReflectionFacade.GetBuildNewHandlerType(type);
            if (buildNewHandlerType != null) typeDescriptor.BuildNewHandlerTypeName = TypeManager.SerializeType(buildNewHandlerType);


            foreach (PropertyInfo propertyInfo in type.GetProperties())
            {
                DataFieldDescriptor fieldDescriptor = BuildFieldDescriptor(propertyInfo, false);

                typeDescriptor.Fields.Add(fieldDescriptor);
            }

            foreach (Type superInterfaceType in superInterfaces)
            {
                foreach (PropertyInfo propertyInfo in superInterfaceType.GetProperties())
                {
                    if (propertyInfo.Name == nameof(IPageData.PageId) && propertyInfo.DeclaringType == typeof(IPageData))
                    {
                        continue;
                    }

                    DataFieldDescriptor fieldDescriptor = BuildFieldDescriptor(propertyInfo, true);

                    typeDescriptor.Fields.Add(fieldDescriptor);
                }
            }

            ValidateAndAddKeyProperties(typeDescriptor.KeyPropertyNames, typeDescriptor.VersionKeyPropertyNames, type);

            string[] storeSortOrder = DynamicTypeReflectionFacade.GetSortOrder(type);
            if (storeSortOrder != null)
            {
                foreach (string name in storeSortOrder)
                {
                    typeDescriptor.StoreSortOrderFieldNames.Add(name);
                }
            }

            CheckSortOrder(typeDescriptor);

            foreach (var dataScopeIdentifier in DynamicTypeReflectionFacade.GetDataScopes(type))
            {
                if (!typeDescriptor.DataScopes.Contains(dataScopeIdentifier))
                {
                    typeDescriptor.DataScopes.Add(dataScopeIdentifier);
                }
            }

            foreach (string keyPropertyName in type.GetKeyPropertyNames())
            {
                if (typeDescriptor.Fields[keyPropertyName] == null)
                {
                    throw new InvalidOperationException(
                        $"The type '{type}' has a non existing key property specified by the attribute '{typeof (KeyPropertyNameAttribute)}'");
                }
            }

            var indexes = new List<DataTypeIndex>();
            foreach (var indexAttribute in type.GetCustomAttributesRecursively<IndexAttribute>())
            {
                foreach (var field in indexAttribute.Fields)
                {
                    if (typeDescriptor.Fields[field.Item1] == null)
                    {
                        throw new InvalidOperationException($"Index field '{field.Item1}' is not defined");
                    }
                }

                indexes.Add(new DataTypeIndex(indexAttribute.Fields) { Clustered = indexAttribute.Clustered });
            }

            indexes.Sort((a,b) => string.Compare(a.ToString(), b.ToString(), StringComparison.Ordinal));

            typeDescriptor.Indexes = indexes;

            return typeDescriptor;
        }
예제 #17
0
        private void CreateNewType()
        {
            _newDataTypeDescriptor = CreateNewDataTypeDescriptor();

            GeneratedTypesFacade.GenerateNewType(_newDataTypeDescriptor);
        }
예제 #18
0
 private static string GetStoreName(DataTypeDescriptor dtd) => dtd.GetFullInterfaceName();
예제 #19
0
        private DataTypeDescriptor CreateNewDataTypeDescriptor(
            string typeNamespace,
            string typeName,
            string typeTitle,
            string labelFieldName,
            string internalUrlPrefix,
            bool cachable,
            bool publishControlled,
            bool localizedControlled,
            IEnumerable <DataFieldDescriptor> dataFieldDescriptors,
            DataFieldDescriptor foreignKeyDataFieldDescriptor,
            DataTypeAssociationDescriptor dataTypeAssociationDescriptor,
            DataFieldDescriptor compositionRuleForeignKeyDataFieldDescriptor)
        {
            Guid id = Guid.NewGuid();
            var  dataTypeDescriptor = new DataTypeDescriptor(id, typeNamespace, typeName, true)
            {
                Cachable          = cachable,
                Title             = typeTitle,
                LabelFieldName    = labelFieldName,
                InternalUrlPrefix = internalUrlPrefix
            };

            dataTypeDescriptor.DataScopes.Add(DataScopeIdentifier.Public);

            if (publishControlled && _dataAssociationType != DataAssociationType.Composition)
            {
                dataTypeDescriptor.AddSuperInterface(typeof(IPublishControlled));
            }

            if (localizedControlled)
            {
                dataTypeDescriptor.AddSuperInterface(typeof(ILocalizedControlled));
            }

            //bool addKeyField = true;
            if (_dataAssociationType == DataAssociationType.Aggregation)
            {
                dataTypeDescriptor.AddSuperInterface(typeof(IPageDataFolder));
            }
            else if (_dataAssociationType == DataAssociationType.Composition)
            {
                //addKeyField = false;
                dataTypeDescriptor.AddSuperInterface(typeof(IPageData));
                dataTypeDescriptor.AddSuperInterface(typeof(IPageRelatedData));
                dataTypeDescriptor.AddSuperInterface(typeof(IPageMetaData));
            }

            //if (addKeyField)
            //{
            //    var idDataFieldDescriptor = BuildKeyFieldDescriptor();

            //    dataTypeDescriptor.Fields.Add(idDataFieldDescriptor);
            //    dataTypeDescriptor.KeyPropertyNames.Add(IdFieldName);
            //}

            foreach (DataFieldDescriptor dataFieldDescriptor in dataFieldDescriptors)
            {
                dataTypeDescriptor.Fields.Add(dataFieldDescriptor);
            }

            if (_newKeyFieldName != null)
            {
                dataTypeDescriptor.KeyPropertyNames.Add(_newKeyFieldName);
            }

            int position = 100;

            if (_foreignKeyDataFieldDescriptor != null)
            {
                _foreignKeyDataFieldDescriptor.Position = position++;

                if (foreignKeyDataFieldDescriptor.Name != PageReferenceFieldName)
                {
                    dataTypeDescriptor.Fields.Add(foreignKeyDataFieldDescriptor);
                    dataTypeDescriptor.DataAssociations.Add(dataTypeAssociationDescriptor);
                }
            }


            return(dataTypeDescriptor);
        }
예제 #20
0
 internal void Remove(DataTypeDescriptor dataTypeDescriptor)
 {
     Remove(dataTypeDescriptor.DataTypeId);
 }
예제 #21
0
        //private DataFieldDescriptor BuildKeyFieldDescriptor()
        //{
        //    DataFieldDescriptor result;

        //    switch (_keyFieldType)
        //    {
        //        case KeyFieldType.Guid:
        //            result = BuildIdField();
        //            break;
        //        case KeyFieldType.RandomString4:
        //            result = new DataFieldDescriptor(Guid.NewGuid(), IdFieldName, StoreFieldType.String(22), typeof (string))
        //            {
        //                DefaultValue = DefaultValue.RandomString(4, true)
        //            };
        //            break;
        //        case KeyFieldType.RandomString8:
        //            result = new DataFieldDescriptor(Guid.NewGuid(), IdFieldName, StoreFieldType.String(22), typeof (string))
        //            {
        //                DefaultValue = DefaultValue.RandomString(8, false)
        //            };
        //            break;
        //        default: throw new InvalidOperationException("Not supported key field type value");
        //    }

        //    result.Position = -1;

        //    return result;
        //}


        private DataTypeDescriptor CreateUpdatedDataTypeDescriptor()
        {
            var dataTypeDescriptor = new DataTypeDescriptor(_oldDataTypeDescriptor.DataTypeId, _newTypeNamespace, _newTypeName, true);

            dataTypeDescriptor.DataScopes.Add(DataScopeIdentifier.Public);

            dataTypeDescriptor.Cachable = _cachable;


            Type[] indirectlyInheritedInterfaces =
            {
                typeof(IPublishControlled), typeof(ILocalizedControlled),
                typeof(IPageData),          typeof(IPageFolderData), typeof(IPageMetaData)
            };

            // Foreign interfaces should stay inherited
            foreach (var superInterface in _oldDataTypeDescriptor.SuperInterfaces)
            {
                if (!indirectlyInheritedInterfaces.Contains(superInterface))
                {
                    dataTypeDescriptor.AddSuperInterface(superInterface);
                }
            }


            if (_publishControlled && _dataAssociationType != DataAssociationType.Composition)
            {
                dataTypeDescriptor.AddSuperInterface(typeof(IPublishControlled));
            }

            if (_localizedControlled && _dataAssociationType != DataAssociationType.Composition)
            {
                dataTypeDescriptor.AddSuperInterface(typeof(ILocalizedControlled));
            }


            if (_oldDataTypeDescriptor.SuperInterfaces.Contains(typeof(IPageFolderData)))
            {
                dataTypeDescriptor.AddSuperInterface(typeof(IPageData));
                dataTypeDescriptor.AddSuperInterface(typeof(IPageFolderData));
            }
            else if (_oldDataTypeDescriptor.SuperInterfaces.Contains(typeof(IPageMetaData)))
            {
                dataTypeDescriptor.AddSuperInterface(typeof(IPageData));
                dataTypeDescriptor.AddSuperInterface(typeof(IPageMetaData));
            }
            else
            {
                //DataFieldDescriptor idDataFieldDescriptor =
                //    (from dfd in _oldDataTypeDescriptor.Fields
                //     where dfd.Name == KeyFieldName
                //     select dfd).Single();

                //dataTypeDescriptor.Fields.Add(idDataFieldDescriptor);
                //dataTypeDescriptor.KeyPropertyNames.Add(KeyFieldName);
            }

            dataTypeDescriptor.Title = _newTypeTitle;

            foreach (DataFieldDescriptor dataFieldDescriptor in _newDataFieldDescriptors)
            {
                dataTypeDescriptor.Fields.Add(dataFieldDescriptor);
            }

            if (KeyFieldName != null && !dataTypeDescriptor.KeyPropertyNames.Contains(KeyFieldName))
            {
                dataTypeDescriptor.KeyPropertyNames.Add(KeyFieldName);
            }


            dataTypeDescriptor.LabelFieldName    = _newLabelFieldName;
            dataTypeDescriptor.InternalUrlPrefix = _newInternalUrlPrefix;

            dataTypeDescriptor.DataAssociations.AddRange(_oldDataTypeDescriptor.DataAssociations);

            int position = 100;

            if (_foreignKeyDataFieldDescriptor != null)
            {
                _foreignKeyDataFieldDescriptor.Position = position++;

                if (_foreignKeyDataFieldDescriptor.Name != PageReferenceFieldName)
                {
                    dataTypeDescriptor.Fields.Add(_foreignKeyDataFieldDescriptor);
                }
            }

            return(dataTypeDescriptor);
        }
예제 #22
0
 public static void CreateStore(string providerName, DataTypeDescriptor typeDescriptor)
 {
     CreateStores(providerName, new[] { typeDescriptor });
 }
예제 #23
0
        internal static void AddEmptyDataClassTypeCode(CodeGenerationBuilder codeGenerationBuilder, DataTypeDescriptor dataTypeDescriptor, Type baseClassType = null, CodeAttributeDeclaration codeAttributeDeclaration = null)
        {
            Type interfaceType = DataTypeTypesManager.GetDataType(dataTypeDescriptor);

            if (interfaceType == null)
            {
                return;
            }

            if (baseClassType == null)
            {
                baseClassType = typeof(EmptyDataClassBase);
            }

            CodeTypeDeclaration codeTypeDeclaration = CreateCodeTypeDeclaration(dataTypeDescriptor, baseClassType, codeAttributeDeclaration);

            codeGenerationBuilder.AddType(NamespaceName, codeTypeDeclaration);
        }
예제 #24
0
        private static DataTypeDescriptorFormsHelper CreateDataTypeDescriptorFormsHelper(IPageMetaDataDefinition pageMetaDataDefinition, DataTypeDescriptor dataTypeDescriptor)
        {
            var bindingPrefix = $"{pageMetaDataDefinition.Name}:{dataTypeDescriptor.Namespace}.{dataTypeDescriptor.Name}";

            var helper = new DataTypeDescriptorFormsHelper(dataTypeDescriptor, bindingPrefix);

            var generatedTypesHelper = new GeneratedTypesHelper(dataTypeDescriptor);

            helper.AddReadOnlyFields(generatedTypesHelper.NotEditableDataFieldDescriptorNames);

            helper.FieldGroupLabel = StringResourceSystemFacade.ParseString(pageMetaDataDefinition.Label);

            return(helper);
        }
예제 #25
0
 internal static string GetEmptyClassTypeFullName(DataTypeDescriptor dataTypeDescriptor)
 {
     return(NamespaceName + "." + CreateClassName(dataTypeDescriptor.GetFullInterfaceName()));
 }
예제 #26
0
 private static bool IsObsoleteField(DataTypeDescriptor dataTypeDescriptor, string fieldName)
 {
     return(dataTypeDescriptor.SuperInterfaces.Any(type => type == typeof(ILocalizedControlled)) &&
            fieldName == "CultureName");
 }
예제 #27
0
        internal static void AddAssemblyReferences(CodeGenerationBuilder codeGenerationBuilder, DataTypeDescriptor dataTypeDescriptor)
        {
            Type interfaceType = DataTypeTypesManager.GetDataType(dataTypeDescriptor);

            if (interfaceType == null)
            {
                return;
            }

            codeGenerationBuilder.AddReference(typeof(EmptyDataClassBase).Assembly);
            codeGenerationBuilder.AddReference(typeof(EditorBrowsableAttribute).Assembly);
            codeGenerationBuilder.AddReference(interfaceType.Assembly);

            if (!string.IsNullOrEmpty(dataTypeDescriptor.BuildNewHandlerTypeName))
            {
                Type buildeNewHandlerType = TypeManager.GetType(dataTypeDescriptor.BuildNewHandlerTypeName);
                codeGenerationBuilder.AddReference(buildeNewHandlerType.Assembly);
            }
        }
예제 #28
0
 public TypeKeyInstallationData(DataTypeDescriptor typeDescriptor)
 {
     _isLocalized   = typeDescriptor.SuperInterfaces.Contains(typeof(ILocalizedControlled));
     _isPublishable = typeDescriptor.SuperInterfaces.Contains(typeof(IPublishControlled));
     _typeName      = typeDescriptor.Name;
 }
예제 #29
0
 internal static string MakeDataProviderHelperClassName(DataTypeDescriptor dataTypeDescriptor)
 {
     return(string.Format("{0}DataProviderHelper", dataTypeDescriptor.GetFullInterfaceName().Replace('.', '_').Replace('+', '_')));
 }
        /// <summary>
        /// Returns null if no alternate form exists.
        /// </summary>
        /// <exclude />
        public static string GetAlternateFormMarkup(DataTypeDescriptor dataTypeDescriptor)
        {
            var file = GetAlternateFormMarkupFile(dataTypeDescriptor.Namespace, dataTypeDescriptor.Name);

            return file != null ? file.ReadAllText() : null;
        }
예제 #31
0
        internal static InterfaceConfigurationElement RefreshLocalizationInfo(string providerName, DataTypeDescriptor dataTypeDescriptor)
        {
            var changeDescriptor = new DataTypeChangeDescriptor(dataTypeDescriptor, dataTypeDescriptor);

            return(Change(providerName, changeDescriptor, true));
        }
예제 #32
0
 public DataWrapperClassGenerator(string wrapperClassName, DataTypeDescriptor dataTypeDescriptor)
 {
     _wrapperClassName   = wrapperClassName;
     _dataTypeDescriptor = dataTypeDescriptor;
 }
예제 #33
0
 /// <summary>
 /// Gets the runtime empty data type for the given data type descriptor.
 /// </summary>
 /// <param name="dataTypeDescriptor"></param>
 /// <returns></returns>
 public static Type GetDataTypeEmptyClass(DataTypeDescriptor dataTypeDescriptor)
 {
     return(EmptyDataClassTypeManager.GetEmptyDataClassType(dataTypeDescriptor, false));
 }
        //private static WidgetFunctionProvider GetWidgetFunctionMarkup(Type propertyType)
        //{
        //    if (propertyType == typeof(string))
        //    {
        //        return StandardWidgetFunctions.TextBoxWidget;
        //    }
        //    if (propertyType == typeof(Guid))
        //    {
        //        return StandardWidgetFunctions.GuidTextBoxWidget;
        //    }
        //    if (propertyType == typeof(int))
        //    {
        //        return StandardWidgetFunctions.IntegerTextBoxWidget;
        //    }
        //    if (propertyType == typeof(DateTime))
        //    {
        //        return StandardWidgetFunctions.DateTimeSelectorWidget;
        //    }
        //    if (propertyType == typeof(decimal))
        //    {
        //        return StandardWidgetFunctions.DecimalTextBoxWidget;
        //    }
        //    return null;
        //}



        private static void CheckSortOrder(DataTypeDescriptor typeDescriptor)
        {
            if (typeDescriptor.StoreSortOrderFieldNames.Count == 0) return;


            if (typeDescriptor.StoreSortOrderFieldNames.Count != typeDescriptor.Fields.Count)
            {
                throw new InvalidOperationException("The store sort order attribute should list all the fields of the interface");
            }
        }
        private static void AddInterfaceAttributes(CodeTypeDeclaration codeTypeDeclaration, DataTypeDescriptor dataTypeDescriptor)
        {
            codeTypeDeclaration.CustomAttributes.Add(
                new CodeAttributeDeclaration(
                    typeof(AutoUpdatebleAttribute).FullName,
                    new CodeAttributeArgument[] {
            }
                    ));


            codeTypeDeclaration.CustomAttributes.Add(
                new CodeAttributeDeclaration(
                    typeof(DataScopeAttribute).FullName,
                    new [] {
                new CodeAttributeArgument(
                    new CodePrimitiveExpression(DataScopeIdentifier.GetDefault().Name))
            }
                    ));


            codeTypeDeclaration.CustomAttributes.Add(
                new CodeAttributeDeclaration(
                    typeof(RelevantToUserTypeAttribute).FullName,
                    new [] {
                new CodeAttributeArgument(
                    new CodePrimitiveExpression(UserType.Developer.ToString()))
            }
                    ));


            codeTypeDeclaration.CustomAttributes.Add(
                new CodeAttributeDeclaration(
                    typeof(CodeGeneratedAttribute).FullName,
                    new CodeAttributeArgument[] {
            }
                    ));


            codeTypeDeclaration.CustomAttributes.Add(
                new CodeAttributeDeclaration(
                    typeof(DataAncestorProviderAttribute).FullName,
                    new [] {
                new CodeAttributeArgument(
                    new CodeTypeOfExpression(typeof(NoAncestorDataAncestorProvider))
                    )
            }
                    ));

            codeTypeDeclaration.CustomAttributes.Add(
                new CodeAttributeDeclaration(
                    typeof(ImmutableTypeIdAttribute).FullName,
                    new [] {
                new CodeAttributeArgument(new CodePrimitiveExpression(dataTypeDescriptor.DataTypeId.ToString()))
            }
                    ));


            var xhtmlEmbedableEnumRef =
                new CodeFieldReferenceExpression(
                    new CodeTypeReferenceExpression(
                        typeof(XhtmlRenderingType)
                        ),
                    XhtmlRenderingType.Embedable.ToString());

            codeTypeDeclaration.CustomAttributes.Add(
                new CodeAttributeDeclaration(
                    typeof(KeyTemplatedXhtmlRendererAttribute).FullName,
                    new [] {
                new CodeAttributeArgument(xhtmlEmbedableEnumRef),
                new CodeAttributeArgument(new CodePrimitiveExpression("<span>{label}</span>"))
            }
                    ));



            foreach (string keyFieldName in dataTypeDescriptor.KeyPropertyNames)
            {
                bool isDefinedOnSuperInterface = dataTypeDescriptor.SuperInterfaces.Any(f => f.GetProperty(keyFieldName) != null);

                if (!isDefinedOnSuperInterface)
                {
                    codeTypeDeclaration.CustomAttributes.Add(
                        new CodeAttributeDeclaration(
                            typeof(KeyPropertyNameAttribute).FullName,
                            new [] {
                        new CodeAttributeArgument(new CodePrimitiveExpression(keyFieldName))
                    }
                            ));
                }
            }

            if (dataTypeDescriptor.StoreSortOrderFieldNames.Count > 0)
            {
                codeTypeDeclaration.CustomAttributes.Add(
                    new CodeAttributeDeclaration(
                        typeof(StoreSortOrderAttribute).FullName,
                        dataTypeDescriptor.StoreSortOrderFieldNames.Select(name => new CodeAttributeArgument(new CodePrimitiveExpression(name))).ToArray()
                        ));
            }

            if (!string.IsNullOrEmpty(dataTypeDescriptor.Title))
            {
                codeTypeDeclaration.CustomAttributes.Add(
                    new CodeAttributeDeclaration(
                        typeof(TitleAttribute).FullName,
                        new CodeAttributeArgument(
                            new CodePrimitiveExpression(dataTypeDescriptor.Title)
                            )
                        ));
            }

            if (!string.IsNullOrEmpty(dataTypeDescriptor.LabelFieldName))
            {
                codeTypeDeclaration.CustomAttributes.Add(
                    new CodeAttributeDeclaration(
                        typeof(LabelPropertyNameAttribute).FullName,
                        new CodeAttributeArgument(
                            new CodePrimitiveExpression(dataTypeDescriptor.LabelFieldName)
                            )
                        ));
            }

            if (!string.IsNullOrEmpty(dataTypeDescriptor.InternalUrlPrefix))
            {
                codeTypeDeclaration.CustomAttributes.Add(
                    new CodeAttributeDeclaration(
                        typeof(InternalUrlAttribute).FullName,
                        new CodeAttributeArgument(
                            new CodePrimitiveExpression(dataTypeDescriptor.InternalUrlPrefix)
                            )
                        ));
            }


            foreach (DataTypeAssociationDescriptor dataTypeAssociationDescriptor in dataTypeDescriptor.DataAssociations)
            {
                codeTypeDeclaration.CustomAttributes.Add(
                    new CodeAttributeDeclaration(
                        typeof(DataAssociationAttribute).FullName,
                        new [] {
                    new CodeAttributeArgument(new CodeTypeOfExpression(dataTypeAssociationDescriptor.AssociatedInterfaceType)),
                    new CodeAttributeArgument(new CodePrimitiveExpression(dataTypeAssociationDescriptor.ForeignKeyPropertyName)),
                    new CodeAttributeArgument(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(DataAssociationType)), dataTypeAssociationDescriptor.AssociationType.ToString()))
                }
                        ));
            }


            if (dataTypeDescriptor.SuperInterfaces.Contains(typeof(IPageMetaData)) == false)
            {
                if (dataTypeDescriptor.SuperInterfaces.Contains(typeof(IPublishControlled)))
                {
                    codeTypeDeclaration.CustomAttributes.Add(
                        new CodeAttributeDeclaration(
                            typeof(PublishProcessControllerTypeAttribute).FullName,
                            new[] {
                        new CodeAttributeArgument(new CodeTypeOfExpression(typeof(GenericPublishProcessController)))
                    }
                            ));
                }
            }


            if (dataTypeDescriptor.Cachable)
            {
                // [CachingAttribute(CachingType.Full)]
                codeTypeDeclaration.CustomAttributes.Add(
                    new CodeAttributeDeclaration(
                        typeof(CachingAttribute).FullName,
                        new CodeAttributeArgument[] {
                    new CodeAttributeArgument(
                        new CodeFieldReferenceExpression(
                            new CodeTypeReferenceExpression(typeof(CachingType)),
                            "Full"
                            )
                        )
                }
                        ));
            }
        }