Reflect_Proxy.cs 16.4 KB
Newer Older
潘栩锋's avatar
潘栩锋 committed
1 2 3 4 5 6 7 8 9 10 11 12 13
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
{
潘栩锋's avatar
潘栩锋 committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
    /// <summary>
    /// obj 服务代理;
    /// 1.如果代理的对象为 INotifyPropertyChanged, 对象内的 property 改变,能推送给客户端( [JsonIgnore] 除外);
    /// 2.代理的对象不为INotifyPropertyChanged, 但 对象内的 property 
    ///     a.是 [PropertyPush], 
    ///     b.且是 INotifyPropertyChanged, 
    ///     c.且 只能是get,不能有set,
    /// 那这个 property 内的 子property 改变,也会推送给 客户端 且 子property 是 [PropertyPush],会继续向下全部注册 PropertyChanged,
    /// 也推送给 客户端;
    /// 3. 客户端 可以通过 Call(.....) 调用 服务 的function,  function返回的内容,需要通过[Call(...)] 定义; 且function 必须是
    /// void function(object param1, object param2,object paramN, AsyncCBHandler asyncDelegate, object asyncContext);
    /// 必须有参数 AsyncCBHandler asyncDelegate, object asyncContext, 名字不能改。 前面的 param1~paramN, 多少个都行
    /// 4. 服务中的event, 通过 [Push(...)] 可以推送给客户端, 但event 只能是 EventHandler
    /// [Push(typeof(BulkDBTempFrameChangedEventArgs))]
    ///  public event EventHandler TempFrameChanged;
    ///  
    /// </summary>
潘栩锋's avatar
潘栩锋 committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
    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>();
        List<string> properties = new List<string>();

        public Reflect_Proxy(int objsys_idx, UInt32 id, Type interfaceType, object obj) : base(objsys_idx)
        {
            ID = id;

            this.interfaceType = interfaceType;
            this.obj = obj;

潘栩锋's avatar
潘栩锋 committed
47 48 49 50 51 52 53
            if (interfaceType == null)
                throw new Exception($"Reflect_Proxy 出错,obj = {obj.GetType()} interfaceType=null");

            //if (!interfaceType.IsAssignableFrom(obj.GetType()))
            //    throw new Exception($"Reflect_Proxy 出错,obj = {obj.GetType()} interfaceType={interfaceType}, obj 非继承于 interfaceType");

            //注册 obj 的PropertyChanged 事件,获取 interfaceType 全部属性名称,包括它的父类的全部属性名称
潘栩锋's avatar
潘栩锋 committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
            InitPropertyChanged();

            //处理[PropertyPush]
            InitPropertyPush();

            //处理[Push]
            InitEventPush();
        }
        void InitPropertyChanged() 
        {
            if (!typeof(INotifyPropertyChanged).IsAssignableFrom(interfaceType))
                return;

            //继承了INotifyPropertyChanged
            ((INotifyPropertyChanged)(this.obj)).PropertyChanged += Obj_PropertyChanged;

潘栩锋's avatar
潘栩锋 committed
70
            var propertyInfos = GetAllPropertyInfos();//获取全部属性, 包括父类的属性
潘栩锋's avatar
潘栩锋 committed
71

潘栩锋's avatar
潘栩锋 committed
72
            //获取全部属性的名称,放入 properties
潘栩锋's avatar
潘栩锋 committed
73 74 75 76 77
            foreach (var propertyInfo in propertyInfos) {
                
                if (propertyInfo.GetCustomAttribute<JsonIgnoreAttribute>() != null)
                    continue;//这个不需要推送

潘栩锋's avatar
潘栩锋 committed
78
                if (properties.Contains(propertyInfo.Name))//子类 有与 父类一样的名字的属性,忽略它
潘栩锋's avatar
潘栩锋 committed
79 80 81 82
                    continue;
                properties.Add(propertyInfo.Name);
            }
        }
潘栩锋's avatar
潘栩锋 committed
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

        /// <summary>
        /// 获取全部属性, 包括父类的属性
        /// </summary>
        /// <returns></returns>
        List<PropertyInfo> GetAllPropertyInfos() {
            var interfaceTypes = new List<Type>();
            interfaceTypes.Add(this.interfaceType);
            interfaceTypes.AddRange(this.interfaceType.GetInterfaces());
            var propertyInfos = new List<PropertyInfo>();//获取全部属性, 包括父类的属性
            foreach (var ifaceType in interfaceTypes)
            {
                propertyInfos.AddRange(ifaceType.GetProperties());
            }
            return propertyInfos;
        }

潘栩锋's avatar
潘栩锋 committed
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
        void InitEventPush() 
        {
            var interfaceTypes = new List<Type>();

            interfaceTypes.Add(this.interfaceType);
            interfaceTypes.AddRange(this.interfaceType.GetInterfaces());


            var eventInfos = new List<EventInfo>();
            foreach (var ifaceType in interfaceTypes) {
                eventInfos.AddRange(ifaceType.GetEvents());
            }
            
            foreach (var eventInfo in eventInfos)
            {
                var pushAttribute = eventInfo.GetCustomAttribute<PushAttribute>();
                if (pushAttribute == null)
                    continue;

                if (anyEvents.Any(ae => ae.eventName == eventInfo.Name))
                    continue;//已经添加了

                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);
                
            }
        }
潘栩锋's avatar
潘栩锋 committed
138 139
        
        
潘栩锋's avatar
潘栩锋 committed
140 141 142
        void InitPropertyPush() {
            //处理[PropertyPush]

潘栩锋's avatar
潘栩锋 committed
143
            var propertyInfos = GetAllPropertyInfos();//获取全部属性, 包括父类的属性
潘栩锋's avatar
潘栩锋 committed
144 145 146 147 148 149 150 151 152

            foreach (var propertyInfo in propertyInfos)
            {
                if (!IsPropertyPush(propertyInfo))
                    continue;

                if (!properties.Contains(propertyInfo.Name)) {
                    properties.Add(propertyInfo.Name);
                }
潘栩锋's avatar
潘栩锋 committed
153 154 155
                //这个属性可能是 父类的, interfaceType可能没有;
                //obj 肯定有
                //继续枚举 propertyInfo 下面的 [PropertyPush]
潘栩锋's avatar
潘栩锋 committed
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
                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);
            }
        }


        
        private void Obj_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
217 218
            //if (ignoreSet)//从服务器接收的数据,不用再推送给服务器
            //    return;
潘栩锋's avatar
潘栩锋 committed
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240

            if (interfaceType == null)
                return;

            if (!properties.Contains(e.PropertyName))
                return;//这个不需要推送

            var v = this.obj.GetType().GetProperty(e.PropertyName).GetValue(sender);
            var jObject = new JObject();
            if(v == null)
                jObject.Add(e.PropertyName, null);
            else
                jObject.Add(e.PropertyName, 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)
        {
241 242
            //if (ignoreSet)//从服务器接收的数据,不用再推送给服务器
            //    return;
潘栩锋's avatar
潘栩锋 committed
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 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
            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();
            if(v == null)
                jObject.Add(propertyInfo.Name, null);
            else
                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();

                        foreach (var propertyName in properties)
                        {
                            var propertyInfo = type.GetProperty(propertyName);
                            var v = propertyInfo.GetValue(obj);
                            if(v == null)
                                jObject.Add(propertyInfo.Name, null);
                            else
                                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);
310
                        //ignoreSet = true;
潘栩锋's avatar
潘栩锋 committed
311
                        JsonConvert.PopulateObject(json, obj);
312
                        //ignoreSet = false;
潘栩锋's avatar
潘栩锋 committed
313 314 315 316 317 318 319 320
                    }
                    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();
321 322 323 324 325 326 327 328
                        var paramNames_req = rData.data.Children().OfType<JProperty>().Select(p => p.Name);
                        MethodInfo methodInfo = GetMethodInfo(type, rData.name, paramNames_req);
                        if (methodInfo == null)
                        {
                            //不能找到,
                            throw new Exception($"程序写错了, 不能找到 rData.name={rData.name} 或者 参数名称不对,没法完全匹配");
                        }

潘栩锋's avatar
潘栩锋 committed
329 330 331 332 333 334
                        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;
335
                            if (string.Compare(pname, Reflect_OBJ_INTERFACE.asyncDelegate, true) == 0)
潘栩锋's avatar
潘栩锋 committed
336 337 338
                            {
                                parameters[i] = new AsyncCBHandler(asyncDelegate);
                            }
339
                            else if (string.Compare(pname, Reflect_OBJ_INTERFACE.asyncContext, true) == 0)
潘栩锋's avatar
潘栩锋 committed
340 341 342 343 344 345 346 347 348
                            {
                                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);
349
                        
潘栩锋's avatar
潘栩锋 committed
350 351 352 353
                    }
                    break;
            }
        }
354 355 356 357 358 359 360 361 362 363 364 365 366
        MethodInfo GetMethodInfo(Type type, string name, IEnumerable<string> parameterNames) 
        {
            
            var methodInfos = from mi in type.GetMethods() where mi.Name == name select mi;
            if(methodInfos.Count()==0)
                return null;
            if (methodInfos.Count() == 1)
                return methodInfos.First();

            //必须完全匹配
            foreach (var methodInfo in methodInfos)
            {
                var parameterInfos = methodInfo.GetParameters();
367 368 369
                //全部参数名称
                var names = parameterInfos.Select(pi => pi.Name).ToList();
                //删除掉 asyncDelegate,asyncContext
370 371
                names.Remove(Reflect_OBJ_INTERFACE.asyncDelegate);
                names.Remove(Reflect_OBJ_INTERFACE.asyncContext);
372
                
373 374
                var names_req = parameterNames;

375 376 377 378 379 380 381 382 383 384 385
                if (names.Count() != names_req.Count())
                    continue;//数量不一致,肯定不同

                var sames = names_req.Intersect(names);

                if (sames.Count() != names_req.Count())
                    continue;// names 与 names_req 的交集数量与names_req不一样,肯定不同

                //就是它
                return methodInfo;

386 387 388
            }
            return null;
        }
潘栩锋's avatar
潘栩锋 committed
389 390 391 392 393 394 395
        void asyncDelegate(object asyncContext, object retData)
        {
            var cc = (CC)asyncContext;
            
            var rData = new Reflect_OBJ_INTERFACE.ReflectData()
            {
                name = cc.methodName,
396
                data = retData==null?null:JToken.FromObject(retData)
潘栩锋's avatar
潘栩锋 committed
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
            };

            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;
        }
    }
}