Esempio n. 1
0
        public void GetEditableRoot_WhenThrowsException_CallsLogger()
        {
            var processName = Guid.NewGuid().ToString();
            var dynamicTypeManager = new DynamicTypeManager();
            var loggerMock = Mock.Create<ILogger>();
            dynamicTypeManager.Logger = loggerMock;
            dynamicTypeManager.GetEditableRoot<IEditableRoot>(processName, 1);

            Mock.Assert(() => loggerMock.Log(LogSeverity.Error, Arg.IsAny<string>(), Arg.IsAny<string>()), Occurs.AtLeastOnce());
        }
Esempio n. 2
0
        public UdpFilterViewModel(FilterValue filterValue, FilterFormatType type, string crProcess, DynamicTypeManager theDynamicTypeManager, string name, string crFieldName, FilterList filterList)
        {
            if (theDynamicTypeManager == null)
            {
                throw new ArgumentNullException("theDynamicTypeManager");
            }

            Name = name;
            Type = type != null ? GetTypeForView(type.MemberType.Name != "Nullable`1" ? type.MemberType : type.MemberType.GenericTypeArguments[0]) : "Text";

            if (crProcess != null)
            {
                //Type itemType = theDynamicTypeManager.GetInfoType<IInfoClass>(crProcess);
                //PropertyInfo guidProperty = itemType.GetPropertyByName("Guid");
               // PropertyInfo crFieldProperty = itemType.GetPropertyByName(crFieldName);

                if (crProcess == Constants.StateProcessName)
                {
                    Values = theDynamicTypeManager.GetList<IInfoList>(crProcess, string.Empty, 0, int.MaxValue, null, filterList)
                            .Cast<IStateInfo>()
                            .Select(x => new IdValuePair
                            {
                                Id = x.Id.ToString(CultureInfo.InvariantCulture),//guidProperty.With(v => v.GetValue(x)).Return(v => v.ToString(), string.Empty),
                                //Value = crFieldProperty.GetValue(x)
                                Value = x.GetValueByPropertyName(crFieldName)

                            })
                            .ToList();
                }
                else
                {
                    Values = theDynamicTypeManager.GetList<IInfoList>(crProcess, string.Empty, 0, int.MaxValue)
                        .Cast<IInfoClass>()
                        .Select(x => new IdValuePair
                        {
                            Id = x.Id.ToString(CultureInfo.InvariantCulture),
                            Value = x.GetValueByPropertyName(crFieldName)
                        })
                        .ToList();
                }
            }
            else
            {
                if (Type == "Approval")
                {
                    Values = Enum.GetValues(typeof(ApprovalStates)).Cast<ApprovalStates>().Select(x => new IdValuePair { Id = x.ToString(), Value = x.GetDescription() }).ToList();
                }
                else
                {
                    Values = null;
                }
            }

            DefaultValue = filterValue != null && filterValue.DefaultValue != null ? Convert.ToString(filterValue.DefaultValue, CultureInfo.InvariantCulture) : string.Empty;
        }
        private void editPreviewCodeActivity_ExecuteCode(object sender, EventArgs e)
        {
            try
            {
                XhtmlDocument templateDocument = GetTemplateDocumentFromBindings();

                IVisualFunction function      = this.GetBinding <IVisualFunction>("Function");
                Type            interfaceType = TypeManager.GetType(function.TypeManagerName);

                DataTypeDescriptor typeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(interfaceType);

                this.LogMessage(Composite.Core.Logging.LogLevel.Info, DataScopeManager.CurrentDataScope.Name);

                FunctionContextContainer fcc = PageRenderer.GetPageRenderFunctionContextContainer();

                XhtmlDocument result = RenderingHelper.RenderCompleteDataList(function, templateDocument, typeDescriptor, fcc);

                IPage previewPage = DataFacade.BuildNew <IPage>();
                previewPage.Id    = GetRootPageId();
                previewPage.Title = function.Name;
                previewPage.DataSourceId.DataScopeIdentifier = DataScopeIdentifier.Administrated;
                previewPage.DataSourceId.LocaleScope         = LocalizationScopeManager.CurrentLocalizationScope;

                previewPage.TemplateId = this.GetBinding <Guid>("PreviewTemplateId");

                var pageTemplate = PageTemplateFacade.GetPageTemplate(previewPage.TemplateId);
                IPagePlaceholderContent placeHolderContent = DataFacade.BuildNew <IPagePlaceholderContent>();
                placeHolderContent.Content       = string.Concat((result.Body.Elements().Select(b => b.ToString())).ToArray());
                placeHolderContent.PlaceHolderId = pageTemplate.DefaultPlaceholderId;

                string output = PagePreviewBuilder.RenderPreview(previewPage, new List <IPagePlaceholderContent> {
                    placeHolderContent
                });

                var serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId);

                var webRenderService = serviceContainer.GetService <IFormFlowWebRenderingService>();
                webRenderService.SetNewPageOutput(new LiteralControl(output));
            }
            catch (Exception ex)
            {
                FlowControllerServicesContainer serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId);
                Control errOutput        = new LiteralControl("<pre>" + ex + "</pre>");
                var     webRenderService = serviceContainer.GetService <IFormFlowWebRenderingService>();
                webRenderService.SetNewPageOutput(errOutput);
            }
        }
        /// <summary>
        /// Adds a locale to the system. Throws exception if the given locale has already been installed or
        /// if the given url mapping name has already been used. If the given locale is the first, its set
        /// to be the default locale.
        /// </summary>
        /// <param name="cultureInfo"></param>
        /// <param name="urlMappingName"></param>
        /// <param name="addAccessToAllUsers"></param>
        /// <param name="makeFlush"></param>
        /// <param name="isDefault"></param>
        internal static void AddLocale(CultureInfo cultureInfo, string urlMappingName, bool addAccessToAllUsers, bool makeFlush, bool isDefault)
        {
            using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope())
            {
                Verify.That(!IsLocaleInstalled(cultureInfo), "The locale '{0}' has already been added to the system", cultureInfo);
                Verify.That(!IsUrlMappingNameInUse(urlMappingName), "The url mapping name '{0}' has already been used in the system", urlMappingName);

                if (!DataLocalizationFacade.ActiveLocalizationCultures.Any())
                {
                    addAccessToAllUsers = true;
                }

                var systemActiveLocale = DataFacade.BuildNew <ISystemActiveLocale>();
                systemActiveLocale.Id             = Guid.NewGuid();
                systemActiveLocale.CultureName    = cultureInfo.Name;
                systemActiveLocale.UrlMappingName = urlMappingName;
                systemActiveLocale.IsDefault      = isDefault;
                DataFacade.AddNew(systemActiveLocale);

                if (addAccessToAllUsers)
                {
                    List <string> usernames =
                        (from u in DataFacade.GetData <IUser>()
                         select u.Username).ToList();

                    foreach (string username in usernames)
                    {
                        UserSettings.AddActiveLocaleCultureInfo(username, cultureInfo);

                        if (UserSettings.GetCurrentActiveLocaleCultureInfo(username) == null)
                        {
                            UserSettings.SetCurrentActiveLocaleCultureInfo(username, cultureInfo);
                            UserSettings.SetForeignLocaleCultureInfo(username, cultureInfo);
                        }
                    }
                }

                if (DataLocalizationFacade.DefaultLocalizationCulture == null)
                {
                    DataLocalizationFacade.DefaultLocalizationCulture = cultureInfo;
                }

                transactionScope.Complete();
            }

            DynamicTypeManager.AddLocale(cultureInfo);
        }
Esempio n. 5
0
        public void DeleteType(string providerName, DataTypeDescriptor dataTypeDescriptor, bool makeAFlush)
        {
            Verify.ArgumentNotNullOrEmpty(providerName, "providerName");
            Verify.ArgumentNotNull(dataTypeDescriptor, "dataTypeDescriptor");

            using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope())
            {
                DynamicTypeManager.DropStore(providerName, dataTypeDescriptor, makeAFlush);

                transactionScope.Complete();
            }

            if (makeAFlush && dataTypeDescriptor.IsCodeGenerated)
            {
                CodeGenerationManager.GenerateCompositeGeneratedAssembly(true);
            }
        }
Esempio n. 6
0
        private static TypeInfo GetTypeInfo(string typeManagerName)
        {
            TypeInfo cachedValue = _typeLookup.Get(typeManagerName);

            if (cachedValue != null)
            {
                return(cachedValue);
            }

            Type type = TypeManager.GetType(typeManagerName);
            DataTypeDescriptor typeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(type);

            var result = new TypeInfo(type, typeDescriptor);

            _typeLookup.Add(typeManagerName, result);
            return(result);
        }
        private void DefaultValuesAreValid(object sender, ConditionalEventArgs e)
        {
            IData newDataTemplate;

            if (!this.TryGetBinding("NewDataTemplate", out newDataTemplate))
            {
                e.Result = true;
                return;
            }
            
            IPageTypeMetaDataTypeLink pageTypeMetaDataTypeLink = this.GetBinding<IPageTypeMetaDataTypeLink>("NewMetaDataTypeLink");

            var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(pageTypeMetaDataTypeLink.DataTypeId);
            var helper = new DataTypeDescriptorFormsHelper(dataTypeDescriptor);

            e.Result = BindAndValidate(helper, newDataTemplate);
        }
        private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e)
        {
            IPageTypeMetaDataTypeLink pageTypeMetaDataTypeLink = this.GetDataItemFromEntityToken <IPageTypeMetaDataTypeLink>();

            DeleteTreeRefresher deleteTreeRefresher = this.CreateDeleteTreeRefresher(this.EntityToken);

            DataTypeDescriptor dataTypeDescriptor;

            if (DynamicTypeManager.TryGetDataTypeDescriptor(pageTypeMetaDataTypeLink.DataTypeId, out dataTypeDescriptor))
            {
                PageMetaDataFacade.RemoveDefinition(pageTypeMetaDataTypeLink.PageTypeId, pageTypeMetaDataTypeLink.Name);
            }

            DataFacade.Delete <IPageTypeMetaDataTypeLink>(pageTypeMetaDataTypeLink);

            deleteTreeRefresher.PostRefreshMesseges();
        }
        /// <exclude />
        public static IEnumerable <Tuple <Type, string> > GetDefinedMetaDataTypeAndNames(this IPage page)
        {
            Guid pageId = page.GetPageIdOrNull();

            IEnumerable <Tuple <Guid, string> > metaDataTypeIdAndNames =
                DataFacade.GetData <IPageMetaDataDefinition>().
                Where(f => f.DefiningItemId == pageId).
                Select(f => new Tuple <Guid, string>(f.MetaDataTypeId, f.Name)).
                Distinct();

            foreach (Tuple <Guid, string> metaDataTypeIdAndName in metaDataTypeIdAndNames)
            {
                DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(metaDataTypeIdAndName.Item1);

                yield return(new Tuple <Type, string>(TypeManager.GetType(dataTypeDescriptor.TypeManagerTypeName), metaDataTypeIdAndName.Item2));
            }
        }
Esempio n. 10
0
        public void CanSpecifyNamespace()
        {
            DynamicTypeManager mgr = new DynamicTypeManager(new DynamicTypeDataRepository(), DataSettings.Default);

            mgr.DynamicTypeDataRepository.Query <DynamicTypeDescriptor>(d => d.Id > 0).Each(d => mgr.DynamicTypeDataRepository.Delete(d));
            mgr.DynamicTypeDataRepository.Query <DynamicTypePropertyDescriptor>(p => p.Id > 0).Each(p => mgr.DynamicTypeDataRepository.Delete(p));
            string testType      = nameof(CanSpecifyNamespace);
            string testType2     = nameof(CanSpecifyNamespace) + "2";
            string testNamespace = "My.Test.Namespace";

            mgr.AddType(testType, testNamespace);
            mgr.AddType(testType2, testNamespace);
            DynamicNamespaceDescriptor ns = mgr.GetNamespaceDescriptor(testNamespace);

            Expect.IsNotNull(ns, "namspace was null");
            Expect.IsTrue(ns.Types.Count == 2);
        }
        /// <summary>
        /// Returns all meta data types that are defined on the given page.
        /// </summary>
        /// <param name="page">If this is null, Guid.Empty is assumed as defining item id</param>
        /// <returns></returns>
        public static IEnumerable <Type> GetDefinedMetaDataTypes(this IPage page)
        {
            Guid pageId = page.GetPageIdOrNull();

            IEnumerable <Guid> metaDataTypeIds =
                DataFacade.GetData <IPageMetaDataDefinition>().
                Where(f => f.DefiningItemId == pageId).
                Select(f => f.MetaDataTypeId).
                Distinct();

            foreach (Guid metaDataTypeId in metaDataTypeIds)
            {
                DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(metaDataTypeId);

                yield return(TypeManager.GetType(dataTypeDescriptor.TypeManagerTypeName));
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Removes the given locale, all data is lost
        /// </summary>
        /// <param name="cultureInfo"></param>
        /// <param name="makeFlush"></param>
        public static void RemoveLocale(CultureInfo cultureInfo, bool makeFlush = true)
        {
            Verify.That(!IsDefaultLocale(cultureInfo), "The locale '{0}' is the default locale and can not be removed", cultureInfo);
            Verify.That(!IsOnlyActiveLocaleForSomeUsers(cultureInfo), "The locale '{0}' is the only locale for some user(s) and can not be removed", cultureInfo);

            using (var transactionScope = TransactionsFacade.CreateNewScope())
            {
                string cultureName = cultureInfo.Name;

                var systemActiveLocale = DataFacade.GetData <ISystemActiveLocale>().SingleOrDefault(f => f.CultureName == cultureName);

                Verify.IsNotNull(systemActiveLocale, "The locale '{0}' has not beed added and can not be removed", cultureInfo);

                List <string> usernames =
                    (from u in DataFacade.GetData <IUser>()
                     select u.Username).ToList();

                foreach (string username in usernames)
                {
                    if (cultureInfo.Equals(UserSettings.GetCurrentActiveLocaleCultureInfo(username)))
                    {
                        CultureInfo fallbackCultureInfo = UserSettings.GetActiveLocaleCultureInfos(username).First(f => !f.Equals(cultureInfo));

                        UserSettings.SetCurrentActiveLocaleCultureInfo(username, fallbackCultureInfo);
                    }

                    if (cultureInfo.Equals(UserSettings.GetForeignLocaleCultureInfo(username)))
                    {
                        UserSettings.SetForeignLocaleCultureInfo(username, null);
                    }

                    UserSettings.RemoveActiveLocaleCultureInfo(username, cultureInfo);
                }

                DataFacade.Delete <ISystemActiveLocale>(systemActiveLocale);

                transactionScope.Complete();
            }

            DynamicTypeManager.RemoveLocale(cultureInfo);

            if (makeFlush)
            {
                C1Console.Events.GlobalEventSystemFacade.FlushTheSystem(false);
            }
        }
        /// <exclude />
        public virtual string GetFieldLabel(PropertyInfo propertyInfo)
        {
            var fieldName = GetDocumentFieldName(propertyInfo);

            if (fieldName == DocumentFieldNames.Description)
            {
                return(Texts.FieldNames_Description);
            }

            if (fieldName == DocumentFieldNames.LastUpdated)
            {
                return(Texts.FieldNames_LastUpdated);
            }
            if (propertyInfo.Name == nameof(IChangeHistory.ChangedBy))
            {
                return(Texts.FieldNames_UpdatedBy);
            }
            if (propertyInfo.Name == nameof(IMediaFile.MimeType))
            {
                return(Texts.FieldNames_MimeType);
            }

            var frpAttribute = propertyInfo.GetCustomAttribute <FormRenderingProfileAttribute>();

            if (!string.IsNullOrEmpty(frpAttribute?.Label))
            {
                return(frpAttribute.Label);
            }

            Guid immutableTypeId;
            DataTypeDescriptor dataTypeDescriptor;

            if (propertyInfo.DeclaringType.TryGetImmutableTypeId(out immutableTypeId) &&
                DynamicTypeManager.TryGetDataTypeDescriptor(immutableTypeId, out dataTypeDescriptor))
            {
                var fieldDescriptor = dataTypeDescriptor?.Fields.FirstOrDefault(f => f.Name == propertyInfo.Name);
                var label           = fieldDescriptor?.FormRenderingProfile?.Label;
                if (label != null)
                {
                    return(label);
                }
            }

            return(propertyInfo.Name);
        }
Esempio n. 14
0
        /// <summary>
        /// Returns (if any) folder types that are defined on the given page
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public static IEnumerable <Type> GetDefinedFolderTypes(this IPage page)
        {
            Verify.ArgumentNotNull(page, "page");

            IEnumerable <Guid> typeIds =
                DataFacade.GetData <IPageFolderDefinition>().
                Where(f => f.PageId == page.Id).
                Select(f => f.FolderTypeId).
                Evaluate();

            foreach (Guid typeId in typeIds)
            {
                var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(typeId);
                Verify.IsNotNull(dataTypeDescriptor, "Missing a page data folder type with id '{0}', referenced by a IPageFolderDefinition record", typeId);

                yield return(TypeManager.GetType(dataTypeDescriptor.TypeManagerTypeName));
            }
        }
        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);
        }
        public static void OnInitialized(KeywordChangeNotifier keywordChangeNotifier)
        {
            DynamicTypeManager.EnsureCreateStore(typeof(RedirectKeyword));

            DataEvents <RedirectKeyword> .OnAfterAdd    += keywordChangeNotifier.KeywordChange;
            DataEvents <RedirectKeyword> .OnAfterUpdate += keywordChangeNotifier.KeywordChange;
            DataEvents <RedirectKeyword> .OnDeleted     += keywordChangeNotifier.KeywordChange;
            DataEvents <IPage> .OnAfterAdd    += keywordChangeNotifier.KeywordChange;
            DataEvents <IPage> .OnAfterUpdate += keywordChangeNotifier.KeywordChange;
            DataEvents <IPage> .OnDeleted     += keywordChangeNotifier.KeywordChange;

            var functions = MvcFunctionRegistry.NewFunctionCollection();

            RegisterFunctions(functions);
            RegisterFunctionRoutes(functions);

            UrlToEntityTokenFacade.Register(new KeywordsUrlToEntityTokenMapper());
        }
Esempio n. 17
0
        public void CanGetAssembly()
        {
            DynamicTypeManager mgr = new DynamicTypeManager(new DynamicTypeDataRepository(), DataSettings.Default);

            mgr.DynamicTypeDataRepository.Query <DynamicTypeDescriptor>(d => d.Id > 0).Each(d => mgr.DynamicTypeDataRepository.Delete(d));
            mgr.DynamicTypeDataRepository.Query <DynamicTypePropertyDescriptor>(p => p.Id > 0).Each(p => mgr.DynamicTypeDataRepository.Delete(p));
            string testType = nameof(CanAddPropertyToType);

            mgr.AddType(testType);
            string testProperty  = "SomeProperty";
            string testProperty2 = "BooleanProperty";
            DynamicTypePropertyDescriptor prop  = mgr.AddProperty(testType, testProperty, "String");
            DynamicTypePropertyDescriptor prop2 = mgr.AddProperty(testType, testProperty2, "Boolean");

            Assembly ass = mgr.GetAssembly();

            Expect.IsNotNull(ass);
        }
        private void initializeCodeActivity_UpdateBindings_ExecuteCode(object sender, EventArgs e)
        {
            IPageTypeMetaDataTypeLink pageTypeMetaDataTypeLink = this.GetDataItemFromEntityToken <IPageTypeMetaDataTypeLink>();

            IPageMetaDataDefinition pageMetaDataDefinition = PageMetaDataFacade.GetMetaDataDefinition(pageTypeMetaDataTypeLink.PageTypeId, pageTypeMetaDataTypeLink.Name);

            //this.UpdateBinding("CompositionDescriptionName", compositionDescription.Name);
            this.UpdateBinding("CompositionDescriptionLabel", pageMetaDataDefinition.Label);

            List <KeyValuePair <Guid, string> > metaDataContainerOptions = PageMetaDataFacade.GetAllMetaDataContainers();

            this.Bindings.Add("MetaDataContainerOptions", metaDataContainerOptions);
            this.Bindings.Add("CompositionContainerId", pageMetaDataDefinition.MetaDataContainerId);

            var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(pageTypeMetaDataTypeLink.DataTypeId);

            this.Bindings.Add("MetaTypeName", dataTypeDescriptor.TypeManagerTypeName);
        }
Esempio n. 19
0
        internal static bool EnsureUpdateAllInterfaces()
        {
            using (AppDomainLocker.NewLock())
                using (TimerProfilerFacade.CreateTimerProfiler())
                {
                    bool doFlush = false;

                    var knownInterfaces = DataProviderRegistry.AllKnownInterfaces.ToList();

                    foreach (Type interfaceType in knownInterfaces)
                    {
                        if (!interfaceType.IsAutoUpdateble())
                        {
                            continue;
                        }

                        foreach (string providerName in DataProviderRegistry.GetDataProviderNamesByInterfaceType(interfaceType))
                        {
                            try
                            {
                                if (DynamicTypeManager.EnsureUpdateStore(interfaceType, providerName, true))
                                {
                                    doFlush = true;
                                }
                            }
                            catch (TypeUpdateVersionException)
                            {
                                throw;
                            }
                            catch (TypeInitializationException tiex)
                            {
                                throw new InvalidOperationException("The data type meta stored did not initialize. Check configuration", tiex);
                            }
                            catch (Exception ex)
                            {
                                Log.LogCritical(LogTitle, "Update failed for the interface '{0}' on the '{1}' data provider", interfaceType, providerName);
                                Log.LogCritical(LogTitle, ex);
                            }
                        }
                    }

                    return(doFlush);
                }
        }
Esempio n. 20
0
        public void AssociationsAreMade()
        {
            DynamicTypeManager         mgr = new DynamicTypeManager(new DynamicTypeDataRepository(), DataSettings.Default);
            DynamicNamespaceDescriptor ns  = new DynamicNamespaceDescriptor {
                Namespace = $"Test.Name.Space.{nameof(AssociationsAreMade)}"
            };

            ns = mgr.DynamicTypeDataRepository.Save(ns);

            DynamicTypeDescriptor typeDescriptor = new DynamicTypeDescriptor {
                DynamicNamespaceDescriptorId = ns.Id
            };

            Expect.IsNull(typeDescriptor.DynamicNamespaceDescriptor);

            typeDescriptor = mgr.DynamicTypeDataRepository.Save(typeDescriptor);
            Expect.IsNotNull(typeDescriptor.DynamicNamespaceDescriptor);
            Expect.AreEqual(ns, typeDescriptor.DynamicNamespaceDescriptor);
        }
        /// <exclude />
        public void SetForeignKeyReference(DataTypeDescriptor targetDataTypeDescriptor, DataAssociationType dataAssociationType)
        {
            if (dataAssociationType == DataAssociationType.None)
            {
                throw new ArgumentException("dataAssociationType");
            }

            if ((dataAssociationType == DataAssociationType.Aggregation || dataAssociationType == DataAssociationType.Composition) &&
                _pageMetaDataDescriptionForeignKeyDataFieldDescriptor != null)
            {
                throw new InvalidOperationException("The type already has a foreign key reference");
            }


            Type   targetType = TypeManager.GetType(targetDataTypeDescriptor.TypeManagerTypeName);
            string fieldName  = null;

            if (targetType == typeof(IPage))
            {
                fieldName            = PageReferenceFieldName;
                _dataAssociationType = dataAssociationType;
            }

            string foreignKeyFieldName;

            _foreignKeyDataFieldDescriptor = CreateReferenceDataFieldDescriptor(targetDataTypeDescriptor, out foreignKeyFieldName, fieldName);

            if (dataAssociationType != DataAssociationType.None)
            {
                _dataTypeAssociationDescriptor = new DataTypeAssociationDescriptor(
                    targetType,
                    foreignKeyFieldName,
                    dataAssociationType
                    );
            }

            if (dataAssociationType == DataAssociationType.Composition)
            {
                DataTypeDescriptor compositionRuleDataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(typeof(IPageMetaDataDefinition));

                _pageMetaDataDescriptionForeignKeyDataFieldDescriptor = CreateWeakReferenceDataFieldDescriptor(compositionRuleDataTypeDescriptor, compositionRuleDataTypeDescriptor.Fields["Name"], CompositionDescriptionFieldName);
            }
        }
Esempio n. 22
0
        public List <T> AddNew <T>(IEnumerable <T> datas, bool allowStoreCreation, bool suppressEventing, bool performForeignKeyIntegrityCheck, bool performValidation, List <string> writeableProviders)
            where T : class, IData
        {
            if (writeableProviders == null)
            {
                writeableProviders = GetWritableDataProviders(typeof(T));
            }

            if (writeableProviders.Count == 0 &&
                typeof(T).GetCustomInterfaceAttributes <AutoUpdatebleAttribute>().Any() &&
                allowStoreCreation)
            {
                if (!DataTypeTypesManager.IsAllowedDataTypeAssembly(typeof(T)))
                {
                    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", typeof(T));
                    Log.LogError(LogTitle, message);
                    throw new InvalidOperationException(message);
                }

                lock (_storeCreationLock)
                {
                    writeableProviders = GetWritableDataProviders(typeof(T));

                    if (writeableProviders.Count == 0)
                    {
                        Log.LogVerbose(LogTitle, string.Format("Type data interface '{0}' is marked auto updateble and is not supported by any providers. Adding it to the default dynamic type data provider", typeof(T)));

                        List <T> result;
                        DynamicTypeManager.EnsureCreateStore(typeof(T));

                        result = AddNew <T>(datas, false, suppressEventing, performForeignKeyIntegrityCheck, performValidation, null);
                        return(result);
                    }
                }
            }

            if (writeableProviders.Count == 1)
            {
                return(AddNew_AddingMethod <T>(writeableProviders[0], datas, suppressEventing, performForeignKeyIntegrityCheck, performValidation));
            }

            throw new InvalidOperationException(string.Format("{0} writeable data providers exists for data '{1}'.", writeableProviders.Count, typeof(T)));
        }
        /// <summary>
        /// Removes a metadata definition and possibly deletes all data items that are defined by it
        /// </summary>
        /// <param name="definingItemId"></param>
        /// <param name="definitionName"></param>
        /// <param name="deleteExistingMetaData"></param>
        public static void RemoveDefinition(Guid definingItemId, string definitionName, bool deleteExistingMetaData = true)
        {
            IPageMetaDataDefinition pageMetaDataDefinition = GetMetaDataDefinition(definingItemId, definitionName);

            IEnumerable <IPageMetaDataDefinition> otherPageMetaDataDefinitions =
                DataFacade.GetData <IPageMetaDataDefinition>().
                Where(f => f.Name == definitionName && f.Id != pageMetaDataDefinition.Id).
                Evaluate();

            DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(pageMetaDataDefinition.MetaDataTypeId);
            Type metaDataType = TypeManager.GetType(dataTypeDescriptor.TypeManagerTypeName);

            if (deleteExistingMetaData)
            {
                using (var transactionScope = TransactionsFacade.CreateNewScope())
                {
                    foreach (CultureInfo localeCultureInfo in DataLocalizationFacade.ActiveLocalizationCultures)
                    {
                        using (new DataScope(localeCultureInfo))
                        {
                            using (new DataScope(DataScopeIdentifier.Public))
                            {
                                RemoveDefinitionDeleteData(definitionName, metaDataType, otherPageMetaDataDefinitions);
                            }

                            using (new DataScope(DataScopeIdentifier.Administrated))
                            {
                                RemoveDefinitionDeleteData(definitionName, metaDataType, otherPageMetaDataDefinitions);
                            }
                        }
                    }

                    DataFacade.Delete(pageMetaDataDefinition);

                    transactionScope.Complete();
                }
            }
            else
            {
                DataFacade.Delete(pageMetaDataDefinition);
            }
        }
        private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e)
        {
            Type selectedMetaDataType             = this.GetBinding <Type>(SelectedTypeBindingName);
            DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(selectedMetaDataType.GetImmutableTypeId());

            PageMetaDataDescription dataAssociationVisabilityRule = this.GetBinding <PageMetaDataDescription>(DataAssociationVisabilityDescriptionBindingName);
            Guid   metaDataContainerId     = this.GetBinding <Guid>(SelectedContainerBindingName);
            string metaDataDefinitionName  = this.GetBinding <string>(FieldGroupNameBindingName);
            string metaDataDefinitionLabel = this.GetBinding <string>(FieldGroupLabelBindingName);

            IData newDataTemplate = null;

            if (IsAnyPagesAffected())
            {
                DataTypeDescriptorFormsHelper helper = new DataTypeDescriptorFormsHelper(dataTypeDescriptor);

                GeneratedTypesHelper generatedTypesHelper = new GeneratedTypesHelper(dataTypeDescriptor);
                helper.AddReadOnlyFields(generatedTypesHelper.NotEditableDataFieldDescriptorNames);

                newDataTemplate = DataFacade.BuildNew(selectedMetaDataType);
                helper.BindingsToObject(this.Bindings, newDataTemplate);
            }


            using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope())
            {
                IPage page = GetCurrentPage();

                page.AddMetaDataDefinition(metaDataDefinitionName, metaDataDefinitionLabel, selectedMetaDataType.GetImmutableTypeId(), metaDataContainerId, dataAssociationVisabilityRule.StartLevel, dataAssociationVisabilityRule.Levels);

                if (newDataTemplate != null)
                {
                    page.AddNewMetaDataToExistingPages(metaDataDefinitionName, newDataTemplate);
                }

                transactionScope.Complete();
            }

            ParentTreeRefresher parentTreeRefresher = this.CreateParentTreeRefresher();

            parentTreeRefresher.PostRefreshMesseges(this.EntityToken);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        string typeName = this.Request.QueryString["TypeName"];

        Type type = TypeManager.GetType(typeName);

        DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(type);
        XElement           element            = dataTypeDescriptor.ToXml();

        this.DataTypeDescriptorHolder.Controls.Add(new LiteralControl(new XElement("h3", "Xml").ToString()));
        this.DataTypeDescriptorHolder.Controls.Add(new LiteralControl(new XElement("pre", element.ToString()).ToString()));

        this.DataTypeDescriptorHolder.Controls.Add(new LiteralControl(new XElement("h3", "Xml attribute encoded xml").ToString()));
        XElement dummyElement = new XElement("Dummy", new XAttribute("dummy", element.ToString()));
        string   dummyString  = dummyElement.ToString();

        dummyString = dummyString.Remove(0, 13);
        dummyString = dummyString.Remove(dummyString.Length - 3);
        this.DataTypeDescriptorHolder.Controls.Add(new LiteralControl(new XElement("pre", dummyString).ToString()));
    }
Esempio n. 26
0
        public static XElement GetXElement(IData data)
        {
            var      elementName = data.DataSourceId.InterfaceType.Name;
            XElement xml         = new XElement(elementName);

            var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(data.DataSourceId.InterfaceType.GetImmutableTypeId());

            GeneratedTypesHelper generatedTypesHelper = new GeneratedTypesHelper(dataTypeDescriptor);

            //generatedTypesHelper.NotEditableDataFieldDescriptorNames

            foreach (DataFieldDescriptor fieldDescriptor in dataTypeDescriptor.Fields.Where(dfd => dfd.Inherited == false))
            {
                var propertyInfo = data.DataSourceId.InterfaceType.GetProperty(fieldDescriptor.Name);

                if (!generatedTypesHelper.NotEditableDataFieldDescriptorNames.Contains(fieldDescriptor.Name))
                {
                    string label = fieldDescriptor.FormRenderingProfile.Label;
                    object value = propertyInfo.GetValue(data, null);

                    List <ForeignKeyAttribute> foreignKeyAttributes = propertyInfo.GetCustomAttributesRecursively <ForeignKeyAttribute>().ToList();
                    if (foreignKeyAttributes.Count > 0)
                    {
                        IData foreignData = data.GetReferenced(propertyInfo.Name);

                        value = DataAttributeFacade.GetLabel(foreignData);
                    }
                    if (value == null)
                    {
                        value = string.Empty;
                    }
                    xml.Add(
                        new XElement("Property",
                                     new XAttribute("Label", GetLocalized(label)),
                                     new XAttribute("Value", value)
                                     )
                        );
                }
            }
            return(xml);
        }
Esempio n. 27
0
        public static Tuple <string, string>[] GetSearchableDataTypeOptions()
        {
            var result = new List <Tuple <string, string> >();

            var dataTypes = DataFacade.GetAllInterfaces().Where(type =>
                                                                type.GetCustomAttributes(typeof(SearchableTypeAttribute), false).Length > 0 &&
                                                                InternalUrls.DataTypeSupported(type)).ToList();

            dataTypes.Add(typeof(IPage));
            dataTypes.Add(typeof(IMediaFile));

            foreach (var dataType in dataTypes)
            {
                var descriptor = DynamicTypeManager.GetDataTypeDescriptor(dataType);
                result.Add(new Tuple <string, string>(
                               dataType.FullName,
                               descriptor.Title ?? dataType.Name));
            }

            return(result.OrderBy(r => r.Item2).ToArray());
        }
Esempio n. 28
0
            private void Initialize()
            {
                if (_templateDocument == null)
                {
                    lock (_lock)
                    {
                        if (_templateDocument == null)
                        {
                            Type interfaceType = TypeManager.GetType(_visualFunction.TypeManagerName);
                            _typeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(interfaceType);

                            if (_typeDescriptor == null)
                            {
                                throw new InvalidOperationException(string.Format("DataTypeDescriptor not found for type '{0}'", interfaceType));
                            }

                            _templateDocument = XhtmlDocument.Parse(_visualFunction.XhtmlTemplate);
                        }
                    }
                }
            }
Esempio n. 29
0
        public IEnumerable<IInfoClass> Get(string name, string filter = null)
        {
            var dynamicTypeManager = new DynamicTypeManager();
            var listType = dynamicTypeManager.GetListType(name);

            if (listType == null)
                throw new VeyronException(string.Format(CultureInfo.InvariantCulture, "Cannot get List Type {0}", name));

            var methodName = string.Format(CultureInfo.InvariantCulture, "Get{0}List", name);
            //if (!string.IsNullOrWhiteSpace(filter))
            //{
            //    var filterDescriptor = FilterDescriptor.GetFilterList(filter);                
            //}

            var list = (IInfoList)MethodCaller.CallFactoryMethod(listType, methodName, string.Empty, 0, 10, null, filter ?? FilterDescriptor.GetFilterExpression(null));

            if (list == null)
                throw new VeyronException(string.Format(CultureInfo.InvariantCulture, "Cannot get List for process: {0}", name));

            return list.Cast<IInfoClass>().ToList();
        }
        /// <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));
        }
Esempio n. 31
0
        private EntityToken GetDataEntityTokenParent(DataEntityToken dataEntityToken)
        {
            Type interfaceType = dataEntityToken.InterfaceType;

            if (!OnOwnsType(interfaceType))
            {
                return(null);
            }

            var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(interfaceType);

            IEnumerable <DataFieldDescriptor> groupingDataFieldDescriptors =
                from dfd in dataTypeDescriptor.Fields
                where dfd.GroupByPriority != 0
                orderby dfd.GroupByPriority
                select dfd;

            if (!groupingDataFieldDescriptors.Any())
            {
                return(OnGetRootParentEntityToken(interfaceType, dataEntityToken));
            }

            IData data = dataEntityToken.Data;

            var parentToken = new DataGroupingProviderHelperEntityToken(dataEntityToken.Type)
            {
                Payload        = this.OnGetPayload(dataEntityToken),
                GroupingValues = new Dictionary <string, object>()
            };

            foreach (DataFieldDescriptor dfd in groupingDataFieldDescriptors)
            {
                PropertyInfo propertyInfo = interfaceType.GetPropertiesRecursively().Single(f => f.Name == dfd.Name);

                object value = propertyInfo.GetValue(data, null);
                parentToken.GroupingValues.Add(propertyInfo.Name, NormalizeGroupingValue(value));
            }

            return(parentToken);
        }
Esempio n. 32
0
        public void RemoveLocale(CultureInfo cultureInfo)
        {
            var supportedInterfaces = GetSupportedInterfaces();

            foreach (var type in supportedInterfaces)
            {
                if (!DataLocalizationFacade.IsLocalized(type))
                {
                    continue;
                }

                var typeDesrciptor = DynamicTypeManager.GetDataTypeDescriptor(type);
                SqlStoreManipulator.RemoveLocale(_dataProviderContext.ProviderName, typeDesrciptor, cultureInfo);

                InterfaceConfigurationElement oldElement = _interfaceConfigurationElements.Where(f => f.DataTypeId == typeDesrciptor.DataTypeId).Single();

                InterfaceConfigurationElement newElement = InterfaceConfigurationManipulator.RefreshLocalizationInfo(_dataProviderContext.ProviderName, typeDesrciptor);

                _interfaceConfigurationElements.Remove(oldElement);
                _interfaceConfigurationElements.Add(newElement);
            }
        }
Esempio n. 33
0
        public void GetMultiCrossReferenceItem_ShouldReturnItemById()
        {
            var processName = "Process";
            var dynamicTypeManager = new DynamicTypeManager();

            var loggerMock = Mock.Create<ILogger>();
            dynamicTypeManager.Logger = loggerMock;

            var result = new CrossReferenceListBase();
            result.Add(Mock.Create<ICrossRefItemInfo>());

            var type = this.GetType();
            var asm = Assembly.GetCallingAssembly();

            Mock.NonPublic.Arrange<Assembly>(typeof(DynamicTypeManager), "loadAssembly", "Process").Returns(asm);
            Mock.Arrange(() => asm.GetType("DynamicProcess.ProcessFieldList")).Returns(type);
            Mock.Arrange(() => MethodCaller.CallFactoryMethod(type, "GetProcessFieldListById", 1, false)).Returns(result);

            var item = dynamicTypeManager.GetMultiCrossReferenceItem(processName, "Field", 1);

            Assert.AreSame(result[0], item);
        }
Esempio n. 34
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);
        }
Esempio n. 35
0
        public void Put(FieldData field)//, int recordId, string fieldName, string value)
        {
            if (field == null) throw new ArgumentNullException("field");

            MQ1Principal.Login("admin", "aimhi"); //TODO: use http headers instead 

            var dynamicTypeManager = new DynamicTypeManager();
            var editableRootType = dynamicTypeManager.GetEditableRootType(field.ProcessName);

            if (editableRootType == null)
                throw new VeyronException(string.Format(CultureInfo.InvariantCulture, "Cannot get Process Type {0}", field.ProcessName));

            var methodName = string.Format(CultureInfo.InvariantCulture, "Get{0}", field.ProcessName);
            var editableRoot = (IEditableRoot)MethodCaller.CallFactoryMethod(editableRootType, methodName, field.RecordId);
            
            var propertyInfo = GetProperty(field, editableRootType);

            if (propertyInfo.DeclaringType == editableRootType)
            {
                propertyInfo.SetValue(editableRoot,
                                      Convert.ChangeType(field.Value, propertyInfo.PropertyType,
                                                         CultureInfo.InvariantCulture), null);
            }
            else
            {
                var basePropertyInfo = editableRootType.GetProperty(Constants.BaseEditPropertyName);
                if (propertyInfo.DeclaringType == basePropertyInfo.PropertyType)
                {
                    var baseEditableRoot = basePropertyInfo.GetValue(editableRoot);
                    propertyInfo.SetValue(baseEditableRoot, Convert.ChangeType(field.Value, propertyInfo.PropertyType,
                                                         CultureInfo.InvariantCulture), null);
                }
            }

            ((ISavable) editableRoot).Save();
            
        }
Esempio n. 36
0
        public ProcessInfo Get(string name, int id)
        {
            MQ1Principal.Login("admin", "aimhi"); //TODO: use http headers instead 
            var dynamicTypeManager = new DynamicTypeManager();
            var editableRootType = dynamicTypeManager.GetEditableRootType(name);

            if (editableRootType == null)
                throw new VeyronException(string.Format(CultureInfo.InvariantCulture, "Cannot get Process Type {0}", name));

            var methodName = string.Format(CultureInfo.InvariantCulture, "Get{0}", name);
            //if (!string.IsNullOrWhiteSpace(filter))
            //{
            //    var filterDescriptor = FilterDescriptor.GetFilterList(filter);                
            //}

            var editableRoot = (IEditableRoot)MethodCaller.CallFactoryMethod(editableRootType, methodName, id);


            if (editableRoot == null)
                throw new VeyronException(string.Format(CultureInfo.InvariantCulture, "Cannot get List for process: {0}", name));

            var visibleFields = new HashSet<string>(editableRoot.Sections.SelectMany(s => s.Fields).Where(f => !f.IsHidden).Select(f => f.SystemName));

            var fields = GetFields(editableRoot, visibleFields);

            var result = new ProcessInfo();
            foreach (var section in editableRoot.Sections)
            {
                var sectionInfo = new SectionInfo {Name = section.Name};
                foreach (var field in section.Fields)
                {
                    var fieldInfo = fields.FirstOrDefault(f => f.SystemName == field.SystemName);
                    if (fieldInfo != null)
                    {
                        var value = fieldInfo.Model.GetType().GetProperty(field.SystemName).GetValue(fieldInfo.Model, null);
                        fieldInfo.Value = value == null ? string.Empty : value.ToString();
                        sectionInfo.Fields.Add(fieldInfo);
                    }
                }
                result.Sections.Add(sectionInfo);

            }

            result.Name = editableRoot.ProcessName;
            return result;
        }