private DataTypeDescriptor GetDataTypeDescriptor()
        {
            Type sourceDataType = GetSourceDataType();

            DataTypeDescriptor dataTypeDescriptor = null;

            if (DynamicTypeManager.TryGetDataTypeDescriptor(sourceDataType, out dataTypeDescriptor) == false)
            {
                dataTypeDescriptor = DynamicTypeManager.BuildNewDataTypeDescriptor(sourceDataType);
            }

            return(dataTypeDescriptor);
        }
        private void EnsureInterfaces(IEnumerable <Type> allInterfaces)
        {
            var dataTypeDescriptors = new List <DataTypeDescriptor>();

            foreach (Type interfaceType in allInterfaces)
            {
                if (!DataProviderRegistry.GetDataProviderNamesByInterfaceType(interfaceType).Contains(this.TargetProviderName))
                {
                    var dataTypeDescriptor = DynamicTypeManager.BuildNewDataTypeDescriptor(interfaceType);

                    dataTypeDescriptor.Validate();

                    dataTypeDescriptors.Add(dataTypeDescriptor);
                }
            }

            DataProviderPluginFacade.CreateStores(this.TargetProviderName, dataTypeDescriptors);
        }
        /// <summary>
        /// This method returns data type descriptors for dynamic types this is pending
        /// installation (Has passed validaion).
        /// </summary>
        /// <param name="interfaceName"></param>
        /// <returns></returns>
        public DataTypeDescriptor GetPendingDataTypeDescriptor(string interfaceName)
        {
            Verify.ArgumentNotNullOrEmpty(interfaceName, "interfaceName");


            DataTypeDescriptor dataTypeDescriptor;

            if (_pendingDataTypeDescriptors.TryGetValue(interfaceName, out dataTypeDescriptor))
            {
                return(dataTypeDescriptor);
            }

            Type interfaceType = _pendingDataTypes.FirstOrDefault(type => type.FullName == interfaceName);

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

            return(DynamicTypeManager.BuildNewDataTypeDescriptor(interfaceType));
        }
Beispiel #4
0
        public bool EnsureDataStores()
        {
            if (!DataProviderPluginFacade.HasConfiguration())
            {
                Log.LogError(LogTitle, "Failed to load the configuration section '{0}' from the configuration", DataProviderSettings.SectionName);
                return(false);
            }

            var typeDescriptors = new List <DataTypeDescriptor>();

            foreach (Type type in _interfaceTypes)
            {
                try
                {
                    if (!DataProviderRegistry.AllKnownInterfaces.Contains(type))
                    {
                        var dataTypeDescriptor = DynamicTypeManager.BuildNewDataTypeDescriptor(type);

                        dataTypeDescriptor.Validate();

                        typeDescriptors.Add(dataTypeDescriptor);
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException(string.Format("Failed to validate type '{0}'", type), ex);
                }
            }

            if (typeDescriptors.Any())
            {
                DataProviderPluginFacade.CreateStores(DataProviderRegistry.DefaultDynamicTypeDataProviderName, typeDescriptors);

                string typeNames = string.Join(", ", typeDescriptors.Select(t => t.GetFullInterfaceName()));
                Log.LogVerbose(LogTitle, "Stores for the following data types were created: " + typeNames);
            }

            return(typeDescriptors.Count > 0);
        }
Beispiel #5
0
        /// <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);
        }
Beispiel #6
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, 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 == foreignKeyProperty.NullReferenceValue)
                    {
                        continue;
                    }

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

            if (itemsAlreadyPresentInDatabase > 0)
            {
                _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.DataExists").FormatWith(dataType.InterfaceType, itemsAlreadyPresentInDatabase));
            }
        }