lundi 16 janvier 2017

C# Custom Property Attribute Reflection

Building an OpenGraph .net Parser but stuck in property binding. I simple fetch the HTML Document and parse it using HtmlAgilityPack. After that I want to check each Node for the specific OpenGraph Key:

Custom Attribute

    public class OpenGraphAttribute : Attribute
    {
        public string Name { get; set; }

        public OpenGraphAttribute(string name)
        {
            Name = name;
        }
    }

Container Class

public class OGVideoContainer
    {
        [OpenGraphAttribute("og:video:url")]
        public string DefaultUrl { get; set; }

        [OpenGraphAttribute("og:video:secure_url")]
        public string SecureUrl { get; set; }

        [OpenGraphAttribute("og:video:type")]
        public string Type { get; set; }

        [OpenGraphAttribute("og:video:width")]
        public string Width { get; set; }

        [OpenGraphAttribute("og:video:height")]
        public string Height { get; set; }

        [OpenGraphAttribute("og:video:url")]
        public string Url { get; set; }
    }

Parser

 public OGVideoContainer ParseVideo(HtmlDocument doc)
    {
        var result = new OGVideoContainer();
        var parseableAttr = typeof(OGVideoContainer).GetProperties();
        foreach (var prop in parseableAttr)
        {
            var ca = prop.GetCustomAttributes(true).ElementAtOrDefault(0) as OpenGraphAttribute;
            if (doc.DocumentNode.SelectSingleNode(String.Format("/html/head/meta[@property='{0}']", ca.Name)) != null)
            {
                // i am stuck here how can i access the result.propery value?
            }
        }

        return result;
    }

But stuck at the result.parameter binding. I have to assign result.DefaultUrl with the corresponding custom attribute name value. How can this be done?

Thanks for any help.





Aucun commentaire:

Enregistrer un commentaire