Monthly Archive for Oktober, 2009

System.Reflection.Konfusion

Entwickler sind faul – ich zumindest. Ich will möglichst wenig Code schreiben, aber strukturiert. Nun ergab es sich, das man einen Datentyp mit circa 80 eigenen Properties – welche ebenfalls wieder eigene Klassen sind – erstellen sollte. Dieser Job ist ja nun leicht erledigt. Man hacke fix ein Consolenprogramm welches aus einer XMl-Datei (in der die Klassen und Datentypen enthalten sind) einen Datentyp bastelt.
Das sieht dann letztendlich so aus (exemplarisch mal eine Klasse und der Datentyp):

public class ProductReference
{
        public string StaticName { get { return "ProductReference"; } }
        public string DisplayName { get { return Resources.Displayname_ProductReference; } }
        public Guid ID { get { return new Guid("{6ebe0f28-af6a-40f7-9ad8-d9ff37d2b045}"); } }
        public string TypeName { get { return "String"; } }
        public Type Type { get { return typeof(String); } }
        public String Value { get; set; }
	public bool ErrorsDetected { get; set; }
}
public class Item
{
	public ProductReference ProductReference { get; set; }
}

Jetzt soll dieser Datentyp natürlich auch irgendwo gespeichert werden. In meinem Fall ist es einfach eine SharePoint Liste bei der jedes Feld einer Klasseneigenschaft entspricht. (Das Speichern reicht natürlich nicht, es muss ja auch irgendwann wieder geladen werden etc.). Das Problem ist jetzt, das keiner Ernsthaft ~80 Properties einzeln in das ListItem der SharePoint Liste zu schreiben… geht natürlich auch.
Viel schöner ist aber, wenn wir einfach alle Properties der Klasse durchlaufen könnten und den Wert des entsprechenden Feldes zu setzen:

foreach (PropertyInfo mainprop in this.GetType().GetProperties())
{
	object fieldvalue = mainprop.GetValue(this, null).GetType().InvokeMember(
        	"Value", BindingFlags.GetProperty, null, mainprop.GetValue(this, null), null);
        string fieldname = (string)mainprop.GetValue(this, null).GetType().InvokeMember(
                    "DisplayName", BindingFlags.GetProperty, null, mainprop.GetValue(this, null), null);
        Guid fieldid = (Guid)mainprop.GetValue(this, null).GetType().InvokeMember(
                    "ID", BindingFlags.GetProperty, null, mainprop.GetValue(this, null), null);

        if (item.Fields.GetField(fieldname).Type == SPFieldType.DateTime)
                    fieldvalue = SPUtility.CreateISO8601DateTimeFromSystemDateTime((DateTime)fieldvalue);

        item[fieldid] = fieldvalue;

        try
        {
		item.SystemUpdate();
	}
	catch (Exception ex)
        {
		LogMsg(ex.ToString());
                ErrorsOccured = true;
                mainprop.GetValue(this, null).GetType().InvokeMember("ErrorsDetected", BindingFlags.SetProperty, null,
                mainprop.GetValue(this, null),
                new object[] { true });
        }
}

Dank Reflection können wir mittels this.GetType().GetProperties() über alle Properties der aktuellen Klasse iterieren. Jetzt wollen wir aber nicht den Wert der Property haben, sondern den Wert der Value Eigenschaft der Property. Klar? Schön. :)
Da man eine Site Columns im SharePoint am sichersten über seine Guid ansprechen kann, wird die Guid sowie der aktuelle Wert der Value Eigenschaft ausgelesen und in das SPListItem geschrieben. Kling konfus, ist es auch. ;) Mittels InvokeMember und der Option BindingFlags.GetProperty kann man grob gesagt den Wert auslesen. Analog kann man mittems BindingFlags.SetProperty den Setter des Members aufrufen.
Klingt alles irgendwie merkwürdig, und wir lesen ja meistens lieber Code – daher hier einfach mal das was dabei rausgekommen ist:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Collections;
using System.Reflection;
using Microsoft.SharePoint.Utilities;

namespace DataTypeTest
{
    #region class implementations
	// hier stehen alle Klassendefinitionen
	public class ProductReference
	{
	        public string StaticName { get { return "ProductReference"; } }
	        public string DisplayName { get { return Resources.Displayname_ProductReference; } }
	        public Guid ID { get { return new Guid("{6ebe0f28-af6a-40f7-9ad8-d9ff37d2b045}"); } }
	        public string TypeName { get { return "String"; } }
	        public Type Type { get { return typeof(String); } }
	        public String Value { get; set; }
		public bool ErrorsDetected { get; set; }
	}
	// etc.pp.
    #endregion

    public class NPPItem
    {
        #region properties
		// hier stehen die Properties
		public ProductReference ProductReference { get; set; }
		// etc. pp.
        #endregion

        public Action<string> Log;

        /// <summary>
        /// Initializes a new instance of the <see cref="Item"/> class.
        /// </summary>
        public Item(Action<string> LogFunction)
        {
            Log = LogFunction;
            InitFields();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Item"/> class.
        /// </summary>
        /// <param name="ListItemID">The list item ID.</param>
        /// <param name="WebUrl">The web URL.</param>
        /// <param name="ListId">The list id.</param>
        public Item(string ListItemID, string WebUrl, string ListId, Action<string> LogFunction, out bool ErrorsDetected)
        {
            if (string.IsNullOrEmpty(ListItemID) |
                string.IsNullOrEmpty(WebUrl) |
                string.IsNullOrEmpty(ListId))
                throw new ArgumentException("Empty params for Item(string ListItemID, string WebUrl, string ListId)!");
            Log = LogFunction;
            bool ErrorsOccured = false;
            int iItemId;
            if (!Int32.TryParse(ListItemID, out iItemId)) throw new ArgumentException("ListItemID is not a valid int!");

            InitFields();
            SPList liste = GetList(ListId, WebUrl);
            SPListItem litem = liste.GetItemById(iItemId);
            if (litem == null) { ErrorsDetected = true; return; }

            foreach (PropertyInfo mainprop in this.GetType().GetProperties())
            {
                Guid fieldid = (Guid)mainprop.GetValue(this, null).GetType().InvokeMember(
                    "ID", BindingFlags.GetProperty, null, mainprop.GetValue(this, null), null);

                SPField spfield = litem.Fields[fieldid];
                object[] param = new object[1];
                try
                {
                    param[0] = Convert.ChangeType(spfield.GetFieldValueAsText(litem[fieldid]),
                        mainprop.GetValue(this, null).GetType().GetProperty("Value").PropertyType);
                    mainprop.GetValue(this, null).GetType().InvokeMember("Value", BindingFlags.SetProperty, null,
                    mainprop.GetValue(this, null),
                    param);
                }
                catch (Exception ex)
                {
                    LogMsg(ex.ToString());
                    ErrorsOccured = true;
                    mainprop.GetValue(this, null).GetType().InvokeMember("ErrorsDetected", BindingFlags.SetProperty, null,
                    mainprop.GetValue(this, null),
                    new object[] { true });
                }

            }
            ErrorsDetected = ErrorsOccured;
        }

        private void InitFields()
        {
            // instanzen erstellen... sicher ist sicher :)
            this.ProductReference = new ProductReference();
	    // etc.pp.
        }

        /// <summary>
        /// Saves the item.
        /// </summary>
        /// <param name="ListItemID">The list item ID. Submit -1 to create a new item</param>
        /// <param name="Data">The data.</param>
	/// <returns>ID of the new list item</returns>
        public bool SaveItem(int ListItemID, string WebUrl, string ListId, out int newListItemID)
        {
            bool ErrorsOccured = false;
            SPList liste = GetList(ListId, WebUrl);
            if (liste == null)
                throw new ArgumentException(string.Format("List {0} in site {1} does not exist or you have insufficient permissions",
                    ListId, WebUrl));

            SPListItem item = null;
            if (ListItemID == -1) item = liste.Items.Add();
            else item = liste.Items[ListItemID];
            if (item == null) throw new ArgumentException(string.Format("ListItem with ID '{0}' does not exist in list '{1}' at site '{2}' !",
                ListItemID, ListId, WebUrl));

            foreach (PropertyInfo mainprop in this.GetType().GetProperties())
            {
                object fieldvalue = mainprop.GetValue(this, null).GetType().InvokeMember(
                    "Value", BindingFlags.GetProperty, null, mainprop.GetValue(this, null), null);
                string fieldname = (string)mainprop.GetValue(this, null).GetType().InvokeMember(
                    "DisplayName", BindingFlags.GetProperty, null, mainprop.GetValue(this, null), null);
                Guid fieldid = (Guid)mainprop.GetValue(this, null).GetType().InvokeMember(
                    "ID", BindingFlags.GetProperty, null, mainprop.GetValue(this, null), null);

                if (item.Fields.GetField(fieldname).Type == SPFieldType.DateTime)
                    fieldvalue = SPUtility.CreateISO8601DateTimeFromSystemDateTime((DateTime)fieldvalue);

                item[fieldid] = fieldvalue;

                try
                {
                    item.SystemUpdate();
                }
                catch (Exception ex)
                {
                    LogMsg(ex.ToString());
                    ErrorsOccured = true;
                    mainprop.GetValue(this, null).GetType().InvokeMember("ErrorsDetected", BindingFlags.SetProperty, null,
                    mainprop.GetValue(this, null),
                    new object[] { true });
                }
            }
            newListItemID = item.ID;
            return ErrorsOccured;
        }

        public List<string> GetPropertiesWithErrors()
        {
            List<string> result = new List<string>();
            foreach (PropertyInfo mainprop in this.GetType().GetProperties())
            {
                if (Convert.ToBoolean(mainprop.GetValue(this, null).GetType().InvokeMember(
                    "ErrorsDetected", BindingFlags.GetProperty, null, mainprop.GetValue(this, null), null)))
                    result.Add(mainprop.Name);
            }
            return result;
        }

        /// <summary>
        /// Gets a SPList.
        /// </summary>
        /// <param name="ListId">The list id.</param>
        /// <param name="SiteUrl">The site URL.</param>
        /// <returns>SPList if found, otherwise null</returns>
        private SPList GetList(string ListId, string SiteUrl)
        {
            if (ToGuid(ListId) == null) return null;
            SPList retval = null;
            using (SPSite site = new SPSite(SiteUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    retval = web.Lists[ToGuid(ListId)];
                }
            }
            return retval;
        }

        /// <summary>
        /// Get a Guid object from a valid guid string
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns>valid GUID or null</returns>
        private Guid ToGuid(string input)
        {
            if (string.IsNullOrEmpty(input)) throw new ArgumentException("input is null");
            Guid retval = new Guid();
            try
            {
                retval = new Guid(input);
            }
            catch (Exception) { }
            return retval;
        }

        private void LogMsg(string Message)
        {
            if (this.Log != null)
                Log(Message);
        }

    }
}

Nice to have wäre natürlich noch, die ganze Show mit Interfaces zu versehen, so dass man nicht mehr hardcoded auf die Subpropertynamen losgehen muss, wie ich es bisher gemacht habe:

mainprop.GetValue(this, null).GetType().InvokeMember("Value", BindingFlags.GetProperty, null, mainprop.GetValue(this, null), null);

Ich brauch jetzt erstmal ein wenig Frischluft. :)

Kick it on dotnet-kicks.de

Standard Pitfall mit Page.FindControl [Update]

Reminder an micht selbst:
Page.FindControl arbeitet nicht rekursiv. :>
Alternativfunktionen für rekursives Suchen und Holen von Controls:

        private T GetControl(string id, ControlCollection ctls, bool ThrowExceptions) where T : Control
        {
            Control ctl = FindControl(id, ctls);
            if (ThrowExceptions && ctl == null)
                throw new Exception(string.Format("Cannot find control with id '{0}' !\n", id));
            if (ThrowExceptions && ctl.GetType() != typeof(T))
                throw new Exception(string.Format("Control with id '{0}' found , but it's type is not {1}!\n", id, typeof(T)));
            if (ctl == null) return null;
            T castedCtl = (T)ctl;
            return castedCtl;
        }

        private bool ControlExists(string id, ControlCollection ctls)
        {
            return (GetControl(id, ctls, false)) != null;
        }

        private Control FindControl(string id, ControlCollection ctls)
        {
            Control ctlsearched = null;
            foreach (Control ctl in ctls)
            {
                if (!string.IsNullOrEmpty(ctl.ID) && ctl.ID.Equals(id, StringComparison.InvariantCultureIgnoreCase))
                    ctlsearched = ctl;
                if (ctlsearched == null && ctl.HasControls())
                    ctlsearched = FindControl(id, ctl.Controls);

                if (ctlsearched != null) break;
            }
            return ctlsearched;
        }

Update
Manchmal sollte man doch mal Google oder ein paar der Blogs aus seinem RSSReader bemühen… dann wäre man auch auf den Post von Peter Bucher gestossen der das ganze Thema etwas ausführlicher schon im Januar behandelte. :)

Kick it on dotnet-kicks.de