Beispiel #1
0
        /// <summary>
        /// Loades PropertyTypes by Tab/PropertyGroup using the new API.
        /// </summary>
        /// <param name="contentType"></param>
        /// <param name="tabPage"></param>
        /// <param name="inTab"></param>
        /// <param name="tabId"></param>
        /// <param name="tabCaption"></param>
        private void LoadPropertyTypes(IContentTypeComposition contentType, TabPage tabPage, Hashtable inTab, int tabId, string tabCaption)
        {
            var propertyGroups      = contentType.CompositionPropertyGroups.Where(x => x.Id == tabId || x.ParentId == tabId);
            var propertyTypeAliases = propertyGroups.SelectMany(x => x.PropertyTypes.OrderBy(y => y.SortOrder).Select(y => new Tuple <int, string, int>(y.Id, y.Alias, y.SortOrder)));

            foreach (var items in propertyTypeAliases)
            {
                var property = _content.getProperty(items.Item2);
                if (property != null)
                {
                    AddControlNew(property, tabPage, tabCaption);

                    if (!inTab.ContainsKey(items.Item1.ToString(CultureInfo.InvariantCulture)))
                    {
                        inTab.Add(items.Item1.ToString(CultureInfo.InvariantCulture), true);
                    }
                }
                else
                {
                    throw new ArgumentNullException(
                              string.Format(
                                  "Property {0} ({1}) on Content Type {2} could not be retrieved for Document {3} on Tab Page {4}. To fix this problem, delete the property and recreate it.",
                                  items.Item2, items.Item1, _content.ContentType.Alias, _content.Id,
                                  tabCaption));
                }
            }
        }
Beispiel #2
0
 private void DeleteCrops(Content sender)
 {
     //Remove all cropup files
     var context = HttpContext.Current;
     if (context != null)
     {
         foreach (var alias in Settings.PropertyAliases.Split(','))
         {
             var prop = sender.getProperty(alias);
             if (prop != null && prop.Value != null)
             {
                 var umbracoFile = prop.Value.ToString();
                 var path = context.Server.MapPath(umbracoFile);
                 var filename = Path.GetFileNameWithoutExtension(path);
                 var pattern = "*.cropup.*";
                 var dir = Path.GetDirectoryName(path);
                 var files = Directory.GetFiles(dir, pattern);
                 foreach (var file in files)
                 {
                     if (File.Exists(file))
                     {
                         File.Delete(file);
                     }
                 }
             }
         }
     }
 }
Beispiel #3
0
        /// <summary>
        /// Create and setup all of the controls child controls.
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            SaveAndPublish += new EventHandler(standardSaveAndPublishHandler);
            Save           += new EventHandler(standardSaveAndPublishHandler);
            prntpage        = (UmbracoEnsuredPage)Page;
            int i     = 0;
            var inTab = new Hashtable();

            // zb-00036 #29889 : load it only once
            if (virtualTabs == null)
            {
                virtualTabs = _content.ContentType.getVirtualTabs.ToList();
            }

            foreach (ContentType.TabI t in virtualTabs)
            {
                var tp = this.Panels[i] as TabPage;
                if (tp == null)
                {
                    throw new ArgumentException("Unable to load tab \"" + t.Caption + "\"");
                }
                //TabPage tp = NewTabPage(t.Caption);
                //addSaveAndPublishButtons(ref tp);

                tp.Style.Add("text-align", "center");


                // Iterate through the property types and add them to the tab
                // zb-00036 #29889 : fix property types getter to get the right set of properties
                foreach (PropertyType pt in t.GetPropertyTypes(_content.ContentType.Id))
                {
                    // table.Rows.Add(addControl(_content.getProperty(editPropertyType.Alias), tp));
                    addControlNew(_content.getProperty(pt), tp, t.Caption);
                    inTab.Add(pt.Id.ToString(), true);
                }

                i++;
            }

            // Add property pane
            tpProp = NewTabPage(ui.Text("general", "properties", null));
            addSaveAndPublishButtons(ref tpProp);
            tpProp.Controls.Add(
                new LiteralControl("<div id=\"errorPane_" + tpProp.ClientID +
                                   "\" style=\"display: none; text-align: left; color: red;width: 100%; border: 1px solid red; background-color: #FCDEDE\"><div><b>There were errors - data has not been saved!</b><br/></div></div>"));

            //if the property is not in a tab, add it to the general tab
            var props = _content.GenericProperties;

            foreach (Property p in props)
            {
                if (inTab[p.PropertyType.Id.ToString()] == null)
                {
                    addControlNew(p, tpProp, ui.Text("general", "properties", null));
                }
            }
        }
Beispiel #4
0
        /// <summary>
        /// Create and setup all of the controls child controls.
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            SaveAndPublish += new EventHandler(standardSaveAndPublishHandler);
            Save           += new EventHandler(standardSaveAndPublishHandler);
            prntpage        = (UmbracoEnsuredPage)Page;
            int i     = 0;
            var inTab = new Hashtable();

            // zb-00036 #29889 : load it only once
            if (virtualTabs == null)
            {
                virtualTabs = _content.ContentType.getVirtualTabs.ToList();
            }

            foreach (ContentType.TabI tab in virtualTabs)
            {
                var tabPage = this.Panels[i] as TabPage;
                if (tabPage == null)
                {
                    throw new ArgumentException("Unable to load tab \"" + tab.Caption + "\"");
                }
                //TabPage tp = NewTabPage(t.Caption);
                //addSaveAndPublishButtons(ref tp);

                tabPage.Style.Add("text-align", "center");


                // Iterate through the property types and add them to the tab
                // zb-00036 #29889 : fix property types getter to get the right set of properties
                // ge : had a bit of a corrupt db and got weird NRE errors so rewrote this to catch the error and rethrow with detail
                foreach (PropertyType propertyType in tab.GetPropertyTypes(_content.ContentType.Id))
                {
                    // table.Rows.Add(addControl(_content.getProperty(editPropertyType.Alias), tp));
                    var property = _content.getProperty(propertyType);
                    if (property != null && tabPage != null)
                    {
                        addControlNew(property, tabPage, tab.Caption);

                        // adding this check, as we occasionally get an already in dictionary error, though not sure why
                        if (!inTab.ContainsKey(propertyType.Id.ToString()))
                        {
                            inTab.Add(propertyType.Id.ToString(), true);
                        }
                    }
                    else
                    {
                        throw new ArgumentNullException(string.Format("Property {0} ({1}) on Content Type {2} could not be retrieved for Document {3} on Tab Page {4}. To fix this problem, delete the property and recreate it.", propertyType.Alias, propertyType.Id, _content.ContentType.Alias, _content.Id, tab.Caption));
                    }
                }

                i++;
            }

            // Add property pane
            tpProp = NewTabPage(ui.Text("general", "properties", null));
            addSaveAndPublishButtons(ref tpProp);
            tpProp.Controls.Add(
                new LiteralControl("<div id=\"errorPane_" + tpProp.ClientID +
                                   "\" style=\"display: none; text-align: left; color: red;width: 100%; border: 1px solid red; background-color: #FCDEDE\"><div><b>There were errors - data has not been saved!</b><br/></div></div>"));

            //if the property is not in a tab, add it to the general tab
            var props = _content.GenericProperties;

            foreach (Property p in props)
            {
                if (inTab[p.PropertyType.Id.ToString()] == null)
                {
                    addControlNew(p, tpProp, ui.Text("general", "properties", null));
                }
            }
        }
		/// <summary>
		/// Event after all properties have been saved
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void AfterSave(Content sender, SaveEventArgs e)
		{
			Guid pickerRelationsId  = new Guid(DataTypeGuids.PickerRelationsId);

			// For each PickerRelations datatype
			foreach (Property pickerRelationsProperty in from property in sender.GenericProperties
															  where property.PropertyType.DataTypeDefinition.DataType.Id == pickerRelationsId
															  select property)
			{
				// used to identify this datatype instance - relations created are marked with this in the comment field
				string instanceIdentifier = "[\"PropertyTypeId\":" + pickerRelationsProperty.PropertyType.Id.ToString() + "]";

				// get configuration options for datatype
				PickerRelationsOptions options = ((PickerRelationsPreValueEditor)pickerRelationsProperty.PropertyType.DataTypeDefinition.DataType.PrevalueEditor).Options;

				// find Picker source propertyAlias field on sender
				Property pickerProperty = sender.getProperty(options.PropertyAlias);

				if (pickerProperty != null)
				{
					// get relationType from options
					RelationType relationType = RelationType.GetById(options.RelationTypeId);

					if (relationType != null)
					{
						// validate: 1) check current type of sender matches that expected by the relationType, validation method is in the DataEditor
						uQuery.UmbracoObjectType contextObjectType = uQuery.UmbracoObjectType.Unknown;
						switch (sender.GetType().ToString())
						{
							case "umbraco.cms.businesslogic.web.Document": contextObjectType = uQuery.UmbracoObjectType.Document; break;
							case "umbraco.cms.businesslogic.media.Media": contextObjectType = uQuery.UmbracoObjectType.Media; break;
							case "umbraco.cms.businesslogic.member.Member": contextObjectType = uQuery.UmbracoObjectType.Member; break;
						}

						if (((PickerRelationsDataEditor)pickerRelationsProperty.PropertyType.DataTypeDefinition.DataType.DataEditor)
							.IsContextUmbracoObjectTypeValid(contextObjectType, relationType))
						{

							uQuery.UmbracoObjectType pickerUmbracoObjectType = uQuery.UmbracoObjectType.Unknown;

							// Get the object type expected by the associated relation type and if this datatype has been configures as a rever index
							pickerUmbracoObjectType = ((PickerRelationsDataEditor)pickerRelationsProperty.PropertyType.DataTypeDefinition.DataType.DataEditor)
														.GetPickerUmbracoObjectType(relationType);


							// clear all exisitng relations (or look to see previous verion of sender to delete changes ?)
							DeleteRelations(relationType, sender.Id, options.ReverseIndexing, instanceIdentifier);

							string pickerPropertyValue = pickerProperty.Value.ToString();

							var pickerStorageFormat = PickerStorageFormat.Csv; // Assume default of csv

                            if (xmlHelper.CouldItBeXml(pickerPropertyValue))
							{
                                pickerStorageFormat = PickerStorageFormat.Xml;
							}

							// Creating instances of Documents / Media / Members ensures the IDs are of a valid type - be quicker to check with GetUmbracoObjectType(int)
							Dictionary<int, string> pickerItems = null;
							switch (pickerUmbracoObjectType)
							{
								case uQuery.UmbracoObjectType.Document:
									switch (pickerStorageFormat)
									{
                                        case PickerStorageFormat.Csv:
											pickerItems = uQuery.GetDocumentsByCsv(pickerPropertyValue).ToNameIds();
											break;
                                        case PickerStorageFormat.Xml:
											pickerItems = uQuery.GetDocumentsByXml(pickerPropertyValue).ToNameIds();
											break;
									}

									break;
								case uQuery.UmbracoObjectType.Media:
									switch (pickerStorageFormat)
									{
                                        case PickerStorageFormat.Csv:
											pickerItems = uQuery.GetMediaByCsv(pickerPropertyValue).ToNameIds();
											break;
                                        case PickerStorageFormat.Xml:
											pickerItems = uQuery.GetMediaByXml(pickerPropertyValue).ToNameIds();
											break;
									}
									break;
								case uQuery.UmbracoObjectType.Member:
									switch (pickerStorageFormat)
									{
                                        case PickerStorageFormat.Csv:
											pickerItems = uQuery.GetMembersByCsv(pickerPropertyValue).ToNameIds();
											break;
                                        case PickerStorageFormat.Xml:
											pickerItems = uQuery.GetMembersByXml(pickerPropertyValue).ToNameIds();
											break;
									}
									break;
							}
							if (pickerItems != null)
							{
								foreach (KeyValuePair<int, string> pickerItem in pickerItems)
								{
									CreateRelation(relationType, sender.Id, pickerItem.Key, options.ReverseIndexing, instanceIdentifier);
								}
							}
						}
						else
						{
							// Error: content object type invalid with relation type
						}
					}
					else
					{
						// Error: relation type is null
					}
				}
				else
				{
					// Error: pickerProperty alias not found
				}
			}
		}
Beispiel #6
0
        protected virtual string GetContentFromDatabase(AttributeCollectionAdapter itemAttributes, int nodeIdInt, string currentField)
        {
            var c = new Content(nodeIdInt);

            var property = c.getProperty(currentField);
            if (property == null)
                throw new ArgumentException(String.Format("Could not find property {0} of node {1}.", currentField, nodeIdInt));

            var umbItem = new item(property.Value.ToString(), itemAttributes);
            var tempElementContent = umbItem.FieldContent;

            // If the current content object is a document object, we'll only output it if it's published
            if (c.nodeObjectType == Document._objectType)
            {
                try
                {
                    var d = (Document)c;
                    if (!d.Published)
                        tempElementContent = "";
                }
                catch { }
            }

            // Add the content to the cache
            if (!string.IsNullOrEmpty(tempElementContent))
            {
                ApplicationContext.Current.ApplicationCache.InsertCacheItem(
                    string.Format("{0}{1}_{2}", CacheKeys.ContentItemCacheKey, nodeIdInt, currentField),
                    CacheItemPriority.Default, () => tempElementContent);
            }
            return tempElementContent;
        }
		/// <summary>
		/// Gets the field content from database instead of the published XML via the APIs.
		/// </summary>
		/// <param name="nodeIdInt">The node id.</param>
		/// <param name="currentField">The field that should be fetched.</param>
		/// <returns>The contents of the <paramref name="currentField"/> from the <paramref name="nodeIdInt"/> content object</returns>
        protected virtual string GetContentFromDatabase(AttributeCollectionAdapter itemAttributes, int nodeIdInt, string currentField)
		{
			Content c = new Content(nodeIdInt);

			Property property = c.getProperty(currentField);
			if (property == null)
				throw new ArgumentException(String.Format("Could not find property {0} of node {1}.", currentField, nodeIdInt));

			item umbItem = new item(property.Value.ToString(), itemAttributes);
			string tempElementContent = umbItem.FieldContent;

			// If the current content object is a document object, we'll only output it if it's published
			if (c.nodeObjectType == cms.businesslogic.web.Document._objectType)
			{
				try
				{
					Document d = (Document)c;
					if (!d.Published)
						tempElementContent = "";
				}
				catch { }
			}

			// Add the content to the cache
			if (!String.IsNullOrEmpty(tempElementContent))
				HttpContext.Current.Cache.Insert(String.Format("contentItem{0}_{1}", nodeIdInt.ToString(), currentField), tempElementContent);
			return tempElementContent;
		}
        public static void ReadProperties(Type contentType, Content content, object output)
        {
            foreach (PropertyInfo propInfo in contentType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
                {
                    DocumentTypePropertyAttribute propAttr = Util.GetAttribute<DocumentTypePropertyAttribute>(propInfo);
                    if (propAttr == null)
                    {
                        continue; // skip this property - not part of a Document Type
                    }

                    string propertyName;
                    string propertyAlias;
                    DocumentTypeManager.ReadPropertyNameAndAlias(propInfo, propAttr, out propertyName, out propertyAlias);

                    umbraco.cms.businesslogic.property.Property property = content.getProperty(propertyAlias);

                    object value = null;
                    try
                    {
                        if (property == null)
                        {
                            value = null;
                        }
                        else if (propInfo.PropertyType.Equals(typeof(System.Boolean)))
                        {
                            if (String.IsNullOrEmpty(Convert.ToString(property.Value)) || Convert.ToString(property.Value) == "0")
                            {
                                value = false;
                            }
                            else
                            {
                                value = true;
                            }
                        }
                        else if (PropertyConvertors.ContainsKey(propInfo.PropertyType))
                        {
                            value = ContentUtil.GetInnerXml(content.Id.ToString(), propertyAlias);
                        }
                        else if (String.IsNullOrEmpty(Convert.ToString(property.Value)))
                        {
                            // if property type is string or if it's some custom type, try to get the inner xml of this property within a node.
                            if (propInfo.PropertyType == typeof(string) ||
                                PropertyConvertors.ContainsKey(propInfo.PropertyType))
                            {
                                value = ContentUtil.GetInnerXml(content.Id.ToString(), propertyAlias);
                                if (value == null && propInfo.PropertyType == typeof(string))
                                {
                                    value = string.Empty;
                                }
                            }
                            else
                            {
                                value = null;
                            }
                        }
                        else if (propInfo.PropertyType.IsGenericType &&
                                 propInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                        {
                            value = Convert.ChangeType(property.Value, Nullable.GetUnderlyingType(propInfo.PropertyType));

                            // TODO: If data type is DateTime and is nullable and is less than 1.1.1000 than set it to NULL
                        }
                        else
                        {
                            value = Convert.ChangeType(property.Value, propInfo.PropertyType);
                        }

                        if (PropertyConvertors.ContainsKey(propInfo.PropertyType))
                        {
                            value = PropertyConvertors[propInfo.PropertyType].ConvertValueWhenRead(value);
                        }

                        propInfo.SetValue(output, value, null);
                    }
                    catch (Exception exc)
                    {
                        throw new Exception(string.Format("Cannot set the value of a document type property {0}.{1} (document type: {2}) to value: '{3}' (value type: {4}). Error: {5}",
                            contentType.Name, propInfo.Name, propInfo.PropertyType.FullName,
                            value, value != null ? value.GetType().FullName : "", exc.Message));
                    }
                }
        }
Beispiel #9
0
        private void SetDescription(Content content, bool hasLowKarma, ref bool hasAnchors)
        {
            content.getProperty("description").Value = tb_desc.Text;

            // Filter out links when karma is low, probably a spammer
            if (hasLowKarma)
            {
                var doc = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(tb_desc.Text);

                var anchorNodes = doc.DocumentNode.SelectNodes("//a");
                if (anchorNodes != null)
                {
                    hasAnchors = true;

                    foreach (var anchor in anchorNodes)
                        anchor.ParentNode.RemoveChild(anchor, true);
                }

                content.getProperty("description").Value = doc.DocumentNode.OuterHtml;
            }
        }