Reflect_Proxy.cs 11 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.ServiceModel.Security;
using System.Text;
using System.Threading.Tasks;

namespace FObjBase.Reflect
{
    public class Reflect_Proxy : FObj
    {
        Type interfaceType;
        object obj;
        public bool ignoreSet = false;
        List<AnyEvent> anyEvents = new List<AnyEvent>();
        Dictionary<object, string> subProperties = new Dictionary<object, string>();
        public Reflect_Proxy(int objsys_idx, UInt32 id, Type interfaceType, object obj) : base(objsys_idx)
        {
            ID = id;

            this.interfaceType = interfaceType;
            this.obj = obj;
            if(typeof(INotifyPropertyChanged).IsAssignableFrom(interfaceType))
            {
                //继承了INotifyPropertyChanged
                ((INotifyPropertyChanged)(this.obj)).PropertyChanged += Obj_PropertyChanged;
            }

            //处理[PropertyPush]
            InitPropertyPush();

            //注册全部事件
            var eventInfos = this.interfaceType.GetEvents();
            foreach (var eventInfo in eventInfos)
            {
                var pushAttribute = eventInfo.GetCustomAttribute<PushAttribute>();
                if (pushAttribute != null)
                {
                    var anyEvent = new AnyEvent()
                    {
                        eventName = eventInfo.Name,
                        PushObjInfoEx = (msg) => {
                            var buf = Misc.Converter.StringToBytes(msg);
                            CurrObjSys.PushObjInfoEx(
                             this, Reflect_OBJ_INTERFACE.PUSH_Event,
                             buf);
                        }
                    };
                    //这个事件需要推送
                    eventInfo.AddEventHandler(obj, anyEvent.eventHandler);
                    anyEvents.Add(anyEvent);
                }
            }
        }

        void InitPropertyPush() {
            //处理[PropertyPush]
            var propertyInfos = interfaceType.GetProperties();
            foreach (var propertyInfo in propertyInfos)
            {
                if (!IsPropertyPush(propertyInfo))
                    continue;

                InitSubPropertyPush(this.obj.GetType().GetProperty(propertyInfo.Name), this.obj, null);
            }
        }
        bool IsPropertyPush(PropertyInfo propertyInfo) {
            if (propertyInfo.GetCustomAttribute<PropertyPushAttribute>() == null)
                return false;//必须是[PropertyPush]

            if (propertyInfo.CanWrite)
                return false;//它只能是get,不能有set

            if (!typeof(INotifyPropertyChanged).IsAssignableFrom(propertyInfo.PropertyType))
                return false;//必须是从INotifyPropertyChanged派生的

            return true;
        }
        void InitSubPropertyPush(PropertyInfo propertyInfo, object obj, string parentName)
        {
            //下级推送!!!!
            var propertyValue = propertyInfo.GetValue(obj);
            string path = parentName == null ? propertyInfo.Name : $"{parentName}.{propertyInfo.Name}";
            subProperties.Add(propertyValue, path);

            ((INotifyPropertyChanged)(propertyValue)).PropertyChanged += Sub_PropertyChanged;

            //继续向下找
            var subPropertyInfos = propertyInfo.PropertyType.GetProperties();
            foreach (var subPropertyInfo in subPropertyInfos)
            {
                if (!IsPropertyPush(subPropertyInfo))
                    continue;//必须是[PropertyPush]

                InitSubPropertyPush(subPropertyInfo, propertyValue, path);
            }
        }

        class AnyEvent
        {
            public string eventName;
            public Action<string> PushObjInfoEx;
            public EventHandler eventHandler;
            public AnyEvent()
            {
                eventHandler = new EventHandler(Obj_AnyEvent);
            }
            void Obj_AnyEvent(object sender, EventArgs e)
            {

                var rData = new Reflect_OBJ_INTERFACE.ReflectData()
                {
                    name = eventName,
                    data = JObject.FromObject(e)
                };
                string reponse = JsonConvert.SerializeObject(rData);
                PushObjInfoEx?.Invoke(reponse);
            }
        }

        class SubProperty 
        {
            public string propertyName;
            public object value;
        }
        
        private void Obj_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (ignoreSet)//从服务器接收的数据,不用再推送给服务器
                return;

            if (interfaceType == null)
                return;

            var type = interfaceType;

            var propertyInfo = type.GetProperty(e.PropertyName);
            if (propertyInfo == null)
                return;//获取失败!!!

            if(propertyInfo.GetCustomAttribute<JsonIgnoreAttribute>()!=null)
                return;//这个不需要推送
            

            var v = this.obj.GetType().GetProperty(propertyInfo.Name).GetValue(sender);
            var jObject = new JObject();
            jObject.Add(propertyInfo.Name, JToken.FromObject(v));
            string json = jObject.ToString(Formatting.None);
            var buf = Misc.Converter.StringToBytes(json);
            CurrObjSys.PushObjInfoEx(
                this, Reflect_OBJ_INTERFACE.PUSH_PropertyChanged,
                buf);
        }

        private void Sub_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (ignoreSet)//从服务器接收的数据,不用再推送给服务器
                return;
            if (!subProperties.ContainsKey(sender))
                return;//异常, 不是子property

            var type = sender.GetType();

            var propertyInfo = type.GetProperty(e.PropertyName);
            if (propertyInfo == null)
                return;//获取失败!!!

            if (propertyInfo.GetCustomAttribute<JsonIgnoreAttribute>() != null)
                return;//这个不需要推送

            string path = subProperties[sender];
            string[] parentNames = path.Split('.');
            if (parentNames.Count() == 0)
                return;//分解出错

            var v = propertyInfo.GetValue(sender);
            var jObject = new JObject();
            jObject.Add(propertyInfo.Name, JToken.FromObject(v));

            JObject jObject_parent = null;
            for (int i = 0; i < parentNames.Count(); i++) {
                int idx = parentNames.Count() - 1 - i;
                jObject_parent = new JObject();
                jObject_parent.Add(parentNames[idx], jObject);
                jObject = jObject_parent;
            }

            string json = jObject_parent.ToString(Formatting.None);

            CurrObjSys.PushObjInfoEx( this, 
                Reflect_OBJ_INTERFACE.PUSH_PropertyChanged,
                Misc.Converter.StringToBytes(json));
        }

        public override void CallFunction(IFConn from, uint srcid, uint magic, ushort funcid, byte[] infodata)
        {
            switch (funcid)
            {
                case Reflect_OBJ_INTERFACE.CALL_GetAllProperties:
                    {
                        var jObject = new JObject();

                        var type = obj.GetType();

                        var propertyInfos = type.GetProperties();
                        foreach (var propertyInfo in propertyInfos)
                        {
                            var attr = propertyInfo.GetCustomAttribute<JsonIgnoreAttribute>(false);
                            if (attr != null)
                            {
                                return;//这个不需要推送
                            }

                            var v = propertyInfo.GetValue(obj);

                            jObject.Add(propertyInfo.Name, JToken.FromObject(v));
                        }
                        string json = jObject.ToString(Formatting.None);

                        CurrObjSys.PushCallFunctionEx(from, srcid, ID, magic, funcid, Misc.Converter.StringToBytes(json));
                    }
                    break;
                
                case Reflect_OBJ_INTERFACE.CALL_SetProperty:
                    {
                        string json = Misc.Converter.BytesToString(infodata);
                        ignoreSet = true;
                        JsonConvert.PopulateObject(json, obj);
                        ignoreSet = false;
                    }
                    break;

                case Reflect_OBJ_INTERFACE.CALL_MethodInvoke:
                    {
                        string json = Misc.Converter.BytesToString(infodata);
                        var rData = JsonConvert.DeserializeObject<Reflect_OBJ_INTERFACE.ReflectData>(json);
                        var type = obj.GetType();
                        var methodInfo = type.GetMethod(rData.name);
                        var parameterInfos = methodInfo.GetParameters();
                        object[] parameters = new object[parameterInfos.Count()];
                        for (int i = 0; i < parameters.Count(); i++)
                        {
                            var ptype = parameterInfos[i].ParameterType;
                            var pname = parameterInfos[i].Name;
                            if (string.Compare(pname,"asyncDelegate",true)==0)
                            {
                                parameters[i] = new AsyncCBHandler(asyncDelegate);
                            }
                            else if (string.Compare(pname, "asyncContext", true) == 0)
                            {
                                parameters[i] = new CC { from = from, srcid = srcid, magic = magic, methodName = rData.name };
                            }
                            else
                            {
                                parameters[i] = rData.data[pname].ToObject(ptype);
                            }
                        }
                        methodInfo.Invoke(obj, parameters);
                    }
                    break;
            }
        }
        void asyncDelegate(object asyncContext, object retData)
        {
            var cc = (CC)asyncContext;
            
            var rData = new Reflect_OBJ_INTERFACE.ReflectData()
            {
                name = cc.methodName,
                data = JToken.FromObject(retData)
            };

            string json = JsonConvert.SerializeObject(rData);
            CurrObjSys.PushCallFunctionEx(
                cc.from,
                cc.srcid,
                ID,
                cc.magic,
                Reflect_OBJ_INTERFACE.CALL_MethodInvoke,
                Misc.Converter.StringToBytes(json));
        }
        class CC
        {
            public IFConn from;
            public UInt32 srcid;
            public UInt32 magic;
            public string methodName;
        }
    }
}