ln.snmp/types/Variable.cs

119 lines
3.4 KiB
C#

// /**
// * 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;
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 virtual void Write(Stream stream)
{
byte[] payload = Bytes;
BasicEncodingRules.WriteIdentifier(stream,Identifier);
BasicEncodingRules.WriteLength(stream, payload.Length);
stream.Write(payload, 0, payload.Length);
}
public byte[] ToBytes()
{
MemoryStream memoryStream = new MemoryStream();
Write(memoryStream);
return memoryStream.ToArray();
}
public static Variable Read(Stream stream)
{
Variable variable = null;
Identifier identifier = BasicEncodingRules.ReadIdentifier(stream);
int length = BasicEncodingRules.ReadLength(stream);
byte[] payload = new byte[length];
stream.Read(payload, 0, length);
variable = FromIdentifier(identifier);
variable.Bytes = payload;
return variable;
}
public static Variable Read(byte[] bytes)
{
MemoryStream stream = new MemoryStream(bytes);
return Read(stream);
}
public static void Write(Stream stream,Variable variable)
{
variable.Write(stream);
}
public static Variable FromIdentifier(Identifier identifier)
{
if (identifier.IdentifierClass == IdentifierClass.UNIVERSAL)
{
switch (identifier.Number)
{
case 0x02:
return new Integer();
case 0x04:
return new OctetString();
case 0x05:
return NullValue.Instance;
case 0x06:
return new ObjectIdentifier();
case 0x10:
return new Sequence();
}
}
else if (identifier.IdentifierClass == IdentifierClass.CONTEXT)
{
switch (identifier.Number)
{
case 0x00:
return new GetRequest();
case 0x02:
return new GetResponse();
case 0x03:
return new SetRequest();
}
}
else if (identifier.IdentifierClass == IdentifierClass.APPLICATION)
{
switch (identifier.Number)
{
case 0x01:
return new Counter32();
case 0x02:
return new Unsigned32();
case 0x06:
return new Counter64();
}
}
throw new NotSupportedException(String.Format("Unsupported ASN Type: {0}",identifier));
}
}
}