コード例 #1
0
        public XmlDataTypeStoreDataScope GetDataScope(DataScopeIdentifier dataScope, CultureInfo culture, Type type)
        {
            string dataScopeName = dataScope.Name;

            Verify.That(HasDataScopeName(dataScope), "The store named '{0}' is not supported for data type '{1}'", dataScopeName, type);

            string cultureName = culture.Name;

            XmlDataTypeStoreDataScope dateTypeStoreDataScope =
                _xmlDateTypeStoreDataScopes.SingleOrDefault(f => f.DataScopeName == dataScopeName && f.CultureName == cultureName);

            if (dateTypeStoreDataScope == null)
            {
                if (culture.Equals(CultureInfo.InvariantCulture) && DataLocalizationFacade.IsLocalized(type))
                {
                    throw new InvalidOperationException("Failed to get data for type '{0}', no localization scope is provided for a localized type."
                                                        .FormatWith(type.FullName));
                }

                throw new InvalidOperationException("Failed to get '{0}' data for data scope ({1}, {2})"
                                                    .FormatWith(type.FullName, dataScopeName, culture.Equals(CultureInfo.InvariantCulture) ? "invariant" : cultureName));
            }

            return(dateTypeStoreDataScope);
        }
コード例 #2
0
        public static void AddLocale(string providerName, IEnumerable <Type> interfaceTypes, CultureInfo cultureInfo)
        {
            XmlDataProviderConfiguration xmlDataProviderConfiguration = new XmlDataProviderConfiguration(providerName);

            foreach (Type type in interfaceTypes)
            {
                if (!DataLocalizationFacade.IsLocalized(type))
                {
                    continue;
                }

                var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(type);

                object key = xmlDataProviderConfiguration.Section.Interfaces.GetKey(dataTypeDescriptor);

                var oldConfigurationElement = xmlDataProviderConfiguration.Section.Interfaces.Get(key);
                var newConfigurationElement = BuildXmlProviderInterfaceConfigurationElement(dataTypeDescriptor, cultureInfo, null, oldConfigurationElement);

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

                foreach (Dictionary <string, DataScopeConfigurationElement> filesByCulture in newConfigurationElement.DataScopes.Values)
                {
                    XmlDataProviderStoreManipulator.CreateStore(providerName, filesByCulture[cultureInfo.Name]);
                }
            }

            xmlDataProviderConfiguration.Save();
        }
コード例 #3
0
        /// <exclude />
        public void UpdateWithNewBindings(Dictionary <string, object> bindings, IEnumerable <CultureInfo> userActiveLocales)
        {
            Dictionary <string, string> options = new Dictionary <string, string>();

            foreach (CultureInfo cultureInfo in DataLocalizationFacade.ActiveLocalizationCultures)
            {
                options.Add(
                    cultureInfo.Name,
                    DataLocalizationFacade.GetCultureTitle(cultureInfo)
                    );
            }

            if (bindings.ContainsKey(MultiKeySelectorOptionsBindingName) == false)
            {
                bindings.Add(MultiKeySelectorOptionsBindingName, options);
            }
            else
            {
                bindings[MultiKeySelectorOptionsBindingName] = options;
            }

            if (bindings.ContainsKey(MultiKeySelectorSelectedBindingName) == false)
            {
                bindings.Add(MultiKeySelectorSelectedBindingName, userActiveLocales.Select(f => f.Name).ToList());
            }
            else
            {
                bindings[MultiKeySelectorSelectedBindingName] = userActiveLocales.Select(f => f.Name).ToList();
            }
        }
コード例 #4
0
        private void ValidateReferencingProperties(object sender, ConditionalEventArgs e)
        {
            var dataEntityToken = (DataEntityToken)this.EntityToken;
            var data            = dataEntityToken.Data as ILocalizedControlled;

            IEnumerable <ReferenceFailingPropertyInfo> referenceFailingProperties = DataLocalizationFacade.GetReferencingLocalizeFailingProperties(data).Evaluate();

            if (referenceFailingProperties.Any(f => f.OptionalReferenceWithValue == false))
            {
                List <string> row = new List <string>();

                row.Add(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "LocalizeData.ShowError.Description"));

                foreach (ReferenceFailingPropertyInfo referenceFailingPropertyInfo in referenceFailingProperties.Where(f => f.OptionalReferenceWithValue == false))
                {
                    row.Add(string.Format(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "LocalizeData.ShowError.FieldErrorFormat"), referenceFailingPropertyInfo.DataFieldDescriptor.Name, referenceFailingPropertyInfo.ReferencedType.GetTypeTitle(), referenceFailingPropertyInfo.OriginLocaleDataValue.GetLabel()));
                }

                List <List <string> > rows = new List <List <string> > {
                    row
                };

                this.UpdateBinding("ErrorHeader", new List <string> {
                    "Fields"
                });
                this.UpdateBinding("Errors", rows);

                e.Result = false;
            }
            else
            {
                e.Result = true;
            }
        }
コード例 #5
0
        public static CultureInfo GetCultureInfo(string requestPath, out string requestPathWithoutUrlMappingName)
        {
            requestPathWithoutUrlMappingName = requestPath;

            int startIndex = requestPath.IndexOf('/', UrlUtils.PublicRootPath.Length) + 1;

            if (startIndex >= 0)
            {
                int endIndex = requestPath.IndexOf('/', startIndex) - 1;
                if (endIndex >= 0)
                {
                    string urlMappingName = requestPath.Substring(startIndex, endIndex - startIndex + 1).ToLowerInvariant();

                    if (DataLocalizationFacade.UrlMappingNames.Contains(urlMappingName))
                    {
                        CultureInfo cultureInfo = DataLocalizationFacade.GetCultureInfoByUrlMappingName(urlMappingName);

                        bool exists = DataLocalizationFacade.ActiveLocalizationNames.Contains(cultureInfo.Name);

                        if (exists)
                        {
                            requestPathWithoutUrlMappingName = requestPath.Remove(startIndex - 1, endIndex - startIndex + 2);

                            return(cultureInfo);
                        }
                        return(null);
                    }
                }
            }

            return(DataLocalizationFacade.DefaultUrlMappingCulture);
        }
コード例 #6
0
        /// <exclude />
        public override SiteMapNode FindSiteMapNode(string rawUrl)
        {
            var culture = DataLocalizationFacade.DefaultLocalizationCulture;

            foreach (var activeCulture in DataLocalizationFacade.ActiveLocalizationCultures)
            {
                string cultureUrlMapping = DataLocalizationFacade.GetUrlMappingName(activeCulture);
                if (cultureUrlMapping.IsNullOrEmpty())
                {
                    continue;
                }

                string mappingPrefix = UrlUtils.PublicRootPath + "/" + cultureUrlMapping;

                if (rawUrl.Equals(mappingPrefix, StringComparison.OrdinalIgnoreCase) ||
                    rawUrl.StartsWith(mappingPrefix + "/", StringComparison.OrdinalIgnoreCase))
                {
                    culture = activeCulture;
                    break;
                }
            }

            var node = FindSiteMapNode(rawUrl, culture) as CompositeC1SiteMapNode;

            if (node == null)
            {
                if (IsDefaultDocumentUrl(rawUrl))
                {
                    node = RootNode as CompositeC1SiteMapNode;
                }
            }

            return(node);
        }
コード例 #7
0
        private bool BuildRootPageUrl(IPage rootPage, CultureInfo cultureInfo, UrlSpace urlSpace, StringBuilder result)
        {
            var bindings = GetHostnameBindings();

            bool knownHostname = urlSpace.Hostname != null &&
                                 bindings.Any(b => b.Hostname == urlSpace.Hostname);

            IHostnameBinding hostnameBinding = null;

            // Searching for a hostname binding matching either the root page, or current hostname/UrlSpace
            if (!urlSpace.ForceRelativeUrls && knownHostname)
            {
                Guid   pageId      = rootPage.Id;
                string host        = urlSpace.Hostname;
                string cultureName = cultureInfo.Name;

                hostnameBinding =
                    bindings.FirstOrDefault(b => b.HomePageId == pageId && b.Hostname == host && b.Culture == cultureName)
                    ?? bindings.FirstOrDefault(b => b.HomePageId == pageId && b.Culture == cultureName)
                    ?? bindings.FirstOrDefault(b => b.HomePageId == pageId && b.Hostname == host)
                    ?? bindings.FirstOrDefault(b => b.HomePageId == pageId);

                if (hostnameBinding != null)
                {
                    if (hostnameBinding.Hostname != urlSpace.Hostname)
                    {
                        result.AppendFormat("http{0}://", hostnameBinding.EnforceHttps ? "s" : "")
                        .Append(hostnameBinding.Hostname);
                    }
                }
                else
                {
                    hostnameBinding = bindings.FirstOrDefault(b => b.Hostname == urlSpace.Hostname);
                }
            }

            result.Append(UrlUtils.PublicRootPath);

            string cultureUrlMapping = DataLocalizationFacade.GetUrlMappingName(cultureInfo);

            if (cultureUrlMapping != string.Empty &&
                (hostnameBinding == null ||
                 hostnameBinding.IncludeCultureInUrl ||
                 hostnameBinding.Culture != cultureInfo.Name))
            {
                result.Append("/").Append(cultureUrlMapping);
            }


            AppendSlash(result);

            if (rootPage.UrlTitle != string.Empty &&
                (hostnameBinding == null || hostnameBinding.IncludeHomePageInUrl || hostnameBinding.HomePageId != rootPage.Id))
            {
                result.Append(rootPage.UrlTitle);
            }

            return(true);
        }
コード例 #8
0
        private Element ShowForeignElement(IData data, bool enabled)
        {
            string label = string.Format("{0} ({1})", data.GetLabel(true), DataLocalizationFacade.GetCultureTitle(UserSettings.ForeignLocaleCultureInfo));

            EntityToken entityToken = data.GetDataEntityToken();

            if (enabled)
            {
                var element = new Element(_elementProviderContext.CreateElementHandle(entityToken))
                {
                    VisualData = new ElementVisualizedData
                    {
                        Label       = label,
                        ToolTip     = label,
                        HasChildren = false,
                        Icon        = DataIconFacade.DataGhostedIcon,
                        IsDisabled  = false
                    }
                };

                element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.LocalizeDataWorkflow"), _localizeDataPermissionTypes)
                {
                    Payload = "Pagefolder"
                }))
                {
                    VisualData = new ActionVisualizedData
                    {
                        Label          = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.LocalizeData"),
                        ToolTip        = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.LocalizeDataToolTip"),
                        Icon           = GeneratedDataTypesElementProvider.LocalizeDataIcon,
                        Disabled       = false,
                        ActionLocation = new ActionLocation
                        {
                            ActionType  = ActionType.Add,
                            IsInFolder  = false,
                            IsInToolbar = true,
                            ActionGroup = PrimaryActionGroup
                        }
                    }
                });

                return(element);
            }

            return(new Element(_elementProviderContext.CreateElementHandle(entityToken))
            {
                VisualData = new ElementVisualizedData
                {
                    Label = label,
                    ToolTip = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.DisabledData"),
                    HasChildren = false,
                    Icon = DataIconFacade.DataDisabledIcon,
                    IsDisabled = true
                }
            });
        }
コード例 #9
0
        public QueryCache(string name, Expression <Func <TDataType, TPropertyType> > propertyGetter, int size)
        {
            _innerCache     = new Cache <string, ExtendedNullable <TDataType> >(name, size);
            _propertyGetter = propertyGetter;

            DataEventSystemFacade.SubscribeToDataAfterAdd <TDataType>(OnDataChanged, true);
            DataEventSystemFacade.SubscribeToDataAfterUpdate <TDataType>(OnDataChanged, true);
            DataEventSystemFacade.SubscribeToDataDeleted <TDataType>(OnDataChanged, true);

            _typeIsLocalizable = DataLocalizationFacade.IsLocalized(typeof(TDataType));
        }
コード例 #10
0
        private static string GetRedirectBaseUrl(CultureInfo cultureInfo)
        {
            string cultureUrlMapping = DataLocalizationFacade.GetUrlMappingName(cultureInfo);

            if (cultureUrlMapping != "")
            {
                return(UrlUtils.PublicRootPath + "/" + cultureUrlMapping);
            }

            return(UrlUtils.PublicRootPath);
        }
コード例 #11
0
        /// <exclude />
        public static IUnpublishSchedule GetUnpublishSchedule(Type dataType, string id, string cultureName)
        {
            Guid dataTypeId = dataType.GetImmutableTypeId();
            var  query      = DataFacade.GetData <IUnpublishSchedule>().Where(ps => ps.DataId == id && ps.DataTypeId == dataTypeId);

            if (DataLocalizationFacade.IsLocalized(dataType))
            {
                query = query.Where(ps => ps.LocaleCultureName == cultureName);
            }

            return(query.FirstOrDefault());
        }
コード例 #12
0
        /// <exclude />
        public static void CreateUnpublishSchedule(Type dataType, string id, string cultureName, DateTime date, WorkflowInstance workflow)
        {
            var unpublishSchedule = DataFacade.BuildNew <IUnpublishSchedule>();

            unpublishSchedule.Id                 = Guid.NewGuid();
            unpublishSchedule.DataTypeId         = dataType.GetImmutableTypeId();
            unpublishSchedule.DataId             = id;
            unpublishSchedule.UnpublishDate      = date;
            unpublishSchedule.WorkflowInstanceId = workflow.InstanceId;
            unpublishSchedule.LocaleCultureName  = DataLocalizationFacade.IsLocalized(dataType) ? cultureName : "";

            DataFacade.AddNew(unpublishSchedule);
        }
コード例 #13
0
        private string GetRootPageBaseUrl(Guid pageId, CultureInfo cultureInfo, out IHostnameBinding appliedHostnameBinding)
        {
            // TODO: merge with DefaultPageUrlProvider logic
            string cultureUrlMapping = DataLocalizationFacade.GetUrlMappingName(cultureInfo);

            if (!_forceRelativeUrls && _hostnameBindings.Any())
            {
                IHostnameBinding match = _hostnameBindings.FirstOrDefault(b => b.HomePageId == pageId && b.Culture == cultureInfo.Name);

                if (match == null)
                {
                    match = _hostnameBindings.FirstOrDefault(b => b.HomePageId == pageId);
                }

                if (match != null)
                {
                    string result = string.Empty;

                    if (match.Hostname != _urlSpace.Hostname)
                    {
                        result = "http://" + match.Hostname;
                    }

                    result += UrlUtils.PublicRootPath;

                    if (match.IncludeCultureInUrl || match.Culture != cultureInfo.Name)
                    {
                        if (cultureUrlMapping != string.Empty)
                        {
                            result += "/" + cultureUrlMapping;
                        }
                    }

                    appliedHostnameBinding = match;

                    return(result);
                }
            }

            appliedHostnameBinding = _hostnameBinding;

            if (cultureUrlMapping != "" &&
                (appliedHostnameBinding == null ||
                 appliedHostnameBinding.IncludeCultureInUrl ||
                 appliedHostnameBinding.Culture != cultureInfo.Name))
            {
                return(UrlUtils.PublicRootPath + "/" + cultureUrlMapping);
            }

            return(UrlUtils.PublicRootPath);
        }
コード例 #14
0
ファイル: GetXml.cs プロジェクト: wwl2013/C1-CMS
        private static QueryInfo GetQueryInfo(IEnumerable <string> propertyNames)
        {
            string key = string.Join("|", propertyNames);

            QueryInfo queryInfo = _queryInfoTable[key];

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


            lock (_queryInfoTable)
            {
                queryInfo = _queryInfoTable[key];
                if (queryInfo != null)
                {
                    return(queryInfo);
                }

                queryInfo = new QueryInfo();
                queryInfo.HasLocalizableReference = DataLocalizationFacade.IsLocalized(typeof(T));
                queryInfo.HasPublishableReference = DataFacade.GetSupportedDataScopes(typeof(T)).Count() > 1;

                List <Type> relatedTypesList = new List <Type>();

                foreach (string propertyName in propertyNames.Where(f => f.Contains(".")))
                {
                    string foreignKeyPropertyName = propertyName.Substring(0, propertyName.IndexOf("."));
                    ForeignPropertyInfo keyInfo   = DataReferenceFacade.GetForeignKeyPropertyInfo(typeof(T),
                                                                                                  foreignKeyPropertyName);

                    Type targetType = keyInfo.TargetType;
                    if (!relatedTypesList.Contains(targetType))
                    {
                        relatedTypesList.Add(targetType);
                    }

                    queryInfo.HasLocalizableReference = queryInfo.HasLocalizableReference || DataLocalizationFacade.IsLocalized(targetType);
                    queryInfo.HasPublishableReference = queryInfo.HasPublishableReference || (DataFacade.GetSupportedDataScopes(targetType).Count() > 1);
                }

                queryInfo.ReferencedDataTypes = relatedTypesList;

                _queryInfoTable.Add(key, queryInfo);
                return(queryInfo);
            }
        }
コード例 #15
0
        internal static void ClearCache(Type interfaceType, DataScopeIdentifier dataScopeIdentifier, CultureInfo localizationScope)
        {
            if (!_cachedData.TryGetValue(interfaceType, out TypeData typeData))
            {
                return;
            }

            dataScopeIdentifier = dataScopeIdentifier ?? DataScopeManager.MapByType(interfaceType);
            localizationScope   = !DataLocalizationFacade.IsLocalized(interfaceType)
                ? CultureInfo.InvariantCulture
                : (localizationScope ?? LocalizationScopeManager.CurrentLocalizationScope);

            var key = new Tuple <DataScopeIdentifier, CultureInfo>(dataScopeIdentifier, localizationScope);

            typeData.TryRemove(key, out _);
        }
コード例 #16
0
        public PageUrlBuilder(PublicationScope publicationScope, CultureInfo localizationScope, UrlSpace urlSpace)
        {
            _publicationScope  = publicationScope;
            _localizationScope = localizationScope;

            var localeMappedName = DataLocalizationFacade.GetUrlMappingName(localizationScope) ?? string.Empty;

            _forceRelativeUrls = urlSpace != null && urlSpace.ForceRelativeUrls;

            if (!_forceRelativeUrls &&
                urlSpace != null &&
                urlSpace.Hostname != null)
            {
                List <IHostnameBinding> hostnameBindings = DataFacade.GetData <IHostnameBinding>().ToList();

                _hostnameBinding = hostnameBindings.FirstOrDefault(b => b.Hostname == urlSpace.Hostname);

                bool knownHostname = _hostnameBinding != null;

                if (knownHostname)
                {
                    _hostnameBindings = hostnameBindings;

                    _urlSpace = urlSpace;
                }
            }

            if (_hostnameBinding != null &&
                !_hostnameBinding.IncludeCultureInUrl &&
                _hostnameBinding.Culture == localizationScope.Name)
            {
                _friendlyUrlPrefix = UrlUtils.PublicRootPath;

                if (!localeMappedName.IsNullOrEmpty())
                {
                    _friendlyUrlPrefixWithLanguageCode = UrlUtils.PublicRootPath + "/" + localeMappedName;
                }
            }
            else
            {
                _friendlyUrlPrefix = UrlUtils.PublicRootPath + (localeMappedName.IsNullOrEmpty() ? string.Empty : "/" + localeMappedName);
            }

            UrlSuffix = DataFacade.GetData <IUrlConfiguration>().Select(c => c.PageUrlSuffix).FirstOrDefault() ?? string.Empty;
        }
コード例 #17
0
        CultureInfo GetCultureInfo(string requestPath, IHostnameBinding hostnameBinding, out string pathWithoutLanguageAndAppRoot)
        {
            int startIndex = requestPath.IndexOf('/', UrlUtils.PublicRootPath.Length) + 1;

            if (startIndex > 0 && requestPath.Length > startIndex)
            {
                int endIndex = requestPath.IndexOf('/', startIndex + 1) - 1;
                if (endIndex < 0)
                {
                    endIndex = requestPath.Length - 1;
                }

                if (endIndex > startIndex)
                {
                    string urlMappingName = requestPath.Substring(startIndex, endIndex - startIndex + 1);

                    if (DataLocalizationFacade.UrlMappingNames.Any(um => String.Equals(um, urlMappingName, StringComparison.OrdinalIgnoreCase)))
                    {
                        CultureInfo cultureInfo = DataLocalizationFacade.GetCultureInfoByUrlMappingName(urlMappingName);

                        bool exists = DataLocalizationFacade.ActiveLocalizationNames.Contains(cultureInfo.Name);

                        if (exists)
                        {
                            pathWithoutLanguageAndAppRoot = requestPath.Substring(endIndex + 1);
                            return(cultureInfo);
                        }

                        // Culture is inactive
                        pathWithoutLanguageAndAppRoot = null;
                        return(null);
                    }
                }
            }

            pathWithoutLanguageAndAppRoot = requestPath.Substring(UrlUtils.PublicRootPath.Length);

            if (hostnameBinding != null && !hostnameBinding.IncludeCultureInUrl)
            {
                return(new CultureInfo(hostnameBinding.Culture));
            }

            return(DataLocalizationFacade.DefaultUrlMappingCulture);
        }
コード例 #18
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);
            }
        }
コード例 #19
0
        public static void RemoveLocale(string providerName, IEnumerable <Type> interfaceTypes, CultureInfo cultureInfo)
        {
            XmlDataProviderConfiguration xmlDataProviderConfiguration = new XmlDataProviderConfiguration(providerName);

            foreach (Type type in interfaceTypes)
            {
                if (DataLocalizationFacade.IsLocalizable(type))
                {
                    DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(type);

                    object key = xmlDataProviderConfiguration.Section.Interfaces.GetKey(dataTypeDescriptor);

                    bool configurationChanged = false;

                    var oldConfigurationElement = xmlDataProviderConfiguration.Section.Interfaces.Get(key);
                    foreach (Dictionary <string, DataScopeConfigurationElement> scopesByLanguage in oldConfigurationElement.DataScopes.Values)
                    {
                        if (scopesByLanguage.ContainsKey(cultureInfo.Name))
                        {
                            XmlDataProviderStoreManipulator.DropStore(providerName, scopesByLanguage[cultureInfo.Name]);
                            configurationChanged = true;
                        }
                    }

                    if (configurationChanged)
                    {
                        var newConfigurationElement = BuildXmlProviderInterfaceConfigurationElement(dataTypeDescriptor, null, cultureInfo, oldConfigurationElement);

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

            xmlDataProviderConfiguration.Save();
        }
コード例 #20
0
        private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e)
        {
            DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken;
            IXsltFunction   xsltFunction    = (IXsltFunction)dataEntityToken.Data;
            IFile           file            = IFileServices.GetFile <IXsltFile>(xsltFunction.XslFilePath);
            IEnumerable <ManagedParameterDefinition> parameters = ManagedParameterManager.Load(xsltFunction.Id);

            this.Bindings.Add("CurrentXslt", dataEntityToken.Data);
            this.Bindings.Add("Parameters", parameters);

            // popular type widgets
            List <Type> popularTypes       = DataFacade.GetAllInterfaces(UserType.Developer);
            var         popularWidgetTypes = FunctionFacade.WidgetFunctionSupportedTypes.Where(f => f.GetGenericArguments().Any(g => popularTypes.Any(h => h.IsAssignableFrom(g))));

            IEnumerable <Type> parameterTypeOptions = FunctionFacade.FunctionSupportedTypes.Union(popularWidgetTypes).Union(FunctionFacade.WidgetFunctionSupportedTypes);

            // At the moment we don't have functions that return IEnumerable<XNode>, so we're hardcoding this type for now
            parameterTypeOptions = parameterTypeOptions.Union(new [] { typeof(IEnumerable <XNode>) });

            this.Bindings.Add("ParameterTypeOptions", parameterTypeOptions.ToList());

            string xsltDocumentString = file.ReadAllText();

            this.Bindings.Add("XslTemplate", xsltDocumentString);
            this.Bindings.Add("XslTemplateLastSaveHash", xsltDocumentString.GetHashCode());

            List <string>            functionErrors;
            List <NamedFunctionCall> FunctionCalls = RenderHelper.GetValidFunctionCalls(xsltFunction.Id, out functionErrors).ToList();

            if ((functionErrors != null) && (functionErrors.Any()))
            {
                foreach (string error in functionErrors)
                {
                    this.ShowMessage(DialogType.Error, "A function call has been dropped", error);
                }
            }

            this.Bindings.Add("FunctionCalls", FunctionCalls);
            this.Bindings.Add("PageId", PageManager.GetChildrenIDs(Guid.Empty).FirstOrDefault());

            if (UserSettings.ActiveLocaleCultureInfo != null)
            {
                List <KeyValuePair <string, string> > activeCulturesDictionary = UserSettings.ActiveLocaleCultureInfos.Select(f => new KeyValuePair <string, string>(f.Name, DataLocalizationFacade.GetCultureTitle(f))).ToList();
                this.Bindings.Add("ActiveCultureName", UserSettings.ActiveLocaleCultureInfo.Name);
                this.Bindings.Add("ActiveCulturesList", activeCulturesDictionary);
            }

            this.Bindings.Add("PageDataScopeName", DataScopeIdentifier.AdministratedName);
            this.Bindings.Add("PageDataScopeList", new Dictionary <string, string>
            {
                { DataScopeIdentifier.AdministratedName, GetString("EditXsltFunction.LabelAdminitrativeScope") },
                { DataScopeIdentifier.PublicName, GetString("EditXsltFunction.LabelPublicScope") }
            });


            // Creating a session state object
            Guid stateId = Guid.NewGuid();
            var  state   = new FunctionCallDesignerState {
                WorkflowId = WorkflowInstanceId, ConsoleIdInternal = GetCurrentConsoleId()
            };

            SessionStateManager.DefaultProvider.AddState <IFunctionCallEditorState>(stateId, state, DateTime.Now.AddDays(7.0));

            this.Bindings.Add("SessionStateProvider", SessionStateManager.DefaultProviderName);
            this.Bindings.Add("SessionStateId", stateId);
        }
コード例 #21
0
        private Element BuildElement(IData data,
                                     DynamicValuesHelperReplaceContext replaceContext,
                                     TreeNodeDynamicContext dynamicContext,
                                     bool localizationEnabled,
                                     List <object> itemKeys,
                                     ref IEnumerable <object> keysJoinedByParentFilters,
                                     EntityToken parentEntityToken
                                     )
        {
            replaceContext.CurrentDataItem = data;

            object keyValue = this.KeyPropertyInfo.GetValue(data, null);

            bool itemLocalizationEnabledAndForeign = localizationEnabled && !data.DataSourceId.LocaleScope.Equals(UserSettings.ActiveLocaleCultureInfo);

            if (itemLocalizationEnabledAndForeign && itemKeys.Contains(keyValue))
            {
                return(null);
            }

            var currentEntityToken = data.GetDataEntityToken();

            var element = new Element(new ElementHandle
                                      (
                                          dynamicContext.ElementProviderName,
                                          currentEntityToken,
                                          dynamicContext.Piggybag.PreparePiggybag(this.ParentNode, parentEntityToken)
                                      ));


            bool           hasChildren;
            bool           isDisabled = false;
            ResourceHandle icon, openedIcon;

            if (itemLocalizationEnabledAndForeign)
            {
                hasChildren = false;
                isDisabled  = !data.IsTranslatable();

                if (this.Icon != null)
                {
                    icon       = this.Icon;
                    openedIcon = this.OpenedIcon;
                }
                else
                {
                    icon       = data.GetForeignIcon();
                    openedIcon = icon;
                }
            }
            else
            {
                if (this.Display != LeafDisplayMode.Auto)
                {
                    hasChildren = ChildNodes.Any();
                }
                else
                {
                    hasChildren = ChildNodes.OfType <SimpleElementTreeNode>().Any();

                    if (!hasChildren)
                    {
                        if (keysJoinedByParentFilters != null)
                        {
                            keysJoinedByParentFilters = keysJoinedByParentFilters.Evaluate();

                            hasChildren = keysJoinedByParentFilters.Contains(keyValue);
                        }
                    }

                    // Checking children filtered by FunctionFilters
                    if (!hasChildren)
                    {
                        foreach (var childNode in this.ChildNodes.OfType <DataElementsTreeNode>()
                                 .Where(n => n.FilterNodes.OfType <FunctionFilterNode>().Any()))
                        {
                            var newDynamicContext = new TreeNodeDynamicContext(TreeNodeDynamicContextDirection.Down)
                            {
                                ElementProviderName = dynamicContext.ElementProviderName,
                                Piggybag            = dynamicContext.Piggybag.PreparePiggybag(this.ParentNode, parentEntityToken),
                                CurrentEntityToken  = currentEntityToken
                            };

                            if (childNode.GetDataset(newDynamicContext, false).DataItems.Any())
                            {
                                hasChildren = true;
                                break;
                            }
                        }
                    }
                }

                if (this.Icon != null)
                {
                    icon       = this.Icon;
                    openedIcon = this.OpenedIcon;
                }
                else
                {
                    openedIcon = icon = data.GetIcon();
                }
            }

            string label = this.Label.IsNullOrEmpty()
                            ? data.GetLabel()
                            : this.LabelDynamicValuesHelper.ReplaceValues(replaceContext);

            string toolTip = this.ToolTip.IsNullOrEmpty()
                            ? label
                            : this.ToolTipDynamicValuesHelper.ReplaceValues(replaceContext);

            if (itemLocalizationEnabledAndForeign)
            {
                label = string.Format("{0} ({1})", label, DataLocalizationFacade.GetCultureTitle(UserSettings.ForeignLocaleCultureInfo));

                if (!data.IsTranslatable())
                {
                    toolTip = StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "LocalizeDataWorkflow.DisabledData");
                }
                else
                {
                    toolTip = string.Format("{0} ({1})", toolTip, DataLocalizationFacade.GetCultureTitle(UserSettings.ForeignLocaleCultureInfo));
                }
            }

            element.VisualData = new ElementVisualizedData
            {
                Label       = label,
                ToolTip     = toolTip,
                HasChildren = hasChildren,
                Icon        = icon,
                OpenedIcon  = openedIcon,
                IsDisabled  = isDisabled
            };


            if (InternalUrls.DataTypeSupported(data.DataSourceId.InterfaceType))
            {
                var dataReference = data.ToDataReference();

                if (DataUrls.CanBuildUrlForData(dataReference))
                {
                    string internalUrl = InternalUrls.TryBuildInternalUrl(dataReference);

                    if (internalUrl != null)
                    {
                        element.PropertyBag.Add("Uri", internalUrl);
                    }
                }
            }


            if (itemLocalizationEnabledAndForeign)
            {
                var actionToken = new WorkflowActionToken(
                    WorkflowFacade.GetWorkflowType("Composite.C1Console.Trees.Workflows.LocalizeDataWorkflow"),
                    LocalizeDataPermissionTypes);

                element.AddAction(new ElementAction(new ActionHandle(actionToken))
                {
                    VisualData = new ActionVisualizedData
                    {
                        Label          = StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "LocalizeDataWorkflow.LocalizeDataLabel"),
                        ToolTip        = StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "LocalizeDataWorkflow.LocalizeDataToolTip"),
                        Icon           = LocalizeDataTypeIcon,
                        Disabled       = false,
                        ActionLocation = ActionLocation.OtherPrimaryActionLocation
                    }
                });
            }

            return(element);
        }
コード例 #22
0
        private void stepInitialize_codeActivity_ExecuteCode(object sender, EventArgs e)
        {
            Guid templateId;

            if (this.EntityToken is PageElementProviderEntityToken)
            {
                templateId = PageTemplateFacade.GetPageTemplates().Select(t => t.Id).FirstOrDefault();
            }
            else if (this.EntityToken is DataEntityToken)
            {
                DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken;
                IPage           selectedPage    = (IPage)dataEntityToken.Data;

                templateId = selectedPage.TemplateId;
            }
            else
            {
                throw new NotImplementedException();
            }


            List <IPageType> selectablePageTypes = GetSelectablePageTypes();

            Guid?pageTypeId = GetDefaultPageTypeId(selectablePageTypes);

            Verify.That(pageTypeId.HasValue, "Failed to get a page type");

            Guid parentId = GetParentId();

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



            List <KeyValuePair <Guid, string> > pageTypeOptions =
                selectablePageTypes.
                Select(f => new KeyValuePair <Guid, string>(f.Id, f.Name)).
                ToList();

            bindings.Add("PageTypeOptions", pageTypeOptions);


            IPage newPage = DataFacade.BuildNew <IPage>();

            newPage.Id                = Guid.NewGuid();
            newPage.TemplateId        = templateId;
            newPage.PageTypeId        = pageTypeId.Value;
            newPage.Title             = "";
            newPage.MenuTitle         = "";
            newPage.UrlTitle          = "";
            newPage.FriendlyUrl       = "";
            newPage.PublicationStatus = GenericPublishProcessController.Draft;

            bindings.Add("NewPage", newPage);

            bindings.Add("UrlTitleIsRequired", true /* ThereAreOtherPages()*/);

            int existingPagesCount = PageServices.GetChildrenCount(parentId);
            Dictionary <string, string> sortOrder = new Dictionary <string, string>();

            sortOrder.Add("Bottom", GetText("AddNewPageStep1.LabelAddToBottom"));
            if (existingPagesCount > 0)
            {
                sortOrder.Add("Top", GetText("AddNewPageStep1.LabelAddToTop"));
                if (existingPagesCount > 1)
                {
                    sortOrder.Add("Relative", GetText("AddNewPageStep1.LabelAddBelowOtherPage"));
                }

                bool isAlpabeticOrdered = PageServices.IsChildrenAlphabeticOrdered(parentId);
                if (isAlpabeticOrdered)
                {
                    sortOrder.Add("Alphabetic", GetText("AddNewPageStep1.LabelAddAlphabetic"));
                }
            }
            bindings.Add("SortOrder", sortOrder);
            bindings.Add("SelectedSortOrder", sortOrder.Keys.First());

            if (parentId == Guid.Empty)
            {
                bindings.Add("ShowCulture", true);
                bindings.Add("Cultures", DataLocalizationFacade.WhiteListedLocales
                             .Select(f => new KeyValuePair <string, string>(f.Name, DataLocalizationFacade.GetCultureTitle(f))).ToList());
            }
            else
            {
                bindings.Add("ShowCulture", false);
            }

            this.Bindings = bindings;
        }
コード例 #23
0
        private void codeActivity1_ExecuteCode(object sender, EventArgs e)
        {
            try
            {
                string typeName             = this.GetBinding <string>(BindingNames.NewTypeName);
                string typeNamespace        = this.GetBinding <string>(BindingNames.NewTypeNamespace);
                string typeTitle            = this.GetBinding <string>(BindingNames.NewTypeTitle);
                bool   hasCaching           = this.GetBinding <bool>(BindingNames.HasCaching);
                bool   hasPublishing        = this.GetBinding <bool>(BindingNames.HasPublishing);
                bool   hasLocalization      = this.GetBinding <bool>(BindingNames.HasLocalization);
                bool   isSearchable         = this.GetBinding <bool>(BindingNames.IsSearchable);
                string keyFieldName         = this.GetBinding <string>(BindingNames.KeyFieldName);
                string labelFieldName       = this.GetBinding <string>(BindingNames.LabelFieldName);
                string internalUrlPrefix    = this.GetBinding <string>(BindingNames.InternalUrlPrefix);
                var    dataFieldDescriptors = this.GetBinding <List <DataFieldDescriptor> >(BindingNames.DataFieldDescriptors);

                GeneratedTypesHelper helper;
                Type interfaceType = null;
                if (this.BindingExist(BindingNames.InterfaceType))
                {
                    interfaceType = this.GetBinding <Type>(BindingNames.InterfaceType);

                    helper = new GeneratedTypesHelper(interfaceType);
                }
                else
                {
                    helper = new GeneratedTypesHelper();
                }

                string errorMessage;
                if (!helper.ValidateNewTypeName(typeName, out errorMessage))
                {
                    this.ShowFieldMessage(BindingNames.NewTypeName, errorMessage);
                    return;
                }

                if (!helper.ValidateNewTypeNamespace(typeNamespace, out errorMessage))
                {
                    this.ShowFieldMessage(BindingNames.NewTypeNamespace, errorMessage);
                    return;
                }

                if (!helper.ValidateNewTypeFullName(typeName, typeNamespace, out errorMessage))
                {
                    this.ShowFieldMessage(BindingNames.NewTypeName, errorMessage);
                    return;
                }

                if (!helper.ValidateNewFieldDescriptors(dataFieldDescriptors, keyFieldName, out errorMessage))
                {
                    this.ShowMessage(
                        DialogType.Warning,
                        Texts.AddNewInterfaceTypeStep1_ErrorTitle,
                        errorMessage
                        );
                    return;
                }

                if (interfaceType != null)
                {
                    if (hasLocalization != DataLocalizationFacade.IsLocalized(interfaceType) &&
                        DataFacade.GetData(interfaceType).ToDataEnumerable().Any())
                    {
                        this.ShowMessage(
                            DialogType.Error,
                            Texts.AddNewInterfaceTypeStep1_ErrorTitle,
                            "It's not possible to change localization through the current tab"
                            );
                        return;
                    }
                }


                if (helper.IsEditProcessControlledAllowed)
                {
                    helper.SetCacheable(hasCaching);
                    helper.SetPublishControlled(hasPublishing);
                    helper.SetLocalizedControlled(hasLocalization);
                    helper.SetSearchable(isSearchable);
                }

                helper.SetNewTypeFullName(typeName, typeNamespace);
                helper.SetNewTypeTitle(typeTitle);
                helper.SetNewInternalUrlPrefix(internalUrlPrefix);
                helper.SetNewFieldDescriptors(dataFieldDescriptors, keyFieldName, labelFieldName);


                if (IsPageDataFolder && !this.BindingExist(BindingNames.InterfaceType))
                {
                    Type targetType = TypeManager.GetType(this.Payload);

                    helper.SetForeignKeyReference(targetType, Composite.Data.DataAssociationType.Aggregation);
                }

                bool originalTypeDataExists = false;
                if (interfaceType != null)
                {
                    originalTypeDataExists = DataFacade.HasDataInAnyScope(interfaceType);
                }

                if (!helper.TryValidateUpdate(originalTypeDataExists, out errorMessage))
                {
                    this.ShowMessage(
                        DialogType.Warning,
                        Texts.AddNewInterfaceTypeStep1_ErrorTitle,
                        errorMessage
                        );
                    return;
                }


                helper.CreateType(originalTypeDataExists);

                string serializedTypeName = TypeManager.SerializeType(helper.InterfaceType);

                EntityToken entityToken = new GeneratedDataTypesElementProviderTypeEntityToken(
                    serializedTypeName,
                    this.EntityToken.Source,
                    IsPageDataFolder ? GeneratedDataTypesElementProviderRootEntityToken.PageDataFolderTypeFolderId
                                     : GeneratedDataTypesElementProviderRootEntityToken.GlobalDataTypeFolderId
                    );

                if (originalTypeDataExists)
                {
                    SetSaveStatus(true);
                }
                else
                {
                    SetSaveStatus(true, entityToken);
                }


                if (!this.BindingExist(BindingNames.InterfaceType))
                {
                    this.AcquireLock(entityToken);
                }

                this.UpdateBinding(BindingNames.InterfaceType, helper.InterfaceType);
                this.UpdateBinding(BindingNames.KeyFieldReadOnly, true);

                this.UpdateBinding(BindingNames.ViewLabel, typeTitle);
                RerenderView();

                //this.WorkflowResult = TypeManager.SerializeType(helper.InterfaceType);


                UserSettings.LastSpecifiedNamespace = typeNamespace;

                var parentTreeRefresher = this.CreateParentTreeRefresher();
                parentTreeRefresher.PostRefreshMessages(entityToken);
            }
            catch (Exception ex)
            {
                Log.LogCritical("Add New Interface Failed", ex);

                this.ShowMessage(DialogType.Error, ex.Message, ex.Message);
            }
        }
コード例 #24
0
        private void initializeCodeActivity_Copy_ExecuteCode(object sender, EventArgs e)
        {
            var castedEntityToken = (DataEntityToken)this.EntityToken;

            IPage newPage;

            using (var transactionScope = TransactionsFacade.CreateNewScope())
            {
                CultureInfo sourceCultureInfo = UserSettings.ForeignLocaleCultureInfo;

                IPage sourcePage;
                List <IPagePlaceholderContent> sourcePagePlaceholders;
                List <IData> sourceMetaDataSet;

                using (new DataScope(sourceCultureInfo))
                {
                    var  pageFromEntityToken = (IPage)castedEntityToken.Data;
                    Guid sourcePageId        = pageFromEntityToken.Id;
                    Guid sourcePageVersionId = pageFromEntityToken.VersionId;

                    using (new DataScope(DataScopeIdentifier.Administrated))
                    {
                        sourcePage = DataFacade.GetData <IPage>(f => f.Id == sourcePageId).Single();
                        sourcePage = sourcePage.GetTranslationSource();

                        using (new DataScope(sourcePage.DataSourceId.DataScopeIdentifier))
                        {
                            sourcePagePlaceholders = DataFacade
                                                     .GetData <IPagePlaceholderContent>(f => f.PageId == sourcePageId && f.VersionId == sourcePageVersionId)
                                                     .ToList();
                            sourceMetaDataSet = sourcePage.GetMetaData().ToList();
                        }
                    }
                }


                CultureInfo targetCultureInfo = UserSettings.ActiveLocaleCultureInfo;

                using (new DataScope(targetCultureInfo))
                {
                    newPage = DataFacade.BuildNew <IPage>();
                    sourcePage.ProjectedCopyTo(newPage);

                    newPage.SourceCultureName = targetCultureInfo.Name;
                    newPage.PublicationStatus = GenericPublishProcessController.Draft;
                    newPage = DataFacade.AddNew <IPage>(newPage);

                    foreach (IPagePlaceholderContent sourcePagePlaceholderContent in sourcePagePlaceholders)
                    {
                        IPagePlaceholderContent newPagePlaceholderContent = DataFacade.BuildNew <IPagePlaceholderContent>();
                        sourcePagePlaceholderContent.ProjectedCopyTo(newPagePlaceholderContent);

                        newPagePlaceholderContent.SourceCultureName = targetCultureInfo.Name;
                        newPagePlaceholderContent.PublicationStatus = GenericPublishProcessController.Draft;
                        DataFacade.AddNew <IPagePlaceholderContent>(newPagePlaceholderContent);
                    }

                    foreach (IData metaData in sourceMetaDataSet)
                    {
                        ILocalizedControlled localizedData = metaData as ILocalizedControlled;

                        if (localizedData == null)
                        {
                            continue;
                        }

                        IEnumerable <ReferenceFailingPropertyInfo> referenceFailingPropertyInfos = DataLocalizationFacade.GetReferencingLocalizeFailingProperties(localizedData).Evaluate();

                        if (!referenceFailingPropertyInfos.Any())
                        {
                            IData newMetaData = DataFacade.BuildNew(metaData.DataSourceId.InterfaceType);
                            metaData.ProjectedCopyTo(newMetaData);

                            ILocalizedControlled localizedControlled = newMetaData as ILocalizedControlled;
                            localizedControlled.SourceCultureName = targetCultureInfo.Name;

                            IPublishControlled publishControlled = newMetaData as IPublishControlled;
                            publishControlled.PublicationStatus = GenericPublishProcessController.Draft;

                            DataFacade.AddNew(newMetaData);
                        }
                        else
                        {
                            foreach (ReferenceFailingPropertyInfo referenceFailingPropertyInfo in referenceFailingPropertyInfos)
                            {
                                Log.LogVerbose("LocalizePageWorkflow",
                                               "Meta data of type '{0}' is not localized because the field '{1}' is referring some not yet localzed data"
                                               .FormatWith(metaData.DataSourceId.InterfaceType, referenceFailingPropertyInfo.DataFieldDescriptor.Name));
                            }
                        }
                    }
                }

                EntityTokenCacheFacade.ClearCache(sourcePage.GetDataEntityToken());
                EntityTokenCacheFacade.ClearCache(newPage.GetDataEntityToken());

                foreach (var folderType in PageFolderFacade.GetDefinedFolderTypes(newPage))
                {
                    EntityTokenCacheFacade.ClearCache(new AssociatedDataElementProviderHelperEntityToken(
                                                          TypeManager.SerializeType(typeof(IPage)),
                                                          PageElementProvider.DefaultConfigurationName,
                                                          newPage.Id.ToString(),
                                                          TypeManager.SerializeType(folderType)));
                }


                transactionScope.Complete();
            }

            ParentTreeRefresher parentTreeRefresher = this.CreateParentTreeRefresher();

            parentTreeRefresher.PostRefreshMesseges(newPage.GetDataEntityToken(), 2);

            this.ExecuteWorklow(newPage.GetDataEntityToken(), typeof(EditPageWorkflow));
        }
コード例 #25
0
 public TypeKeyInstallationData(Type type)
 {
     _isLocalized   = DataLocalizationFacade.IsLocalized(type);
     _isPublishable = typeof(IPublishControlled).IsAssignableFrom(type);
     _type          = type;
 }
コード例 #26
0
        public IEnumerable <Element> GetChildren(EntityToken entityToken, SearchToken seachToken)
        {
            if ((entityToken is LocalizationElementProviderRootEntityToken) == false)
            {
                throw new InvalidOperationException();
            }

            IEnumerable <ISystemActiveLocale> locales = DataFacade.GetData <ISystemActiveLocale>().ToList();

            List <Element> elements = new List <Element>();

            foreach (ISystemActiveLocale locale in locales)
            {
                bool isDefault = LocalizationFacade.IsDefaultLocale(locale.CultureName);

                ResourceHandle iconHandle = LocaleItemIcon;
                if (isDefault)
                {
                    //lable = string.Format("{0} ({1})", lable, StringResourceSystemFacade.GetString("Composite.Plugins.LocalizationElementProvider", "ElementProvider.DefaultLabel"));
                    iconHandle = DefaultLocaleItemIcon;
                }

                Element element = new Element(_context.CreateElementHandle(locale.GetDataEntityToken()));
                element.VisualData = new ElementVisualizedData
                {
                    Label       = DataLocalizationFacade.GetCultureTitle(new CultureInfo(locale.CultureName)),
                    ToolTip     = DataLocalizationFacade.GetCultureTitle(new CultureInfo(locale.CultureName)),
                    HasChildren = false,
                    Icon        = iconHandle
                };


                element.AddAction(new ElementAction(new ActionHandle(
                                                        new WorkflowActionToken(
                                                            WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.LocalizationElementProvider.EditSystemLocaleWorkflow"),
                                                            new PermissionType[] { PermissionType.Administrate }
                                                            )))
                {
                    VisualData = new ActionVisualizedData
                    {
                        Label          = StringResourceSystemFacade.GetString("Composite.Plugins.LocalizationElementProvider", "EditSystemLocaleWorkflow.EditElementActionLabel"),
                        ToolTip        = StringResourceSystemFacade.GetString("Composite.Plugins.LocalizationElementProvider", "EditSystemLocaleWorkflow.EditElementActionToolTip"),
                        Icon           = EditSystemLocaleIcon,
                        Disabled       = false,
                        ActionLocation = new ActionLocation
                        {
                            ActionType  = ActionType.Edit,
                            IsInFolder  = false,
                            IsInToolbar = true,
                            ActionGroup = PrimaryActionGroup
                        }
                    }
                });


                if (isDefault == false)
                {
                    element.AddAction(new ElementAction(new ActionHandle(
                                                            new WorkflowActionToken(
                                                                WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.LocalizationElementProvider.DefineDefaultActiveLocaleWorkflow"),
                                                                new PermissionType[] { PermissionType.Administrate }
                                                                )))
                    {
                        VisualData = new ActionVisualizedData
                        {
                            Label          = StringResourceSystemFacade.GetString("Composite.Plugins.LocalizationElementProvider", "DefineDefaultActiveLocaleWorkflow.ElementActionLabel"),
                            ToolTip        = StringResourceSystemFacade.GetString("Composite.Plugins.LocalizationElementProvider", "DefineDefaultActiveLocaleWorkflow.ElementActionToolTip"),
                            Icon           = SetAsDefaultIcon,
                            Disabled       = false,
                            ActionLocation = new ActionLocation
                            {
                                ActionType  = ActionType.Edit,
                                IsInFolder  = false,
                                IsInToolbar = true,
                                ActionGroup = PrimaryActionGroup
                            }
                        }
                    });


                    element.AddAction(new ElementAction(new ActionHandle(
                                                            new WorkflowActionToken(
                                                                WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.LocalizationElementProvider.RemoveSystemLocaleWorkflow"),
                                                                new PermissionType[] { PermissionType.Administrate }
                                                                )))
                    {
                        VisualData = new ActionVisualizedData
                        {
                            Label          = StringResourceSystemFacade.GetString("Composite.Plugins.LocalizationElementProvider", "RemoveSystemLocaleWorkflow.RemoveElementActionLabel"),
                            ToolTip        = StringResourceSystemFacade.GetString("Composite.Plugins.LocalizationElementProvider", "RemoveSystemLocaleWorkflow.RemoveElementActionToolTip"),
                            Icon           = RemoveSystemLocaleIcon,
                            Disabled       = false,
                            ActionLocation = new ActionLocation
                            {
                                ActionType  = ActionType.Delete,
                                IsInFolder  = false,
                                IsInToolbar = true,
                                ActionGroup = PrimaryActionGroup
                            }
                        }
                    });
                }

                elements.Add(element);
            }

            return(elements.OrderBy(f => f.VisualData.Label));
        }
コード例 #27
0
        private void initializeCodeActivity_InitBindings_ExecuteCode(object sender, EventArgs e)
        {
            IInlineFunction functionInfo = this.GetDataItemFromEntityToken <IInlineFunction>();

            this.Bindings.Add("Function", functionInfo);
            this.Bindings.Add("PageId", PageManager.GetChildrenIDs(Guid.Empty).FirstOrDefault());

            if (UserSettings.ActiveLocaleCultureInfo != null)
            {
                List <KeyValuePair <string, string> > activeCulturesDictionary = UserSettings.ActiveLocaleCultureInfos.Select(f => new KeyValuePair <string, string>(f.Name, DataLocalizationFacade.GetCultureTitle(f))).ToList();
                this.Bindings.Add("ActiveCultureName", UserSettings.ActiveLocaleCultureInfo.Name);
                this.Bindings.Add("ActiveCulturesList", activeCulturesDictionary);
            }

            this.Bindings.Add("PageDataScopeName", DataScopeIdentifier.AdministratedName);
            this.Bindings.Add("PageDataScopeList", new Dictionary <string, string>
            {
                { DataScopeIdentifier.AdministratedName, GetText("EditInlineFunctionWorkflow.AdminitrativeScope.Label") },
                { DataScopeIdentifier.PublicName, GetText("EditInlineFunctionWorkflow.PublicScope.Label") }
            });


            this.Bindings.Add("FunctionCode", functionInfo.GetFunctionCode());

            List <KeyValuePair> assemblies = new List <KeyValuePair>();

            foreach (string assembly in InlineFunctionHelper.GetReferencableAssemblies())
            {
                assemblies.Add(new KeyValuePair(assembly.ToLowerInvariant(), System.IO.Path.GetFileName(assembly)));
            }

            assemblies.Sort(delegate(KeyValuePair kvp1, KeyValuePair kvp2) { return(kvp1.Value.CompareTo(kvp2.Value)); });

            this.Bindings.Add("Assemblies", assemblies);


            List <string> selectedAssemblies =
                DataFacade.GetData <IInlineFunctionAssemblyReference>().
                Where(f => f.Function == functionInfo.Id).
                OrderBy(f => f.Name).
                Evaluate().
                Select(f => InlineFunctionHelper.GetAssemblyFullPath(f.Name, f.Location).ToLowerInvariant()).
                ToList();

            this.Bindings.Add("SelectedAssemblies", selectedAssemblies);


            List <ManagedParameterDefinition> parameters = ManagedParameterManager.Load(functionInfo.Id).ToList();;

            this.Bindings.Add("Parameters", parameters);


            IEnumerable <Type> popularWidgetTypes   = FunctionFacade.WidgetFunctionSupportedTypes.Where(f => f.GetGenericArguments().Any(g => DataFacade.GetAllInterfaces(UserType.Developer).Any(h => h.IsAssignableFrom(g))));
            List <Type>        parameterTypeOptions = FunctionFacade.FunctionSupportedTypes.Union(popularWidgetTypes).Union(FunctionFacade.WidgetFunctionSupportedTypes).ToList();

            this.Bindings.Add("ParameterTypeOptions", parameterTypeOptions);

            Guid stateId = Guid.NewGuid();
            ParameterEditorState parameterEditorState = new ParameterEditorState {
                WorkflowId = WorkflowInstanceId
            };

            SessionStateManager.DefaultProvider.AddState <IParameterEditorState>(stateId, parameterEditorState, DateTime.Now.AddDays(7.0));

            this.Bindings.Add("SessionStateProvider", SessionStateManager.DefaultProviderName);
            this.Bindings.Add("SessionStateId", stateId);
        }
コード例 #28
0
    protected bool TestOutOfBoundStringFields()
    {
        var sb  = new StringBuilder();
        var err = new StringBuilder();

        Guid guid;
        var  datatypes = DataFacade.GetAllInterfaces().Where(x => x.TryGetImmutableTypeId(out guid));

        foreach (var datatype in datatypes)
        {
            try
            {
                var fields = DynamicTypeManager.GetDataTypeDescriptor(datatype).Fields;
                foreach (var dataScopeIdentifier in DataFacade.GetSupportedDataScopes(datatype))
                {
                    var cultures = DataLocalizationFacade.IsLocalized(datatype) ? DataLocalizationFacade.ActiveLocalizationCultures.ToArray() : new[] { CultureInfo.InvariantCulture };
                    foreach (var cultureInfo in cultures)
                    {
                        using (new DataScope(dataScopeIdentifier, cultureInfo))
                        {
                            var recordCount = 0;
                            foreach (var field in fields.Where(field => field.StoreType.IsLargeString || field.StoreType.IsString))
                            {
                                try
                                {
                                    int          maxLength    = field.StoreType.MaximumLength;
                                    PropertyInfo propertyName = datatype.GetPropertiesRecursively(x => x.Name == field.Name).FirstOrDefault();
                                    PropertyInfo propertyId   = datatype.GetProperty("Id") ?? (datatype.GetProperty("PageId") ?? datatype.GetProperty("VisabilityForeignKey"));

                                    var records = from x in DataFacade.GetData(datatype).ToDataEnumerable() select new { Value = (propertyName != null) ? propertyName.GetValue(x, null) : string.Empty, Id = (propertyId != null) ? propertyId.GetValue(x, null) : Guid.Empty };
                                    foreach (var record in records.Where(record => record.Value != null).Where(record => record.Value.ToString().Length > maxLength))
                                    {
                                        if (recordCount == 0)
                                        {
                                            sb.Append(string.Format("<tr class='datatype'><td colspan='3'><strong>{0}</strong> ({1}), {2}, {3}</td></tr>", datatype.Name, datatype, dataScopeIdentifier.Name, cultureInfo.Name));
                                        }

                                        sb.Append(string.Format("<tr><td>{0}</td><td>{1}</td><td>{2} ({3} chars, {4} max)</td></tr>", record.Id, record.Value, field.Name, record.Value.ToString().Length, field.StoreType.MaximumLength));
                                        recordCount++;
                                    }
                                }
                                catch (Exception x)
                                {
                                    err.Append(string.Format("<tr class='error'><td>{0} ({1})</td><td>{2}</td><td>{3}</td></tr>", datatype.Name, datatype, x.Message, field.Name));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception x)
            {
                err.Append(string.Format("<tr class='error'><td>{0} ({1})</td><td colspan='2'>{2}</td></tr>", datatype.Name, datatype, x.Message));
            }
        }

        var output = string.Empty;

        if (err.Length > 0)
        {
            output = string.Format("<tr class='error'><td colspan='3'><h1>Exceptions</h1></td></tr>{0}", err);
        }

        if (sb.Length > 0)
        {
            output = string.Format("{0}<tr><td colspan='3'><h1>Out-of-bound string fields</h1><p>Data records listed below contain string values that exceed the maximum length specified on the data type. You need to either truncate the string values to the maximum length or edit the data type and allow for a larger length.</p></td></tr>{1}", output, sb);
            output = string.Format("<table border='0' cellpadding='3'  cellspacing='0' width='100%' class='list'>{0}</table>", output);
            SourceValidator.Text = output;
        }

        if (err.Length > 0)
        {
            return(false);
        }
        return(true);
    }
コード例 #29
0
ファイル: PageElementProvider.cs プロジェクト: wwl2013/C1-CMS
        private List <Element> GetElements(List <KeyValuePair <PageLocaleState, IPage> > pages, bool rootPages)
        {
            //ElementDragAndDropInfo dragAndDropInfo = new ElementDragAndDropInfo(typeof(IPage));
            //dragAndDropInfo.AddDropType(typeof(IPage));
            //dragAndDropInfo.SupportsIndexedPosition = true;



            string editPageLabel       = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.EditPage");
            string editPageToolTip     = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.EditPageToolTip");
            string localizePageLabel   = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.LocalizePage");
            string localizePageToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.LocalizePageToolTip");
            string addNewPageLabel     = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.AddSubPage");
            string addNewPageToolTip   = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.AddSubPageToolTip");
            string deletePageLabel     = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.Delete");
            string deletePageToolTip   = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.DeleteToolTip");

            string urlMappingName = null;

            if (UserSettings.ForeignLocaleCultureInfo != null)
            {
                urlMappingName = DataLocalizationFacade.GetCultureTitle(UserSettings.ForeignLocaleCultureInfo);
            }

            var elements = new Element[pages.Count];

            ParallelFacade.For("PageElementProvider. Getting elements", 0, pages.Count, i =>
            {
                var kvp    = pages[i];
                IPage page = kvp.Value;

                EntityToken entityToken = page.GetDataEntityToken();

                var dragAndDropInfo = new ElementDragAndDropInfo(typeof(IPage));
                dragAndDropInfo.AddDropType(typeof(IPage));
                dragAndDropInfo.SupportsIndexedPosition = true;

                var element = new Element(_context.CreateElementHandle(entityToken), MakeVisualData(page, kvp.Key, urlMappingName, rootPages), dragAndDropInfo);

                element.PropertyBag.Add("Uri", "~/page({0})".FormatWith(page.Id));
                element.PropertyBag.Add("ElementType", "application/x-composite-page");
                element.PropertyBag.Add("DataId", page.Id.ToString());

                if (kvp.Key == PageLocaleState.Own)
                {
                    // Normal actions
                    element.AddAction(new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.Edit, EditPermissionTypes)))
                    {
                        VisualData = new ActionVisualizedData
                        {
                            Label          = editPageLabel,
                            ToolTip        = editPageToolTip,
                            Icon           = PageElementProvider.EditPage,
                            Disabled       = false,
                            ActionLocation = new ActionLocation
                            {
                                ActionType  = ActionType.Edit,
                                IsInFolder  = false,
                                IsInToolbar = true,
                                ActionGroup = PrimaryActionGroup
                            }
                        }
                    });

                    element.AddAction(new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.Add, AddPermissionTypes)))
                    {
                        VisualData = new ActionVisualizedData
                        {
                            Label          = addNewPageLabel,
                            ToolTip        = addNewPageToolTip,
                            Icon           = PageElementProvider.AddPage,
                            Disabled       = false,
                            ActionLocation = new ActionLocation
                            {
                                ActionType  = ActionType.Add,
                                IsInFolder  = false,
                                IsInToolbar = true,
                                ActionGroup = PrimaryActionGroup
                            }
                        }
                    });

                    element.AddAction(new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.Delete, DeletePermissionTypes)))
                    {
                        VisualData = new ActionVisualizedData
                        {
                            Label          = deletePageLabel,
                            ToolTip        = deletePageToolTip,
                            Icon           = DeletePage,
                            Disabled       = false,
                            ActionLocation = new ActionLocation
                            {
                                ActionType  = ActionType.Delete,
                                IsInFolder  = false,
                                IsInToolbar = true,
                                ActionGroup = PrimaryActionGroup
                            }
                        }
                    });

                    _pageAssociatedHelper.AttachElementActions(element, page);
                }
                else if (kvp.Key == PageLocaleState.ForeignActive)
                {
                    // Localized actions
                    bool addAction = false;

                    Guid parentId = page.GetParentId();
                    if (parentId == Guid.Empty)
                    {
                        addAction = true;
                    }
                    else
                    {
                        using (new DataScope(DataScopeIdentifier.Administrated, UserSettings.ActiveLocaleCultureInfo))
                        {
                            bool exists = DataFacade.GetData <IPage>(f => f.Id == parentId).Any();
                            if (exists)
                            {
                                addAction = true;
                            }
                        }
                    }


                    if (addAction)
                    {
                        element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PageElementProvider.LocalizePageWorkflow"), LocalizePermissionTypes)))
                        {
                            VisualData = new ActionVisualizedData
                            {
                                Label          = localizePageLabel,
                                ToolTip        = localizePageToolTip,
                                Icon           = PageElementProvider.LocalizePage,
                                Disabled       = false,
                                ActionLocation = new ActionLocation
                                {
                                    ActionType  = ActionType.Edit,
                                    IsInFolder  = false,
                                    IsInToolbar = true,
                                    ActionGroup = PrimaryActionGroup
                                }
                            }
                        });
                    }
                }

                elements[i] = element;
            });

            return(new List <Element>(elements));
        }
コード例 #30
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));
            }
        }