Exemplo n.º 1
0
        /// <summary>
        /// This method will remove a foreign key (if any exists) that is no longer possible with the
        /// new meta data system (IPageMetaDataDefinition)
        /// </summary>
        /// <param name="dataTypeDescriptor"></param>
        /// <param name="dataStoreExists"></param>
        private void UpdateWithNewPageFolderForeignKeySystem(DataTypeDescriptor dataTypeDescriptor, bool dataStoreExists)
        {
            if (dataTypeDescriptor.IsPageFolderDataType == false)
            {
                return;
            }

            DataFieldDescriptor dataFieldDescriptor = dataTypeDescriptor.Fields["IAggregationDescriptionIdForeignKey"];

            if (dataFieldDescriptor == null)
            {
                return;
            }

            Log.LogVerbose("GeneratedTypesFacade", string.Format("Removing the property {0} on the type {1}.{2}", dataFieldDescriptor.Name, dataTypeDescriptor.Namespace, dataTypeDescriptor.Name));

            if (!dataStoreExists)
            {
                dataTypeDescriptor.Fields.Remove(dataFieldDescriptor);
                DynamicTypeManager.UpdateDataTypeDescriptor(dataTypeDescriptor, false);
                return;
            }

            DataTypeDescriptor oldDataTypeDescriptor = dataTypeDescriptor.Clone();

            dataTypeDescriptor.Fields.Remove(dataFieldDescriptor);

            var dataTypeChangeDescriptor = new DataTypeChangeDescriptor(oldDataTypeDescriptor, dataTypeDescriptor);

            var updateDataTypeDescriptor = new UpdateDataTypeDescriptor(oldDataTypeDescriptor, dataTypeDescriptor);

            DynamicTypeManager.AlterStore(updateDataTypeDescriptor, false);
        }
        internal void AlterStoresForType(UpdateDataTypeDescriptor updateDataTypeDescriptor)
        {
            DataTypeChangeDescriptor changeDescriptor = updateDataTypeDescriptor.CreateDataTypeChangeDescriptor();

            lock (_lock)
            {
                foreach (DataScopeIdentifier dataScope in changeDescriptor.AddedDataScopes)
                {
                    CreateScopeData(changeDescriptor.AlteredType, dataScope);
                }

                foreach (DataScopeIdentifier dataScope in changeDescriptor.ExistingDataScopes)
                {
                    AlterScopeData(updateDataTypeDescriptor, changeDescriptor, dataScope);
                }


                if (updateDataTypeDescriptor.PublicationAdded)
                {
                    HandleEnablingOfPublication(changeDescriptor);
                }

                if (updateDataTypeDescriptor.PublicationRemoved)
                {
                    HandleDisablingOfPublication(changeDescriptor);
                }

                foreach (DataScopeIdentifier dataScope in changeDescriptor.DeletedDataScopes)
                {
                    DropScopeData(changeDescriptor.AlteredType, dataScope);
                }
            }
        }
        private void AppendFields(string tableName,
                                  DataTypeChangeDescriptor changeDescriptor,
                                  IEnumerable <DataFieldDescriptor> addedFieldDescriptions,
                                  Dictionary <string, object> defaultValues = null)
        {
            foreach (var addedFieldDescriptor in addedFieldDescriptions)
            {
                string fieldName    = addedFieldDescriptor.Name;
                object defaultValue = null;
                if (defaultValues != null && defaultValues.ContainsKey(fieldName))
                {
                    defaultValue = defaultValues[addedFieldDescriptor.Name];
                }



                CreateColumn(tableName, changeDescriptor.AlteredType, addedFieldDescriptor, defaultValue);

                // Updating VersionId field
                if (addedFieldDescriptor.Name == nameof(IVersioned.VersionId) &&
                    changeDescriptor.AlteredType.SuperInterfaces.Contains(typeof(IVersioned)))
                {
                    string sourceField;

                    if (changeDescriptor.AlteredType.DataTypeId == typeof(IPage).GetImmutableTypeId())
                    {
                        sourceField = nameof(IPage.Id);
                    }
                    else
                    {
                        sourceField = changeDescriptor.AlteredType.Fields
                                      .Where(f => f.InstanceType == typeof(Guid) &&
                                             (f.ForeignKeyReferenceTypeName?.Contains(typeof(IPage).FullName) ?? false))
                                      .OrderByDescending(f => f.Name == nameof(IPageData.PageId))
                                      .Select(f => f.Name)
                                      .FirstOrDefault();
                    }

                    if (sourceField != null)
                    {
                        string updateVersionIdCommandText =
                            $"UPDATE [{tableName}] SET [{nameof(IVersioned.VersionId)}] = [{sourceField}]";
                        ExecuteNonQuery(updateVersionIdCommandText);
                    }
                }
            }
        }
Exemplo n.º 4
0
        public static XmlProviderInterfaceConfigurationElement Change(UpdateDataTypeDescriptor updateDataTypeDescriptor)
        {
            DataTypeChangeDescriptor changeDescriptor = updateDataTypeDescriptor.CreateDataTypeChangeDescriptor();

            var xmlDataProviderConfiguration = new XmlDataProviderConfiguration(updateDataTypeDescriptor.ProviderName);

            object key = xmlDataProviderConfiguration.Section.Interfaces.GetKey(changeDescriptor.OriginalType);

            var oldConfigurationElement = xmlDataProviderConfiguration.Section.Interfaces.Get(key);
            var newConfigurationElement = BuildXmlProviderInterfaceConfigurationElement(changeDescriptor.AlteredType, oldConfigurationElement);

            XmlDataProviderStoreManipulator.AlterStore(updateDataTypeDescriptor, oldConfigurationElement, newConfigurationElement);

            xmlDataProviderConfiguration.Section.Interfaces.Remove(key);
            xmlDataProviderConfiguration.Section.Interfaces.Add(newConfigurationElement);

            xmlDataProviderConfiguration.Save();

            return(newConfigurationElement);
        }
        private static StringBuilder GetCommonFields(DataTypeChangeDescriptor changeDescriptor)
        {
            var fieldList = new StringBuilder();

            foreach (DataFieldDescriptor dataFieldDescriptor in changeDescriptor.OriginalType.Fields)
            {
                if (!changeDescriptor.AlteredType.Fields.Any(f => f.Id == dataFieldDescriptor.Id))
                {
                    continue;
                }

                if (fieldList.Length > 0)
                {
                    fieldList.Append(", ");
                }

                fieldList.Append("[" + dataFieldDescriptor.Name + "]");
            }
            return(fieldList);
        }
Exemplo n.º 6
0
        internal static InterfaceConfigurationElement Change(string providerName, DataTypeChangeDescriptor changeDescriptor, bool localeChanges)
        {
            lock (_syncRoot)
            {
                var originalType = changeDescriptor.OriginalType;
                var alteredType  = changeDescriptor.AlteredType;

                bool typeNameChanged = originalType.Namespace != alteredType.Namespace ||
                                       originalType.Name != alteredType.Name;

                if (!localeChanges &&
                    !changeDescriptor.AddedDataScopes.Any() &&
                    !changeDescriptor.DeletedDataScopes.Any() &&
                    !changeDescriptor.AddedKeyFields.Any() &&
                    !changeDescriptor.DeletedKeyFields.Any() &&
                    !changeDescriptor.KeyFieldsOrderChanged &&
                    !typeNameChanged)
                {
                    // No changes to the config is needed, lets not touch the file.
                    return(null);
                }

                var configuration = new SqlDataProviderConfiguration(providerName);

                Guid dataTypeId = originalType.DataTypeId;

                var existingElement = configuration.Section.Interfaces.Get(originalType);

                Verify.IsNotNull(existingElement, "Configuration does not contain the original interface with id '{0}'", dataTypeId);

                configuration.Section.Interfaces.Remove(originalType);

                InterfaceConfigurationElement newInterfaceConfig = BuildInterfaceConfigurationElement(alteredType, existingElement, typeNameChanged);

                configuration.Section.Interfaces.Add(newInterfaceConfig);

                configuration.Save();

                return(newInterfaceConfig);
            }
        }
        private void HandleDisablingOfPublication(DataTypeChangeDescriptor changeDescriptor)
        {
            IEnumerable <CultureInfo> locales = GetCultures(changeDescriptor.OriginalType);

            foreach (CultureInfo locale in locales)
            {
                string oldTableName = GetConfiguredTableName(changeDescriptor.OriginalType, DataScopeIdentifier.Administrated, locale.Name);
                string newTableName = DynamicTypesCommon.GenerateTableName(changeDescriptor.AlteredType, DataScopeIdentifier.Public, locale);

                StringBuilder fieldList = GetCommonFields(changeDescriptor);

                string removeCommandText = string.Format(@"DELETE FROM [{0}];", newTableName);
                ExecuteNonQuery(removeCommandText);

                string copyCommandText = string.Format(@"
                            INSERT INTO [{0}] ({2})
                            SELECT {2}                             
                            FROM [{1}];", newTableName, oldTableName, fieldList);
                ExecuteNonQuery(copyCommandText);
            }
        }
        private void HandleEnablingOfPublication(DataTypeChangeDescriptor changeDescriptor)
        {
            IEnumerable <CultureInfo> locales = GetCultures(changeDescriptor.OriginalType);

            foreach (CultureInfo locale in locales)
            {
                string oldTableName = GetConfiguredTableName(changeDescriptor.OriginalType, DataScopeIdentifier.Public, locale.Name);
                string newTableName = DynamicTypesCommon.GenerateTableName(changeDescriptor.AlteredType, DataScopeIdentifier.Administrated, locale);

                StringBuilder fieldList = GetCommonFields(changeDescriptor);

                string copyCommandText = string.Format(@"
                            INSERT INTO [{0}] ({2})
                            SELECT {2}                             
                            FROM [{1}];", newTableName, oldTableName, fieldList);
                ExecuteNonQuery(copyCommandText);

                string updateOldCommandText = string.Format("UPDATE [{0}] SET [{1}] = '{2}'", oldTableName, "PublicationStatus", GenericPublishProcessController.Published);
                ExecuteNonQuery(updateOldCommandText);

                string updateNewCommandText = string.Format("UPDATE [{0}] SET [{1}] = '{2}'", newTableName, "PublicationStatus", GenericPublishProcessController.Published);
                ExecuteNonQuery(updateNewCommandText);
            }
        }
Exemplo n.º 9
0
 private static DataTypeChangeDescriptor.ExistingFieldInfo GetExistingFieldInfo(DataTypeChangeDescriptor dataTypeChangeDescriptor, string name)
 {
     return(dataTypeChangeDescriptor.ExistingFields.FirstOrDefault(f => f.OriginalField.Name == name));
 }
Exemplo n.º 10
0
        public static void AlterStore(UpdateDataTypeDescriptor updateDescriptor, XmlProviderInterfaceConfigurationElement oldConfigurationElement, XmlProviderInterfaceConfigurationElement newConfigurationElement)
        {
            DataTypeChangeDescriptor dataTypeChangeDescriptor = updateDescriptor.CreateDataTypeChangeDescriptor();

            foreach (KeyValuePair <string, Type> kvp in oldConfigurationElement.PropertyInitializers)
            {
                newConfigurationElement.AddPropertyInitializer(kvp.Key, kvp.Value);
            }

            Dictionary <string, object> newFieldValues = new Dictionary <string, object>();

            foreach (DataScopeIdentifier scopeIdentifier in dataTypeChangeDescriptor.AddedDataScopes)
            {
                foreach (DataScopeConfigurationElement dataScopeConfigurationElement in newConfigurationElement.DataScopes[scopeIdentifier.Name].Values)
                {
                    CreateStore(updateDescriptor.ProviderName, dataScopeConfigurationElement);
                }
            }



            foreach (DataScopeIdentifier scopeIdentifier in dataTypeChangeDescriptor.ExistingDataScopes)
            {
                foreach (KeyValuePair <string, DataScopeConfigurationElement> fileForLanguage in oldConfigurationElement.DataScopes[scopeIdentifier.Name])
                {
                    string cultureName = fileForLanguage.Key;

                    if (!newConfigurationElement.DataScopes[scopeIdentifier.Name].ContainsKey(cultureName))
                    {
                        continue;
                    }

                    var oldDataScopeConfigurationElement = fileForLanguage.Value;
                    var newDataScopeConfigurationElement = newConfigurationElement.DataScopes[scopeIdentifier.Name][cultureName];

                    newFieldValues = new Dictionary <string, object>
                    {
                        { "PublicationStatus", GenericPublishProcessController.Published }
                    };

                    CopyData(updateDescriptor.ProviderName, dataTypeChangeDescriptor, oldDataScopeConfigurationElement, newDataScopeConfigurationElement, newFieldValues);
                }
            }


            if (updateDescriptor.PublicationAdded)
            {
                foreach (var fileByLanguage in oldConfigurationElement.DataScopes[DataScopeIdentifier.PublicName])
                {
                    var oldDataScopeConfigurationElement = fileByLanguage.Value;
                    var newDataScopeConfigurationElement = newConfigurationElement.DataScopes[DataScopeIdentifier.AdministratedName][fileByLanguage.Key];

                    newFieldValues = new Dictionary <string, object>
                    {
                        { "PublicationStatus", GenericPublishProcessController.Published }
                    };

                    CopyData(updateDescriptor.ProviderName, dataTypeChangeDescriptor, oldDataScopeConfigurationElement, newDataScopeConfigurationElement, newFieldValues, false);
                }
            }

            if (updateDescriptor.PublicationRemoved)
            {
                foreach (var fileByLanguage in oldConfigurationElement.DataScopes[DataScopeIdentifier.AdministratedName])
                {
                    var oldDataScopeConfigurationElement = fileByLanguage.Value;
                    var newDataScopeConfigurationElement = newConfigurationElement.DataScopes[DataScopeIdentifier.PublicName][fileByLanguage.Key];

                    CopyData(updateDescriptor.ProviderName, dataTypeChangeDescriptor, oldDataScopeConfigurationElement, newDataScopeConfigurationElement, newFieldValues, false);
                }
            }


            bool oldTypeLocalized = updateDescriptor.OldDataTypeDescriptor.Localizeable;
            bool newTypeLocalized = updateDescriptor.NewDataTypeDescriptor.Localizeable;

            if (!oldTypeLocalized && newTypeLocalized)
            {
                foreach (var newStore in newConfigurationElement.DataScopes.Values.SelectMany(kvp => kvp.Values))
                {
                    CreateStore(updateDescriptor.ProviderName, newStore);
                }

                foreach (string dataScopeIdentifier in oldConfigurationElement.DataScopes.Keys)
                {
                    var oldFilesByCulture = oldConfigurationElement.DataScopes[dataScopeIdentifier];

                    string invariantCultureKey = "";

                    if (oldFilesByCulture.ContainsKey(invariantCultureKey))
                    {
                        var oldDataScopeConfigurationElement = oldFilesByCulture[invariantCultureKey];

                        if (updateDescriptor.LocalesToCopyTo != null)
                        {
                            foreach (CultureInfo locale in updateDescriptor.LocalesToCopyTo)
                            {
                                var newDataScopeConfigurationElement = newConfigurationElement.DataScopes[dataScopeIdentifier][locale.Name];

                                var nfv = new Dictionary <string, object>(newFieldValues)
                                {
                                    { "SourceCultureName", locale.Name }
                                };

                                CopyData(updateDescriptor.ProviderName, dataTypeChangeDescriptor, oldDataScopeConfigurationElement, newDataScopeConfigurationElement, nfv, false);
                            }
                        }

                        DropStore(updateDescriptor.ProviderName, oldDataScopeConfigurationElement);
                    }
                }
            }

            if (oldTypeLocalized && !newTypeLocalized)
            {
                foreach (var newStore in newConfigurationElement.DataScopes.Values.SelectMany(kvp => kvp.Values))
                {
                    CreateStore(updateDescriptor.ProviderName, newStore);
                }

                if (updateDescriptor.LocaleToCopyFrom != null)
                {
                    foreach (string dataScopeIdentifier in oldConfigurationElement.DataScopes.Keys)
                    {
                        var oldDataScopeConfigurationElement = oldConfigurationElement.DataScopes[dataScopeIdentifier][updateDescriptor.LocaleToCopyFrom.Name];
                        var newDataScopeConfigurationElement = newConfigurationElement.DataScopes[dataScopeIdentifier][""];

                        CopyData(updateDescriptor.ProviderName, dataTypeChangeDescriptor, oldDataScopeConfigurationElement, newDataScopeConfigurationElement, newFieldValues, false);
                    }
                }

                foreach (var oldStore in oldConfigurationElement.DataScopes.SelectMany(d => d.Value).Where(f => f.Key != "").Select(f => f.Value))
                {
                    DropStore(updateDescriptor.ProviderName, oldStore);
                }
            }

            foreach (DataScopeIdentifier scopeIdentifier in dataTypeChangeDescriptor.DeletedDataScopes)
            {
                foreach (DataScopeConfigurationElement dataScopeConfigurationElement in oldConfigurationElement.DataScopes[scopeIdentifier.Name].Values)
                {
                    DropStore(updateDescriptor.ProviderName, dataScopeConfigurationElement);
                }
            }
        }
Exemplo n.º 11
0
        private static void CopyData(string providerName, DataTypeChangeDescriptor dataTypeChangeDescriptor, DataScopeConfigurationElement oldDataScopeConfigurationElement, DataScopeConfigurationElement newDataScopeConfigurationElement, Dictionary <string, object> newFieldValues, bool deleteOldFile = true)
        {
            string oldFilename = ResolvePath(oldDataScopeConfigurationElement.Filename, providerName);
            string newFilename = ResolvePath(newDataScopeConfigurationElement.Filename, providerName);

            XDocument oldDocument = XDocumentUtils.Load(PathUtil.Resolve(oldFilename));

            List <XElement> newElements = new List <XElement>();

            bool addingVersionId = dataTypeChangeDescriptor.AddedFields.Any(f => f.Name == nameof(IVersioned.VersionId)) &&
                                   dataTypeChangeDescriptor.AlteredType.SuperInterfaces.Any(s => s == typeof(IVersioned));

            string versionIdSourceFieldName = null;

            if (addingVersionId)
            {
                if (dataTypeChangeDescriptor.AlteredType.DataTypeId == typeof(IPage).GetImmutableTypeId())
                {
                    versionIdSourceFieldName = nameof(IPage.Id);
                }
                else
                {
                    versionIdSourceFieldName = dataTypeChangeDescriptor.AlteredType.Fields
                                               .Where(f => f.InstanceType == typeof(Guid) &&
                                                      (f.ForeignKeyReferenceTypeName?.Contains(typeof(IPage).FullName) ?? false))
                                               .OrderByDescending(f => f.Name == nameof(IPageData.PageId))
                                               .Select(f => f.Name)
                                               .FirstOrDefault();
                }
            }


            foreach (XElement oldElement in oldDocument.Root.Elements())
            {
                List <XAttribute> newChildAttributes = new List <XAttribute>();

                foreach (XAttribute oldChildAttribute in oldElement.Attributes())
                {
                    var existingFieldInfo = GetExistingFieldInfo(dataTypeChangeDescriptor, oldChildAttribute.Name.LocalName);

                    if (existingFieldInfo != null)
                    {
                        if (existingFieldInfo.OriginalField.Name != existingFieldInfo.AlteredField.Name)
                        {
                            XAttribute newChildAttribute = new XAttribute(existingFieldInfo.AlteredField.Name, oldChildAttribute.Value);

                            newChildAttributes.Add(newChildAttribute);
                        }
                        else
                        {
                            newChildAttributes.Add(oldChildAttribute);
                        }
                    }
                    // It may happen that some data were added before data descriptors are updated, in the case of using
                    // [AutoUpdateable] attribute.
                    else if (dataTypeChangeDescriptor.AddedFields.Any(addedField => addedField.Name == oldChildAttribute.Name))
                    {
                        newChildAttributes.Add(oldChildAttribute);
                    }
                }

                // Adding default value for fields that are NULL and become required
                foreach (var existingFieldInfo in dataTypeChangeDescriptor.ExistingFields)
                {
                    bool fieldBecomeRequired = existingFieldInfo.OriginalField.IsNullable && !existingFieldInfo.AlteredField.IsNullable;

                    string fieldName = existingFieldInfo.AlteredField.Name;

                    if (fieldBecomeRequired && !newChildAttributes.Any(attr => attr.Name.LocalName == fieldName))
                    {
                        newChildAttributes.Add(new XAttribute(fieldName, GetDefaultValue(existingFieldInfo.AlteredField)));
                    }
                }

                foreach (DataFieldDescriptor fieldDescriptor in dataTypeChangeDescriptor.AddedFields)
                {
                    if (addingVersionId && fieldDescriptor.Name == nameof(IVersioned.VersionId) && versionIdSourceFieldName != null)
                    {
                        var existingField = (Guid)oldElement.Attribute(versionIdSourceFieldName);
                        if (existingField != null)
                        {
                            newChildAttributes.Add(new XAttribute(fieldDescriptor.Name, existingField));
                            continue;
                        }
                    }

                    if (!fieldDescriptor.IsNullable &&
                        !newChildAttributes.Any(attr => attr.Name == fieldDescriptor.Name))
                    {
                        object value;
                        if (!newFieldValues.TryGetValue(fieldDescriptor.Name, out value))
                        {
                            value = GetDefaultValue(fieldDescriptor);
                        }

                        newChildAttributes.Add(new XAttribute(fieldDescriptor.Name, value));
                    }
                    else if (newFieldValues.ContainsKey(fieldDescriptor.Name))
                    {
                        XAttribute attribute = newChildAttributes.SingleOrDefault(attr => attr.Name == fieldDescriptor.Name);

                        attribute?.SetValue(newFieldValues[fieldDescriptor.Name]);
                    }
                }

                XElement newElement = new XElement(newDataScopeConfigurationElement.ElementName, newChildAttributes);

                newElements.Add(newElement);
            }

            if (deleteOldFile)
            {
                C1File.Delete(oldFilename);
            }

            XElement newRoot = new XElement(XmlDataProviderDocumentWriter.GetRootElementName(newDataScopeConfigurationElement.ElementName));

            newRoot.Add(newElements);

            XDocument newDocument = new XDocument();

            newDocument.Add(newRoot);

            XDocumentUtils.Save(newDocument, newFilename);
        }
Exemplo n.º 12
0
        private static void CopyData(string providerName, DataTypeChangeDescriptor dataTypeChangeDescriptor, DataScopeConfigurationElement oldDataScopeConfigurationElement, DataScopeConfigurationElement newDataScopeConfigurationElement, Dictionary <string, object> newFieldValues, bool deleteOldFile = true)
        {
            string oldFilename = ResolvePath(oldDataScopeConfigurationElement.Filename, providerName);
            string newFilename = ResolvePath(newDataScopeConfigurationElement.Filename, providerName);

            XDocument oldDocument = XDocumentUtils.Load(PathUtil.Resolve(oldFilename));

            List <XElement> newElements = new List <XElement>();

            foreach (XElement oldElement in oldDocument.Root.Elements())
            {
                List <XAttribute> newChildAttributes = new List <XAttribute>();

                foreach (XAttribute oldChildAttribute in oldElement.Attributes())
                {
                    var existingFieldInfo = GetExistingFieldInfo(dataTypeChangeDescriptor, oldChildAttribute.Name.LocalName);

                    if (existingFieldInfo != null)
                    {
                        if (existingFieldInfo.OriginalField.Name != existingFieldInfo.AlteredField.Name)
                        {
                            XAttribute newChildAttribute = new XAttribute(existingFieldInfo.AlteredField.Name, oldChildAttribute.Value);

                            newChildAttributes.Add(newChildAttribute);
                        }
                        else
                        {
                            newChildAttributes.Add(oldChildAttribute);
                        }
                    }
                    // It may happen that some data were added before data descriptors are updated, in the case of using
                    // [AutoUpdateable] attribute.
                    else if (dataTypeChangeDescriptor.AddedFields.Any(addedField => addedField.Name == oldChildAttribute.Name))
                    {
                        newChildAttributes.Add(oldChildAttribute);
                    }
                }

                // Adding default value for fields that are NULL and become required
                foreach (var existingFieldInfo in dataTypeChangeDescriptor.ExistingFields)
                {
                    bool fieldBecomeRequired = existingFieldInfo.OriginalField.IsNullable && !existingFieldInfo.AlteredField.IsNullable;

                    string fieldName = existingFieldInfo.AlteredField.Name;

                    if (fieldBecomeRequired && !newChildAttributes.Any(attr => attr.Name.LocalName == fieldName))
                    {
                        newChildAttributes.Add(new XAttribute(fieldName, GetDefaultValue(existingFieldInfo.AlteredField)));
                    }
                }

                foreach (DataFieldDescriptor fieldDescriptor in dataTypeChangeDescriptor.AddedFields)
                {
                    if (fieldDescriptor.IsNullable == false &&
                        !newChildAttributes.Any(attr => attr.Name == fieldDescriptor.Name))
                    {
                        XAttribute newChildAttribute = new XAttribute(fieldDescriptor.Name, GetDefaultValue(fieldDescriptor));

                        if (newFieldValues.ContainsKey(fieldDescriptor.Name))
                        {
                            newChildAttribute.SetValue(newFieldValues[fieldDescriptor.Name]);
                        }

                        newChildAttributes.Add(newChildAttribute);
                    }
                    else if (newFieldValues.ContainsKey(fieldDescriptor.Name))
                    {
                        XAttribute attribute = newChildAttributes.SingleOrDefault(attr => attr.Name == fieldDescriptor.Name);
                        if (attribute != null)
                        {
                            attribute.SetValue(newFieldValues[fieldDescriptor.Name]);
                        }
                    }
                }

                XElement newElement = new XElement(newDataScopeConfigurationElement.ElementName, newChildAttributes);

                newElements.Add(newElement);
            }

            if (deleteOldFile)
            {
                C1File.Delete(oldFilename);
            }

            XElement newRoot = new XElement(XmlDataProviderDocumentWriter.GetRootElementName(newDataScopeConfigurationElement.ElementName));

            newRoot.Add(newElements);

            XDocument newDocument = new XDocument();

            newDocument.Add(newRoot);

            XDocumentUtils.Save(newDocument, newFilename);
        }
        private void AlterStore(UpdateDataTypeDescriptor updateDataTypeDescriptor, DataTypeChangeDescriptor changeDescriptor, DataScopeIdentifier dataScope, CultureInfo culture)
        {
            try
            {
                string originalTableName = GetConfiguredTableName(changeDescriptor.OriginalType, dataScope, culture.Name);
                string alteredTableName  = originalTableName;

                // This could be done more nicely! But only give the table a new name if the type has changed its name and not because we changed the naming scheme
                if (updateDataTypeDescriptor.OldDataTypeDescriptor.Name != updateDataTypeDescriptor.NewDataTypeDescriptor.Name ||
                    updateDataTypeDescriptor.OldDataTypeDescriptor.Namespace != updateDataTypeDescriptor.NewDataTypeDescriptor.Namespace)
                {
                    alteredTableName = DynamicTypesCommon.GenerateTableName(changeDescriptor.AlteredType, dataScope, culture);
                }

                var tables = GetTablesList();

                if (!tables.Contains(originalTableName))
                {
                    throw new InvalidOperationException(
                              string.Format(
                                  "Unable to alter data type store. The database does not contain expected table {0}",
                                  originalTableName));
                }


                bool primaryKeyChanged = changeDescriptor.AddedKeyFields.Any() ||
                                         changeDescriptor.DeletedKeyFields.Any() ||
                                         changeDescriptor.KeyFieldsOrderChanged ||
                                         changeDescriptor.OriginalType.PrimaryKeyIsClusteredIndex != changeDescriptor.AlteredType.PrimaryKeyIsClusteredIndex;

                DropConstraints(originalTableName, primaryKeyChanged);

                if (originalTableName != alteredTableName)
                {
                    if (tables.Contains(alteredTableName))
                    {
                        throw new InvalidOperationException(
                                  string.Format("Can not rename table to {0}. A table with that name already exists",
                                                alteredTableName));
                    }
                    RenameTable(originalTableName, alteredTableName);
                }

                var newIndexes = changeDescriptor.AlteredType.Indexes.Select(i => i.ToString()).ToList();
                foreach (var oldIndex in changeDescriptor.OriginalType.Indexes)
                {
                    if (!newIndexes.Contains(oldIndex.ToString()))
                    {
                        DropIndex(alteredTableName, oldIndex);
                    }
                }

                DropFields(alteredTableName, changeDescriptor.DeletedFields, changeDescriptor.OriginalType.Fields);
                ImplementFieldChanges(alteredTableName, changeDescriptor.ExistingFields);


                Dictionary <string, object> defaultValues = null;
                if (updateDataTypeDescriptor.PublicationAdded)
                {
                    defaultValues = new Dictionary <string, object>
                    {
                        { "PublicationStatus", GenericPublishProcessController.Draft }
                    };
                }

                AppendFields(alteredTableName, changeDescriptor.AddedFields, defaultValues);

                // Clustered index has to be created first.
                var createIndexActions = new List <Tuple <bool, Action> >();

                if (primaryKeyChanged)
                {
                    bool isClusteredIndex = changeDescriptor.AlteredType.PrimaryKeyIsClusteredIndex;

                    createIndexActions.Add(new Tuple <bool, Action>(isClusteredIndex,
                                                                    () => ExecuteNonQuery(SetPrimaryKey(alteredTableName, changeDescriptor.AlteredType.KeyPropertyNames, isClusteredIndex))
                                                                    ));
                }

                var oldIndexes = changeDescriptor.OriginalType.Indexes.Select(i => i.ToString()).ToList();
                foreach (var newIndex in changeDescriptor.AlteredType.Indexes)
                {
                    if (!oldIndexes.Contains(newIndex.ToString()))
                    {
                        var index = newIndex;

                        createIndexActions.Add(new Tuple <bool, Action>(newIndex.Clustered,
                                                                        () => CreateIndex(alteredTableName, index)));
                    }
                }

                createIndexActions.Sort((a, b) => b.Item1.CompareTo(a.Item1));

                foreach (var createIndex in createIndexActions)
                {
                    createIndex.Item2();
                }

                SqlTableInformationStore.ClearCache(_connectionString, originalTableName);
                SqlTableInformationStore.ClearCache(_connectionString, alteredTableName);
            }
            catch (Exception ex)
            {
                throw MakeVerboseException(ex);
            }
        }
        private void AlterScopeData(UpdateDataTypeDescriptor updateDataTypeDescriptor, DataTypeChangeDescriptor changeDescriptor, DataScopeIdentifier dataScope)
        {
            var culturesToDelete = new List <CultureInfo>();
            var culturesToChange = new List <CultureInfo>();

            var oldCultures = GetCultures(changeDescriptor.OriginalType).Evaluate();
            var newCultures = GetCultures(changeDescriptor.AlteredType).Evaluate();

            foreach (var culture in oldCultures)
            {
                if (newCultures.Contains(culture))
                {
                    culturesToChange.Add(culture);
                }
                else
                {
                    culturesToDelete.Add(culture);
                }
            }

            var culturesToAdd = newCultures.Where(culture => !oldCultures.Contains(culture)).ToList();


            culturesToAdd.ForEach(culture => CreateStore(changeDescriptor.AlteredType, dataScope, culture));
            culturesToChange.ForEach(culture => AlterStore(updateDataTypeDescriptor, changeDescriptor, dataScope, culture));

            if (updateDataTypeDescriptor.LocalesToCopyTo != null)
            {
                StringBuilder fieldList = GetCommonFields(changeDescriptor);

                string fromTableName = GetConfiguredTableName(changeDescriptor.OriginalType, dataScope, "");

                foreach (CultureInfo locale in updateDataTypeDescriptor.LocalesToCopyTo)
                {
                    string toTableName = DynamicTypesCommon.GenerateTableName(changeDescriptor.AlteredType, dataScope, locale);

                    string copyCommandText = string.Format(@"
                            INSERT INTO [{0}] ({2})
                            SELECT {2}                             
                            FROM [{1}];", toTableName, fromTableName, fieldList);
                    ExecuteNonQuery(copyCommandText);

                    string updateCommandText = string.Format("UPDATE [{0}] SET [{1}] = '{2}'", toTableName, "SourceCultureName", locale.Name);
                    ExecuteNonQuery(updateCommandText);
                }

                string removeCommandText = string.Format(@"DELETE FROM [{0}];", fromTableName);
                ExecuteNonQuery(removeCommandText);
            }

            if (updateDataTypeDescriptor.LocaleToCopyFrom != null)
            {
                StringBuilder fieldList = GetCommonFields(changeDescriptor);

                string fromTableName = GetConfiguredTableName(changeDescriptor.OriginalType, dataScope, updateDataTypeDescriptor.LocaleToCopyFrom.Name);
                string toTableName   = DynamicTypesCommon.GenerateTableName(changeDescriptor.AlteredType, dataScope, CultureInfo.InvariantCulture);

                string copyCommandText = string.Format(@"
                            INSERT INTO [{0}] ({2})
                            SELECT {2}                             
                            FROM [{1}];", toTableName, fromTableName, fieldList);
                ExecuteNonQuery(copyCommandText);
            }


            culturesToDelete.ForEach(culture => DropStore(changeDescriptor.OriginalType, dataScope, culture));
        }
Exemplo n.º 15
0
        internal static InterfaceConfigurationElement RefreshLocalizationInfo(string providerName, DataTypeDescriptor dataTypeDescriptor)
        {
            var changeDescriptor = new DataTypeChangeDescriptor(dataTypeDescriptor, dataTypeDescriptor);

            return(Change(providerName, changeDescriptor, true));
        }