lundi 19 décembre 2016

Dynamically convert property to Type

Is it possible to simplify this logic, Is there generic way to do it. The code finds marked attributes and parses it according to the attribute type. Please suggest some way to optimize this code, all the data type of Product class will be string, I'm getting product input as xml directly converting serialized data to a class with decimal,int,float will not give proper error message, If there is list of item it throws error in xml we wont know which row has caused the error.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace TestSolution
{
  public interface ICustomParser
  {
    bool Parse(string input);
  }

public class DecimalParserAttribute : Attribute, ICustomParser
{
    public bool Parse(string input)
    {
        if (input == null) return false;

        decimal decimalValue;

        return decimal.TryParse(input, out decimalValue);
    }
}

public class intParserAttribute : Attribute, ICustomParser
{
    public bool Parse(string input)
    {
        if (input == null) return false;

        int intValue;

        return int.TryParse(input, out intValue);
    }
}

public class Product
{
    [DecimalParser]
    public string Weight { get; set; }

    [intParser]
    public string NoOfItems { get; set; }

    [intParser]
    public string GRodes { get; set; }

    [intParser]
    public string WRodes { get; set; }
}

class Program
{
    static void Main(string[] args)
    {

        var sb = Validate(new Product() { NoOfItems = "1", GRodes = "4", Weight = "5", WRodes = "23" });

        Console.WriteLine(sb);
        sb = Validate(new Product() { NoOfItems = "1", GRodes = "4w", Weight = "5", WRodes = "23" });

        Console.WriteLine(sb);
        Console.ReadKey();
    }

    private static string Validate(Product product)
    {
        var sb = new StringBuilder();

        foreach (var property in product.GetType().GetProperties())
        {
            var value = Convert.ToString(property.GetValue(product, null));

            var sel = property.GetAttribute<ICustomParser>();

            if (sel == null) continue;

            var parserinstance = (ICustomParser)Activator.CreateInstance(sel.GetType());

            if (parserinstance.Parse(value)) continue;

            sb.AppendLine(string.Format("{0} Has invalid value", property.Name));
        }
        return sb.ToString();
    }
}

public static class Extensions
{
    public static T GetAttribute<T>(this PropertyInfo property)
    {
        return (T)property.GetCustomAttributes(false).Where(s => s is T).FirstOrDefault();
    }
}





Aucun commentaire:

Enregistrer un commentaire