Dan Sewell
Dan Sewell

Reputation: 1290

Reflection issue in WinRT

I am having an issue porting a WP7 app to a win8 store app...

I run this code to populate fields from elements inside XML file:

Venue lv = new Venue();

            foreach (var t in Fields)
            {
                foreach (var f in t.Elements())
                {
                    lv.SaveData(f.Attribute("name").Value, f.Value, lv);
                }
            }

Data class:

 public class Venue //: INotifyPropertyChanged
    {
        public string updated_at { get; set; }
        public string name { get; set; }
        public string authority { get; set; }
        public string organisation { get; set; }
        public string control_type { get; set; }
    }

Run SaveData Method:

public void SaveData(string field, string value, Venue v)
        {

            foreach (MemberInfo mi in v.GetType().GetTypeInfo().GetMembers())
            {
                if (mi.MemberType == MemberTypes.Property)
                {
                    PropertyInfo pi = mi as PropertyInfo;

                    if (pi.Name == "Coordinate")
                        continue;

                    if (pi.Name == field)
                    {
                        pi.SetValue(v, value, null);
                    }
                }
            }
        }

The issue is, the GetMembers definition does not exist in WinRT, so either need to find an alternative to expose the same proeprties, or have to find a way to rewrite the system.

I did not write this piece of code myself, but I can just about understand what it is doing. I am not too familar on reflection, apart from the basic introductions I have just read Any quick fixes

Upvotes: 0

Views: 903

Answers (1)

chue x
chue x

Reputation: 18823

GetType is an extension method. You need to include the reflection namespace:

using System.Reflection;

For your SaveData method, you can do something like:

public void SaveData(string field, string value, Venue v)
{
    var typeinfo = v.GetType().GetTypeInfo();
    var pi = typeinfo.GetDeclaredProperty(field);

    if (pi != null && pi.Name != "Coordinate")
       pi.SetValue(v, value);
}

You probably want to do some better error checking than the code above. For example making sure v and pi.Name are not null.

Upvotes: 2

Related Questions