Initial project commit
This commit is contained in:
57
TorControlLibrary/Responses/CommandResponse.cs
Normal file
57
TorControlLibrary/Responses/CommandResponse.cs
Normal file
@@ -0,0 +1,57 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Reflection;
|
||||
|
||||
namespace TorControlLibrary.Responses
|
||||
{
|
||||
public class CommandResponse
|
||||
{
|
||||
public CommandResponse()
|
||||
{
|
||||
}
|
||||
public CommandResponse(Int32 status, String response)
|
||||
{
|
||||
StatusCode = status;
|
||||
Response = response.EndsWith(Environment.NewLine) ? response : response + Environment.NewLine;
|
||||
}
|
||||
public virtual void AppendResponse(String line)
|
||||
{
|
||||
Response += line + Environment.NewLine;
|
||||
}
|
||||
|
||||
protected virtual void PopulateData(String dataLine, CommandResponse response)
|
||||
{
|
||||
String[] parts = dataLine.Split(' ');
|
||||
List<PropertyInfo> props = response.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(ParseAttribute), true).Any())
|
||||
.OrderBy(p => ((ParseAttribute)p.GetCustomAttributes(typeof(ParseAttribute), true).FirstOrDefault()).Order).ToList();
|
||||
|
||||
foreach (PropertyInfo prop in props)
|
||||
{
|
||||
ParseAttribute attribute = (ParseAttribute)prop.GetCustomAttributes(true).FirstOrDefault();
|
||||
String value = String.Empty;
|
||||
for (int i = 0; i < (attribute.DataElementsToRead == 0 ? 1 : attribute.DataElementsToRead ); i++)
|
||||
value += parts[(i + attribute.Order) - 1] + " ";
|
||||
value = value.Trim();
|
||||
|
||||
MethodInfo parseMethod;
|
||||
if (!String.IsNullOrWhiteSpace(attribute.CustomParser))
|
||||
{
|
||||
parseMethod = response.GetType().GetMethod(attribute.CustomParser,BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
if (parseMethod != null)
|
||||
prop.SetValue(response, parseMethod.Invoke(response, new object[] { value }), null);
|
||||
}
|
||||
else if (prop.PropertyType == typeof(string))
|
||||
prop.SetValue(response, value, null);
|
||||
else
|
||||
{
|
||||
parseMethod = prop.PropertyType.GetMethod("Parse", new Type[] { typeof(String) });
|
||||
prop.SetValue(response, parseMethod.Invoke(null, new object[] { value }), null);
|
||||
}
|
||||
}
|
||||
}
|
||||
public Int32 StatusCode { get; set; }
|
||||
public String Response { get; set; }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user