view datagear/dg/MessagePackDataGear.cs @ 56:dc3f59937772

remote dynamic
author riono <e165729@ie.u-ryukyu.ac.jp>
date Tue, 25 Jan 2022 16:46:26 +0900
parents 476b6efeca5b
children
line wrap: on
line source

using System;
using System.Collections.Generic;
using System.Diagnostics;
using Christie_net.Test.Example.RemoteTake;
using MessagePack;

namespace Christie_net.datagear.dg {
public class MessagePackDataGear<T> : DataGear<T> {
    private int dataSize;
    private byte[] messagePack;
    private readonly object syncObject = new object();

    public MessagePackDataGear(T data) : base(data) {
        GetMessagePack();
    }

    public MessagePackDataGear(Type clazz) : base(clazz) { }

    public MessagePackDataGear(byte[] messagePack, Type clazz) : base(clazz) {
        //Console.WriteLine("call");
        this.messagePack = messagePack;
    }

    public byte[] GetMessagePack() {
        if (messagePack != null)
            return messagePack;
        try {
            messagePack = MessagePackSerializer.Serialize(data);

            SetDataSize(messagePack.Length);
        } catch (Exception e) {
            Console.WriteLine("\n" + e.ToString());
        }

        return messagePack;
    }

    public override T GetData() {
        lock (syncObject) {
            if (data == null)
                try {
                    var dataObj = MessagePackSerializer.Deserialize<T>(messagePack);
                    var convertData = MessagePackDataFormed(dataObj);


                    SetData(convertData);
                } catch (Exception e) {
                    Console.WriteLine(e.StackTrace);
                }

            return base.GetData();
        }
    }

    public void SetDataSize(int dataSize) {
        this.dataSize = dataSize;
    }

    // If deserialize data is not primitive type, it is dictionary 
    public T MessagePackDataFormed(dynamic deserializedData) {
        var type = deserializedData.GetType();
        T instance;
        
        if (type.IsPrimitive || type == typeof(string) || type == typeof(decimal)) {
            instance = Convert.ChangeType(deserializedData, clazz);
        } else {
            List<object> valueArray = new List<object>();
            foreach (var VARIABLE in (dynamic) deserializedData) {
                Console.WriteLine("val:" + VARIABLE);
                valueArray.Add(VARIABLE.Value);
            }

            object[] convertArray = valueArray.ToArray();

            instance = (T) Activator.CreateInstance(clazz, convertArray);
        }
        return instance;
    }
}
}