public void CreateStores(IReadOnlyCollection <DataTypeDescriptor> dataTypeDescriptors)
        {
            var dataTypes = DataTypeTypesManager.GetDataTypes(dataTypeDescriptors);

            var storesToCreate = new List <GeneratedTypesInfo>();

            foreach (var dataTypeDescriptor in dataTypeDescriptors)
            {
                Type interfaceType = dataTypes[dataTypeDescriptor.DataTypeId];

                storesToCreate.Add(BuildGeneratedTypesInfo(dataTypeDescriptor, interfaceType));
            }

            CompileMissingTypes(storesToCreate);

            foreach (var storeToCreate in storesToCreate)
            {
                var dataTypeDescriptor = storeToCreate.DataTypeDescriptor;

                InterfaceConfigurationManipulator.AddNew(_dataProviderContext.ProviderName, dataTypeDescriptor);

                var xmlDataTypeStoreCreator = new XmlDataTypeStoreCreator(_fileStoreDirectory);

                XmlDataTypeStore xmlDateTypeStore = xmlDataTypeStoreCreator.CreateStoreResult(
                    dataTypeDescriptor,
                    storeToCreate.DataProviderHelperClass,
                    storeToCreate.DataIdClass, null);

                Type interfaceType = storeToCreate.InterfaceType;

                AddDataTypeStore(dataTypeDescriptor, interfaceType, xmlDateTypeStore);
            }
        }
Ejemplo n.º 2
0
        internal void AddDataType(DataTypeDescriptor dataTypeDescriptor)
        {
            Type interfaceType = DataTypeTypesManager.GetDataType(dataTypeDescriptor);

            if (interfaceType == null)
            {
                return;
            }

            XmlProviderCodeGenerator          codeGenerator        = new XmlProviderCodeGenerator(dataTypeDescriptor, _namespaceName);
            IEnumerable <CodeTypeDeclaration> codeTypeDeclarations = codeGenerator.CreateCodeDOMs();

            codeTypeDeclarations.ForEach(f => _codeGenerationBuilder.AddType(_namespaceName, f));

            // Property serializer for entity tokens and more
            var keyPropertiesDictionary = new Dictionary <string, Type>();
            var keyPropertiesList       = new List <Tuple <string, Type> >();

            foreach (var keyField in dataTypeDescriptor.PhysicalKeyFields)
            {
                Verify.That(!keyPropertiesDictionary.ContainsKey(keyField.Name), "Key field with name '{0}' already present. Data type: {1}. Check for multiple [KeyPropertyName(...)] attributes.", keyField.Name, dataTypeDescriptor.Namespace + "." + dataTypeDescriptor.Name);

                keyPropertiesDictionary.Add(keyField.Name, keyField.InstanceType);
                keyPropertiesList.Add(new Tuple <string, Type>(keyField.Name, keyField.InstanceType));
            }

            PropertySerializerTypeCodeGenerator.AddPropertySerializerTypeCode(_codeGenerationBuilder, codeGenerator.DataIdClassFullName, keyPropertiesList);

            _codeGenerationBuilder.AddReference(interfaceType.Assembly);
        }
Ejemplo n.º 3
0
        public void GenerateNewTypes(string providerName, IReadOnlyCollection <DataTypeDescriptor> dataTypeDescriptors, bool makeAFlush)
        {
            Verify.ArgumentNotNullOrEmpty(providerName, "providerName");
            Verify.ArgumentNotNull(dataTypeDescriptors, "dataTypeDescriptors");

            foreach (var dataTypeDescriptor in dataTypeDescriptors)
            {
                UpdateWithNewMetaDataForeignKeySystem(dataTypeDescriptor);
                UpdateWithNewPageFolderForeignKeySystem(dataTypeDescriptor, false);
            }

            var types = DataTypeTypesManager.GetDataTypes(dataTypeDescriptors);

            foreach (var dataTypeDescriptor in dataTypeDescriptors)
            {
                dataTypeDescriptor.TypeManagerTypeName = TypeManager.SerializeType(types[dataTypeDescriptor.DataTypeId]);
            }

            DynamicTypeManager.CreateStores(providerName, dataTypeDescriptors, makeAFlush);

            if (makeAFlush && dataTypeDescriptors.Any(d => d.IsCodeGenerated))
            {
                CodeGenerationManager.GenerateCompositeGeneratedAssembly(true);
            }
        }
Ejemplo n.º 4
0
        private void LoadDataTypesFromDll(string filePath)
        {
            string fileName = Path.GetFileName(filePath);

            if (DllsNotToLoad.Any(fileName.StartsWith))
            {
                return;
            }

            var assembly = PackageAssemblyHandler.TryGetAlreadyLoadedAssembly(filePath);

            if (assembly == null)
            {
                try
                {
                    assembly = Assembly.LoadFrom(filePath);
                }
                catch (Exception)
                {
                    return;
                }
            }

            DataTypeTypesManager.AddNewAssembly(assembly, false);
        }
Ejemplo n.º 5
0
 private static void VerifyAssemblyLocation(Type interfaceType)
 {
     if (!DataTypeTypesManager.IsAllowedDataTypeAssembly(interfaceType))
     {
         string message = $"The data interface '{interfaceType}' is not located in an assembly in the website Bin folder. Please move it to that location";
         Log.LogError(nameof(EmptyDataClassTypeManager), message);
         throw new InvalidOperationException(message);
     }
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Returns the CLT Type for this data type description.
        /// </summary>
        /// <returns></returns>
        public Type GetInterfaceType()
        {
            if (this.TypeManagerTypeName == null)
            {
                throw new InvalidOperationException("The TypeManagerTypeName has not been set");
            }

            return(DataTypeTypesManager.GetDataType(this));
        }
Ejemplo n.º 7
0
        private static Type GetEmptyClassFromBuildNewHandler(DataTypeDescriptor dataTypeDescriptor)
        {
            Type             buildNewHandlerType = TypeManager.GetType(dataTypeDescriptor.BuildNewHandlerTypeName);
            IBuildNewHandler buildNewHandler     = (IBuildNewHandler)Activator.CreateInstance(buildNewHandlerType);

            Type dataType = DataTypeTypesManager.GetDataType(dataTypeDescriptor);

            VerifyAssemblyLocation(dataType);

            return(buildNewHandler.GetTypeToBuild(dataType));
        }
        /// <summary>
        /// Loads all the data types referenced in the provider's configuration file.
        /// </summary>
        private static Dictionary <Guid, Type> LoadDataTypes(IEnumerable <XmlProviderInterfaceConfigurationElement> configurationElements)
        {
            var dataTypeDescriptors = new List <DataTypeDescriptor>();

            foreach (XmlProviderInterfaceConfigurationElement element in configurationElements)
            {
                var dataTypeDescriptor = GetDataTypeDescriptorNotNull(element);

                dataTypeDescriptors.Add(dataTypeDescriptor);
            }

            return(DataTypeTypesManager.GetDataTypes(dataTypeDescriptors));
        }
Ejemplo n.º 9
0
        /// <summary>
        /// This method will return the type of the empty data class type.
        /// If the type does not exist, one will be runtime code generated
        /// using the type to get a data type descriptor.
        /// </summary>
        /// <param name="interfaceType">The data interface type to get the empty class type for.</param>
        /// <param name="forceReCompilation">
        /// If this is true a new empty class will be
        /// compiled at runtime regardless if it exists or not.
        /// Use with caution!
        /// </param>
        /// <returns>The empty class type for the given data interface type.</returns>
        public static Type GetEmptyDataClassType(Type interfaceType, bool forceReCompilation = false)
        {
            if (!DataTypeTypesManager.IsAllowedDataTypeAssembly(interfaceType))
            {
                string message = string.Format("The data interface '{0}' is not located in an assembly in the website Bin folder. Please move it to that location", interfaceType);
                Log.LogError("EmptyDataClassTypeManager", message);
                throw new InvalidOperationException(message);
            }

            DataTypeDescriptor dataTypeDescriptor = DataMetaDataFacade.GetDataTypeDescriptor(interfaceType.GetImmutableTypeId(), true);

            return(GetEmptyDataClassType(dataTypeDescriptor, forceReCompilation));
        }
Ejemplo n.º 10
0
        private static Type GetEmptyClassFromBuildNewHandler(DataTypeDescriptor dataTypeDescriptor)
        {
            Type             buildNewHandlerType = TypeManager.GetType(dataTypeDescriptor.BuildNewHandlerTypeName);
            IBuildNewHandler buildNewHandler     = (IBuildNewHandler)Activator.CreateInstance(buildNewHandlerType);

            Type dataType = DataTypeTypesManager.GetDataType(dataTypeDescriptor);

            if (!DataTypeTypesManager.IsAllowedDataTypeAssembly(dataType))
            {
                string message = string.Format("The data interface '{0}' is not located in an assembly in the website Bin folder. Please move it to that location", dataType);
                Log.LogError("EmptyDataClassTypeManager", message);
                throw new InvalidOperationException(message);
            }

            return(buildNewHandler.GetTypeToBuild(dataType));
        }
        internal static void AddDataWrapperClassCode(CodeGenerationBuilder codeGenerationBuilder, DataTypeDescriptor dataTypeDescriptor)
        {
            Type interfaceType = DataTypeTypesManager.GetDataType(dataTypeDescriptor);

            if (interfaceType == null)
            {
                return;
            }

            codeGenerationBuilder.AddReference(typeof(IDataWrapper).Assembly);
            codeGenerationBuilder.AddReference(typeof(EditorBrowsableAttribute).Assembly);

            CodeTypeDeclaration codeTypeDeclaration = CreateCodeTypeDeclaration(dataTypeDescriptor);

            codeGenerationBuilder.AddType(NamespaceName, codeTypeDeclaration);
        }
Ejemplo n.º 12
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);
        }
        private bool EnsureNeededTypes(DataTypeDescriptor dataTypeDescriptor, out Type dataProviderHelperType, out Type dataIdClassType, bool forceCompile = false)
        {
            lock (_lock)
            {
                // Getting the interface (ensuring that it exists)
                Type interfaceType = DataTypeTypesManager.GetDataType(dataTypeDescriptor);
                if (interfaceType == null)
                {
                    dataProviderHelperType = null;
                    dataIdClassType        = null;
                    return(false);
                }

                string dataProviderHelperClassFullName, dataIdClassFullName;

                GetGeneratedClassNames(dataTypeDescriptor, out dataProviderHelperClassFullName, out dataIdClassFullName);

                dataProviderHelperType = TypeManager.TryGetType(dataProviderHelperClassFullName);
                dataIdClassType        = TypeManager.TryGetType(dataIdClassFullName);

                if (!forceCompile)
                {
                    forceCompile = CodeGenerationManager.IsRecompileNeeded(interfaceType, new[] { dataProviderHelperType, dataIdClassType });
                }

                if (forceCompile)
                {
                    var codeGenerationBuilder = new CodeGenerationBuilder(_dataProviderContext.ProviderName + ":" + dataTypeDescriptor.Name);

                    // XmlDataProvider types
                    var codeBuilder = new XmlDataProviderCodeBuilder(_dataProviderContext.ProviderName, codeGenerationBuilder);
                    codeBuilder.AddDataType(dataTypeDescriptor);

                    DataWrapperCodeGenerator.AddDataWrapperClassCode(codeGenerationBuilder, dataTypeDescriptor);

                    IEnumerable <Type> types = CodeGenerationManager.CompileRuntimeTempTypes(codeGenerationBuilder, false);

                    dataProviderHelperType = types.Single(f => f.FullName == dataProviderHelperClassFullName);
                    dataIdClassType        = types.Single(f => f.FullName == dataIdClassFullName);
                }

                return(true);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Loads all the data types referenced in the provider's configuration file.
        /// </summary>
        private static Dictionary <Guid, Type> LoadDataTypes(IEnumerable <InterfaceConfigurationElement> configurationElements)
        {
            var dataTypeDescriptors = new List <DataTypeDescriptor>();

            foreach (InterfaceConfigurationElement element in configurationElements)
            {
                Guid dataTypeId = element.DataTypeId;

                var dataTypeDescriptor = DataMetaDataFacade.GetDataTypeDescriptor(dataTypeId, true);
                if (dataTypeDescriptor == null)
                {
                    throw NewConfigurationException(element, "Failed to get a DataTypeDescriptor by id '{0}'".FormatWith(dataTypeId));
                }

                dataTypeDescriptors.Add(dataTypeDescriptor);
            }

            return(DataTypeTypesManager.GetDataTypes(dataTypeDescriptors));
        }
Ejemplo n.º 15
0
        internal static CodeTypeDeclaration CreateCodeTypeDeclaration(DataTypeDescriptor dataTypeDescriptor, Type baseClass, CodeAttributeDeclaration codeAttributeDeclaration)
        {
            Type interfaceType = DataTypeTypesManager.GetDataType(dataTypeDescriptor);

            string interfaceTypeFullName    = interfaceType.FullName;
            CodeTypeDeclaration declaration = new CodeTypeDeclaration();

            declaration.Name           = CreateClassName(interfaceTypeFullName);
            declaration.IsClass        = true;
            declaration.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed;
            declaration.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(SerializableAttribute))));
            declaration.CustomAttributes.Add(
                new CodeAttributeDeclaration(
                    new CodeTypeReference(typeof(EditorBrowsableAttribute)),
                    new CodeAttributeArgument(
                        new CodeFieldReferenceExpression(
                            new CodeTypeReferenceExpression(typeof(EditorBrowsableState)),
                            EditorBrowsableState.Never.ToString()
                            )
                        )
                    )
                );

            if (baseClass != null)
            {
                declaration.BaseTypes.Add(baseClass);
            }
            declaration.BaseTypes.Add(new CodeTypeReference(interfaceType, CodeTypeReferenceOptions.GlobalReference));


            if (codeAttributeDeclaration != null)
            {
                declaration.CustomAttributes.Add(codeAttributeDeclaration);
            }


            AddConstructor(declaration);
            AddInterfaceProperties(declaration, dataTypeDescriptor.Fields);

            AddInterfaceTypeProperty(declaration, interfaceTypeFullName);

            return(declaration);
        }
Ejemplo n.º 16
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);
            }
        }
        public void AlterStore(UpdateDataTypeDescriptor updateDataTypeDescriptor, bool forceCompile)
        {
            XmlDataProviderDocumentCache.ClearCache();

            XmlProviderInterfaceConfigurationElement element = InterfaceConfigurationManipulator.Change(updateDataTypeDescriptor);

            if (forceCompile)
            {
                DataTypeDescriptor dataTypeDescriptor = updateDataTypeDescriptor.NewDataTypeDescriptor;

                Type dataProviderHelperType;
                Type dataIdClassType;
                bool typesExists = EnsureNeededTypes(dataTypeDescriptor, out dataProviderHelperType, out dataIdClassType, true);
                Verify.That(typesExists, "Could not find or code generated the type '{0}' or one of the needed helper types", dataTypeDescriptor.GetFullInterfaceName());

                var xmlDataTypeStoreDataScopes = new List <XmlDataTypeStoreDataScope>();
                foreach (DataScopeConfigurationElement dataScopeConfigurationElement in element.ConfigurationStores)
                {
                    var xmlDataTypeStoreDataScope = new XmlDataTypeStoreDataScope
                    {
                        DataScopeName = dataScopeConfigurationElement.DataScope,
                        CultureName   = dataScopeConfigurationElement.CultureName,
                        ElementName   = dataScopeConfigurationElement.ElementName,
                        Filename      = Path.Combine(_fileStoreDirectory, dataScopeConfigurationElement.Filename)
                    };

                    xmlDataTypeStoreDataScopes.Add(xmlDataTypeStoreDataScope);
                }

                var xmlDataTypeStoreCreator = new XmlDataTypeStoreCreator(_fileStoreDirectory);

                XmlDataTypeStore xmlDateTypeStore = xmlDataTypeStoreCreator.CreateStoreResult(dataTypeDescriptor, dataProviderHelperType, dataIdClassType, xmlDataTypeStoreDataScopes);

                Type interfaceType = DataTypeTypesManager.GetDataType(dataTypeDescriptor);

                UpdateDataTypeStore(dataTypeDescriptor, interfaceType, xmlDateTypeStore);
            }
        }
Ejemplo n.º 18
0
        public void UpdateType(UpdateDataTypeDescriptor updateDataTypeDescriptor)
        {
            Verify.ArgumentNotNullOrEmpty(updateDataTypeDescriptor.ProviderName, "providerName");
            Verify.ArgumentNotNull(updateDataTypeDescriptor.OldDataTypeDescriptor, "oldDataTypeDescriptor");
            Verify.ArgumentNotNull(updateDataTypeDescriptor.NewDataTypeDescriptor, "newDataTypeDescriptor");

            Type interfaceType = null;

            if (updateDataTypeDescriptor.OldDataTypeDescriptor.IsCodeGenerated)
            {
                interfaceType = InterfaceCodeManager.GetType(updateDataTypeDescriptor.NewDataTypeDescriptor, true);
            }
            else
            {
                interfaceType = DataTypeTypesManager.GetDataType(updateDataTypeDescriptor.NewDataTypeDescriptor);
            }

            updateDataTypeDescriptor.NewDataTypeDescriptor.TypeManagerTypeName = TypeManager.SerializeType(interfaceType);

            DynamicTypeManager.AlterStore(updateDataTypeDescriptor, false);

            CodeGenerationManager.GenerateCompositeGeneratedAssembly(true);
        }
Ejemplo n.º 19
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);
        }
Ejemplo n.º 20
0
        private InterfaceGeneratedClassesInfo InitializeStoreTypes(InterfaceConfigurationElement element,
                                                                   Dictionary <DataTypeDescriptor, IEnumerable <SqlDataTypeStoreDataScope> > allSqlDataTypeStoreDataScopes,
                                                                   Type dataContextClass,
                                                                   Dictionary <Guid, Type> dataTypes,
                                                                   bool forceCompile,
                                                                   ref bool dataContextRecompilationNeeded,
                                                                   ref HelperClassesGenerationInfo helperClassesGenerationInfo)
        {
            var result = new InterfaceGeneratedClassesInfo();

            var dataScopes = new List <SqlDataTypeStoreDataScope>();

            foreach (StorageInformation storageInformation in element.Stores)
            {
                var sqlDataTypeStoreDataScope = new SqlDataTypeStoreDataScope
                {
                    DataScopeName = storageInformation.DataScope,
                    CultureName   = storageInformation.CultureName,
                    TableName     = storageInformation.TableName
                };

                dataScopes.Add(sqlDataTypeStoreDataScope);
            }

            result.DataScopes = dataScopes;

            Guid dataTypeId = element.DataTypeId;

            var dataTypeDescriptor = DataMetaDataFacade.GetDataTypeDescriptor(dataTypeId, true);

            if (dataTypeDescriptor == null)
            {
                throw NewConfigurationException(element, "Failed to get a DataTypeDescriptor by id '{0}'".FormatWith(dataTypeId));
            }

            result.DataTypeDescriptor = dataTypeDescriptor;

            Type interfaceType = null;

            try
            {
                if (dataTypes == null ||
                    !dataTypes.TryGetValue(dataTypeId, out interfaceType) ||
                    interfaceType == null)
                {
                    interfaceType = DataTypeTypesManager.GetDataType(dataTypeDescriptor);
                }

                if (interfaceType == null)
                {
                    Log.LogWarning(LogTitle, "The data interface type '{0}' does not exists and is not code generated. It will not be unusable", dataTypeDescriptor.TypeManagerTypeName);
                    return(result);
                }

                result.InterfaceType = interfaceType;

                string validationMessage;
                bool   isValid = DataTypeValidationRegistry.Validate(interfaceType, dataTypeDescriptor, out validationMessage);
                if (!isValid)
                {
                    Log.LogCritical(LogTitle, validationMessage);
                    throw new InvalidOperationException(validationMessage);
                }

                Dictionary <SqlDataTypeStoreTableKey, StoreTypeInfo> fields;
                helperClassesGenerationInfo = EnsureNeededTypes(dataTypeDescriptor,
                                                                dataScopes, allSqlDataTypeStoreDataScopes, dataContextClass,
                                                                out fields, ref dataContextRecompilationNeeded, forceCompile);

                result.Fields = fields;
                return(result);
            }
            catch (Exception ex)
            {
                if (interfaceType != null)
                {
                    DataProviderRegistry.RegisterDataTypeInitializationError(interfaceType, ex);
                    DataProviderRegistry.AddKnownDataType(interfaceType, _dataProviderContext.ProviderName);

                    Log.LogError(LogTitle, "Failed initialization for the datatype {0}", dataTypeDescriptor.TypeManagerTypeName);
                }
                Log.LogError(LogTitle, ex);

                result.Fields = new Dictionary <SqlDataTypeStoreTableKey, StoreTypeInfo>();

                return(result);
            }
        }
Ejemplo n.º 21
0
        public void CreateStores(IReadOnlyCollection <DataTypeDescriptor> dataTypeDescriptors)
        {
            var types = DataTypeTypesManager.GetDataTypes(dataTypeDescriptors);

            foreach (var dataTypeDescriptor in dataTypeDescriptors)
            {
                if (InterfaceConfigurationManipulator.ConfigurationExists(_dataProviderContext.ProviderName, dataTypeDescriptor))
                {
                    var filePath = InterfaceConfigurationManipulator.GetConfigurationFilePath(_dataProviderContext.ProviderName);

                    throw new InvalidOperationException(
                              $"SqlDataProvider configuration already contains a interface named '{dataTypeDescriptor.TypeManagerTypeName}', Id: '{dataTypeDescriptor.DataTypeId}'. Remove it from the configuration file '{filePath}' and restart the application.");
                }
            }

            // Creating Sql tables and adding to the configuration
            var configElements = new Dictionary <DataTypeDescriptor, InterfaceConfigurationElement>();

            foreach (var dataTypeDescriptor in dataTypeDescriptors)
            {
                Type type = types[dataTypeDescriptor.DataTypeId];

                Action <string> existingTablesValidator = tableName =>
                {
                    var errors        = new StringBuilder();
                    var interfaceType = type;
                    if (!ValidateTable(interfaceType, tableName, errors))
                    {
                        throw new InvalidOperationException("Table '{0}' already exist but isn't valid: {1}".FormatWith(tableName, errors.ToString()));
                    }
                };

                SqlStoreManipulator.CreateStoresForType(dataTypeDescriptor, existingTablesValidator);

                InterfaceConfigurationElement element = InterfaceConfigurationManipulator.AddNew(_dataProviderContext.ProviderName, dataTypeDescriptor);
                _interfaceConfigurationElements.Add(element);

                configElements.Add(dataTypeDescriptor, element);
            }


            // Generating necessary classes and performing validation
            Dictionary <DataTypeDescriptor, IEnumerable <SqlDataTypeStoreDataScope> > allSqlDataTypeStoreDataScopes = BuildAllExistingDataTypeStoreDataScopes();

            bool dataContextRecompilationNeeded = false;

            var toCompileList        = new List <HelperClassesGenerationInfo>();
            var generatedClassesInfo = new Dictionary <DataTypeDescriptor, InterfaceGeneratedClassesInfo>();

            Type dataContextClass = _sqlDataTypeStoresContainer.DataContextClass;

            foreach (var dataTypeDescriptor in dataTypeDescriptors)
            {
                var element = configElements[dataTypeDescriptor];

                // InitializeStoreResult initializeStoreResult = InitializeStore(element, allSqlDataTypeStoreDataScopes);

                HelperClassesGenerationInfo toCompile = null;

                var classesInfo = InitializeStoreTypes(element, allSqlDataTypeStoreDataScopes, dataContextClass, null, false, ref dataContextRecompilationNeeded, ref toCompile);

                if (classesInfo != null && toCompile != null)
                {
                    toCompileList.Add(toCompile);

                    generatedClassesInfo[dataTypeDescriptor] = classesInfo;
                }
            }

            // Compiling missing classes
            if (toCompileList.Any())
            {
                var codeGenerationBuilder = new CodeGenerationBuilder(_dataProviderContext.ProviderName + ":CreateStores");

                foreach (var toCompile in toCompileList)
                {
                    toCompile.GenerateCodeAction(codeGenerationBuilder);
                }

                var generatedHelperClasses = CodeGenerationManager.CompileRuntimeTempTypes(codeGenerationBuilder, false).ToArray();

                foreach (var toCompile in toCompileList)
                {
                    toCompile.PopulateFieldsAction(generatedHelperClasses);
                }
            }

            // Emitting a new DataContext class
            if (dataContextRecompilationNeeded)
            {
                var newDataTypeIds = new HashSet <Guid>(dataTypeDescriptors.Select(d => d.DataTypeId));

                _createdSqlDataTypeStoreTables.RemoveAll(f => newDataTypeIds.Contains(f.DataTypeId));

                var fields = _createdSqlDataTypeStoreTables.Select(s => new Tuple <string, Type>(s.DataContextFieldName, s.DataContextFieldType)).ToList();

                foreach (var classesInfo in generatedClassesInfo.Values)
                {
                    fields.AddRange(classesInfo.Fields.Select(f => new Tuple <string, Type>(f.Value.FieldName, f.Value.FieldType)));
                }

                dataContextClass = DataContextAssembler.EmitDataContextClass(fields);

                UpdateCreatedSqlDataTypeStoreTables(dataContextClass);
            }

            _sqlDataTypeStoresContainer.DataContextClass = dataContextClass;

            // Registering the new type/tables
            foreach (var dataTypeDescriptor in dataTypeDescriptors)
            {
                InterfaceGeneratedClassesInfo classesInfo;

                if (!generatedClassesInfo.TryGetValue(dataTypeDescriptor, out classesInfo))
                {
                    throw new InvalidOperationException("No generated classes for data type '{0}' found".FormatWith(dataTypeDescriptor.Name));
                }
                InitializeStoreResult initInfo = EmbedDataContextInfo(classesInfo, dataContextClass);

                AddDataTypeStore(initInfo, false);
            }
        }
Ejemplo n.º 22
0
        /// <exclude />
        public override IEnumerable <XElement> Install()
        {
            Verify.IsNotNull(_filesToCopy, "{0} has not been validated", this.GetType().Name);

            foreach (string directoryToDelete in _directoriesToDelete)
            {
                Directory.Delete(directoryToDelete, true);
            }

            var fileElements = new List <XElement>();

            foreach (FileToCopy fileToCopy in _filesToCopy)
            {
                Log.LogVerbose(LogTitle, "Installing the file '{0}' to the target filename '{1}'", fileToCopy.SourceFilename, fileToCopy.TargetFilePath);

                string targetDirectory = Path.GetDirectoryName(fileToCopy.TargetFilePath);
                if (!Directory.Exists(targetDirectory))
                {
                    Directory.CreateDirectory(targetDirectory);
                }

                string backupFileName = null;

                if (C1File.Exists(fileToCopy.TargetFilePath) && fileToCopy.Overwrite)
                {
                    if ((C1File.GetAttributes(fileToCopy.TargetFilePath) & FileAttributes.ReadOnly) > 0)
                    {
                        FileUtils.RemoveReadOnly(fileToCopy.TargetFilePath);
                    }

                    if (InstallerContext.PackageInformation.CanBeUninstalled)
                    {
                        backupFileName = GetBackupFileName(fileToCopy.TargetFilePath);

                        string backupFilesFolder = this.InstallerContext.PackageDirectory + "\\FileBackup";

                        C1Directory.CreateDirectory(backupFilesFolder);

                        C1File.Copy(fileToCopy.TargetFilePath, backupFilesFolder + "\\" + backupFileName);
                    }
                }

                this.InstallerContext.ZipFileSystem.WriteFileToDisk(fileToCopy.SourceFilename, fileToCopy.TargetFilePath);

                // Searching for static IData interfaces
                string targetFilePath = fileToCopy.TargetFilePath;

                if (targetFilePath.StartsWith(Path.Combine(PathUtil.BaseDirectory, "Bin"), StringComparison.InvariantCultureIgnoreCase) &&
                    targetFilePath.EndsWith(".dll", StringComparison.InvariantCultureIgnoreCase))
                {
                    string fileName = Path.GetFileName(targetFilePath);

                    if (!DllsNotToLoad.Any(fileName.StartsWith))
                    {
                        Assembly assembly;

                        try
                        {
                            assembly = Assembly.LoadFrom(targetFilePath);
                        }
                        catch (Exception)
                        {
                            continue;
                        }

                        DataTypeTypesManager.AddNewAssembly(assembly, false);
                    }
                }

                var fileElement = new XElement("File", new XAttribute("filename", fileToCopy.TargetRelativeFilePath));

                if (backupFileName != null)
                {
                    fileElement.Add(new XAttribute("backupFile", backupFileName));
                }

                fileElements.Add(fileElement);
            }

            yield return(new XElement("Files", fileElements));
        }