// /** // * File: Variable.cs // * Author: haraldwolff // * // * This file and it's content is copyrighted by the Author and / or copyright holder. // * Any use wihtout proper permission is illegal and may lead to legal actions. // * // * // **/ using System; using System.IO; using ln.snmp.asn1; using ln.logging; using System.Collections.Generic; using System.CodeDom; using System.Reflection; using System.Linq; namespace ln.snmp.types { public abstract class Variable { public Identifier Identifier { get; private set; } public Variable(Identifier identifier) { Identifier = identifier; } public abstract byte[] Bytes { get; set; } public abstract object Value { get; set; } public void Dump() { Dump(""); } public void Dump(string prefix) { if (this is AbstractSequence) { AbstractSequence sequence = this as AbstractSequence; Logging.Log(LogLevel.DEBUG, "{0}{1}", prefix, this.ToString()); foreach (Variable item in sequence.Items) { if (item != null) item.Dump(prefix + " "); else Logging.Log(LogLevel.DEBUG, "{0}NULL", prefix); } } else { Logging.Log(LogLevel.DEBUG, "{0}{1} {2}", prefix, this.ToString(), BitConverter.ToString(this.Bytes)); } } public static implicit operator ASN1Value(Variable variable) { ASN1Value value = new ASN1Value(variable.Identifier); if (variable is AbstractSequence) { AbstractSequence sequence = variable as AbstractSequence; foreach (Variable item in sequence.Items) value.Add(item); } else { value.Bytes = variable.Bytes; } return value; } public static implicit operator Variable(ASN1Value value) { try { if (knownTypes.ContainsKey(value.Identifier)) { Type type = knownTypes[value.Identifier]; //Logging.Log(LogLevel.DEBUGDETAIL, "ASN1Value->Variable: {0} -> {1}", value, type.Name); Variable variable = Activator.CreateInstance(type,true) as Variable; if (variable is AbstractSequence) { AbstractSequence sequence = variable as AbstractSequence; sequence.Items = value.Items.Select((x) => (Variable)x).ToArray(); } else { variable.Bytes = value.Bytes; } return variable; } throw new ArgumentException(String.Format("{0}",value.Identifier),nameof(value)); } catch (Exception e) { Logging.Log(e); throw e; } } static Dictionary knownTypes = new Dictionary(); static bool __initialized__ = initialize(); static void registerKnownType() where T:Variable, new() { T i = new T(); knownTypes.Add(i.Identifier, typeof(T)); } static bool initialize() { registerKnownType(); registerKnownType(); registerKnownType(); registerKnownType(); registerKnownType(); registerKnownType(); registerKnownType(); registerKnownType(); registerKnownType(); registerKnownType(); registerKnownType(); registerKnownType(); registerKnownType(); registerKnownType(); return true; } } }