Exemple #1
0
        public IEnumerable <DataListItem> GetItems(Dictionary <string, object> config)
        {
            if (config.TryGetValue("imageCropper", out var v) &&
                v is JArray a &&
                a.Count > 0 &&
                a[0].Value <string>() is string s &&
                string.IsNullOrWhiteSpace(s) == false &&
                GuidUdi.TryParse(s, out var udi))
            {
                return(_dataTypeService
                       .GetDataType(udi.Guid)?
                       .ConfigurationAs <ImageCropperConfiguration>()?
                       .Crops?
                       .Select(x => new DataListItem
                {
                    Name = x.Alias,
                    Value = x.Alias,
                    Icon = this.Icon,
                    Description = $"{x.Width}px × {x.Height}px"
                }));
            }

            return(Enumerable.Empty <DataListItem>());
        }
        //borrowed from CMS core until SetValue is fixed with a stream
        private string CreateImageCropperValue(PropertyType propertyType, object value, IDataTypeService dataTypeService)
        {
            if (value == null || string.IsNullOrEmpty(value.ToString()))
            {
                return(null);
            }

            // if we don't have a json structure, we will get it from the property type
            var val = value.ToString();

            if (val.DetectIsJson())
            {
                return(val);
            }

            var configuration = dataTypeService.GetDataType(propertyType.DataTypeId).ConfigurationAs <ImageCropperConfiguration>();
            var crops         = configuration?.Crops ?? Array.Empty <ImageCropperConfiguration.Crop>();

            return(JsonConvert.SerializeObject(new
            {
                src = val,
                crops = crops
            }));
        }
 public ElementsPropertyType(PropertyType propertyType, IDataTypeService dataTypeService) : this(propertyType, dataTypeService.GetDataType(propertyType.DataTypeId))
 {
 }
Exemple #4
0
 private IDataType GetDataType(PropertyDataType dataType)
 {
     return(_DataTypeService.GetDataType((int)dataType));
 }
        public void Initialize()
        {
            try
            {
                var homeDocType = _contentTypeService.Get(DOCUMENT_TYPE_ALIAS);
                if (!homeDocType.PropertyTypeExists(HOME_SPINNER_PROPERTY_ALIAS))
                {
                    PropertyType spinner = new PropertyType(_dataTypeService.GetDataType(SPINNER_PROPERTY_TYPE_NAME), HOME_SPINNER_PROPERTY_ALIAS)
                    {
                        Name        = HOME_SPINNER_PROPERTY_NAME,
                        Description = HOME_SPINNER_PROPERTY_DESCRIPTION,
                        Variations  = ContentVariation.Culture
                    };
                    homeDocType.AddPropertyType(spinner, TAB_NAME);
                    _contentTypeService.Save(homeDocType);
                }

                var imgCropper = _dataTypeService.GetDataType(IMAGE_CROPPER_PROPERTY_TYPE_NAME);
                if (imgCropper != null)
                {
                    if (imgCropper.Configuration is Umbraco.Core.PropertyEditors.ImageCropperConfiguration)
                    {
                        var imageCropperConfiguration = (Umbraco.Core.PropertyEditors.ImageCropperConfiguration)imgCropper.Configuration;

                        if (imageCropperConfiguration == null)
                        {
                            imageCropperConfiguration = new Umbraco.Core.PropertyEditors.ImageCropperConfiguration()
                            {
                                Crops = new Core.PropertyEditors.ImageCropperConfiguration.Crop[0]
                            };
                        }

                        if (imageCropperConfiguration.Crops == null)
                        {
                            imageCropperConfiguration.Crops = new Core.PropertyEditors.ImageCropperConfiguration.Crop[0];
                        }

                        if (imageCropperConfiguration.Crops.FirstOrDefault(p => p.Alias == FORM_IMAGE_CROPPER_ALIAS) == null)
                        {
                            var crops = new List <Core.PropertyEditors.ImageCropperConfiguration.Crop>();
                            crops.AddRange(imageCropperConfiguration.Crops);
                            crops.Add(new Core.PropertyEditors.ImageCropperConfiguration.Crop()
                            {
                                Alias  = FORM_IMAGE_CROPPER_ALIAS,
                                Height = FORM_IMAGE_CROPPER_ALIAS_HEIGHT,
                                Width  = FORM_IMAGE_CROPPER_ALIAS_WIDTH
                            });
                            imageCropperConfiguration.Crops = crops.ToArray();

                            _dataTypeService.Save(imgCropper);

                            _logger.Info(typeof(_38_HomeDocumentTypeSpinner), $"{IMAGE_CROPPER_PROPERTY_TYPE_NAME} Alias saved: {JsonConvert.SerializeObject(imageCropperConfiguration.Crops)}");
                        }
                        else
                        {
                            _logger.Info(typeof(_38_HomeDocumentTypeSpinner), $"{IMAGE_CROPPER_PROPERTY_TYPE_NAME} Alias {FORM_IMAGE_CROPPER_ALIAS} Already Exists");
                        }
                    }
                    else
                    {
                        _logger.Info(typeof(_38_HomeDocumentTypeSpinner), $"Invalid type for imgCropper.Configuration TYPE: {imgCropper.Configuration.GetType()}");
                    }
                }
                else
                {
                    _logger.Info(typeof(_38_HomeDocumentTypeSpinner), $"Datatype {IMAGE_CROPPER_PROPERTY_TYPE_NAME} Not Found");
                }
            }
            catch (System.Exception ex)
            {
                _logger.Error(typeof(_38_HomeDocumentTypeSpinner), ex.Message);
                _logger.Error(typeof(_38_HomeDocumentTypeSpinner), ex.StackTrace);
            }
        }
 public FieldSqlWriter DataType(IDataTypeService dataTypeService) {
     foreach (var key in CopyOutputKeys()) {
         _output[key] = string.Concat(_output[key], " ", dataTypeService.GetDataType(_original[key]));
     }
     return this;
 }
            // note: there is NO variant support here

            /// <summary>
            /// Ensure that sub-editor values are translated through their ToEditor methods
            /// </summary>
            /// <param name="property"></param>
            /// <param name="dataTypeService"></param>
            /// <param name="culture"></param>
            /// <param name="segment"></param>
            /// <returns></returns>
            public override object ToEditor(IProperty property, string?culture = null, string?segment = null)
            {
                var val        = property.GetValue(culture, segment);
                var valEditors = new Dictionary <int, IDataValueEditor>();

                BlockEditorData?blockEditorData;

                try
                {
                    blockEditorData = _blockEditorValues.DeserializeAndClean(val);
                }
                catch (JsonSerializationException)
                {
                    // if this occurs it means the data is invalid, shouldn't happen but has happened if we change the data format.
                    return(string.Empty);
                }

                if (blockEditorData == null)
                {
                    return(string.Empty);
                }

                void MapBlockItemData(List <BlockItemData> items)
                {
                    foreach (var row in items)
                    {
                        foreach (var prop in row.PropertyValues)
                        {
                            // create a temp property with the value
                            // - force it to be culture invariant as the block editor can't handle culture variant element properties
                            prop.Value.PropertyType.Variations = ContentVariation.Nothing;
                            var tempProp = new Property(prop.Value.PropertyType);
                            tempProp.SetValue(prop.Value.Value);

                            var propEditor = _propertyEditors[prop.Value.PropertyType.PropertyEditorAlias];
                            if (propEditor == null)
                            {
                                // NOTE: This logic was borrowed from Nested Content and I'm unsure why it exists.
                                // if the property editor doesn't exist I think everything will break anyways?
                                // update the raw value since this is what will get serialized out
                                row.RawPropertyValues[prop.Key] = tempProp.GetValue()?.ToString();
                                continue;
                            }

                            var dataType = _dataTypeService.GetDataType(prop.Value.PropertyType.DataTypeId);
                            if (dataType == null)
                            {
                                // deal with weird situations by ignoring them (no comment)
                                row.PropertyValues.Remove(prop.Key);
                                _logger.LogWarning(
                                    "ToEditor removed property value {PropertyKey} in row {RowId} for property type {PropertyTypeAlias}",
                                    prop.Key, row.Key, property.PropertyType.Alias);
                                continue;
                            }

                            if (!valEditors.TryGetValue(dataType.Id, out var valEditor))
                            {
                                var tempConfig = dataType.Configuration;
                                valEditor = propEditor.GetValueEditor(tempConfig);

                                valEditors.Add(dataType.Id, valEditor);
                            }

                            var convValue = valEditor.ToEditor(tempProp);

                            // update the raw value since this is what will get serialized out
                            row.RawPropertyValues[prop.Key] = convValue;
                        }
                    }
                }

                MapBlockItemData(blockEditorData.BlockValue.ContentData);
                MapBlockItemData(blockEditorData.BlockValue.SettingsData);

                // return json convertable object
                return(blockEditorData.BlockValue);
            }
Exemple #8
0
            public void OnActionExecuting(ActionExecutingContext context)
            {
                var dataType = (DataTypeSave?)context.ActionArguments["dataType"];

                if (dataType is not null)
                {
                    dataType.Name  = dataType.Name?.CleanForXss('[', ']', '(', ')', ':');
                    dataType.Alias = dataType.Alias == null ? dataType.Name ! : dataType.Alias.CleanForXss('[', ']', '(', ')', ':');
                }

                // get the property editor, ensuring that it exits
                if (!_propertyEditorCollection.TryGet(dataType?.EditorAlias, out var propertyEditor))
                {
                    var message = $"Property editor \"{dataType?.EditorAlias}\" was not found.";
                    context.Result = new UmbracoProblemResult(message, HttpStatusCode.NotFound);
                    return;
                }

                if (dataType is null)
                {
                    return;
                }

                // assign
                dataType.PropertyEditor = propertyEditor;

                // validate that the data type exists, or create one if required
                IDataType?persisted;

                switch (dataType.Action)
                {
                case ContentSaveAction.Save:
                    persisted = _dataTypeService.GetDataType(Convert.ToInt32(dataType.Id));
                    if (persisted == null)
                    {
                        var message = $"Data type with id {dataType.Id} was not found.";
                        context.Result = new UmbracoProblemResult(message, HttpStatusCode.NotFound);
                        return;
                    }
                    // map the model to the persisted instance
                    _umbracoMapper.Map(dataType, persisted);
                    break;

                case ContentSaveAction.SaveNew:
                    // create the persisted model from mapping the saved model
                    persisted = _umbracoMapper.Map <IDataType>(dataType);
                    ((DataType?)persisted)?.ResetIdentity();
                    break;

                default:
                    context.Result = new UmbracoProblemResult($"Data type action {dataType.Action} was not found.", HttpStatusCode.NotFound);
                    return;
                }

                // assign (so it's available in the action)
                dataType.PersistedDataType = persisted;

                // validate the configuration
                // which is posted as a set of fields with key (string) and value (object)
                var configurationEditor = propertyEditor.GetConfigurationEditor();

                if (dataType.ConfigurationFields is not null)
                {
                    foreach (var field in dataType.ConfigurationFields)
                    {
                        var editorField = configurationEditor.Fields.SingleOrDefault(x => x.Key == field.Key);
                        if (editorField == null)
                        {
                            continue;
                        }

                        // run each IValueValidator (with null valueType and dataTypeConfiguration: not relevant here)
                        foreach (var validator in editorField.Validators)
                        {
                            foreach (var result in validator.Validate(field.Value, null, null))
                            {
                                context.ModelState.AddValidationError(result, "Properties", field.Key ?? string.Empty);
                            }
                        }
                    }
                }

                if (context.ModelState.IsValid == false)
                {
                    // if it is not valid, do not continue and return the model state
                    context.Result = new ValidationErrorResult(context.ModelState);
                }
            }
        public XElement Serialize(IMediaType mediaType)
        {
            var info = new XElement("Info",
                                    new XElement("Name", mediaType.Name),
                                    new XElement("Alias", mediaType.Alias),
                                    new XElement("Icon", mediaType.Icon),
                                    new XElement("Thumbnail", mediaType.Thumbnail),
                                    new XElement("Description", mediaType.Description),
                                    new XElement("AllowAtRoot", mediaType.AllowedAsRoot.ToString()));

            var masterContentType = mediaType.CompositionAliases().FirstOrDefault();

            if (masterContentType != null)
            {
                info.Add(new XElement("Master", masterContentType));
            }

            var structure = new XElement("Structure");

            foreach (var allowedType in mediaType.AllowedContentTypes)
            {
                structure.Add(new XElement("MediaType", allowedType.Alias));
            }

            var genericProperties = new XElement("GenericProperties"); // actually, all of them

            foreach (var propertyType in mediaType.PropertyTypes)
            {
                var definition = _dataTypeService.GetDataType(propertyType.DataTypeId);

                var propertyGroup = propertyType.PropertyGroupId == null // true generic property
                    ? null
                    : mediaType.PropertyGroups.FirstOrDefault(x => x.Id == propertyType.PropertyGroupId.Value);

                var genericProperty = new XElement("GenericProperty",
                                                   new XElement("Name", propertyType.Name),
                                                   new XElement("Alias", propertyType.Alias),
                                                   new XElement("Type", propertyType.PropertyEditorAlias),
                                                   new XElement("Definition", definition.Key),
                                                   new XElement("Tab", propertyGroup == null ? "" : propertyGroup.Name),
                                                   new XElement("Mandatory", propertyType.Mandatory.ToString()),
                                                   new XElement("Validation", propertyType.ValidationRegExp),
                                                   new XElement("Description", new XCData(propertyType.Description)));
                genericProperties.Add(genericProperty);
            }

            var tabs = new XElement("Tabs");

            foreach (var propertyGroup in mediaType.PropertyGroups)
            {
                var tab = new XElement("Tab",
                                       new XElement("Id", propertyGroup.Id.ToString(CultureInfo.InvariantCulture)),
                                       new XElement("Caption", propertyGroup.Name),
                                       new XElement("SortOrder", propertyGroup.SortOrder));

                tabs.Add(tab);
            }

            var xml = new XElement("MediaType",
                                   info,
                                   structure,
                                   genericProperties,
                                   tabs);

            return(xml);
        }
Exemple #10
0
        private void Reconfigure()
        {
            try
            {
                var homeDocType = contentTypeService.Get(DOCUMENT_TYPE_ALIAS);
                homeDocType.AddPropertyGroup(TAB_NAME);

                //if (!homeDocType.PropertyTypeExists("gameMessage"))
                //{

                //    var richTextEditor = dataTypeService.GetDataType("Full Rich Text Editor");
                //    PropertyType richTextPropType = new PropertyType(dataTypeService.GetDataType(richTextEditor.Id), "gameMessage")
                //    {
                //        Name = "Game Terms and Conditions",
                //        Description = "Terms and Conditions for playing games",
                //        Variations = ContentVariation.Culture
                //    };
                //    homeDocType.AddPropertyType(richTextPropType, TAB_NAME);
                //}

                if (homeDocType.PropertyTypeExists("gameMessage"))
                {
                    homeDocType.RemovePropertyType("gameMessage");
                    contentTypeService.Save(homeDocType);
                }

                if (!homeDocType.PropertyTypeExists("gameAgreeText"))
                {
                    PropertyType gameAgreePropType = new PropertyType(dataTypeService.GetDataType(-88), "gameAgreeText")
                    {
                        Name        = "Agreement text",
                        Description = "Agreement text with checkbox",
                        Variations  = ContentVariation.Culture
                    };
                    homeDocType.AddPropertyType(gameAgreePropType, TAB_NAME);

                    PropertyType playButtonTextPropType = new PropertyType(dataTypeService.GetDataType(-88), "playButtonText")
                    {
                        Name        = "Play Button Text",
                        Description = "Text for the play button",
                        Variations  = ContentVariation.Culture
                    };
                    homeDocType.AddPropertyType(playButtonTextPropType, TAB_NAME);

                    PropertyType demoButtonTextPropType = new PropertyType(dataTypeService.GetDataType(-88), "demoButtonText")
                    {
                        Name        = "Demo Button Text",
                        Description = "Text for the demo button",
                        Variations  = ContentVariation.Culture
                    };
                    homeDocType.AddPropertyType(demoButtonTextPropType, TAB_NAME);

                    var mediaPickerContainer   = dataTypeService.GetContainers(DATA_TYPE_CONTAINER, 1).FirstOrDefault();
                    var mediaPickerContainerId = -1;

                    if (mediaPickerContainer != null)
                    {
                        mediaPickerContainerId = mediaPickerContainer.Id;
                    }

                    var mediaPickerDataType = dataTypeService.GetDataType("Demo Page Media Picker");


                    PropertyType demoPageImages = new PropertyType(dataTypeService.GetDataType(mediaPickerDataType.Id), "demoPageImages")
                    {
                        Name        = "Game Mode Images",
                        Description = "Images to display in the Game Mode Dialog",
                        Variations  = ContentVariation.Culture
                    };
                    homeDocType.AddPropertyType(demoPageImages, TAB_NAME);

                    contentTypeService.Save(homeDocType);
                    ConnectorContext.AuditService.Add(AuditType.Save, -1, homeDocType.Id, "DocumentType", $"Document Type '{DOCUMENT_TYPE_ALIAS}' has been updated");
                }
            }

            catch (Exception ex)
            {
                logger.Error(typeof(_24_HomeDocumentTypeGameModeDialog), ex.Message);
                logger.Error(typeof(_24_HomeDocumentTypeGameModeDialog), ex.StackTrace);
            }
        }
    private IEnumerable <TPropertyType> MapProperties(
        IEnumerable <IPropertyType>?properties,
        IContentTypeBase contentType,
        int groupId,
        bool inherited)
    {
        var mappedProperties = new List <TPropertyType>();

        foreach (IPropertyType p in properties?.Where(x => x.DataTypeId != 0).OrderBy(x => x.SortOrder) ??
                 Enumerable.Empty <IPropertyType>())
        {
            var         propertyEditorAlias = p.PropertyEditorAlias;
            IDataEditor?propertyEditor      = _propertyEditors[propertyEditorAlias];
            IDataType?  dataType            = _dataTypeService.GetDataType(p.DataTypeId);

            // fixme: Don't explode if we can't find this, log an error and change this to a label
            if (propertyEditor == null)
            {
                _logger.LogError(
                    "No property editor could be resolved with the alias: {PropertyEditorAlias}, defaulting to label",
                    p.PropertyEditorAlias);
                propertyEditorAlias = Constants.PropertyEditors.Aliases.Label;
                propertyEditor      = _propertyEditors[propertyEditorAlias];
            }

            IDictionary <string, object>?config = propertyEditor is null || dataType is null ? new Dictionary <string, object>()
                : dataType.Editor?.GetConfigurationEditor().ToConfigurationEditor(dataType.Configuration);

            mappedProperties.Add(new TPropertyType
            {
                Id          = p.Id,
                Alias       = p.Alias,
                Description = p.Description,
                LabelOnTop  = p.LabelOnTop,
                Editor      = p.PropertyEditorAlias,
                Validation  = new PropertyTypeValidation
                {
                    Mandatory        = p.Mandatory,
                    MandatoryMessage = p.MandatoryMessage,
                    Pattern          = p.ValidationRegExp,
                    PatternMessage   = p.ValidationRegExpMessage,
                },
                Label  = p.Name,
                View   = propertyEditor?.GetValueEditor().View,
                Config = config,

                // Value = "",
                GroupId             = groupId,
                Inherited           = inherited,
                DataTypeId          = p.DataTypeId,
                DataTypeKey         = p.DataTypeKey,
                DataTypeName        = dataType?.Name,
                DataTypeIcon        = propertyEditor?.Icon,
                SortOrder           = p.SortOrder,
                ContentTypeId       = contentType.Id,
                ContentTypeName     = contentType.Name,
                AllowCultureVariant = p.VariesByCulture(),
                AllowSegmentVariant = p.VariesBySegment(),
            });
        }

        return(mappedProperties);
    }
        private void UpdateDocumentType()
        {
            const string
                propertyAlias       = "bannerSlider",
                propertyName        = "Banner Slider",
                propertyDescription = "Slider with banner images";

            try
            {
                #region Nested Document Type
                var container   = contentTypeService.GetContainers(DOCUMENT_TYPE_CONTAINER, 1).FirstOrDefault();
                int containerId = -1;

                if (container != null)
                {
                    containerId = container.Id;
                }

                var contentType = contentTypeService.Get(NESTED_DOCUMENT_TYPE_ALIAS);
                if (contentType == null)
                {
                    ContentType docType = (ContentType)contentType ?? new ContentType(containerId)
                    {
                        Name          = NESTED_DOCUMENT_TYPE_NAME,
                        Alias         = NESTED_DOCUMENT_TYPE_ALIAS,
                        AllowedAsRoot = false,
                        Description   = NESTED_DOCUMENT_TYPE_DESCRIPTION,
                        Icon          = NESTED_DOCUMENT_TYPE_ICON,
                        IsElement     = true,
                        SortOrder     = 0,
                        ParentId      = contentTypeService.Get(NESTED_DOCUMENT_TYPE_PARENT_ALIAS).Id,
                        Variations    = ContentVariation.Culture
                    };

                    docType.AddPropertyGroup(SLIDERS_TAB);

                    #region Nested Document Type Properties
                    PropertyType ImagePropType = new PropertyType(dataTypeService.GetDataType(-88), "sliderItemImage")
                    {
                        Name        = "Image",
                        Description = "Image used in the Slider",
                        Variations  = ContentVariation.Nothing
                    };
                    docType.AddPropertyType(ImagePropType, SLIDERS_TAB);

                    PropertyType ButtonLabelPropType = new PropertyType(dataTypeService.GetDataType(-88), "sliderItemButtonLabel")
                    {
                        Name        = " Button Label",
                        Description = "Label for the Button",
                        Variations  = ContentVariation.Nothing
                    };
                    docType.AddPropertyType(ButtonLabelPropType, SLIDERS_TAB);

                    PropertyType TitlePropType = new PropertyType(dataTypeService.GetDataType(-88), "sliderItemTitle")
                    {
                        Name        = "Title",
                        Description = "Title for the banner item",
                        Variations  = ContentVariation.Nothing
                    };
                    docType.AddPropertyType(TitlePropType, SLIDERS_TAB);

                    PropertyType SubtitlePropType = new PropertyType(dataTypeService.GetDataType(-88), "sliderItemSubtitle")
                    {
                        Name        = "Subtitle",
                        Description = "Subtitle for the banner item",
                        Variations  = ContentVariation.Nothing
                    };
                    docType.AddPropertyType(SubtitlePropType, SLIDERS_TAB);

                    PropertyType UrlPropType = new PropertyType(dataTypeService.GetDataType(-88), "sliderItemUrl")
                    {
                        Name        = "Url",
                        Description = "The Link to the item",
                        Variations  = ContentVariation.Nothing
                    };
                    docType.AddPropertyType(UrlPropType, SLIDERS_TAB);
                    #endregion

                    contentTypeService.Save(docType);
                    ConnectorContext.AuditService.Add(AuditType.New, -1, docType.Id, "Document Type", $"Document Type '{NESTED_DOCUMENT_TYPE_ALIAS}' has been created");
                }

                else
                {
                    if (contentType.PropertyTypeExists("sliderItemImage") && contentType.PropertyTypes.Single(x => x.Alias == "sliderItemImage").DataTypeId == -88)
                    {
                        var mediaPickerContainer   = dataTypeService.GetContainers(DATA_TYPE_CONTAINER, 1).FirstOrDefault();
                        var mediaPickerContainerId = -1;

                        if (mediaPickerContainer != null)
                        {
                            mediaPickerContainerId = mediaPickerContainer.Id;
                        }

                        var dataTypeExists = dataTypeService.GetDataType("sliderItemImageMediaPicker") != null;
                        if (!dataTypeExists)
                        {
                            var created = Web.Composing.Current.PropertyEditors.TryGet("Umbraco.MediaPicker", out IDataEditor editor);
                            if (created)
                            {
                                DataType mediaPickerSliderImage = new DataType(editor, mediaPickerContainerId)
                                {
                                    Name          = "sliderItemImageMediaPicker",
                                    ParentId      = mediaPickerContainerId,
                                    Configuration = new MediaPickerConfiguration
                                    {
                                        DisableFolderSelect = true,
                                        Multiple            = false,
                                        OnlyImages          = true
                                    }
                                };
                                dataTypeService.Save(mediaPickerSliderImage);
                                contentType.PropertyTypes.Single(x => x.Alias == "sliderItemImage").DataTypeId = mediaPickerSliderImage.Id;
                                contentTypeService.Save(contentType);
                            }
                        }
                    }
                }
                #endregion

                #region Update Home Document Type
                var homeDocumentType = contentTypeService.Get(DOCUMENT_TYPE_ALIAS);

                var dataTypeContainer   = dataTypeService.GetContainers(DATA_TYPE_CONTAINER, 1).FirstOrDefault();
                var dataTypeContainerId = -1;

                if (dataTypeContainer != null)
                {
                    dataTypeContainerId = dataTypeContainer.Id;
                }

                var exists = dataTypeService.GetDataType(propertyName) != null;
                if (!exists)
                {
                    var created = Web.Composing.Current.PropertyEditors.TryGet("Umbraco.NestedContent", out IDataEditor editor);
                    if (!created)
                    {
                        DataType bannerSliderNestedDataType = new DataType(editor, dataTypeContainerId)
                        {
                            Name          = propertyName,
                            ParentId      = dataTypeContainerId,
                            Configuration = new NestedContentConfiguration
                            {
                                MinItems       = 0,
                                MaxItems       = 999,
                                ConfirmDeletes = true,
                                HideLabel      = false,
                                ShowIcons      = true,
                                ContentTypes   = new[]
                                {
                                    new NestedContentConfiguration.ContentType {
                                        Alias = NESTED_DOCUMENT_TYPE_ALIAS, TabAlias = SLIDERS_TAB
                                    }
                                }
                            }
                        };
                        dataTypeService.Save(bannerSliderNestedDataType);
                    }
                }
                if (!homeDocumentType.PropertyTypeExists("bannerSlider"))
                {
                    var          bannerSliderNestedDataType = dataTypeService.GetDataType(propertyName);
                    PropertyType BannerSlider = new PropertyType(bannerSliderNestedDataType, propertyAlias)
                    {
                        Name        = propertyName,
                        Description = propertyDescription,
                        Variations  = ContentVariation.Culture
                    };

                    var propertyGroup = homeDocumentType.PropertyGroups.SingleOrDefault(x => x.Name == SLIDERS_TAB);
                    if (propertyGroup == null)
                    {
                        homeDocumentType.AddPropertyGroup(SLIDERS_TAB);
                    }

                    homeDocumentType.AddPropertyType(BannerSlider, SLIDERS_TAB);
                    contentTypeService.Save(homeDocumentType);

                    ConnectorContext.AuditService.Add(AuditType.Save, -1, homeDocumentType.Id, "Document Type", $"Document Type '{DOCUMENT_TYPE_ALIAS}' has been updated");
                }

                #endregion
            }
            catch (System.Exception ex)
            {
                logger.Error(typeof(_17_HomeDocumentTypeSlider), ex.Message);
                logger.Error(typeof(_17_HomeDocumentTypeSlider), ex.StackTrace);
            }
        }
Exemple #13
0
        private void Reconfigure()
        {
            try
            {
                var oldControlAlias = "links";
                var contentType     = contentTypeService.Get(DOCUMENT_TYPE_ALIAS);

                if (contentType == null)
                {
                    return;
                }

                if (!contentType.PropertyTypeExists(oldControlAlias))
                {
                    return;
                }


                var MNTPpropertyName          = "Total Code MNTP Menu - Single Site";
                var NestedContentPropertyName = "Nested Content Footer Link Group";

                var dataTypeContainer   = dataTypeService.GetContainers(DATA_TYPE_CONTAINER, 1).FirstOrDefault();
                var dataTypeContainerId = -1;

                if (dataTypeContainer != null)
                {
                    dataTypeContainerId = dataTypeContainer.Id;
                }

                var exists = dataTypeService.GetDataType(MNTPpropertyName) != null;
                if (!exists)
                {
                    var created = Web.Composing.Current.PropertyEditors.TryGet("Umbraco.MultiNodeTreePicker", out IDataEditor editor);
                    if (editor != null)
                    {
                        DataType MNTPMenu_SingleSite = new DataType(editor, dataTypeContainerId)
                        {
                            Name          = MNTPpropertyName,
                            ParentId      = dataTypeContainerId,
                            Configuration = new MultiNodePickerConfiguration()
                            {
                                MaxNumber  = 1,
                                MinNumber  = 1,
                                ShowOpen   = false,
                                TreeSource = new MultiNodePickerConfigurationTreeSource()
                                {
                                    StartNodeQuery = "$site",
                                    ObjectType     = "content"
                                },
                            }
                        };
                        dataTypeService.Save(MNTPMenu_SingleSite);
                    }
                }


                var container   = contentTypeService.GetContainers(DOCUMENT_TYPE_CONTAINER, 1).FirstOrDefault();
                int containerId = -1;

                if (container != null)
                {
                    containerId = container.Id;
                }

                contentType = contentTypeService.Get(NESTED_FOOTERLINKSSETTING_DOCUMENT_TYPE_ALIAS);
                if (contentType == null)
                {
                    ContentType docType = (ContentType)contentType ?? new ContentType(containerId)
                    {
                        Name          = NESTED_FOOTERLINKSSETTING_DOCUMENT_TYPE_NAME,
                        Alias         = NESTED_FOOTERLINKSSETTING_DOCUMENT_TYPE_ALIAS,
                        AllowedAsRoot = false,
                        Description   = "",
                        Icon          = NESTED_DOCUMENT_TYPE_ICON,
                        IsElement     = true,
                        SortOrder     = 0,
                        ParentId      = 1087,
                        Variations    = ContentVariation.Culture
                    };

                    docType.AddPropertyGroup(NESTED_TAB_NAME);

                    #region Nested Document Type Properties

                    var          FooterContent_MNTPpropertyName = dataTypeService.GetDataType(MNTPpropertyName);
                    PropertyType internalLinkPropType           = new PropertyType(FooterContent_MNTPpropertyName, "internalLink")
                    {
                        Name        = "Internal Link",
                        Description = "",
                        Variations  = ContentVariation.Culture
                    };
                    docType.AddPropertyType(internalLinkPropType, NESTED_TAB_NAME);

                    PropertyType ExternalLinkTextPropType = new PropertyType(dataTypeService.GetDataType(-88), "externalLinkText")
                    {
                        Name        = "External Link Text",
                        Description = "",
                        Variations  = ContentVariation.Culture,
                    };
                    docType.AddPropertyType(ExternalLinkTextPropType, NESTED_TAB_NAME);

                    PropertyType LinkUrlPropType = new PropertyType(dataTypeService.GetDataType(-88), "externalLinkUrl")
                    {
                        Name             = "External Link URL",
                        Description      = "",
                        Variations       = ContentVariation.Culture,
                        ValidationRegExp = "https?://[a-zA-Z0-9-.]+.[a-zA-Z]{2,}"
                    };
                    docType.AddPropertyType(LinkUrlPropType, NESTED_TAB_NAME);


                    #endregion

                    contentTypeService.Save(docType);
                    ConnectorContext.AuditService.Add(AuditType.New, -1, docType.Id, "Document Type", $"Document Type '{NESTED_FOOTERLINKSSETTING_DOCUMENT_TYPE_ALIAS}' has been created");
                }


                exists = dataTypeService.GetDataType(NestedContentPropertyName) != null;
                if (!exists)
                {
                    var created = Web.Composing.Current.PropertyEditors.TryGet("Umbraco.NestedContent", out IDataEditor editor);
                    if (editor != null)
                    {
                        DataType bannerSliderNestedDataType = new DataType(editor, dataTypeContainerId)
                        {
                            Name          = NestedContentPropertyName,
                            ParentId      = dataTypeContainerId,
                            Configuration = new NestedContentConfiguration
                            {
                                MinItems       = 0,
                                MaxItems       = 999,
                                ConfirmDeletes = true,
                                HideLabel      = false,
                                ShowIcons      = true,
                                ContentTypes   = new[]
                                {
                                    new NestedContentConfiguration.ContentType {
                                        Alias = NESTED_FOOTERLINKSSETTING_DOCUMENT_TYPE_ALIAS, TabAlias = NESTED_TAB_NAME
                                    }
                                }
                            }
                        };
                        dataTypeService.Save(bannerSliderNestedDataType);
                    }
                }
                contentType = contentTypeService.Get(DOCUMENT_TYPE_ALIAS);
                contentType.RemovePropertyType(oldControlAlias);


                var          FooterContent_NestedContentPropertyName = dataTypeService.GetDataType(NestedContentPropertyName);
                PropertyType linksPropType = new PropertyType(FooterContent_NestedContentPropertyName, "footerLinks")
                {
                    Name        = "Links",
                    Description = "",
                    Variations  = ContentVariation.Culture
                };
                contentType.AddPropertyType(linksPropType, NESTED_TAB_NAME);

                contentTypeService.Save(contentType);
                ConnectorContext.AuditService.Add(AuditType.New, -1, contentType.Id, "Document Type", $"Document Type '{DOCUMENT_TYPE_ALIAS}' has been created");
            }
            catch (Exception ex)
            {
                logger.Error(typeof(_35_FooterLinkGroupChangesDocumentType), ex.Message);
                logger.Error(typeof(_35_FooterLinkGroupChangesDocumentType), ex.StackTrace);
            }
        }
        private void Reconfigure()
        {
            const string
                propertyAlias       = "gameSlider",
                propertyName        = "Game Slider",
                propertyDescription = "Slider with game banners";

            try
            {
                var casinoDocType = contentTypeService.Get(DOCUMENT_TYPE_ALIAS);
                // Create the Template if it doesn't exist
                if (fileService.GetTemplate(TEMPLATE_ALIAS) == null)
                {
                    //then create the template
                    Template  newTemplate    = new Template(TEMPLATE_NAME, TEMPLATE_ALIAS);
                    ITemplate masterTemplate = fileService.GetTemplate(PARENT_TEMPLATE_ALIAS);
                    newTemplate.SetMasterTemplate(masterTemplate);
                    fileService.SaveTemplate(newTemplate);

                    // Set template for document type
                    casinoDocType.AddTemplate(contentTypeService, newTemplate);

                    ContentHelper.CopyPhysicalAssets(new ReconfigureCasinoPageEmbeddedResources());

                    ConnectorContext.AuditService.Add(AuditType.Save, -1, newTemplate.Id, "Template", $"Teplate '{TEMPLATE_NAME}' has been created and assigned");
                }

                var dataTypeContainer   = dataTypeService.GetContainers(DATA_TYPE_CONTAINER, 1).FirstOrDefault();
                var dataTypeContainerId = -1;

                if (dataTypeContainer != null)
                {
                    dataTypeContainerId = dataTypeContainer.Id;
                }
                var exists = dataTypeService.GetDataType(propertyName) != null;
                if (!exists)
                {
                    var created = Web.Composing.Current.PropertyEditors.TryGet("Umbraco.NestedContent", out IDataEditor editor);
                    if (created)
                    {
                        DataType bannerSliderNestedDataType = new DataType(editor, dataTypeContainerId)
                        {
                            Name          = propertyName,
                            ParentId      = dataTypeContainerId,
                            Configuration = new NestedContentConfiguration
                            {
                                MinItems       = 0,
                                MaxItems       = 999,
                                ConfirmDeletes = true,
                                HideLabel      = false,
                                ShowIcons      = true,
                                ContentTypes   = new[]
                                {
                                    new NestedContentConfiguration.ContentType {
                                        Alias = NESTED_DOCUMENT_TYPE_ALIAS, TabAlias = SLIDERS_TAB
                                    }
                                }
                            }
                        };
                        dataTypeService.Save(bannerSliderNestedDataType);
                        ConnectorContext.AuditService.Add(AuditType.Save, -1, casinoDocType.Id, "Document Type", $"Document Type '{DOCUMENT_TYPE_ALIAS}' has been updated");
                    }
                }
                if (!casinoDocType.PropertyTypeExists(propertyAlias))
                {
                    var          bannerSliderNestedDataType = dataTypeService.GetDataType(propertyName);
                    PropertyType BannerSlider = new PropertyType(bannerSliderNestedDataType, propertyAlias)
                    {
                        Name        = propertyName,
                        Description = propertyDescription,
                        Variations  = ContentVariation.Culture
                    };
                    casinoDocType.AddPropertyGroup(SLIDERS_TAB);
                    casinoDocType.AddPropertyType(BannerSlider, SLIDERS_TAB);
                    contentTypeService.Save(casinoDocType);
                }
            }

            catch (Exception ex)
            {
                logger.Error(typeof(_10_CasinoPageIntegration), ex.Message);
                logger.Error(typeof(_10_CasinoPageIntegration), ex.StackTrace);
            }
        }
Exemple #15
0
        private void CreateDocumentType()
        {
            try
            {
                var richTextContainer   = dataTypeService.GetContainers(DATA_TYPE_CONTAINER, 1).FirstOrDefault();
                var richTextContainerId = -1;

                if (richTextContainer != null)
                {
                    richTextContainerId = richTextContainer.Id;
                }

                var dataTypeExists = dataTypeService.GetDataType("Full Rich Text Editor") != null;
                if (!dataTypeExists)
                {
                    var created = Web.Composing.Current.PropertyEditors.TryGet("Umbraco.TinyMCE", out IDataEditor editor);
                    if (created)
                    {
                        DataType richTextEditor = new DataType(editor, richTextContainerId)
                        {
                            Name          = "Full Rich Text Editor",
                            ParentId      = richTextContainerId,
                            Configuration = new RichTextConfiguration
                            {
                                Editor    = JObject.Parse("{\"toolbar\":[\"ace\",\"removeformat\",\"undo\",\"redo\",\"cut\",\"copy\",\"paste\",\"styleselect\",\"bold\",\"italic\",\"underline\",\"strikethrough\",\"alignleft\",\"aligncenter\",\"alignright\",\"alignjustify\",\"bullist\",\"numlist\",\"outdent\",\"indent\",\"link\",\"unlink\",\"anchor\",\"umbmediapicker\",\"umbmacro\",\"table\",\"umbembeddialog\",\"hr\",\"subscript\",\"superscript\",\"charmap\",\"rtl\",\"ltr\"],\"stylesheets\":[],\"maxImageSize\":500,\"mode\":\"classic\"}"),
                                HideLabel = true
                            }
                        };
                        dataTypeService.Save(richTextEditor);

                        var container   = contentTypeService.GetContainers(CONTAINER, 1).FirstOrDefault();
                        var containerId = container.Id;

                        string propertyName        = "Page Content",
                               propertyDescription = "Text to be displayed on the Page";

                        // categories page
                        var contentCategoriesType = contentTypeService.Get(CATEGORIES_DOCUMENT_TYPE_ALIAS);
                        if (contentCategoriesType != null)
                        {
                            PropertyType richTextPropType = new PropertyType(dataTypeService.GetDataType(richTextEditor.Id), "pageContent")
                            {
                                Name        = propertyName,
                                Description = propertyDescription,
                                Variations  = ContentVariation.Culture
                            };
                            contentCategoriesType.AddPropertyType(richTextPropType, TAB);
                            contentTypeService.Save(contentCategoriesType);
                            ConnectorContext.AuditService.Add(AuditType.Save, -1, contentCategoriesType.Id, "Document Type", $"Document Type '{CATEGORIES_DOCUMENT_TYPE_ALIAS}' has been updated");
                        }

                        // category page
                        var contentCategoryType = contentTypeService.Get(CATEGORY_DOCUMENT_TYPE_ALIAS);
                        if (contentCategoryType != null)
                        {
                            PropertyType richTextPropType = new PropertyType(dataTypeService.GetDataType(richTextEditor.Id), "pageContent")
                            {
                                Name        = propertyName,
                                Description = propertyDescription,
                                Variations  = ContentVariation.Culture
                            };
                            contentCategoryType.AddPropertyType(richTextPropType, TAB);
                            contentTypeService.Save(contentCategoryType);
                            ConnectorContext.AuditService.Add(AuditType.Save, -1, contentCategoryType.Id, "Document Type", $"Document Type '{CATEGORY_DOCUMENT_TYPE_ALIAS}' has been updated");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(typeof(_20_ContentPagesReconfiguration), ex.Message);
                logger.Error(typeof(_20_ContentPagesReconfiguration), ex.StackTrace);
            }
        }
        private void UpdateHomeDocumentType()
        {
            try
            {
                var contentType = contentTypeService.Get(DOCUMENT_TYPE_ALIAS);

                var container = contentTypeService.GetContainers(CONTAINER, 1).FirstOrDefault();

                if (contentType != null)
                {
                    if (contentType.PropertyTypes.ToList().SingleOrDefault(x => x.Alias == "termsAndConditionsMessage") == null)
                    {
                        // Add Document Type Properties
                        #region Tenant Home Page Content
                        PropertyType termsAndConditionsMessagePropType = new PropertyType(dataTypeService.GetDataType(-88), "termsAndConditionsMessage")
                        {
                            Name        = "Terms and Conditions",
                            Description = "Message to display for required accepting Terms and Conditions",
                            Variations  = ContentVariation.Culture
                        };
                        contentType.AddPropertyType(termsAndConditionsMessagePropType, CONTENT_TAB);
                        #endregion

                        contentTypeService.Save(contentType);
                        ConnectorContext.AuditService.Add(AuditType.New, -1, contentType.Id, "Document Type", $"Document Type '{DOCUMENT_TYPE_ALIAS}' has been updated");

                        ContentHelper.CopyPhysicalAssets(new RegisterUpdateHomeEmbeddedResources());
                        //CreateMasterTemplate();
                    }

                    var telegramUsername = contentType.PropertyTypes.ToList().SingleOrDefault(x => x.Alias == "telegramUsername");
                    if (telegramUsername != null)
                    {
                        if (telegramUsername.Name != "Telegram URL")
                        {
                            telegramUsername.Name        = "Telegram URL";
                            telegramUsername.Description = "";

                            telegramUsername.ValidationRegExp = "";
                            contentType.AddPropertyType(telegramUsername);

                            contentTypeService.Save(contentType);
                        }
                        else if (!string.IsNullOrEmpty(telegramUsername.ValidationRegExp))
                        {
                            telegramUsername.ValidationRegExp = "";
                            contentType.AddPropertyType(telegramUsername);

                            contentTypeService.Save(contentType);
                        }
                    }

                    var helpdeskTelegramAccount = contentType.PropertyTypes.ToList().SingleOrDefault(x => x.Alias == "helpdeskTelegramAccount");
                    if (helpdeskTelegramAccount != null)
                    {
                        if (helpdeskTelegramAccount.Name != "HelpDesk Telegram Bot")
                        {
                            helpdeskTelegramAccount.Name        = "HelpDesk Telegram Bot";
                            helpdeskTelegramAccount.Description = "";

                            helpdeskTelegramAccount.ValidationRegExp = "";
                            contentType.AddPropertyType(helpdeskTelegramAccount);

                            contentTypeService.Save(contentType);
                        }
                        else if (!string.IsNullOrEmpty(helpdeskTelegramAccount.ValidationRegExp))
                        {
                            helpdeskTelegramAccount.ValidationRegExp = "";
                            contentType.AddPropertyType(helpdeskTelegramAccount);

                            contentTypeService.Save(contentType);
                        }
                    }

                    var whatsAppNumber = contentType.PropertyTypes.ToList().SingleOrDefault(x => x.Alias == "whatsAppNumber");
                    if (whatsAppNumber != null)
                    {
                        if (whatsAppNumber.Name != "Whatsapp URL")
                        {
                            whatsAppNumber.Name        = "Whatsapp URL";
                            whatsAppNumber.Description = "";

                            whatsAppNumber.ValidationRegExp = "";
                            contentType.AddPropertyType(whatsAppNumber);

                            contentTypeService.Save(contentType);
                        }
                        else if (!string.IsNullOrEmpty(whatsAppNumber.ValidationRegExp))
                        {
                            whatsAppNumber.ValidationRegExp = "";
                            contentType.AddPropertyType(whatsAppNumber);

                            contentTypeService.Save(contentType);
                        }
                    }
                    //var
                    //var
                }

                if (createDictionaryItems)
                {
                    var language = new LanguageDictionaryService(ConnectorContext.LocalizationService, ConnectorContext.DomainService, ConnectorContext.Logger);
                    // Check if parent Key exists, and skip if true
                    if (!language.CheckExists(typeof(Home_ParentKey)))
                    {
                        // Add Dictionary Items
                        var dictionaryItems = new List <Type>
                        {
                            typeof(Home_ParentKey),
                            typeof(Home_Register),
                            typeof(Site_ParentKey),
                            typeof(Site_AlreadyHaveAccount),
                            typeof(Register_ParentKey),
                            typeof(Register_RegisterTitle),
                            typeof(Register_RegisterStep),
                            typeof(Register_RegisterOf),
                            typeof(Register_PhoneNumber),
                            typeof(Register_PhoneNumberPlaceholder),
                            typeof(Register_IsMandatory),
                            typeof(Register_Continue),
                            typeof(Register_PhoneNumberInstructions),
                            typeof(Register_VerificationCode),
                            typeof(Register_VerificationCodePlaceholder),
                            typeof(Register_EnterCode),
                            typeof(Register_Enter6DigitVerificationCode),
                            typeof(Register_EnterVerificationCode),
                            typeof(Register_ResendCode),
                            typeof(Register_Wait),
                            typeof(Register_VerificationCodeInvalidOrExpired),
                            typeof(Register_Email),
                            typeof(Register_EmailPlaceholder),
                            typeof(Register_Password),
                            typeof(Register_PasswordPlaceholder),
                            typeof(Register_ConfirmPassword),
                            typeof(Register_FirstName),
                            typeof(Register_FirstNamePlaceholder),
                            typeof(Register_LastName),
                            typeof(Register_LastNamePlaceholder),
                            typeof(Register_Username),
                            typeof(Register_UsernamePlaceholder),
                            typeof(Register_Gender),
                            typeof(Register_DateOfBirth),
                            typeof(Register_DateOfBirthDay),
                            typeof(Register_DateOfBirthMonth),
                            typeof(Register_DateOfBirthMonthJanuary),
                            typeof(Register_DateOfBirthMonthFebruary),
                            typeof(Register_DateOfBirthMonthMarch),
                            typeof(Register_DateOfBirthMonthApril),
                            typeof(Register_DateOfBirthMonthMay),
                            typeof(Register_DateOfBirthMonthJune),
                            typeof(Register_DateOfBirthMonthJuly),
                            typeof(Register_DateOfBirthMonthAugust),
                            typeof(Register_DateOfBirthMonthSeptember),
                            typeof(Register_DateOfBirthMonthOctober),
                            typeof(Register_DateOfBirthMonthNovember),
                            typeof(Register_DateOfBirthMonthDecember),
                            typeof(Register_DateOfBirthYear),
                            typeof(Register_IAgreeWithThe),
                            typeof(Register_TermsAndConditions),
                            typeof(Register_Finish),
                            typeof(Register_IncorrectOrInvalid),
                            typeof(Register_VerifyEmailSentToTitle),
                            typeof(Register_VerifyEmailSentTo),
                            typeof(Register_VerifyEmailSentToPleaseClick),
                            typeof(Register_ResendVerificationEmail),
                            typeof(Register_ResendVerificationEmailSent),
                            typeof(Register_ChangeEmail),
                            typeof(Register_IsInvalid),
                            typeof(Register_Title),
                            typeof(Register_Address1),
                            typeof(Register_Address1Placeholder),
                            typeof(Register_Address2),
                            typeof(Register_Address2Placeholder),
                            typeof(Register_Address3),
                            typeof(Register_Address3Placeholder),
                            typeof(Register_CityOrTown),
                            typeof(Register_CityOrTownPlaceholder),
                            typeof(Register_PostalCode),
                            typeof(Register_PostalCodePlaceholder),
                            typeof(Register_Country),
                            typeof(Register_Preferences),
                            typeof(Register_Language),
                            typeof(Register_Currency),
                            typeof(Register_OddsDisplay),
                            typeof(Register_TimeZone),
                            typeof(Register_BonusCode),
                            typeof(Register_BonusCodePlaceholder),
                            typeof(Register_Referrer),
                            typeof(Register_ReferrerPlaceholder),
                            typeof(Register_ReceiveNotifications),
                            typeof(Register_ReceiveNotificationsViaInPlatformMessages),
                            typeof(Register_ReceiveNotificationsViaEmail),
                            typeof(Register_ReceiveNotificationsViaSMS),
                            typeof(Register_CookiesPolicy),
                            typeof(Register_PrivacyPolicy),
                            typeof(Register_MinimunAge),
                            typeof(Register_Age),
                            typeof(Register_AgeYearsOld),
                            typeof(Register_NewEmail),
                            typeof(Register_CurrentEmail)
                        };
                        language.CreateDictionaryItems(dictionaryItems); // Create Dictionary Items

                        ConnectorContext.AuditService.Add(AuditType.Save, -1, contentType.Id, "Document Type", $"Document Type '{DOCUMENT_TYPE_ALIAS}' has been updated, and Dictionaries Created");
                    }
                }

                var oldHome = contentTypeService.Get(HomeDocumentType.DOCUMENT_TYPE_ALIAS);
                if (oldHome != null)
                {
                    // remove old home document type
                    contentTypeService.Delete(contentTypeService.Get(HomeDocumentType.DOCUMENT_TYPE_ALIAS));
                    // remove old home template
                    fileService.DeleteTemplate(HomeDocumentType.TEMPLATE_ALIAS);
                }
            }
            catch (Exception ex)
            {
                logger.Error(typeof(_02_HomeDocumentTypePhase2Milestone6), ex.Message);
                logger.Error(typeof(_02_HomeDocumentTypePhase2Milestone6), ex.StackTrace);
            }
        }
            public IEnumerable <ValidationResult> Validate(object rawValue, string valueType, object dataTypeConfiguration)
            {
                var validationResults = new List <ValidationResult>();

                foreach (var row in _nestedContentValues.GetPropertyValues(rawValue, out _))
                {
                    if (row.PropType == null)
                    {
                        continue;
                    }

                    var config         = _dataTypeService.GetDataType(row.PropType.DataTypeId).Configuration;
                    var propertyEditor = _propertyEditors[row.PropType.PropertyEditorAlias];
                    if (propertyEditor == null)
                    {
                        continue;
                    }

                    foreach (var validator in propertyEditor.GetValueEditor().Validators)
                    {
                        foreach (var result in validator.Validate(row.JsonRowValue[row.PropKey], propertyEditor.GetValueEditor().ValueType, config))
                        {
                            result.ErrorMessage = "Item " + (row.RowIndex + 1) + " '" + row.PropType.Name + "' " + result.ErrorMessage;
                            validationResults.Add(result);
                        }
                    }

                    // Check mandatory
                    if (row.PropType.Mandatory)
                    {
                        if (row.JsonRowValue[row.PropKey] == null)
                        {
                            var message = string.IsNullOrWhiteSpace(row.PropType.MandatoryMessage)
                                                      ? $"'{row.PropType.Name}' cannot be null"
                                                      : row.PropType.MandatoryMessage;
                            validationResults.Add(new ValidationResult($"Item {(row.RowIndex + 1)}: {message}", new[] { row.PropKey }));
                        }
                        else if (row.JsonRowValue[row.PropKey].ToString().IsNullOrWhiteSpace() || (row.JsonRowValue[row.PropKey].Type == JTokenType.Array && !row.JsonRowValue[row.PropKey].HasValues))
                        {
                            var message = string.IsNullOrWhiteSpace(row.PropType.MandatoryMessage)
                                                      ? $"'{row.PropType.Name}' cannot be empty"
                                                      : row.PropType.MandatoryMessage;
                            validationResults.Add(new ValidationResult($"Item {(row.RowIndex + 1)}: {message}", new[] { row.PropKey }));
                        }
                    }

                    // Check regex
                    if (!row.PropType.ValidationRegExp.IsNullOrWhiteSpace() &&
                        row.JsonRowValue[row.PropKey] != null && !row.JsonRowValue[row.PropKey].ToString().IsNullOrWhiteSpace())
                    {
                        var regex = new Regex(row.PropType.ValidationRegExp);
                        if (!regex.IsMatch(row.JsonRowValue[row.PropKey].ToString()))
                        {
                            var message = string.IsNullOrWhiteSpace(row.PropType.ValidationRegExpMessage)
                                                      ? $"'{row.PropType.Name}' is invalid, it does not match the correct pattern"
                                                      : row.PropType.ValidationRegExpMessage;
                            validationResults.Add(new ValidationResult($"Item {(row.RowIndex + 1)}: {message}", new[] { row.PropKey }));
                        }
                    }
                }

                return(validationResults);
            }
        private void CreateHomeDocumentType()
        {
            try
            {
                var container   = contentTypeService.GetContainers(CONTAINER, 1).FirstOrDefault();
                int containerId = 0;

                if (container == null)
                {
                    var newcontainer = contentTypeService.CreateContainer(-1, CONTAINER);

                    if (newcontainer.Success)
                    {
                        containerId = newcontainer.Result.Entity.Id;
                    }
                }
                else
                {
                    containerId = container.Id;
                }

                var contentType = contentTypeService.Get(DOCUMENT_TYPE_ALIAS);
                if (contentType == null)
                {
                    //http://refreshwebsites.co.uk/blog/umbraco-document-types-explained-in-60-seconds/
                    //https://our.umbraco.org/forum/developers/api-questions/43278-programmatically-creating-a-document-type
                    ContentType docType = (ContentType)contentType ?? new ContentType(containerId)
                    {
                        Name          = DOCUMENT_TYPE_NAME,
                        Alias         = DOCUMENT_TYPE_ALIAS,
                        AllowedAsRoot = true,
                        Description   = DOCUMENT_TYPE_DESCRIPTION,
                        Icon          = ICON,
                        SortOrder     = 0,
                        Variations    = ContentVariation.Culture
                    };

                    // Create the Template if it doesn't exist
                    if (fileService.GetTemplate(TEMPLATE_ALIAS) == null)
                    {
                        //then create the template
                        Template newTemplate = new Template(TEMPLATE_NAME, TEMPLATE_ALIAS);
                        fileService.SaveTemplate(newTemplate);
                    }

                    // Set templates for document type
                    var template = fileService.GetTemplate(TEMPLATE_ALIAS);
                    docType.AllowedTemplates = new List <ITemplate> {
                        template
                    };
                    docType.SetDefaultTemplate(template);
                    docType.AddPropertyGroup(CONTENT_TAB);
                    docType.AddPropertyGroup(TENANT_TAB);

                    // Set Document Type Properties
                    #region Tenant Home Page Content
                    PropertyType brandLogoPropType = new PropertyType(dataTypeService.GetDataType(1043), "brandLogo")
                    {
                        Name       = "Brand Logo",
                        Variations = ContentVariation.Nothing
                    };
                    docType.AddPropertyType(brandLogoPropType, CONTENT_TAB);

                    PropertyType homeContentProType = new PropertyType(dataTypeService.GetDataType(-87), "homeContent")
                    {
                        Name       = "Content",
                        Variations = ContentVariation.Culture
                    };
                    docType.AddPropertyType(homeContentProType, CONTENT_TAB);
                    #endregion

                    #region Tenant Info Tab
                    PropertyType tenantUidPropType = new PropertyType(dataTypeService.GetDataType(-92), "tenantUid")
                    {
                        Name        = "Tenant Uid",
                        Description = "Tenant Unique Id",
                        Variations  = ContentVariation.Nothing
                    };
                    docType.AddPropertyType(tenantUidPropType, TENANT_TAB);

                    PropertyType brandNamePropType = new PropertyType(dataTypeService.GetDataType(-92), "brandName")
                    {
                        Name       = "Brand Name",
                        Variations = ContentVariation.Nothing
                    };
                    docType.AddPropertyType(brandNamePropType, TENANT_TAB);

                    PropertyType domainPropType = new PropertyType(dataTypeService.GetDataType(-92), "domain")
                    {
                        Name       = "Domain",
                        Variations = ContentVariation.Nothing
                    };
                    docType.AddPropertyType(domainPropType, TENANT_TAB);

                    PropertyType subDomainPropType = new PropertyType(dataTypeService.GetDataType(-92), "subDomain")
                    {
                        Name       = "Sub Domain",
                        Variations = ContentVariation.Nothing
                    };
                    docType.AddPropertyType(subDomainPropType, TENANT_TAB);

                    PropertyType appIdPropType = new PropertyType(dataTypeService.GetDataType(-92), "appId")
                    {
                        Name       = "App Id",
                        Variations = ContentVariation.Nothing
                    };

                    docType.AddPropertyType(appIdPropType, TENANT_TAB);

                    PropertyType apiKeyPropType = new PropertyType(dataTypeService.GetDataType(-92), "apiKey")
                    {
                        Name       = "Api Key",
                        Variations = ContentVariation.Nothing
                    };
                    docType.AddPropertyType(apiKeyPropType, TENANT_TAB);

                    PropertyType defaultLanguagePropType = new PropertyType(dataTypeService.GetDataType(-92), "defaultLanguage")
                    {
                        Name        = "Default Language",
                        Description = "System Default Language",
                        Variations  = ContentVariation.Nothing
                    };
                    docType.AddPropertyType(defaultLanguagePropType, TENANT_TAB);

                    PropertyType languagestPropType = new PropertyType(dataTypeService.GetDataType(-92), "languages")
                    {
                        Name       = "Alternate Languages",
                        Variations = ContentVariation.Nothing
                    };
                    docType.AddPropertyType(languagestPropType, TENANT_TAB);

                    PropertyType tenantStatusPropType = new PropertyType(dataTypeService.GetDataType(-92), "tenantStatus")
                    {
                        Name        = "Tenant Status",
                        Description = "Total Code Tenant Status",
                        Variations  = ContentVariation.Nothing
                    };
                    docType.AddPropertyType(tenantStatusPropType, TENANT_TAB);
                    #endregion

                    contentTypeService.Save(docType);
                    ConnectorContext.AuditService.Add(AuditType.New, -1, docType.Id, "Document Type", $"Document Type '{DOCUMENT_TYPE_NAME}' has been created");

                    ContentHelper.CopyPhysicalAssets(new EmbeddedResources());
                }
            }
            catch (System.Exception ex)
            {
                logger.Error(typeof(HomeDocumentType), ex.Message);
                logger.Error(typeof(HomeDocumentType), ex.StackTrace);
            }
        }
Exemple #19
0
        private IDataValueEditor GetPropertyValueEditor(int dataTypeId, out object wrappedConfiguration)
        {
            var dataType = _dataTypeService.GetDataType(dataTypeId);

            return(GetPropertyValueEditor(dataType?.ConfigurationAs <TextCountConfiguration>(), out wrappedConfiguration));
        }
        public static ContentApp CreateContentApp(IDataTypeService dataTypeService,
                                                  PropertyEditorCollection propertyEditors,
                                                  string entityType, string contentTypeAlias,
                                                  int defaultListViewDataType)
        {
            if (dataTypeService == null)
            {
                throw new ArgumentNullException(nameof(dataTypeService));
            }
            if (propertyEditors == null)
            {
                throw new ArgumentNullException(nameof(propertyEditors));
            }
            if (string.IsNullOrWhiteSpace(entityType))
            {
                throw new ArgumentException("message", nameof(entityType));
            }
            if (string.IsNullOrWhiteSpace(contentTypeAlias))
            {
                throw new ArgumentException("message", nameof(contentTypeAlias));
            }
            if (defaultListViewDataType == default)
            {
                throw new ArgumentException("defaultListViewDataType", nameof(defaultListViewDataType));
            }

            var contentApp = new ContentApp
            {
                Alias  = "umbListView",
                Name   = "Child items",
                Icon   = "icon-list",
                View   = "views/content/apps/listview/listview.html",
                Weight = Weight
            };

            var customDtdName = Constants.Conventions.DataTypes.ListViewPrefix + contentTypeAlias;

            //first try to get the custom one if there is one
            var dt = dataTypeService.GetDataType(customDtdName)
                     ?? dataTypeService.GetDataType(defaultListViewDataType);

            if (dt == null)
            {
                throw new InvalidOperationException("No list view data type was found for this document type, ensure that the default list view data types exists and/or that your custom list view data type exists");
            }

            var editor = propertyEditors[dt.EditorAlias];

            if (editor == null)
            {
                throw new NullReferenceException("The property editor with alias " + dt.EditorAlias + " does not exist");
            }

            var listViewConfig = editor.GetConfigurationEditor().ToConfigurationEditor(dt.Configuration);

            //add the entity type to the config
            listViewConfig["entityType"] = entityType;

            //Override Tab Label if tabName is provided
            if (listViewConfig.ContainsKey("tabName"))
            {
                var configTabName = listViewConfig["tabName"];
                if (configTabName != null && String.IsNullOrWhiteSpace(configTabName.ToString()) == false)
                {
                    contentApp.Name = configTabName.ToString();
                }
            }

            //Override Icon if icon is provided
            if (listViewConfig.ContainsKey("icon"))
            {
                var configIcon = listViewConfig["icon"];
                if (configIcon != null && String.IsNullOrWhiteSpace(configIcon.ToString()) == false)
                {
                    contentApp.Icon = configIcon.ToString();
                }
            }

            // if the list view is configured to show umbContent first, update the list view content app weight accordingly
            if (listViewConfig.ContainsKey("showContentFirst") &&
                listViewConfig["showContentFirst"]?.ToString().TryConvertTo <bool>().Result == true)
            {
                contentApp.Weight = ContentEditorContentAppFactory.Weight + 1;
            }

            //This is the view model used for the list view app
            contentApp.ViewModel = new List <ContentPropertyDisplay>
            {
                new ContentPropertyDisplay
                {
                    Alias     = $"{Constants.PropertyEditors.InternalGenericPropertiesPrefix}containerView",
                    Label     = "",
                    Value     = null,
                    View      = editor.GetValueEditor().View,
                    HideLabel = true,
                    Config    = listViewConfig
                }
            };

            return(contentApp);
        }
Exemple #21
0
        public XElement Serialize(IDataTypeService dataTypeService, IContentTypeService contentTypeService, IContentType contentType)
        {
            var info = new XElement("Info",
                                    new XElement("Name", contentType.Name),
                                    new XElement("Alias", contentType.Alias),
                                    new XElement("Icon", contentType.Icon),
                                    new XElement("Thumbnail", contentType.Thumbnail),
                                    new XElement("Description", contentType.Description),
                                    new XElement("AllowAtRoot", contentType.AllowedAsRoot.ToString()),
                                    new XElement("IsListView", contentType.IsContainer.ToString()),
                                    new XElement("IsElement", contentType.IsElement.ToString()));

            var masterContentType = contentType.ContentTypeComposition.FirstOrDefault(x => x.Id == contentType.ParentId);

            if (masterContentType != null)
            {
                info.Add(new XElement("Master", masterContentType.Alias));
            }

            var compositionsElement = new XElement("Compositions");
            var compositions        = contentType.ContentTypeComposition;

            foreach (var composition in compositions)
            {
                compositionsElement.Add(new XElement("Composition", composition.Alias));
            }
            info.Add(compositionsElement);

            var allowedTemplates = new XElement("AllowedTemplates");

            foreach (var template in contentType.AllowedTemplates)
            {
                allowedTemplates.Add(new XElement("Template", template.Alias));
            }
            info.Add(allowedTemplates);

            if (contentType.DefaultTemplate != null && contentType.DefaultTemplate.Id != 0)
            {
                info.Add(new XElement("DefaultTemplate", contentType.DefaultTemplate.Alias));
            }
            else
            {
                info.Add(new XElement("DefaultTemplate", ""));
            }

            var structure = new XElement("Structure");

            foreach (var allowedType in contentType.AllowedContentTypes)
            {
                structure.Add(new XElement("DocumentType", allowedType.Alias));
            }

            var genericProperties = new XElement("GenericProperties"); // actually, all of them

            foreach (var propertyType in contentType.PropertyTypes)
            {
                var definition = dataTypeService.GetDataType(propertyType.DataTypeId);

                var propertyGroup = propertyType.PropertyGroupId == null // true generic property
                    ? null
                    : contentType.PropertyGroups.FirstOrDefault(x => x.Id == propertyType.PropertyGroupId.Value);

                var genericProperty = new XElement("GenericProperty",
                                                   new XElement("Name", propertyType.Name),
                                                   new XElement("Alias", propertyType.Alias),
                                                   new XElement("Type", propertyType.PropertyEditorAlias),
                                                   new XElement("Definition", definition.Key),
                                                   new XElement("Tab", propertyGroup == null ? "" : propertyGroup.Name),
                                                   new XElement("SortOrder", propertyType.SortOrder),
                                                   new XElement("Mandatory", propertyType.Mandatory.ToString()),
                                                   propertyType.ValidationRegExp != null ? new XElement("Validation", propertyType.ValidationRegExp) : null,
                                                   propertyType.Description != null ? new XElement("Description", new XCData(propertyType.Description)) : null);

                genericProperties.Add(genericProperty);
            }

            var tabs = new XElement("Tabs");

            foreach (var propertyGroup in contentType.PropertyGroups)
            {
                var tab = new XElement("Tab",
                                       new XElement("Id", propertyGroup.Id.ToString(CultureInfo.InvariantCulture)),
                                       new XElement("Caption", propertyGroup.Name),
                                       new XElement("SortOrder", propertyGroup.SortOrder));
                tabs.Add(tab);
            }

            var xml = new XElement("DocumentType",
                                   info,
                                   structure,
                                   genericProperties,
                                   tabs);

            var folderNames = string.Empty;

            //don't add folders if this is a child doc type
            if (contentType.Level != 1 && masterContentType == null)
            {
                //get url encoded folder names
                var folders = contentTypeService.GetContainers(contentType)
                              .OrderBy(x => x.Level)
                              .Select(x => HttpUtility.UrlEncode(x.Name));

                folderNames = string.Join("/", folders.ToArray());
            }

            if (string.IsNullOrWhiteSpace(folderNames) == false)
            {
                xml.Add(new XAttribute("Folders", folderNames));
            }

            return(xml);
        }
Exemple #22
0
        private void UpdateHomeDocumentType()
        {
            const string faviconName = "Tenant Favicon";
            const string faviconDescription = "Favicon (Browser Tab icon)";
            const string faviconAlias = "tenantFavicon";
            const string size16x16 = "16x16", size32x32 = "32x32", size72x72 = "72x72", size144x144 = "144x144", size192x192 = "192x192", size256x256 = "256x256";

            try
            {
                var contentType = contentTypeService.Get(DOCUMENT_TYPE_ALIAS);
                if (contentType != null)
                {
                    var changed = false;
                    #region Tenant Favicons
                    if (!contentType.PropertyTypeExists($"{faviconAlias}{size16x16}"))
                    {
                        PropertyType tenantFavicon16x16PropType = new PropertyType(dataTypeService.GetDataType(-90), $"{faviconAlias}{size16x16}")
                        {
                            Name        = $"{faviconName} {size16x16}",
                            Description = $"{faviconDescription} size {size16x16} (*.ico)",
                            Variations  = ContentVariation.Nothing
                        };
                        contentType.AddPropertyType(tenantFavicon16x16PropType, TENANT_TAB);
                        changed = true;
                    }

                    if (!contentType.PropertyTypeExists($"{faviconAlias}{size32x32}"))
                    {
                        PropertyType tenantFavicon32x32PropType = new PropertyType(dataTypeService.GetDataType(-90), $"{faviconAlias}{size32x32}")
                        {
                            Name        = $"{faviconName} {size32x32}",
                            Description = $"{faviconDescription} size {size32x32} (*.png)",
                            Variations  = ContentVariation.Nothing
                        };
                        contentType.AddPropertyType(tenantFavicon32x32PropType, TENANT_TAB);
                        changed = true;
                    }

                    if (!contentType.PropertyTypeExists($"{faviconAlias}{size72x72}"))
                    {
                        PropertyType tenantFavicon72x72PropType = new PropertyType(dataTypeService.GetDataType(-90), $"{faviconAlias}{size72x72}")
                        {
                            Name        = $"{faviconName} {size72x72}",
                            Description = $"{faviconDescription} size {size72x72} (*.png)",
                            Variations  = ContentVariation.Nothing
                        };
                        contentType.AddPropertyType(tenantFavicon72x72PropType, TENANT_TAB);
                        changed = true;
                    }

                    if (!contentType.PropertyTypeExists($"{faviconAlias}{size144x144}"))
                    {
                        PropertyType tenantFavicon144x144PropType = new PropertyType(dataTypeService.GetDataType(-90), $"{faviconAlias}{size144x144}")
                        {
                            Name        = $"{faviconName} {size144x144}",
                            Description = $"{faviconDescription} size {size144x144} (*.png)",
                            Variations  = ContentVariation.Nothing
                        };
                        contentType.AddPropertyType(tenantFavicon144x144PropType, TENANT_TAB);
                        changed = true;
                    }

                    if (!contentType.PropertyTypeExists($"{faviconAlias}{size192x192}"))
                    {
                        PropertyType tenantFavicon192x192PropType = new PropertyType(dataTypeService.GetDataType(-90), $"{faviconAlias}{size192x192}")
                        {
                            Name        = $"{faviconName} {size192x192}",
                            Description = $"{faviconDescription} size {size192x192} (*.png)",
                            Variations  = ContentVariation.Nothing
                        };
                        contentType.AddPropertyType(tenantFavicon192x192PropType, TENANT_TAB);
                        changed = true;
                    }

                    if (!contentType.PropertyTypeExists($"{faviconAlias}{size256x256}"))
                    {
                        PropertyType tenantFavicon256x256PropType = new PropertyType(dataTypeService.GetDataType(-90), $"{faviconAlias}{size256x256}")
                        {
                            Name        = $"{faviconName} {size256x256}",
                            Description = $"{faviconDescription} size {size256x256} (*.png)",
                            Variations  = ContentVariation.Nothing
                        };
                        contentType.AddPropertyType(tenantFavicon256x256PropType, TENANT_TAB);
                        changed = true;
                    }

                    if (changed)
                    {
                        contentTypeService.Save(contentType);
                    }
                    #endregion
                }
            }
            catch (System.Exception ex)
            {
                logger.Error(typeof(_29_TenantFavicon), ex.Message);
                logger.Error(typeof(_29_TenantFavicon), ex.StackTrace);
            }
        }
        private static void ContentService_Saved(IContentService contentService, ContentSavedEventArgs e)
        {
            foreach (IContent content in e.SavedEntities)
            {
                List <string> editors = new List <string>
                {
                    Umbraco.Core.Constants.PropertyEditors.Aliases.Grid,
                    BentoItemDataEditor.EditorAlias,
                    BentoStackDataEditor.EditorAlias
                };

                foreach (Property contentProperty in content.Properties.Where(x => editors.Contains(x.PropertyType.PropertyEditorAlias)))
                {
                    IDataType editor = DataTypeService.GetDataType(contentProperty.PropertyType.DataTypeId);

                    IRelationType bentoBlocksRelationType = RelationService.GetRelationTypeByAlias(RelationTypes.BentoItemsAlias);

                    if (bentoBlocksRelationType == null)
                    {
                        RelationType relationType = new RelationType(
                            RelationTypes.BentoItemsAlias,
                            RelationTypes.BentoItemsName,
                            true,
                            UmbracoObjectTypes.Document.GetGuid(),
                            UmbracoObjectTypes.Document.GetGuid());

                        RelationService.Save(relationType);

                        bentoBlocksRelationType = RelationService.GetRelationTypeByAlias(RelationTypes.BentoItemsAlias);
                    }

                    //todo: this does work but it's a bit brute force...
                    //i guess we could store the current relationships and then store the ones we're creating and compare them and then
                    //delete the ones from the old list that arent in the new list? but that's a lot of db hits...
                    IEnumerable <IRelation> rels = RelationService.GetByParentId(content.Id);
                    foreach (IRelation currentRelation in rels.Where(x => x.RelationType.Id == bentoBlocksRelationType.Id))
                    {
                        RelationService.Delete(currentRelation);
                    }

                    if (contentProperty.PropertyType.PropertyEditorAlias == BentoItemDataEditor.EditorAlias)
                    {
                        foreach (Property.PropertyValue value in contentProperty.Values)
                        {
                            if (value.PublishedValue == null)
                            {
                                break;
                            }

                            var area = JsonConvert.DeserializeObject <Area>(value.PublishedValue.ToString());

                            if (area.Id <= 0)
                            {
                                continue;
                            }

                            var bentoContent = contentService.GetById(area.Id);

                            if (bentoContent == null)
                            {
                                continue;
                            }

                            BentoItemConfiguration config = (BentoItemConfiguration)editor.Configuration;

                            ProcessRelationship(contentService, bentoContent, content, bentoBlocksRelationType, config.ItemDoctypeCompositionAlias);
                        }
                    }
                    else
                    {
                        foreach (Property.PropertyValue value in contentProperty.Values)
                        {
                            if (value.PublishedValue == null)
                            {
                                break;
                            }

                            string valueString = value.PublishedValue?.ToString();

                            if (string.IsNullOrWhiteSpace(valueString))
                            {
                                continue;
                            }

                            IEnumerable <StackItem> items = JsonConvert.DeserializeObject <IEnumerable <StackItem> >(valueString, new StackItemConverter());

                            var itemList = items.Where(x => x.Areas != null && x.Areas.Any())
                                           .SelectMany(stackItem => stackItem.Areas.Where(x => x.Id > 0), (stackItem, x) => contentService.GetById(x.Id))
                                           .Where(bentoContent => bentoContent != null)
                                           .Distinct();

                            BentoStackConfiguration config = (BentoStackConfiguration)editor.Configuration;

                            foreach (IContent item in itemList)
                            {
                                ProcessRelationship(contentService, item, content, bentoBlocksRelationType, config.ItemDoctypeCompositionAlias);
                            }
                        }
                    }
                }
            }
        }
Exemple #24
0
        private void UpdateDocumentType()
        {
            const string
                propertyAlias = "meta",
                propertyName  = "Meta Tag";

            try
            {
                #region Home Document Type
                var container   = contentTypeService.GetContainers(DOCUMENT_TYPE_CONTAINER, 1).FirstOrDefault();
                int containerId = -1;

                if (container != null)
                {
                    containerId = container.Id;
                }

                var contentType = contentTypeService.Get(DOCUMENT_TYPE_ALIAS);
                if (contentType != null)
                {
                    var changed = false;
                    #region Meta Tags Property Type
                    if (!contentType.PropertyTypeExists($"{propertyAlias}Author"))
                    {
                        PropertyType metaAuthorPropType = new PropertyType(dataTypeService.GetDataType(-88), $"{propertyAlias}Author")
                        {
                            Name       = $"Author {propertyName}",
                            Variations = ContentVariation.Culture
                        };
                        contentType.AddPropertyType(metaAuthorPropType, META_TAB);
                        changed = true;
                    }

                    if (!contentType.PropertyTypeExists($"{propertyAlias}Copyright"))
                    {
                        PropertyType metaCopyrightPropType = new PropertyType(dataTypeService.GetDataType(-88), $"{propertyAlias}Copyright")
                        {
                            Name       = $"Copyright {propertyName}",
                            Variations = ContentVariation.Culture
                        };
                        contentType.AddPropertyType(metaCopyrightPropType, META_TAB);
                        changed = true;
                    }

                    if (!contentType.PropertyTypeExists($"{propertyAlias}Description"))
                    {
                        PropertyType metaDescriptionPropType = new PropertyType(dataTypeService.GetDataType(-88), $"{propertyAlias}Description")
                        {
                            Name       = $"Description {propertyName}",
                            Variations = ContentVariation.Culture
                        };
                        contentType.AddPropertyType(metaDescriptionPropType, META_TAB);
                        changed = true;
                    }

                    if (!contentType.PropertyTypeExists($"{propertyAlias}Keywords"))
                    {
                        PropertyType metaKeywordsPropType = new PropertyType(dataTypeService.GetDataType(-88), $"{propertyAlias}Keywords")
                        {
                            Name       = $"Keywords {propertyName}",
                            Variations = ContentVariation.Culture
                        };
                        contentType.AddPropertyType(metaKeywordsPropType, META_TAB);
                        changed = true;
                    }

                    if (!contentType.PropertyTypeExists($"{propertyAlias}Robots"))
                    {
                        PropertyType metaRobotsPropType = new PropertyType(dataTypeService.GetDataType(-88), $"{propertyAlias}Robots")
                        {
                            Name       = $"Robots {propertyName}",
                            Variations = ContentVariation.Culture
                        };
                        contentType.AddPropertyType(metaRobotsPropType, META_TAB);
                        changed = true;
                    }

                    #endregion

                    if (changed)
                    {
                        contentTypeService.Save(contentType);
                    }
                    ConnectorContext.AuditService.Add(AuditType.New, -1, contentType.Id, "Document Type", $"Document Type '{DOCUMENT_TYPE_ALIAS}' has been updated");
                }
                #endregion
            }
            catch (System.Exception ex)
            {
                logger.Error(typeof(_31_MetaTags), ex.Message);
                logger.Error(typeof(_31_MetaTags), ex.StackTrace);
            }
        }
        public ContentTypeMapperProfile(PropertyEditorCollection propertyEditors, IDataTypeService dataTypeService, IFileService fileService, IContentTypeService contentTypeService, IMediaTypeService mediaTypeService)
        {
            CreateMap <DocumentTypeSave, IContentType>()
            //do the base mapping
            .MapBaseContentTypeSaveToEntity <DocumentTypeSave, PropertyTypeBasic, IContentType>()
            .ConstructUsing((source) => new ContentType(source.ParentId))
            .ForMember(source => source.AllowedTemplates, opt => opt.Ignore())
            .ForMember(dto => dto.DefaultTemplate, opt => opt.Ignore())
            .AfterMap((source, dest) =>
            {
                dest.AllowedTemplates = source.AllowedTemplates
                                        .Where(x => x != null)
                                        .Select(fileService.GetTemplate)
                                        .Where(x => x != null)
                                        .ToArray();

                if (source.DefaultTemplate != null)
                {
                    dest.SetDefaultTemplate(fileService.GetTemplate(source.DefaultTemplate));
                }
                else
                {
                    dest.SetDefaultTemplate(null);
                }

                ContentTypeProfileExtensions.AfterMapContentTypeSaveToEntity(source, dest, contentTypeService);
            });

            CreateMap <MediaTypeSave, IMediaType>()
            //do the base mapping
            .MapBaseContentTypeSaveToEntity <MediaTypeSave, PropertyTypeBasic, IMediaType>()
            .ConstructUsing((source) => new MediaType(source.ParentId))
            .AfterMap((source, dest) =>
            {
                ContentTypeProfileExtensions.AfterMapMediaTypeSaveToEntity(source, dest, mediaTypeService);
            });

            CreateMap <MemberTypeSave, IMemberType>()
            //do the base mapping
            .MapBaseContentTypeSaveToEntity <MemberTypeSave, MemberPropertyTypeBasic, IMemberType>()
            .ConstructUsing(source => new MemberType(source.ParentId))
            .AfterMap((source, dest) =>
            {
                ContentTypeProfileExtensions.AfterMapContentTypeSaveToEntity(source, dest, contentTypeService);

                //map the MemberCanEditProperty,MemberCanViewProperty,IsSensitiveData
                foreach (var propertyType in source.Groups.SelectMany(x => x.Properties))
                {
                    var localCopy = propertyType;
                    var destProp  = dest.PropertyTypes.SingleOrDefault(x => x.Alias.InvariantEquals(localCopy.Alias));
                    if (destProp != null)
                    {
                        dest.SetMemberCanEditProperty(localCopy.Alias, localCopy.MemberCanEditProperty);
                        dest.SetMemberCanViewProperty(localCopy.Alias, localCopy.MemberCanViewProperty);
                        dest.SetIsSensitiveProperty(localCopy.Alias, localCopy.IsSensitiveData);
                    }
                }
            });

            CreateMap <IContentTypeComposition, string>().ConvertUsing(dest => dest.Alias);

            CreateMap <IMemberType, MemberTypeDisplay>()
            //map base logic
            .MapBaseContentTypeEntityToDisplay <IMemberType, MemberTypeDisplay, MemberPropertyTypeDisplay>(propertyEditors, dataTypeService, contentTypeService)
            .AfterMap((memberType, display) =>
            {
                //map the MemberCanEditProperty,MemberCanViewProperty,IsSensitiveData
                foreach (var propertyType in memberType.PropertyTypes)
                {
                    var localCopy   = propertyType;
                    var displayProp = display.Groups.SelectMany(dest => dest.Properties).SingleOrDefault(dest => dest.Alias.InvariantEquals(localCopy.Alias));
                    if (displayProp != null)
                    {
                        displayProp.MemberCanEditProperty = memberType.MemberCanEditProperty(localCopy.Alias);
                        displayProp.MemberCanViewProperty = memberType.MemberCanViewProperty(localCopy.Alias);
                        displayProp.IsSensitiveData       = memberType.IsSensitiveProperty(localCopy.Alias);
                    }
                }
            });

            CreateMap <IMediaType, MediaTypeDisplay>()
            //map base logic
            .MapBaseContentTypeEntityToDisplay <IMediaType, MediaTypeDisplay, PropertyTypeDisplay>(propertyEditors, dataTypeService, contentTypeService)
            .AfterMap((source, dest) =>
            {
                //default listview
                dest.ListViewEditorName = Constants.Conventions.DataTypes.ListViewPrefix + "Media";

                if (string.IsNullOrEmpty(source.Name) == false)
                {
                    var name = Constants.Conventions.DataTypes.ListViewPrefix + source.Name;
                    if (dataTypeService.GetDataType(name) != null)
                    {
                        dest.ListViewEditorName = name;
                    }
                }
            });

            CreateMap <IContentType, DocumentTypeDisplay>()
            //map base logic
            .MapBaseContentTypeEntityToDisplay <IContentType, DocumentTypeDisplay, PropertyTypeDisplay>(propertyEditors, dataTypeService, contentTypeService)
            .ForMember(dto => dto.AllowedTemplates, opt => opt.Ignore())
            .ForMember(dto => dto.DefaultTemplate, opt => opt.Ignore())
            .ForMember(display => display.Notifications, opt => opt.Ignore())
            .ForMember(display => display.AllowCultureVariant, opt => opt.MapFrom(type => type.VariesByCulture()))
            .AfterMap((source, dest) =>
            {
                //sync templates
                dest.AllowedTemplates = source.AllowedTemplates.Select(Mapper.Map <EntityBasic>).ToArray();

                if (source.DefaultTemplate != null)
                {
                    dest.DefaultTemplate = Mapper.Map <EntityBasic>(source.DefaultTemplate);
                }

                //default listview
                dest.ListViewEditorName = Constants.Conventions.DataTypes.ListViewPrefix + "Content";

                if (string.IsNullOrEmpty(source.Alias) == false)
                {
                    var name = Constants.Conventions.DataTypes.ListViewPrefix + source.Alias;
                    if (dataTypeService.GetDataType(name) != null)
                    {
                        dest.ListViewEditorName = name;
                    }
                }
            });

            CreateMap <IMemberType, ContentTypeBasic>()
            .ForMember(dest => dest.Udi, opt => opt.MapFrom(source => Udi.Create(Constants.UdiEntityType.MemberType, source.Key)))
            .ForMember(dest => dest.Blueprints, opt => opt.Ignore())
            .ForMember(dest => dest.AdditionalData, opt => opt.Ignore());
            CreateMap <IMediaType, ContentTypeBasic>()
            .ForMember(dest => dest.Udi, opt => opt.MapFrom(source => Udi.Create(Constants.UdiEntityType.MediaType, source.Key)))
            .ForMember(dest => dest.Blueprints, opt => opt.Ignore())
            .ForMember(dest => dest.AdditionalData, opt => opt.Ignore());
            CreateMap <IContentType, ContentTypeBasic>()
            .ForMember(dest => dest.Udi, opt => opt.MapFrom(source => Udi.Create(Constants.UdiEntityType.DocumentType, source.Key)))
            .ForMember(dest => dest.Blueprints, opt => opt.Ignore())
            .ForMember(dest => dest.AdditionalData, opt => opt.Ignore());

            CreateMap <PropertyTypeBasic, PropertyType>()

            .ConstructUsing(propertyTypeBasic =>
            {
                var dataType = dataTypeService.GetDataType(propertyTypeBasic.DataTypeId);
                if (dataType == null)
                {
                    throw new NullReferenceException("No data type found with id " + propertyTypeBasic.DataTypeId);
                }
                return(new PropertyType(dataType, propertyTypeBasic.Alias));
            })

            .IgnoreEntityCommonProperties()

            .ForMember(dest => dest.IsPublishing, opt => opt.Ignore())

            // see note above - have to do this here?
            .ForMember(dest => dest.PropertyEditorAlias, opt => opt.Ignore())
            .ForMember(dest => dest.DeleteDate, opt => opt.Ignore())

            .ForMember(dto => dto.Variations, opt => opt.ResolveUsing <PropertyTypeVariationsResolver>())

            //only map if it is actually set
            .ForMember(dest => dest.Id, opt => opt.Condition(source => source.Id > 0))
            //only map if it is actually set, if it's  not set, it needs to be handled differently and will be taken care of in the
            // IContentType.AddPropertyType
            .ForMember(dest => dest.PropertyGroupId, opt => opt.Condition(source => source.GroupId > 0))
            .ForMember(dest => dest.PropertyGroupId, opt => opt.MapFrom(display => new Lazy <int>(() => display.GroupId, false)))
            .ForMember(dest => dest.Key, opt => opt.Ignore())
            .ForMember(dest => dest.HasIdentity, opt => opt.Ignore())
            //ignore because this is set in the ctor NOT ON UPDATE, STUPID!
            //.ForMember(type => type.Alias, opt => opt.Ignore())
            //ignore because this is obsolete and shouldn't be used
            .ForMember(dest => dest.DataTypeId, opt => opt.Ignore())
            .ForMember(dest => dest.Mandatory, opt => opt.MapFrom(source => source.Validation.Mandatory))
            .ForMember(dest => dest.ValidationRegExp, opt => opt.MapFrom(source => source.Validation.Pattern))
            .ForMember(dest => dest.DataTypeId, opt => opt.MapFrom(source => source.DataTypeId))
            .ForMember(dest => dest.Name, opt => opt.MapFrom(source => source.Label));

            #region *** Used for mapping on top of an existing display object from a save object ***

            CreateMap <MemberTypeSave, MemberTypeDisplay>()
            .MapBaseContentTypeSaveToDisplay <MemberTypeSave, MemberPropertyTypeBasic, MemberTypeDisplay, MemberPropertyTypeDisplay>();

            CreateMap <MediaTypeSave, MediaTypeDisplay>()
            .MapBaseContentTypeSaveToDisplay <MediaTypeSave, PropertyTypeBasic, MediaTypeDisplay, PropertyTypeDisplay>();

            CreateMap <DocumentTypeSave, DocumentTypeDisplay>()
            .MapBaseContentTypeSaveToDisplay <DocumentTypeSave, PropertyTypeBasic, DocumentTypeDisplay, PropertyTypeDisplay>()
            .ForMember(dto => dto.AllowedTemplates, opt => opt.Ignore())
            .ForMember(dto => dto.DefaultTemplate, opt => opt.Ignore())
            .AfterMap((source, dest) =>
            {
                //sync templates
                var destAllowedTemplateAliases = dest.AllowedTemplates.Select(x => x.Alias);
                //if the dest is set and it's the same as the source, then don't change
                if (destAllowedTemplateAliases.SequenceEqual(source.AllowedTemplates) == false)
                {
                    var templates         = fileService.GetTemplates(source.AllowedTemplates.ToArray());
                    dest.AllowedTemplates = source.AllowedTemplates
                                            .Select(x => Mapper.Map <EntityBasic>(templates.SingleOrDefault(t => t.Alias == x)))
                                            .WhereNotNull()
                                            .ToArray();
                }

                if (source.DefaultTemplate.IsNullOrWhiteSpace() == false)
                {
                    //if the dest is set and it's the same as the source, then don't change
                    if (dest.DefaultTemplate == null || source.DefaultTemplate != dest.DefaultTemplate.Alias)
                    {
                        var template         = fileService.GetTemplate(source.DefaultTemplate);
                        dest.DefaultTemplate = template == null ? null : Mapper.Map <EntityBasic>(template);
                    }
                }
                else
                {
                    dest.DefaultTemplate = null;
                }
            });

            //for doc types, media types
            CreateMap <PropertyGroupBasic <PropertyTypeBasic>, PropertyGroup>()
            .MapPropertyGroupBasicToPropertyGroupPersistence <PropertyGroupBasic <PropertyTypeBasic>, PropertyTypeBasic>();

            //for members
            CreateMap <PropertyGroupBasic <MemberPropertyTypeBasic>, PropertyGroup>()
            .MapPropertyGroupBasicToPropertyGroupPersistence <PropertyGroupBasic <MemberPropertyTypeBasic>, MemberPropertyTypeBasic>();

            //for doc types, media types
            CreateMap <PropertyGroupBasic <PropertyTypeBasic>, PropertyGroupDisplay <PropertyTypeDisplay> >()
            .MapPropertyGroupBasicToPropertyGroupDisplay <PropertyGroupBasic <PropertyTypeBasic>, PropertyTypeBasic, PropertyTypeDisplay>();

            //for members
            CreateMap <PropertyGroupBasic <MemberPropertyTypeBasic>, PropertyGroupDisplay <MemberPropertyTypeDisplay> >()
            .MapPropertyGroupBasicToPropertyGroupDisplay <PropertyGroupBasic <MemberPropertyTypeBasic>, MemberPropertyTypeBasic, MemberPropertyTypeDisplay>();

            CreateMap <PropertyTypeBasic, PropertyTypeDisplay>()
            .ForMember(g => g.Editor, opt => opt.Ignore())
            .ForMember(g => g.View, opt => opt.Ignore())
            .ForMember(g => g.Config, opt => opt.Ignore())
            .ForMember(g => g.ContentTypeId, opt => opt.Ignore())
            .ForMember(g => g.ContentTypeName, opt => opt.Ignore())
            .ForMember(g => g.Locked, exp => exp.Ignore());

            CreateMap <MemberPropertyTypeBasic, MemberPropertyTypeDisplay>()
            .ForMember(g => g.Editor, opt => opt.Ignore())
            .ForMember(g => g.View, opt => opt.Ignore())
            .ForMember(g => g.Config, opt => opt.Ignore())
            .ForMember(g => g.ContentTypeId, opt => opt.Ignore())
            .ForMember(g => g.ContentTypeName, opt => opt.Ignore())
            .ForMember(g => g.Locked, exp => exp.Ignore());

            #endregion
        }
Exemple #26
0
        /// <summary>
        /// Gets data type by name
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public DataTypeDisplay GetByName(string name)
        {
            var dataType = _dataTypeService.GetDataType(name);

            return(dataType == null ? null : _umbracoMapper.Map <IDataType, DataTypeDisplay>(dataType));
        }
Exemple #27
0
        public void Export(
            string fileName,
            int blogRootNode)
        {
            var root = _contentService.GetById(blogRootNode);

            if (root == null)
            {
                throw new InvalidOperationException("No node found with id " + blogRootNode);
            }
            if (!root.ContentType.Alias.InvariantEquals("Articulate"))
            {
                throw new InvalidOperationException("The node with id " + blogRootNode + " is not an Articulate root node");
            }

            var postType = _contentTypeService.Get("ArticulateRichText");

            if (postType == null)
            {
                throw new InvalidOperationException("Articulate is not installed properly, the ArticulateRichText doc type could not be found");
            }

            var archiveContentType = _contentTypeService.Get("ArticulateArchive");
            var archiveNodes       = _contentService.GetPagedOfType(archiveContentType.Id, 0, int.MaxValue, out long totalArchive, null);

            var authorsContentType = _contentTypeService.Get("ArticulateAuthors");
            var authorsNodes       = _contentService.GetPagedOfType(authorsContentType.Id, 0, int.MaxValue, out long totalAuthors, null);

            if (totalArchive == 0)
            {
                throw new InvalidOperationException("No ArticulateArchive found under the blog root node");
            }

            if (totalAuthors == 0)
            {
                throw new InvalidOperationException("No ArticulateAuthors found under the blog root node");
            }

            var categoryDataType = _dataTypeService.GetDataType("Articulate Categories");

            if (categoryDataType == null)
            {
                throw new InvalidOperationException("No Articulate Categories data type found");
            }
            var categoryConfiguration = categoryDataType.ConfigurationAs <TagConfiguration>();
            var categoryGroup         = categoryConfiguration.Group;

            var tagDataType = _dataTypeService.GetDataType("Articulate Tags");

            if (tagDataType == null)
            {
                throw new InvalidOperationException("No Articulate Tags data type found");
            }
            var tagConfiguration = tagDataType.ConfigurationAs <TagConfiguration>();
            var tagGroup         = tagConfiguration.Group;

            //TODO: See: http://argotic.codeplex.com/wikipage?title=Generating%20portable%20web%20log%20content&referringTitle=Home

            var blogMlDoc = new BlogMLDocument
            {
                RootUrl     = new Uri(_umbracoContextAccessor.UmbracoContext.UrlProvider.GetUrl(root.Id), UriKind.RelativeOrAbsolute),
                GeneratedOn = DateTime.Now,
                Title       = new BlogMLTextConstruct(root.GetValue <string>("blogTitle")),
                Subtitle    = new BlogMLTextConstruct(root.GetValue <string>("blogDescription"))
            };

            foreach (var authorsNode in authorsNodes)
            {
                AddBlogAuthors(authorsNode, blogMlDoc);
            }
            AddBlogCategories(blogMlDoc, categoryGroup);
            foreach (var archiveNode in archiveNodes)
            {
                AddBlogPosts(archiveNode, blogMlDoc, categoryGroup, tagGroup);
            }
            WriteFile(blogMlDoc);
        }
Exemple #28
0
 protected override IDataType FindItem(Guid key)
 => dataTypeService.GetDataType(key);
        public void Initialize()
        {
            try
            {
                var contentType = contentTypeService.Get(DOCUMENT_TYPE_ALIAS);

                if (contentType == null)
                {
                    return;
                }

                if (!contentType.PropertyGroups.Any(x => x.Name == NOTIFICATION_SETTINGS_TAB))
                {
                    contentType.AddPropertyGroup(NOTIFICATION_SETTINGS_TAB);
                }

                const string ddlNotificationPositions = "ddl Notification Positions";

                var dataTypeContainer   = dataTypeService.GetContainers(DATA_TYPE_CONTAINER, 1).FirstOrDefault();
                var dataTypeContainerId = -1;

                if (dataTypeContainer != null)
                {
                    dataTypeContainerId = dataTypeContainer.Id;
                }
                var exists = dataTypeService.GetDataType(ddlNotificationPositions) != null;
                if (!exists)
                {
                    var created = Web.Composing.Current.PropertyEditors.TryGet("Umbraco.DropDown.Flexible", out IDataEditor editor);
                    if (editor != null)
                    {
                        var positionList = new List <ValueListConfiguration.ValueListItem>();
                        positionList.Add(new ValueListConfiguration.ValueListItem {
                            Id = 1, Value = "Top Right"
                        });
                        positionList.Add(new ValueListConfiguration.ValueListItem {
                            Id = 2, Value = "Bottom Right"
                        });
                        positionList.Add(new ValueListConfiguration.ValueListItem {
                            Id = 3, Value = "Bottom Left"
                        });
                        positionList.Add(new ValueListConfiguration.ValueListItem {
                            Id = 4, Value = "Top Left"
                        });
                        positionList.Add(new ValueListConfiguration.ValueListItem {
                            Id = 5, Value = "Top Center"
                        });
                        positionList.Add(new ValueListConfiguration.ValueListItem {
                            Id = 6, Value = "Bottom Center"
                        });

                        DataType ddlNotificationPositionsDataType = new DataType(editor, dataTypeContainerId)
                        {
                            Name          = ddlNotificationPositions,
                            ParentId      = dataTypeContainerId,
                            Configuration = new DropDownFlexibleConfiguration()
                            {
                                Multiple = false,
                                Items    = positionList
                            }
                        };
                        dataTypeService.Save(ddlNotificationPositionsDataType);
                    }
                }
                var isNewPropertyAdded = false;
                if (!contentType.PropertyTypeExists("notificationPosition"))
                {
                    isNewPropertyAdded = true;
                    var ddlPositionsDataType = dataTypeService.GetDataType(ddlNotificationPositions);

                    PropertyType ddlPositionsPropType = new PropertyType(ddlPositionsDataType, "notificationPosition")
                    {
                        Name       = "Position",
                        Variations = ContentVariation.Culture
                    };
                    contentType.AddPropertyType(ddlPositionsPropType, NOTIFICATION_SETTINGS_TAB);
                }

                if (!contentType.PropertyTypeExists("notificationBgColor"))
                {
                    isNewPropertyAdded = true;
                    PropertyType notificationBackgroundColor = new PropertyType(dataTypeService.GetDataType(6018), "notificationBgColor")
                    {
                        Name       = "Background Color",
                        Variations = ContentVariation.Culture
                    };
                    contentType.AddPropertyType(notificationBackgroundColor, NOTIFICATION_SETTINGS_TAB);
                }

                if (!contentType.PropertyTypeExists("notificationWidth"))
                {
                    isNewPropertyAdded = true;
                    PropertyType widthPropType = new PropertyType(dataTypeService.GetDataType(-88), "notificationWidth")
                    {
                        Name        = "Width",
                        Description = "If required enter only numeric value",
                        Variations  = ContentVariation.Culture
                    };
                    contentType.AddPropertyType(widthPropType, NOTIFICATION_SETTINGS_TAB);
                }

                if (isNewPropertyAdded)
                {
                    contentTypeService.Save(contentType);
                    ConnectorContext.AuditService.Add(AuditType.New, -1, contentType.Id, "Document Type", $"Document Type '{DOCUMENT_TYPE_ALIAS}' has been updated");
                }
            }

            catch (Exception ex)
            {
                logger.Error(typeof(_39_HomeDocTypeNotificationSettings), ex.Message);
                logger.Error(typeof(_39_HomeDocTypeNotificationSettings), ex.StackTrace);
            }
        }
        /// <summary>
        /// Used to submit a media file
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// We cannot validate this request with attributes (nicely) due to the nature of the multi-part for data.
        /// </remarks>
        public async Task <IActionResult> PostAddFile([FromForm] string path, [FromForm] string currentFolder, [FromForm] string contentTypeAlias, List <IFormFile> file)
        {
            var root = _hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.TempFileUploads);

            //ensure it exists
            Directory.CreateDirectory(root);

            //must have a file
            if (file.Count == 0)
            {
                return(NotFound());
            }

            //get the string json from the request
            var parentIdResult = await GetParentIdAsIntAsync(currentFolder, validatePermissions : true);

            if (!(parentIdResult.Result is null))
            {
                return(parentIdResult.Result);
            }

            var parentId = parentIdResult.Value;

            if (!parentId.HasValue)
            {
                return(NotFound("The passed id doesn't exist"));
            }

            var tempFiles = new PostedFiles();

            //in case we pass a path with a folder in it, we will create it and upload media to it.
            if (!string.IsNullOrEmpty(path))
            {
                if (!IsFolderCreationAllowedHere(parentId.Value))
                {
                    AddCancelMessage(tempFiles, _localizedTextService.Localize("speechBubbles", "folderUploadNotAllowed"));
                    return(Ok(tempFiles));
                }

                var folders = path.Split(Constants.CharArrays.ForwardSlash);

                for (int i = 0; i < folders.Length - 1; i++)
                {
                    var    folderName = folders[i];
                    IMedia folderMediaItem;

                    //if uploading directly to media root and not a subfolder
                    if (parentId == Constants.System.Root)
                    {
                        //look for matching folder
                        folderMediaItem =
                            _mediaService.GetRootMedia().FirstOrDefault(x => x.Name == folderName && x.ContentType.Alias == Constants.Conventions.MediaTypes.Folder);
                        if (folderMediaItem == null)
                        {
                            //if null, create a folder
                            folderMediaItem = _mediaService.CreateMedia(folderName, -1, Constants.Conventions.MediaTypes.Folder);
                            _mediaService.Save(folderMediaItem);
                        }
                    }
                    else
                    {
                        //get current parent
                        var mediaRoot = _mediaService.GetById(parentId.Value);

                        //if the media root is null, something went wrong, we'll abort
                        if (mediaRoot == null)
                        {
                            return(Problem(
                                       "The folder: " + folderName + " could not be used for storing images, its ID: " + parentId +
                                       " returned null"));
                        }

                        //look for matching folder
                        folderMediaItem = FindInChildren(mediaRoot.Id, folderName, Constants.Conventions.MediaTypes.Folder);

                        if (folderMediaItem == null)
                        {
                            //if null, create a folder
                            folderMediaItem = _mediaService.CreateMedia(folderName, mediaRoot, Constants.Conventions.MediaTypes.Folder);
                            _mediaService.Save(folderMediaItem);
                        }
                    }

                    //set the media root to the folder id so uploaded files will end there.
                    parentId = folderMediaItem.Id;
                }
            }

            var mediaTypeAlias      = string.Empty;
            var allMediaTypes       = _mediaTypeService.GetAll().ToList();
            var allowedContentTypes = new HashSet <IMediaType>();

            if (parentId != Constants.System.Root)
            {
                var mediaFolderItem = _mediaService.GetById(parentId.Value);
                var mediaFolderType = allMediaTypes.FirstOrDefault(x => x.Alias == mediaFolderItem.ContentType.Alias);

                if (mediaFolderType != null)
                {
                    IMediaType mediaTypeItem = null;

                    foreach (ContentTypeSort allowedContentType in mediaFolderType.AllowedContentTypes)
                    {
                        IMediaType checkMediaTypeItem = allMediaTypes.FirstOrDefault(x => x.Id == allowedContentType.Id.Value);
                        allowedContentTypes.Add(checkMediaTypeItem);

                        var fileProperty = checkMediaTypeItem?.CompositionPropertyTypes.FirstOrDefault(x => x.Alias == Constants.Conventions.Media.File);
                        if (fileProperty != null)
                        {
                            mediaTypeItem = checkMediaTypeItem;
                        }
                    }

                    //Only set the permission-based mediaType if we only allow 1 specific file under this parent.
                    if (allowedContentTypes.Count == 1 && mediaTypeItem != null)
                    {
                        mediaTypeAlias = mediaTypeItem.Alias;
                    }
                }
            }
            else
            {
                var typesAllowedAtRoot = allMediaTypes.Where(x => x.AllowedAsRoot).ToList();
                allowedContentTypes.UnionWith(typesAllowedAtRoot);
            }

            //get the files
            foreach (var formFile in file)
            {
                var fileName     = formFile.FileName.Trim(Constants.CharArrays.DoubleQuote).TrimEnd();
                var safeFileName = fileName.ToSafeFileName(ShortStringHelper);
                var ext          = safeFileName.Substring(safeFileName.LastIndexOf('.') + 1).ToLower();

                if (!_contentSettings.IsFileAllowedForUpload(ext))
                {
                    tempFiles.Notifications.Add(new BackOfficeNotification(
                                                    _localizedTextService.Localize("speechBubbles", "operationFailedHeader"),
                                                    _localizedTextService.Localize("media", "disallowedFileType"),
                                                    NotificationStyle.Warning));
                    continue;
                }

                if (string.IsNullOrEmpty(mediaTypeAlias))
                {
                    mediaTypeAlias = Constants.Conventions.MediaTypes.File;

                    if (contentTypeAlias == Constants.Conventions.MediaTypes.AutoSelect)
                    {
                        // Look up MediaTypes
                        foreach (var mediaTypeItem in allMediaTypes)
                        {
                            var fileProperty = mediaTypeItem.CompositionPropertyTypes.FirstOrDefault(x => x.Alias == Constants.Conventions.Media.File);
                            if (fileProperty == null)
                            {
                                continue;
                            }

                            var dataTypeKey = fileProperty.DataTypeKey;
                            var dataType    = _dataTypeService.GetDataType(dataTypeKey);

                            if (dataType == null || dataType.Configuration is not IFileExtensionsConfig fileExtensionsConfig)
                            {
                                continue;
                            }

                            var fileExtensions = fileExtensionsConfig.FileExtensions;
                            if (fileExtensions == null || fileExtensions.All(x => x.Value != ext))
                            {
                                continue;
                            }

                            mediaTypeAlias = mediaTypeItem.Alias;
                            break;
                        }

                        // If media type is still File then let's check if it's an image.
                        if (mediaTypeAlias == Constants.Conventions.MediaTypes.File && _imageUrlGenerator.SupportedImageFileTypes.Contains(ext))
                        {
                            mediaTypeAlias = Constants.Conventions.MediaTypes.Image;
                        }
                    }
                    else
                    {
                        mediaTypeAlias = contentTypeAlias;
                    }
                }

                if (allowedContentTypes.Any(x => x.Alias == mediaTypeAlias) == false)
                {
                    tempFiles.Notifications.Add(new BackOfficeNotification(
                                                    _localizedTextService.Localize("speechBubbles", "operationFailedHeader"),
                                                    _localizedTextService.Localize("media", "disallowedMediaType", new[] { mediaTypeAlias }),
                                                    NotificationStyle.Warning));
                    continue;
                }

                var mediaItemName = fileName.ToFriendlyName();

                var createdMediaItem = _mediaService.CreateMedia(mediaItemName, parentId.Value, mediaTypeAlias, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id);

                await using (var stream = formFile.OpenReadStream())
                {
                    createdMediaItem.SetValue(_mediaFileManager, _mediaUrlGenerators, _shortStringHelper, _contentTypeBaseServiceProvider, Constants.Conventions.Media.File, fileName, stream);
                }

                var saveResult = _mediaService.Save(createdMediaItem, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id);
                if (saveResult == false)
                {
                    AddCancelMessage(tempFiles, _localizedTextService.Localize("speechBubbles", "operationCancelledText") + " -- " + mediaItemName);
                }
            }

            //Different response if this is a 'blueimp' request
            if (HttpContext.Request.Query.Any(x => x.Key == "origin"))
            {
                var origin = HttpContext.Request.Query.First(x => x.Key == "origin");
                if (origin.Value == "blueimp")
                {
                    return(new JsonResult(tempFiles)); //Don't output the angular xsrf stuff, blue imp doesn't like that
                }
            }

            return(Ok(tempFiles));
        }
Exemple #31
0
        public void Initialize()
        {
            try
            {
                var container   = contentTypeService.GetContainers(DOCUMENT_TYPE_CONTAINER, 1).FirstOrDefault();
                int containerId = -1;

                if (container != null)
                {
                    containerId = container.Id;
                }


                var contentType = contentTypeService.Get(DOCUMENT_TYPE_ALIAS);
                if (contentType != null)
                {
                    return;
                }

                const string CONTENT_TAB = "CONTENT";

                ContentType docType = (ContentType)contentType ?? new ContentType(containerId)
                {
                    Name          = DOCUMENT_TYPE_NAME,
                    Alias         = DOCUMENT_TYPE_ALIAS,
                    AllowedAsRoot = true,
                    Description   = "",
                    Icon          = NESTED_DOCUMENT_TYPE_ICON,
                    ParentId      = contentTypeService.Get(NESTED_DOCUMENT_TYPE_PARENT_ALIAS).Id,
                    SortOrder     = 0,
                    Variations    = ContentVariation.Culture,
                };


                // Create the Template if it doesn't exist
                if (fileService.GetTemplate(TEMPLATE_ALIAS) == null)
                {
                    //then create the template
                    Template  newTemplate    = new Template(TEMPLATE_NAME, TEMPLATE_ALIAS);
                    ITemplate masterTemplate = fileService.GetTemplate(PARENT_TEMPLATE_ALIAS);
                    newTemplate.SetMasterTemplate(masterTemplate);
                    fileService.SaveTemplate(newTemplate);
                }

                var template = fileService.GetTemplate(TEMPLATE_ALIAS);
                docType.AllowedTemplates = new List <ITemplate> {
                    template
                };
                docType.SetDefaultTemplate(template);

                docType.AddPropertyGroup(CONTENT_TAB);

                #region Content

                PropertyType CotentPageTitlePropType = new PropertyType(dataTypeService.GetDataType(-88), "genericInfoPageTitle")
                {
                    Name       = "Page Title",
                    Variations = ContentVariation.Culture
                };
                docType.AddPropertyType(CotentPageTitlePropType, CONTENT_TAB);


                PropertyType CotentPageContentPropType = new PropertyType(dataTypeService.GetDataType(-87), "genericInfoPageContent")
                {
                    Name       = "Page Content",
                    Variations = ContentVariation.Culture
                };
                docType.AddPropertyType(CotentPageContentPropType, CONTENT_TAB);

                #endregion
                contentTypeService.Save(docType);
                ConnectorContext.AuditService.Add(AuditType.New, -1, docType.Id, "Document Type", $"Document Type '{DOCUMENT_TYPE_NAME}' has been created");

                ContentHelper.CopyPhysicalAssets(new GenericInfoPageEmbeddedResources());
            }

            catch (Exception ex)
            {
                logger.Error(typeof(_40_GenericInfoPageDocumentType), ex.Message);
                logger.Error(typeof(_40_GenericInfoPageDocumentType), ex.StackTrace);
            }
        }