CascadeInitializer

CSharp · Console

/Program.cs

using System;
using System.Xml;
using System.Xml.Serialization;
using System.Reflection;
using System.Linq;
					
public class Program
{
	public static void Main()
	{
		var x =  CascadeInitializer<Envelope>();
	
		Console.WriteLine ($"Is Envelope null : {x == null}");
		Console.WriteLine ($"Is Body null : {x.Body == null}");
		Console.WriteLine ($"Is Body.GetUser null : {x.Body.GetUser == null}");
	}
	
	
	 
public static T CascadeInitializer<T>() => (T)CascadeInitializer(typeof(T));

public static object CascadeInitializer(Type type)
{
	var newObj = Activator.CreateInstance(type);
	Func<PropertyInfo,bool> query = q
		=> q.PropertyType.IsClass &&            // Check if property is a class
		   q.CanWrite &&                        // Check if property is not readOnly
		   q.PropertyType != typeof(string) &&  // Check if property is not string
		   q.PropertyType.GetInterfaces()       // Check what classes should be initialize 
		      .Any(i => i.Name == nameof(IInitializable) );
		
	
	foreach (var el in type.GetProperties().Where(query))
	{
		// create new instance of el cascade
		var elInstance = CascadeInitializer(el.PropertyType);
		el.SetValue(newObj, elInstance);
	}
	return newObj;

}
 	
public interface IInitializable{}
	
[XmlRoot(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Body : IInitializable
{
	[XmlElement(ElementName = "getUser", Namespace = "http://www.cisco.com/AXL/API/9.1")]
	public GetUser GetUser { get; set; }
}
public class GetUser : IInitializable
{
	public ReturnedTags ReturnedTags { get; set; }
}
public class ReturnedTags
{
	public AssociatedGroups AssociatedGroups { get; set; }
	public AssociatedDevices AssociatedDevices { get; set; }
}
public class AssociatedGroups { }
public class AssociatedDevices { }
public class GetUserReq
{
	public Envelope Envelope { get; set; }
	public Body Body { get; set; }

}
public class GetUserResponse
{
	public Envelope Envelope { get; set; }

}
[XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Envelope : IInitializable
{
	[XmlElement(ElementName = "Header", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
	public string Header { get; set; }
	[XmlElement(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
	public Body Body { get; set; }
	[XmlAttribute(AttributeName = "soapenv", Namespace = "http://www.w3.org/2000/xmlns/")]
	public string Soapenv { get; set; }
	[XmlAttribute(AttributeName = "ns", Namespace = "http://www.w3.org/2000/xmlns/")]
	public string Ns { get; set; }
}
	
}
;