private static Dictionary <string, object> GetChildPropertiesAndContent(object element, XmlWriter writer, Type type, ref object contentPropertyValue) { ContentPropertyAttribute attribute = WindowProfileSerializer.GetAttribute <ContentPropertyAttribute>((MemberInfo)type); Dictionary <string, object> dictionary = new Dictionary <string, object>(); foreach (PropertyInfo property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { if (WindowProfileSerializer.IsPropertySerializable(property)) { object obj = property.GetValue(element, (object[])null); if (!WindowProfileSerializer.IsDefaultValue(property, obj)) { if (WindowProfileSerializer.IsContentProperty(attribute, property)) { contentPropertyValue = obj; } else { TypeConverter converter = TypeDescriptor.GetConverter(obj == null ? property.PropertyType : obj.GetType()); if (converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string))) { writer.WriteStartAttribute(property.Name); WindowProfileSerializer.WriteAttributeValue(converter, obj, writer); writer.WriteEndAttribute(); } else { dictionary[property.Name] = obj; } } } } } return(dictionary); }
private void UpdateLoader(BusyInfo info) { lock (_lockObject) { info.Depth++; } if (info.BusyViewModel == null || info.BusyIndicator == null) { return; } Type indicatorType = info.BusyIndicator.GetType(); PropertyInfo content = indicatorType.GetProperty("BusyContent"); if (content == null) { ContentPropertyAttribute contentProperty = indicatorType.GetAttributes <ContentPropertyAttribute>(true) .FirstOrDefault(); if (contentProperty == null) { return; } content = indicatorType.GetProperty(contentProperty.Name); } content.SetValue(info.BusyIndicator, info.BusyViewModel, null); }
public PropertyRegistration(ContentPropertyAttribute propertyAttribute, string name, string alias, DataTypeRegistration dataType, PropertyInfo metadata, string cssClasses) { PropertyAttribute = propertyAttribute; Name = name; Alias = alias; DataType = dataType; Metadata = metadata; }
private static bool IsContentProperty(ContentPropertyAttribute attribute, PropertyInfo property) { if (attribute == null) { return(false); } return(attribute.Name == property.Name); }
public void CtorTest() { ContentPropertyAttribute attr = new ContentPropertyAttribute("name"); Assert.AreEqual("name", attr.Name); attr = new ContentPropertyAttribute(); Assert.IsNull(attr.Name); }
/// <summary> /// Creates a new property on the ContentType under the correct tab /// </summary> /// <param name="newContentType"></param> /// <param name="tabName"></param> /// <param name="dataTypeService"></param> /// <param name="atTabGeneric"></param> /// <param name="item"></param> public PropertyRegistration CreateProperty(IContentTypeBase newContentType, TabRegistration tab, PropertyInfo item, Type documentClrType) { ContentPropertyAttribute attribute = item.GetCodeFirstAttribute <ContentPropertyAttribute>(); var tabPostfix = tab == null || !attribute.AddTabAliasToPropertyAlias ? null : tab.OriginalName == null ? tab.Name : tab.OriginalName; var dataType = _dataTypeModule.GetDataType(item); var property = new PropertyRegistration(); property.Name = attribute.Name; property.Alias = tabPostfix == null ? attribute.Alias : StringHelperExtensions.HyphenToUnderscore(StringHelperExtensions.ParseUrl(attribute.Alias + "_" + tabPostfix, false)); property.DataType = dataType; property.PropertyAttribute = attribute; property.Metadata = item; PropertyType propertyType = new PropertyType(dataType.Definition); propertyType.Name = property.Name; propertyType.Alias = property.Alias; propertyType.Description = attribute.Description; propertyType.Mandatory = attribute.Mandatory; propertyType.SortOrder = attribute.SortOrder; propertyType.ValidationRegExp = attribute.ValidationRegularExpression; var propertyDeclaredOnThisDocType = property.Metadata.DeclaringType == documentClrType || property.Metadata.DeclaringType.GetCodeFirstAttribute <CodeFirstCommonBaseAttribute>(false) != null; var propertyDeclaredOnThisTab = tab == null ? false : property.Metadata.DeclaringType == tab.ClrType; var tabDeclaredOnThisDocType = tab == null ? false : tab.PropertyOfParent.DeclaringType == documentClrType || tab.PropertyOfParent.DeclaringType.GetCodeFirstAttribute <CodeFirstCommonBaseAttribute>() != null; var declaringTypeIsDocType = property.Metadata.DeclaringType.GetCodeFirstAttribute <ContentTypeAttribute>(false) != null; var propertyIsFromCommonBase = tab == null? property.Metadata.DeclaringType.GetCodeFirstAttribute <CodeFirstCommonBaseAttribute>() != null && property.Metadata.DeclaringType == documentClrType.BaseType : property.Metadata.DeclaringType.GetCodeFirstAttribute <CodeFirstCommonBaseAttribute>() != null && property.Metadata.DeclaringType == tab.ClrType.BaseType; if (tab == null) { if (propertyDeclaredOnThisDocType || propertyIsFromCommonBase) //only if property declared at this level (or inherited from a non-doctype class) { if (!propertyIsFromCommonBase || !newContentType.PropertyTypeExists(propertyType.Alias)) //check if common base properties already exist { CodeFirstManager.Current.Log("Adding property " + property.Name + " on content type " + newContentType.Name, this); newContentType.AddPropertyType(propertyType); } } } else if (tabDeclaredOnThisDocType || propertyIsFromCommonBase) //only if tab declared at this level { if (propertyDeclaredOnThisTab || propertyIsFromCommonBase) //only if property declared at this level { if (!propertyIsFromCommonBase || !newContentType.PropertyTypeExists(propertyType.Alias)) //check if common base properties already exist { CodeFirstManager.Current.Log("Adding property " + property.Name + " on tab " + tab.Name + " of content type " + newContentType.Name, this); newContentType.AddPropertyType(propertyType, tab.Name); } } } return(property); }
public void ContentPropertyAttributeConstructor() { tlog.Debug(tag, $"ContentPropertyAttributeConstructor START"); var testingTarget = new ContentPropertyAttribute("content"); tlog.Debug(tag, "Name : " + testingTarget.Name); tlog.Debug(tag, $"ContentPropertyAttributeConstructor END"); }
public void Register() { var builder = new AttributeTableBuilder(); builder.AddCustomAttributes(typeof(DatabaseConnect), new DesignerAttribute(typeof(ConnectDatabaseDesigner))); builder.AddCustomAttributes(typeof(DatabaseDisconnect), new DesignerAttribute(typeof(DisconnectDesigner))); builder.AddCustomAttributes(typeof(DatabaseTransaction), new DesignerAttribute(typeof(ConnectDatabaseDesigner))); builder.AddCustomAttributes(typeof(ExecuteNonQuery), new DesignerAttribute(typeof(GenericDatabaseDesigner))); builder.AddCustomAttributes(typeof(ExecuteQuery), new DesignerAttribute(typeof(GenericDatabaseDesigner))); builder.AddCustomAttributes(typeof(InsertDataTable), new DesignerAttribute(typeof(InsertDataTableDesigner))); builder.AddCustomAttributes(typeof(BulkInsert), new DesignerAttribute(typeof(BulkInsertDesigner))); builder.AddCustomAttributes(typeof(BulkUpdate), new DesignerAttribute(typeof(BulkUpdateDesigner))); // Editors var EditorAttributeType = new EditorAttribute(typeof(ArgumentDictionaryEditor), typeof(DialogPropertyValueEditor)); builder.AddCustomAttributes(typeof(ExecuteQuery), nameof(ExecuteQuery.Parameters), EditorAttributeType); builder.AddCustomAttributes(typeof(ExecuteNonQuery), nameof(ExecuteNonQuery.Parameters), EditorAttributeType); // Content attribute var contentAttr = new ContentPropertyAttribute(nameof(ExecuteNonQuery.ExistingDbConnection)); builder.AddCustomAttributes(typeof(ExecuteNonQuery), contentAttr); builder.AddCustomAttributes(typeof(ExecuteQuery), contentAttr); builder.AddCustomAttributes(typeof(InsertDataTable), contentAttr); builder.AddCustomAttributes(typeof(BulkInsert), contentAttr); builder.AddCustomAttributes(typeof(BulkUpdate), contentAttr); // DisplayName attribute builder.AddCustomAttributes(typeof(DatabaseConnect), new DisplayNameAttribute(SharedResources.Activity_DatabaseConnect_Name)); builder.AddCustomAttributes(typeof(DatabaseDisconnect), new DisplayNameAttribute(SharedResources.Activity_DatabaseDisconnect_Name)); builder.AddCustomAttributes(typeof(DatabaseTransaction), new DisplayNameAttribute(SharedResources.Activity_DatabaseTransaction_Name)); builder.AddCustomAttributes(typeof(ExecuteNonQuery), new DisplayNameAttribute(SharedResources.Activity_ExecuteNonQuery_Name)); builder.AddCustomAttributes(typeof(ExecuteQuery), new DisplayNameAttribute(SharedResources.Activity_ExecuteQuery_Name)); builder.AddCustomAttributes(typeof(InsertDataTable), new DisplayNameAttribute(SharedResources.Activity_InsertDataTable_Name)); builder.AddCustomAttributes(typeof(BulkInsert), new DisplayNameAttribute(SharedResources.Activity_BulkInsert_Name)); builder.AddCustomAttributes(typeof(BulkUpdate), new DisplayNameAttribute(SharedResources.Activity_BulkUpdate_Name)); // Categories CategoryAttribute appIntegrationDatabaseCategoryAttribute = new CategoryAttribute($"{Resources.CategoryAppIntegration}.{Resources.CategoryDatabase}"); builder.AddCustomAttributes(typeof(DatabaseConnect), appIntegrationDatabaseCategoryAttribute); builder.AddCustomAttributes(typeof(DatabaseDisconnect), appIntegrationDatabaseCategoryAttribute); builder.AddCustomAttributes(typeof(DatabaseTransaction), appIntegrationDatabaseCategoryAttribute); builder.AddCustomAttributes(typeof(ExecuteNonQuery), appIntegrationDatabaseCategoryAttribute); builder.AddCustomAttributes(typeof(ExecuteQuery), appIntegrationDatabaseCategoryAttribute); builder.AddCustomAttributes(typeof(InsertDataTable), appIntegrationDatabaseCategoryAttribute); builder.AddCustomAttributes(typeof(BulkInsert), appIntegrationDatabaseCategoryAttribute); builder.AddCustomAttributes(typeof(BulkUpdate), appIntegrationDatabaseCategoryAttribute); AddDescription(builder); MetadataStore.AddAttributeTable(builder.CreateTable()); }
private string GetContentPropertyName(Type t) { object [] o = t.GetCustomAttributes(typeof(ContentPropertyAttribute), true); if (o.Length == 0) { return(null); } ContentPropertyAttribute cpa = (ContentPropertyAttribute )o [0]; return(cpa.Name); }
protected override bool IsContentElementCore() { using (IEnumerator <object> enumerator = this._item.GetAttributes(typeof(ContentPropertyAttribute)).GetEnumerator()) { if (enumerator.MoveNext()) { ContentPropertyAttribute propertyAttribute = (ContentPropertyAttribute)enumerator.Current; return(true); } } return(false); }
private static void SetContentPropertyCore(object targetLocation, object view) { try { Type type = targetLocation.GetType(); ContentPropertyAttribute contentProperty = Attribute.GetCustomAttributes(type, true).OfType <ContentPropertyAttribute>().FirstOrDefault <ContentPropertyAttribute>() ?? View.DefaultContentProperty; type.GetProperty(contentProperty.Name).SetValue(targetLocation, view, null); } catch (Exception e) { Logger.Error(e); } }
/// <summary> /// /// </summary> /// <param name="element"></param> /// <returns></returns> static string GetCPA(XmlElement element) { Type type = FindType(element.Name); object[] attributes = type.GetCustomAttributes(typeof(ContentPropertyAttribute), true); if (attributes != null && attributes.Length > 0) { ContentPropertyAttribute cpa = (ContentPropertyAttribute)attributes[0]; return(cpa.Name); } return(null); }
private static bool IsContentPropertyHost(FrameworkElement host, out string contentPropertyName) { ContentPropertyAttribute contentProp = (ContentPropertyAttribute)host .GetType() .GetCustomAttributes(typeof(ContentPropertyAttribute), true) .FirstOrDefault(); if (contentProp != null) { contentPropertyName = contentProp.Name; return(true); } contentPropertyName = null; return(false); }
public XamlReflectionPropertySetter FindContentProperty() { Type type = null; ContentPropertyAttribute cnt = FindContentPropertyAttribute(out type); if (cnt == null) { // If there wasn't an explicitly set content property (via attributes) // attempt to use a property named Content. Will return null if the // property is not found. return(XamlReflectionPropertyForName(Type, "Content")); } return(XamlReflectionPropertyForName(type, cnt.Name)); }
// Token: 0x06008D46 RID: 36166 RVA: 0x002590E0 File Offset: 0x002572E0 internal string GetContentProperty(string assemblyName, string fullTypeName) { string clrNamespace = string.Empty; string typeShortName = fullTypeName; int num = fullTypeName.LastIndexOf('.'); if (num >= 0) { clrNamespace = fullTypeName.Substring(0, num); typeShortName = fullTypeName.Substring(num + 1); } short knownTypeIdFromName = BamlMapTable.GetKnownTypeIdFromName(assemblyName, clrNamespace, typeShortName); if (knownTypeIdFromName != 0) { KnownElements knownElement = (KnownElements)(-(KnownElements)knownTypeIdFromName); return(KnownTypes.GetContentPropertyName(knownElement)); } string text = null; if (this._contentPropertyTable != null && this._contentPropertyTable.TryGetValue(fullTypeName, out text)) { return(text); } Assembly assembly = Assembly.Load(assemblyName); Type type = assembly.GetType(fullTypeName); if (type != null) { object[] customAttributes = type.GetCustomAttributes(typeof(ContentPropertyAttribute), true); if (customAttributes.Length != 0) { ContentPropertyAttribute contentPropertyAttribute = customAttributes[0] as ContentPropertyAttribute; text = contentPropertyAttribute.Name; if (this._contentPropertyTable == null) { this._contentPropertyTable = new Dictionary <string, string>(8); } this._contentPropertyTable.Add(fullTypeName, text); } } return(text); }
/// <summary> /// Gets the default property name. /// </summary> /// <param name="type">The type.</param> /// <returns> /// The property name if it exists; otherwise <c>null</c>. /// </returns> public static string GetDefaultPropertyName(Type type) { ArgumentValidator.NotNull(type, "type"); object[] attrs = type.GetCustomAttributes(false); foreach (object attr in attrs) { ContentPropertyAttribute contentAttribute = attr as ContentPropertyAttribute; if (contentAttribute != null) { return(contentAttribute.Name); } DefaultPropertyAttribute defaultAttribute = attr as DefaultPropertyAttribute; if (defaultAttribute != null) { return(defaultAttribute.Name); } } return(null); }
private string GetContentPropertyName(MarkupObject markupObj) { Type objectType = markupObj.ObjectType; if (!_contentPropertiesCache.ContainsKey(objectType)) { string lookedUpContentProperty = string.Empty; foreach (Attribute attr in markupObj.Attributes) { ContentPropertyAttribute cpa = attr as ContentPropertyAttribute; if (cpa != null) { lookedUpContentProperty = cpa.Name; break; //Once content property is found, come out of the loop. } } _contentPropertiesCache.Add(objectType, lookedUpContentProperty); } return(_contentPropertiesCache[objectType]); }
/// <summary> /// Checks whether a property exists and adds if if it does not. The data type, alias, description and mandatory flag are update for existing properties, but not persisted. /// Callers should persist the value. /// </summary> public PropertyRegistration VerifyExistingProperty(IContentTypeBase contentType, TabRegistration tab, PropertyInfo item, Type documentClrType, ref bool modified) { ContentPropertyAttribute attribute = item.GetCodeFirstAttribute <ContentPropertyAttribute>(); var tabPostfix = tab == null || !attribute.AddTabAliasToPropertyAlias ? null : tab.OriginalName == null ? tab.Name : tab.OriginalName; var property = new PropertyRegistration(); var alias = property.Alias = tabPostfix == null ? attribute.Alias : StringHelperExtensions.HyphenToUnderscore(StringHelperExtensions.ParseUrl(attribute.Alias + "_" + tabPostfix, false)); var dataType = property.DataType = _dataTypeModule.GetDataType(item); property.Name = attribute.Name; property.PropertyAttribute = attribute; property.Metadata = item; LogPropertySyncInfo(contentType, tab, property, "Syncing"); bool alreadyExisted = contentType.PropertyTypeExists(alias); PropertyType umbracoProperty = contentType.PropertyTypes.FirstOrDefault(x => x.Alias == alias); if (umbracoProperty == null && alreadyExisted) { //This is a property from an underlying tab. Leave it alone. Log a warning in case this is an orphaned property. LogPropertySyncInfo(contentType, tab, property, "Ignoring inherited"); return(property); } if (alreadyExisted) { modified = modified || !umbracoProperty.Name.Equals(attribute.Name, StringComparison.InvariantCultureIgnoreCase) || umbracoProperty.Mandatory != attribute.Mandatory || (umbracoProperty.SortOrder != attribute.SortOrder && attribute.SortOrder != 0); //don't count sort order changes if no sort order is specified, as Umbraco will have assigned an automatic one if (umbracoProperty.ValidationRegExp != attribute.ValidationRegularExpression) { //If not both null/empty if (!(string.IsNullOrEmpty(umbracoProperty.ValidationRegExp) && string.IsNullOrEmpty(attribute.ValidationRegularExpression))) { modified = true; LogPropertySyncInfo(contentType, tab, property, "ValidationRegExp changed on"); } } if (umbracoProperty.Description != attribute.Description) { //If not both null/empty if (!(string.IsNullOrEmpty(umbracoProperty.Description) && string.IsNullOrEmpty(attribute.Description))) { modified = true; LogPropertySyncInfo(contentType, tab, property, "Description changed on"); } } if (modified) { if (!umbracoProperty.Name.Equals(attribute.Name, StringComparison.InvariantCultureIgnoreCase)) { LogPropertySyncInfo(contentType, tab, property, "Name changed on"); } if (umbracoProperty.Mandatory != attribute.Mandatory) { LogPropertySyncInfo(contentType, tab, property, "Mandatory changed on"); } if ((umbracoProperty.SortOrder != attribute.SortOrder && attribute.SortOrder != 0)) { LogPropertySyncInfo(contentType, tab, property, "SortOrder changed on"); } } } if (umbracoProperty == null) { try { modified = true; umbracoProperty = new PropertyType(dataType.Definition); LogPropertySyncInfo(contentType, tab, property, "Creating new"); } catch (Exception ex) { } } else if (umbracoProperty.DataTypeDefinitionId != dataType.Definition.Id) { modified = true; umbracoProperty.DataTypeDefinitionId = dataType.Definition.Id; LogPropertySyncInfo(contentType, tab, property, "Data type changed for"); } umbracoProperty.Name = attribute.Name; umbracoProperty.Alias = alias; umbracoProperty.Description = attribute.Description; umbracoProperty.Mandatory = attribute.Mandatory; umbracoProperty.SortOrder = attribute.SortOrder; umbracoProperty.ValidationRegExp = attribute.ValidationRegularExpression; var propertyDeclaredOnThisDocType = property.Metadata.DeclaringType == documentClrType; var propertyDeclaredOnThisTab = tab == null ? false : property.Metadata.DeclaringType == tab.ClrType; var tabDeclaredOnThisDocType = tab == null ? false : tab.PropertyOfParent.DeclaringType == documentClrType || tab.PropertyOfParent.DeclaringType.GetCustomAttribute <ContentTypeAttribute>() == null; var declaringTypeIsDocType = property.Metadata.DeclaringType.GetCodeFirstAttribute <ContentTypeAttribute>(false) != null; var propertyIsFromCommonBase = tab == null? property.Metadata.DeclaringType.GetCodeFirstAttribute <CodeFirstCommonBaseAttribute>() != null && property.Metadata.DeclaringType == documentClrType.BaseType : property.Metadata.DeclaringType.GetCodeFirstAttribute <CodeFirstCommonBaseAttribute>() != null && property.Metadata.DeclaringType == tab.ClrType.BaseType; if (alreadyExisted) { if (propertyIsFromCommonBase || (tabDeclaredOnThisDocType && propertyDeclaredOnThisTab)) { var currentTab = contentType.PropertyGroups.Where(x => x.PropertyTypes.Any(y => y.Alias == alias)).FirstOrDefault(); if (currentTab == null || !currentTab.Name.Equals(tab.Name, StringComparison.InvariantCultureIgnoreCase)) { modified = true; contentType.MovePropertyType(alias, tab.Name); LogPropertySyncInfo(contentType, tab, property, string.Format("Moved from tab {0}:", tab.Name)); } } } else { if (tab == null) { if (propertyDeclaredOnThisDocType || !declaringTypeIsDocType) //only if property declared at this level (or inherited from common base) { if (!propertyIsFromCommonBase || !contentType.PropertyTypeExists(umbracoProperty.Alias)) //check if common base properties already exist { LogPropertySyncInfo(contentType, tab, property, "Adding"); contentType.AddPropertyType(umbracoProperty); } } } else if (tabDeclaredOnThisDocType || propertyIsFromCommonBase) //only if tab declared at this level { if (propertyDeclaredOnThisTab || propertyIsFromCommonBase) //only if property declared at this level { if (!propertyIsFromCommonBase || (tabDeclaredOnThisDocType && !contentType.PropertyTypeExists(umbracoProperty.Alias))) //check if common base properties already exist { LogPropertySyncInfo(contentType, tab, property, "Adding"); contentType.AddPropertyType(umbracoProperty, tab.Name); } } } } return(property); }
private static bool TryGetChildrenUsingContentProperty(DependencyObject depObj, out List <DependencyObject> children) { Type depObjType = depObj.GetType(); // Attempt to find the attribute [ContentProperty("Children")] on the object: #if !BRIDGE ContentPropertyAttribute contentPropertyAttribute = (ContentPropertyAttribute)Attribute.GetCustomAttribute(depObjType, typeof(ContentPropertyAttribute)); #else ContentPropertyAttribute contentPropertyAttribute = (ContentPropertyAttribute)GetCustomAttribute(depObjType.GetCustomAttributes(true), typeof(ContentPropertyAttribute)); #endif if (contentPropertyAttribute != null) { // Get the name of the dependency property that contains the children: string contentPropertyName = contentPropertyAttribute.Name; // Attempt to find the property using Reflection: PropertyInfo propertyInfo = depObjType.GetProperty(contentPropertyName); //BRIDGETODO //Verify that GetGetMethod() == GetMethod #if !BRIDGE if (propertyInfo != null && propertyInfo.CanRead && propertyInfo.GetGetMethod() != null) #else if (propertyInfo != null && propertyInfo.CanRead && propertyInfo.GetMethod != null) #endif { // Attempt to read the value of the content property: object value = propertyInfo.GetValue(depObj); children = new List <DependencyObject>(); // If the content of the content property is a single item, we return it. Otherwise we return the whole collection: if (value is DependencyObject) { children.Add((DependencyObject)value); } else if (value is IEnumerable && (!(value is string))) { foreach (var item in (IEnumerable)value) { if (!(item is DependencyObject)) { children = null; //-------- // ERROR: enumerable does not contain dependency objects //-------- return(false); } else { children.Add((DependencyObject)item); } } } return(true); } else { children = null; return(false); } } else { children = null; return(false); } }
/// <remarks> /// The method retrieves the Content property name for the given type. It first looks into /// the KnownTypes table for the value. If not found, it will do a reflection to grab the /// ContentPropertyAttribute on the type. Custom-control assembly is alrady required to be /// present for BamlWriter to generate baml. /// </remarks> internal string GetContentProperty(string assemblyName, string fullTypeName) { // // go to KnownTypes to find the content property first // string nameSpace = string.Empty; string typeName = fullTypeName; int lastDot = fullTypeName.LastIndexOf('.'); if (lastDot >= 0) { nameSpace = fullTypeName.Substring(0, lastDot); typeName = fullTypeName.Substring(lastDot + 1); } short id = BamlMapTable.GetKnownTypeIdFromName(assemblyName, nameSpace, typeName); if (id != 0) { KnownElements knownElement = (KnownElements)(-id); return(KnownTypes.GetContentPropertyName(knownElement)); } string contentProperty = null; // // Look into cached values. // if (_contentPropertyTable != null && _contentPropertyTable.TryGetValue(fullTypeName, out contentProperty)) { return(contentProperty); } // // Need to do reflection for it. // // Assembly.Load will throw exception if it fails. Assembly assm = Assembly.Load(assemblyName); Type type = assm.GetType(fullTypeName); if (type != null) { object[] contentPropertyAttributes = type.GetCustomAttributes( typeof(ContentPropertyAttribute), true // search for inherited value ); if (contentPropertyAttributes.Length > 0) { ContentPropertyAttribute contentPropertyAttribute = contentPropertyAttributes[0] as ContentPropertyAttribute; contentProperty = contentPropertyAttribute.Name; // Cach the value for future use. if (_contentPropertyTable == null) { _contentPropertyTable = new Dictionary <string, string>(8); } _contentPropertyTable.Add(fullTypeName, contentProperty); } } return(contentProperty); }
private void ResolveXmlNamespaces(object obj) { List <MarkupProperty> propertyElements = new List <MarkupProperty>(); MarkupProperty contentProperty = null; string contentPropertyName = null; MarkupObject markupObj = MarkupWriter.GetMarkupObjectFor(obj); Type objectType = markupObj.ObjectType; string ns = _namespaceCache.GetNamespaceUriFor(objectType); if (!string.IsNullOrWhiteSpace(ns)) { string prefix = _namespaceCache.GetDefaultPrefixFor(ns); _dicNamespaceMap[ns] = new NamespaceMap(prefix, ns); } //Look for CPA info in our cache that keeps contentProperty names per Type //If it doesn't have an entry, go get the info and store it. if (!_contentProperties.ContainsKey(objectType)) { string lookedUpContentProperty = string.Empty; foreach (Attribute attr in markupObj.Attributes) { ContentPropertyAttribute cpa = attr as ContentPropertyAttribute; if (cpa != null) { lookedUpContentProperty = cpa.Name; //Once content property is found, come out of the loop. break; } } _contentProperties.Add(objectType, lookedUpContentProperty); } contentPropertyName = _contentProperties[objectType]; string contentString = string.Empty; foreach (MarkupProperty markupProperty in markupObj.Properties) { if (markupProperty.Name != contentPropertyName) { if (markupProperty.IsValueAsString) { contentString = markupProperty.Value as string; } else if (!markupProperty.IsComposite) { //Bug Fix DX-0120123 if (markupProperty.DependencyProperty != null) { string ns1 = _namespaceCache.GetNamespaceUriFor( markupProperty.DependencyProperty.OwnerType); string prefix1 = _namespaceCache.GetDefaultPrefixFor(ns1); if (!string.IsNullOrWhiteSpace(prefix1)) { _dicNamespaceMap[ns1] = new NamespaceMap(prefix1, ns1); } } } else if (markupProperty.Value.GetType() == _nullType) { } else { propertyElements.Add(markupProperty); } } else { contentProperty = markupProperty; } } if (contentProperty != null || propertyElements.Count > 0 || contentString != string.Empty) { foreach (MarkupProperty markupProp in propertyElements) { string ns2 = _namespaceCache.GetNamespaceUriFor(markupObj.ObjectType); if (!string.IsNullOrWhiteSpace(ns2)) { string prefix2 = _namespaceCache.GetDefaultPrefixFor(ns2); _dicNamespaceMap[ns2] = new NamespaceMap(prefix2, ns2); } ResolveChildXmlNamespaces(markupProp); } if (contentProperty != null) { if (!(contentProperty.Value is String)) { ResolveChildXmlNamespaces(contentProperty); } } } }
private void WriteObject(object key, object obj, XmlWriter writer, bool isRoot) { List <MarkupProperty> propertyElements = new List <MarkupProperty>(); MarkupProperty contentProperty = null; string contentPropertyName = null; MarkupObject markupObj = MarkupWriter.GetMarkupObjectFor(obj); Type objectType = markupObj.ObjectType; string ns = _namespaceCache.GetNamespaceUriFor(objectType); string prefix = _namespaceCache.GetDefaultPrefixFor(ns); if (isRoot) { if (string.IsNullOrWhiteSpace(prefix)) { if (string.IsNullOrWhiteSpace(ns)) { writer.WriteStartElement(markupObj.ObjectType.Name, NamespaceCache.DefaultNamespace); writer.WriteAttributeString("xmlns", NamespaceCache.XmlnsNamespace, NamespaceCache.DefaultNamespace); } else { writer.WriteStartElement(markupObj.ObjectType.Name, ns); writer.WriteAttributeString("xmlns", NamespaceCache.XmlnsNamespace, ns); } } else { writer.WriteStartElement(prefix, markupObj.ObjectType.Name, ns); } writer.WriteAttributeString("xmlns", "x", NamespaceCache.XmlnsNamespace, NamespaceCache.XamlNamespace); foreach (NamespaceMap map in _dicNamespaceMap.Values) { if (!string.IsNullOrWhiteSpace(map.Prefix) && !string.Equals(map.Prefix, "x")) { writer.WriteAttributeString("xmlns", map.Prefix, NamespaceCache.XmlnsNamespace, map.XmlNamespace); } } } else { //TODO: Fix - the best way to handle this case... if (markupObj.ObjectType.Name == "PathFigureCollection" && markupObj.Instance != null) { WriteState writeState = writer.WriteState; if (writeState == WriteState.Element) { //writer.WriteAttributeString("Figures", // markupObj.Instance.ToString()); writer.WriteAttributeString("Figures", System.Convert.ToString(markupObj.Instance, _culture)); } else { if (string.IsNullOrWhiteSpace(prefix)) { writer.WriteStartElement("PathGeometry.Figures"); } else { writer.WriteStartElement("PathGeometry.Figures", ns); } //writer.WriteString(markupObj.Instance.ToString()); writer.WriteString(System.Convert.ToString( markupObj.Instance, _culture)); writer.WriteEndElement(); } return; } else { if (string.IsNullOrWhiteSpace(prefix)) { writer.WriteStartElement(markupObj.ObjectType.Name); } else { writer.WriteStartElement(markupObj.ObjectType.Name, ns); } } } // Add the x:Name for object like Geometry/Drawing not derived from FrameworkElement... DependencyObject dep = obj as DependencyObject; if (dep != null) { string nameValue = dep.GetValue(FrameworkElement.NameProperty) as string; if (!string.IsNullOrWhiteSpace(nameValue) && !(dep is FrameworkElement)) { writer.WriteAttributeString("x", "Name", NamespaceCache.XamlNamespace, nameValue); } } if (key != null) { string keyString = key.ToString(); if (keyString.Length > 0) { writer.WriteAttributeString("x", "Key", NamespaceCache.XamlNamespace, keyString); } else { //TODO: key may not be a string, what about x:Type... throw new NotImplementedException( "Sample XamlWriter cannot yet handle keys that aren't strings"); } } //Look for CPA info in our cache that keeps contentProperty names per Type //If it doesn't have an entry, go get the info and store it. if (!_contentProperties.ContainsKey(objectType)) { string lookedUpContentProperty = string.Empty; foreach (Attribute attr in markupObj.Attributes) { ContentPropertyAttribute cpa = attr as ContentPropertyAttribute; if (cpa != null) { lookedUpContentProperty = cpa.Name; //Once content property is found, come out of the loop. break; } } _contentProperties.Add(objectType, lookedUpContentProperty); } contentPropertyName = _contentProperties[objectType]; string contentString = string.Empty; foreach (MarkupProperty markupProperty in markupObj.Properties) { if (markupProperty.Name != contentPropertyName) { if (markupProperty.IsValueAsString) { contentString = markupProperty.Value as string; } else if (!markupProperty.IsComposite) { string temp = markupProperty.StringValue; if (markupProperty.IsAttached) { string ns1 = _namespaceCache.GetNamespaceUriFor(markupProperty.DependencyProperty.OwnerType); string prefix1 = _namespaceCache.GetDefaultPrefixFor(ns1); if (temp.IndexOfAny("{}".ToCharArray()) >= 0) { temp = "{}" + temp; } if (string.IsNullOrWhiteSpace(prefix1)) { writer.WriteAttributeString(markupProperty.Name, temp); } else { writer.WriteAttributeString(markupProperty.Name, ns1, temp); } } else { if (markupProperty.Name == "FontUri" && (_wpfSettings != null && _wpfSettings.IncludeRuntime)) { string fontUri = temp.ToLower(); fontUri = fontUri.Replace(_windowsDir, _windowsPath); StringBuilder builder = new StringBuilder(); builder.Append("{"); builder.Append("svg"); builder.Append(":"); builder.Append("SvgFontUri "); builder.Append(fontUri.Replace('\\', '/')); builder.Append("}"); writer.WriteAttributeString(markupProperty.Name, builder.ToString()); } else { if (temp.IndexOfAny("{}".ToCharArray()) >= 0) { temp = "{}" + temp; } writer.WriteAttributeString(markupProperty.Name, temp); } } } else if (markupProperty.Value.GetType() == _nullType) { if (_nullExtension) { writer.WriteAttributeString(markupProperty.Name, "{x:Null}"); } } else { propertyElements.Add(markupProperty); } } else { contentProperty = markupProperty; } } if (contentProperty != null || propertyElements.Count > 0 || contentString != string.Empty) { foreach (MarkupProperty markupProp in propertyElements) { string ns2 = _namespaceCache.GetNamespaceUriFor(markupObj.ObjectType); string prefix2 = null; if (!string.IsNullOrWhiteSpace(ns2)) { prefix2 = _namespaceCache.GetDefaultPrefixFor(ns2); } string propElementName = markupObj.ObjectType.Name + "." + markupProp.Name; if (string.IsNullOrWhiteSpace(prefix2)) { writer.WriteStartElement(propElementName); } else { writer.WriteStartElement(prefix2, propElementName, ns2); } WriteChildren(writer, markupProp); writer.WriteEndElement(); } if (contentString != string.Empty) { writer.WriteValue(contentString); } else if (contentProperty != null) { if (contentProperty.Value is string) { writer.WriteValue(contentProperty.StringValue); } else { WriteChildren(writer, contentProperty); } } } writer.WriteEndElement(); }
//========================================================================== private void SaveProperty(XmlElement parent, MarkupObject markupObject, MarkupProperty property) { Binding binding = null; if (property.DependencyProperty != null) { // If this property is a DependencyProperty markupObject.Instance... // ...must be a DepedencyObject binding = BindingOperations.GetBinding(markupObject.Instance as DependencyObject, property.DependencyProperty); } if (binding != null) { SaveBindingProperty(parent, property, binding); } else { string content_property_name = null; // Get the content property of markupObject.Instance... if (property.PropertyDescriptor == null) { // SavePropertyContent(parent, property); //return; SaveAttributeProperty(parent, property); return; } if (property.PropertyDescriptor.GetType().ToString() == "System.ComponentModel.ReflectPropertyDescriptor") { //bool breaker = false; if (property.PropertyType.Name == "Object") { if (!property.IsAttached) { /*foreach (var item in property.Attributes) * { * if (item is System.Runtime.InteropServices.ClassInterfaceAttribute) * { * breaker = true; * } * }*/ //if (property.IsComposite) { try { if (property.IsComposite) //if (property.StringValue == null) { } } catch (Exception) { //SaveCompositeProperty(parent, property); return; } } } } // SavePropertyContent(parent, property); //return; //SaveAttributeProperty(parent, property); //return; } //try { object[] attributes = property.PropertyDescriptor.ComponentType.GetCustomAttributes(typeof(ContentPropertyAttribute), true); if (attributes.Length > 0) { ContentPropertyAttribute attribute = attributes[attributes.Length - 1] as ContentPropertyAttribute; content_property_name = attribute.Name; } if (content_property_name == property.Name) { // Only store the property's content SavePropertyContent(parent, property); } else if (property.IsComposite) { // Save property using its own element SaveCompositeProperty(parent, property); } else { // Save as attribute SaveAttributeProperty(parent, property); } } /*catch (Exception ex) * { * MessageBox.Show(ex.ToString()); * }*/ } }
public void WriteObject(object key, object obj, XmlWriter writer, bool isRoot) { var doc = xmldoc.DocumentElement; List <MarkupProperty> propertyElements = new List <MarkupProperty>(); MarkupProperty contentProperty = null; string contentPropertyName = null; MarkupObject markupObj = MarkupWriter.GetMarkupObjectFor(obj); Type objectType = markupObj.ObjectType; string ns = _namespaceCache.GetNamespaceUriFor(objectType); string prefix = _namespaceCache.GetDefaultPrefixFor(ns); if (isRoot) { if (String.IsNullOrEmpty(prefix)) { if (String.IsNullOrEmpty(ns)) { writer.WriteStartElement(markupObj.ObjectType.Name, NamespaceCache.DefaultNamespace); writer.WriteAttributeString("xmlns", NamespaceCache.XmlnsNamespace, NamespaceCache.DefaultNamespace); } else { writer.WriteStartElement(markupObj.ObjectType.Name, ns); writer.WriteAttributeString("xmlns", NamespaceCache.XmlnsNamespace, ns); } } else { if (doc.LocalName == markupObj.ObjectType.Name) { if (doc.NamespaceURI == ns) { if (doc.Prefix == prefix) { } } } } //writer.WriteAttributeString("xmlns", "x", // NamespaceCache.XmlnsNamespace, NamespaceCache.XamlNamespace); //foreach (NamespaceMap map in _dicNamespaceMap.Values) { // if (!String.IsNullOrEmpty(map.Prefix) && !String.Equals(map.Prefix, "x")) // writer.WriteAttributeString("xmlns", map.Prefix, NamespaceCache.XmlnsNamespace, map.XmlNamespace); //} } else { //TODO: Fix - the best way to handle this case... if (markupObj.ObjectType.Name == "PathFigureCollection" && markupObj.Instance != null) { WriteState writeState = writer.WriteState; if (writeState == WriteState.Element) { writer.WriteAttributeString("Figures", markupObj.Instance.ToString()); } else { if (String.IsNullOrEmpty(prefix)) { writer.WriteStartElement("PathGeometry.Figures"); } else { writer.WriteStartElement("PathGeometry.Figures", ns); } writer.WriteString(markupObj.Instance.ToString()); writer.WriteEndElement(); } return; } else { if (String.IsNullOrEmpty(prefix)) { writer.WriteStartElement(markupObj.ObjectType.Name); } else { writer.WriteStartElement(markupObj.ObjectType.Name, ns); } } } // Add the x:Name for object like Geometry/Drawing not derived from FrameworkElement... DependencyObject dep = obj as DependencyObject; if (dep != null) { string nameValue = dep.GetValue(FrameworkElement.NameProperty) as string; if (!String.IsNullOrEmpty(nameValue) && !(dep is FrameworkElement)) { writer.WriteAttributeString("x", "Name", NamespaceCache.XamlNamespace, nameValue); } } if (key != null) { string keyString = key.ToString(); if (keyString.Length > 0) { writer.WriteAttributeString("x", "Key", NamespaceCache.XamlNamespace, keyString); } else { //TODO: key may not be a string, what about x:Type... throw new NotImplementedException( "Sample XamlWriter cannot yet handle keys that aren't strings"); } } //Look for CPA info in our cache that keeps contentProperty names per Type //If it doesn't have an entry, go get the info and store it. if (!_contentProperties.ContainsKey(objectType)) { string lookedUpContentProperty = String.Empty; foreach (Attribute attr in markupObj.Attributes) { ContentPropertyAttribute cpa = attr as ContentPropertyAttribute; if (cpa != null) { lookedUpContentProperty = cpa.Name; //Once content property is found, come out of the loop. break; } } _contentProperties.Add(objectType, lookedUpContentProperty); } contentPropertyName = _contentProperties[objectType]; string contentString = String.Empty; foreach (MarkupProperty markupProperty in markupObj.Properties) { if (markupProperty.Name != contentPropertyName) { if (markupProperty.IsValueAsString) { contentString = markupProperty.Value as string; } else if (!markupProperty.IsComposite) { string temp = markupProperty.StringValue; if (markupProperty.IsAttached) { string ns1 = _namespaceCache.GetNamespaceUriFor(markupProperty.DependencyProperty.OwnerType); string prefix1 = _namespaceCache.GetDefaultPrefixFor(ns1); if (String.IsNullOrEmpty(prefix1)) { writer.WriteAttributeString(markupProperty.Name, temp); } else { writer.WriteAttributeString(markupProperty.Name, ns1, temp); } } else { if (markupProperty.Name == "FontUri" && (_wpfSettings != null)) { string fontUri = temp.ToLower(); fontUri = fontUri.Replace(_windowsDir, _windowsPath); StringBuilder builder = new StringBuilder(); builder.Append("{"); builder.Append("svg"); builder.Append(":"); builder.Append("SvgFontUri "); builder.Append(fontUri); builder.Append("}"); writer.WriteAttributeString(markupProperty.Name, builder.ToString()); } else { if (doc.HasAttribute(markupProperty.Name)) { PropertyInfo pI = obj.GetType().GetProperty(markupProperty.Name); SetValue(pI, doc, obj); } } } } else if (markupProperty.Value.GetType() == _nullType) { if (_nullExtension) { //writer.WriteAttributeString(markupProperty.Name, "{x:Null}"); } } else { propertyElements.Add(markupProperty); } } else { contentProperty = markupProperty; } } if (contentProperty != null || propertyElements.Count > 0 || contentString != String.Empty) { foreach (MarkupProperty markupProp in propertyElements) { string propElementName = markupObj.ObjectType.Name + "." + markupProp.Name; if (doc.HasChildNodes) { foreach (XmlElement child in doc.ChildNodes) { if (child.LocalName == propElementName) { if (child.HasChildNodes) { foreach (XmlElement _child in child.ChildNodes) { string _namespace = _child.NamespaceURI; string _prefix = _child.Prefix; string _nameType = _namespace + "." + _child.LocalName; if (IsKnowType(_nameType)) { Type _type = Type.GetType(_nameType); object _obj = _type.InvokeMember(_type.FullName, BindingFlags.CreateInstance, null, null, null); Create(_type, _child, _obj); IList collection = markupProp.Value as IList; IDictionary dictionary = markupProp.Value as IDictionary; if (collection != null) { collection.Add(_obj); } } } } } } } } if (contentString != String.Empty) { //writer.WriteValue(contentString); } else if (contentProperty != null) { if (contentProperty.Value is string) { //writer.WriteValue(contentProperty.StringValue); } else { //WriteChildren(writer, contentProperty); } } } //writer.WriteEndElement(); }