Пример #1
0
 public void UpdateDelegate(DelegateData delegateData)
 {
     var sessionDelegate = delegateRepository.Find(delegateData.SessionDelegateId);
     sessionDelegate.Update(delegateData);
     delegateRepository.Update(sessionDelegate);
     delegateRepository.Save();
 }
Пример #2
0
        public void AddDelegate(DelegateData delegateData)
        {
            var sessionDelegate = new SessionDelegate(delegateData);

            delegateRepository.Insert(sessionDelegate);
            delegateRepository.Save();
        }
        static DelegateData GetDelegateData(Type delegateType)
        {
            DelegateData value;

            if (m_DelegateDatas.TryGetValue(delegateType, out value))
            {
                return(value);
            }
            var data       = new DelegateData();
            var method     = delegateType.GetMethod("Invoke");
            var parameters = method.GetParameters();
            var length     = parameters.Length;
            var isVoid     = method.ReturnType == Util.TYPE_VOID;
            var types      = new Type[isVoid ? length : length + 1];

            for (var i = 0; i < length; ++i)
            {
                types[i] = parameters[i].ParameterType;
            }
            data.length = length;
            if (isVoid)
            {
                data.types = types;
                data.ret   = false;
            }
            else
            {
                types[length] = method.ReturnType;
                data.types    = types;
                data.ret      = true;
            }
            return(m_DelegateDatas[delegateType] = data);
        }
Пример #4
0
        public void UpdateDelegate(DelegateData delegateData)
        {
            var sessionDelegate = delegateRepository.Find(delegateData.SessionDelegateId);

            sessionDelegate.Update(delegateData);
            delegateRepository.Update(sessionDelegate);
            delegateRepository.Save();
        }
Пример #5
0
        public static void AddDelegate(string scheme, GamebaseCallback.DataDelegate <NativeMessage> eventDelegate, GamebaseCallback.DataDelegate <NativeMessage> pluginEventDelegate = null)
        {
            DelegateData delegateData = new DelegateData();

            delegateData.eventDelegate       = eventDelegate;
            delegateData.pluginEventDelegate = pluginEventDelegate;

            delegateDictionary.Add(scheme, delegateData);
        }
Пример #6
0
        internal TFunc DeserializeForDebug <TFunc>(DelegateData delegateData) where TFunc : class
        {
            AssemblyBuilder assemblyBuilder = null;
            ModuleBuilder   moduleBuilder   = null;
            var             method          = BuildAssembly(delegateData, ref assemblyBuilder, ref moduleBuilder, saveAssembly: true);

            assemblyBuilder.Save("asm.dll");
            return(method.CreateDelegate(typeof(TFunc)) as TFunc);
        }
Пример #7
0
        public TFunc Deserialize <TFunc>(DelegateData m) where TFunc : class
        {
            var method = new DynamicMethod(Guid.NewGuid().ToString(), typeResolver.GetType(m.ReturnType),
                                           typeResolver.GetTypes(m.ParametersType), true);
            AssemblyBuilder assemblyBuilder = null;
            ModuleBuilder   moduleBuilder   = null;

            BuildMethod(m, method.GetILGenerator(), ref assemblyBuilder, ref moduleBuilder);
            return(method.CreateDelegate(typeof(TFunc)) as TFunc);
        }
        public static DelegateData GetDelegate(string scheme)
        {
            DelegateData delegateData = null;

            if (delegateDictionary.TryGetValue(scheme, out delegateData) == true)
            {
                return(delegateData);
            }

            return(null);
        }
Пример #9
0
    public void AddMethod(Component c, MethodInfo method)
    {
        Type   type      = typeof(OnEventTrigger);
        string name      = method.Name;
        string strIdx    = c.name + "::" + method.Name;
        var    mDelegate = (OnEventTrigger)
                           Delegate.CreateDelegate(type, c, method);

        MethodDict[strIdx] = new DelegateData(name, c, mDelegate);

        AddMethodName(strIdx);
    }
Пример #10
0
        private MethodInfo BuildAssembly(DelegateData delegateData,
                                         ref AssemblyBuilder assemblyBuilder,
                                         ref ModuleBuilder moduleBuilder,
                                         bool saveAssembly = false)
        {
            var assemblyName = string.Format("DelegateSerializer_{0}", Guid.NewGuid());
            var typeName     = string.Format("InternalDelegate_{0}", Guid.NewGuid());

            if (assemblyBuilder == null)
            {
                if (saveAssembly)
                {
                    assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(AssemblyFileName),
                                                                                    AssemblyBuilderAccess.RunAndSave);
                }

                else
                {
                    assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
                        new AssemblyName(assemblyName),
                        AssemblyBuilderAccess.RunAndSave);
                }
            }

            if (moduleBuilder == null)
            {
                if (saveAssembly)
                {
                    moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName, AssemblyFileName);
                }
                else
                {
                    moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName);
                }
            }

            var typeBuilder   = moduleBuilder.DefineType(typeName, TypeAttributes.Public, null);
            var methodName    = "Delegate";
            var methodBuilder = typeBuilder.DefineMethod(methodName,
                                                         MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig,
                                                         typeResolver.GetType(delegateData.ReturnType),
                                                         typeResolver.GetTypes(delegateData.ParametersType));

            BuildMethod(delegateData, methodBuilder.GetILGenerator(), ref assemblyBuilder, ref moduleBuilder);
            var type = typeBuilder.CreateType();

            var method = typeResolver.GetMethod(type, methodName, typeResolver.GetTypes(delegateData.ParametersType), new Type[0]);

            return(method);
        }
Пример #11
0
        /// <summary>
        /// Method for adding a delegate to the collection.
        /// </summary>
        /// <param name="type">Type of the class containing the delegate</param>
        /// <param name="eventInfo">MethodInfo for the method to be invoked by the delegate</param>
        public void AddDelegate(Type type, MethodInfo eventInfo)
        {
            if (delegateNameDictionary.ContainsKey(type + "_" + eventInfo.Name))
            {
                Debug.Log("Warning: tried to add event delegate " + eventInfo.Name + " for module " + type + ", but an entry already exists!");
                return;
            }
            BuildingEvents eventID     = (BuildingEvents)Enum.Parse(typeof(BuildingEvents), eventInfo.Name);
            var            delType     = EventMap[eventID];
            Delegate       newDelegate = Delegate.CreateDelegate(delType, eventInfo);

            DelegateData newDelegateData = new DelegateData(newDelegate, delType, type, eventID);

            delegates.Add(newDelegateData);
            delegateEventMapping[eventID].Add(newDelegateData);
            delegateNameDictionary[newDelegateData.name] = newDelegateData;
        }
Пример #12
0
        public static void unHookDelegate(object callingObject, DelegateData dd)
        {
            List <object> lst = new List <object>(10);

            if (String.IsNullOrEmpty(dd.SourceName))
            {
                lst.Add(callingObject);
            }
            else
            {
                lst = getWindows(dd.SourceName, callingObject);
            }

            //List<object>
            foreach (object obj in lst)
            {
                unHookDelegate(obj, dd.Target, dd.EventName, dd.FunctionName, callingObject);
            }
        }
Пример #13
0
        private void BackGrounForeachCallType(QueryQQParam param)
        {//backGroundwork
            string       key    = ForachCallEvent.PickUpUin.ToString();
            DelegateData delete = new DelegateData()
            {
                BaseDelegateParam = param
            };

            //要实现定时
            if (BackGroundCallRunEvent.ContainsKey(key))
            {
                BackGroundCallRunEvent.Remove(key);
            }
            if (ckStartQuartz.Checked && rbGuid.Checked)
            {//开启随机轮询
                delete.BaseDel = QuartzGuidForach;
                BackGroundCallRunEvent.Add(key, delete);
                //QuartzGuidForach(param);
            }
            else if (ckStartQuartz.Checked && rbDepth.Checked)
            {//该查询结果页轮询
                delete.BaseDel = QuartzForeachPage;
                BackGroundCallRunEvent.Add(key, delete);
                //QuartzForeachPage(param);
            }
            else if (ckStartQuartz.Checked)
            {
                delete.BaseDel = QuartzCallBack;
                BackGroundCallRunEvent.Add(key, delete);
                //QuartzCallBack(param);
            }
            else
            {
                //只查询一遍
                JustQuery(param);
            }
        }
Пример #14
0
        private void BackGroundDoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bg = sender as BackgroundWorker;

            while (true)
            {
                if (BackGroundCallRunEvent.Count > 0)
                {
                    foreach (KeyValuePair <string, DelegateData> item in BackGroundCallRunEvent)
                    {
                        System.Threading.Tasks.Task.Factory.StartNew(() =>
                        {
                            DelegateData delete = item.Value;
                            delete.BaseDel(delete.BaseDelegateParam);
                        });
                    }
                    Thread.Sleep(intervalSec * 1000);//20秒执行一次
                }
                else
                {
                    return;
                }
            }
        }
Пример #15
0
        private void BuildMethod(DelegateData m, ILGenerator il, ref
                                 AssemblyBuilder assemblyBuilder, ref ModuleBuilder moduleBuilder)
        {
            foreach (var localVariable in m.LocalVariables)
            {
                localVariableInfoDataConverter.Emit(il, localVariable);
            }

            var labels = new Dictionary <int, Label>();

            foreach (var ilInstruction in m.Instructions)
            {
                if (((OpCodeValues)ilInstruction.Code).IsLabel())
                {
                    var instruction = (int)ilInstruction.Operand;
                    if (!labels.ContainsKey(instruction))
                    {
                        labels.Add(instruction, il.DefineLabel());
                    }
                }
            }

            foreach (var ilInstruction in m.Instructions)
            {
                foreach (var clause in m.ExceptionHandlingClauses)
                {
                    exceptionHandlingClauseDataConverter.Emit(il, ilInstruction.Offset, clause);
                }

                var opCodeValues = (OpCodeValues)(ilInstruction.Code);
                var code         = opCodeValues.GetOpCode();
                if (labels.ContainsKey(ilInstruction.Offset))
                {
                    il.MarkLabel(labels[ilInstruction.Offset]);
                }

                var operand = ilInstruction.Operand;
                if (ilInstruction.OperandDelegateData != null)
                {
                    il.Emit(code, BuildAssembly(ilInstruction.OperandDelegateData, ref assemblyBuilder, ref moduleBuilder));
                }
                else if (ilInstruction.OperandConstructor != null)
                {
                    il.Emit(code, typeResolver.GetConstructor(ilInstruction.OperandConstructor));
                }
                else if (ilInstruction.OperandMethod != null)
                {
                    il.Emit(code, typeResolver.GetMethod(ilInstruction.OperandMethod));
                }
                else if (ilInstruction.OperandType != null)
                {
                    il.Emit(code, typeResolver.GetType(ilInstruction.OperandType));
                }
                else if (opCodeValues.IsLabel())
                {
                    il.Emit(code, labels[(int)ilInstruction.Operand]);
                }
                else if (operand is sbyte)
                {
                    il.Emit(code, (sbyte)operand);
                }
                else if (operand is byte)
                {
                    il.Emit(code, (byte)operand);
                }
                else if (operand is int)
                {
                    il.Emit(code, (int)operand);
                }
                else if (operand is long)
                {
                    il.Emit(code, (long)operand);
                }
                else if (operand is string)
                {
                    il.Emit(code, (string)operand);
                }
                else if (!(operand is Type))
                {
                    if (operand != null)
                    {
                        throw new DelegateDeserializationException(
                                  string.Format("Unknown operand type {0} for opCode {1}", operand.GetType(), opCodeValues));
                    }
                    il.Emit(code);
                }
            }
        }
Пример #16
0
        internal CallConversionParameters(CallConversionInfo conversionInfo, IntPtr callerTransitionBlockParam)
        {
            // Make sure the thred static variable has been initialized for this thread
            s_pinnedGCHandles = s_pinnedGCHandles ?? new GCHandleContainer();

            _conversionInfo            = conversionInfo;
            _callerTransitionBlock     = (byte *)callerTransitionBlockParam.ToPointer();
            _functionPointerToCall     = conversionInfo.TargetFunctionPointer;
            _instantiatingStubArgument = conversionInfo.InstantiatingStubArgument;
            _delegateData                 = default(DelegateData);
            _calleeArgs                   = default(ArgIterator);
            _invokeReturnValue            = IntPtr.Zero;
            _copyReturnValue              = true;
            _dynamicInvokeParams          = null;
            _dynamicInvokeByRefObjectArgs = null;

            //
            // Setup input argument iterator for the caller
            //
            ArgIteratorData callerIteratorData;

            if (conversionInfo.IsDelegateDynamicInvokeThunk)
            {
                callerIteratorData = s_delegateDynamicInvokeImplArgIteratorData;
            }
            else if (conversionInfo.IsReflectionDynamicInvokerThunk)
            {
                callerIteratorData = s_reflectionDynamicInvokeImplArgIteratorData;
            }
            else
            {
                callerIteratorData = conversionInfo.ArgIteratorData;
            }

            _callerArgs = new ArgIterator(callerIteratorData,
                                          callerIteratorData.HasThis() ?
                                          CallingConvention.ManagedInstance :
                                          CallingConvention.ManagedStatic,
                                          conversionInfo.CallerHasParamType,
                                          conversionInfo.CallerHasExtraParameterWhichIsFunctionTarget,
                                          conversionInfo.CallerForcedByRefData,
                                          false, false);     // Setup input

            bool forceCalleeHasParamType = false;

            // If the callee MAY have a param type, we need to know before we create the callee arg iterator
            // To do this we need to actually load the target address and see if it has the generic method pointer
            // bit set.
            if (conversionInfo.CalleeMayHaveParamType)
            {
                ArgIterator callerArgsLookupTargetFunctionPointer = new ArgIterator(conversionInfo.ArgIteratorData,
                                                                                    conversionInfo.ArgIteratorData.HasThis() ?
                                                                                    CallingConvention.ManagedInstance :
                                                                                    CallingConvention.ManagedStatic,
                                                                                    conversionInfo.CallerHasParamType,
                                                                                    conversionInfo.CallerHasExtraParameterWhichIsFunctionTarget,
                                                                                    conversionInfo.CallerForcedByRefData,
                                                                                    false, false);

                // Find the last valid caller offset. That's the offset of the target function pointer.
                int ofsCallerValid = TransitionBlock.InvalidOffset;
                while (true)
                {
                    // Setup argument offsets.
                    int ofsCallerTemp = callerArgsLookupTargetFunctionPointer.GetNextOffset();

                    // Check to see if we've handled all the arguments that we are to pass to the callee.
                    if (TransitionBlock.InvalidOffset == ofsCallerTemp)
                    {
                        break;
                    }

                    ofsCallerValid = ofsCallerTemp;
                }

                if (ofsCallerValid == TransitionBlock.InvalidOffset)
                {
                    throw new InvalidProgramException();
                }

                int stackSizeCaller = callerArgsLookupTargetFunctionPointer.GetArgSize();
                Debug.Assert(stackSizeCaller == IntPtr.Size);
                void * pSrc = _callerTransitionBlock + ofsCallerValid;
                IntPtr tempFunctionPointer = *((IntPtr *)pSrc);

                forceCalleeHasParamType = UpdateCalleeFunctionPointer(tempFunctionPointer);
            }

            // Retrieve target function pointer and instantiation argument for delegate thunks
            if (conversionInfo.IsDelegateThunk)
            {
                Debug.Assert(_callerArgs.HasThis() && !_conversionInfo.IsUnboxingThunk);

                IntPtr locationOfThisPointer = (IntPtr)(_callerTransitionBlock + ArgIterator.GetThisOffset());
                _delegateData._delegateObject = (Delegate)Unsafe.As <IntPtr, Object>(ref *(IntPtr *)locationOfThisPointer);
                Debug.Assert(_delegateData._delegateObject != null);

                RuntimeAugments.GetDelegateData(
                    _delegateData._delegateObject,
                    out _delegateData._firstParameter,
                    out _delegateData._helperObject,
                    out _delegateData._extraFunctionPointerOrData,
                    out _delegateData._functionPointer);

                if (conversionInfo.TargetDelegateFunctionIsExtraFunctionPointerOrDataField)
                {
                    if (conversionInfo.IsOpenInstanceDelegateThunk)
                    {
                        _delegateData._boxedFirstParameter = BoxedCallerFirstArgument;
                        Debug.Assert(_delegateData._boxedFirstParameter != null);
                        _callerArgs.Reset();

                        IntPtr resolvedTargetFunctionPointer = OpenMethodResolver.ResolveMethod(_delegateData._extraFunctionPointerOrData, _delegateData._boxedFirstParameter);
                        forceCalleeHasParamType = UpdateCalleeFunctionPointer(resolvedTargetFunctionPointer);
                    }
                    else
                    {
                        forceCalleeHasParamType = UpdateCalleeFunctionPointer(_delegateData._extraFunctionPointerOrData);
                    }
                }
                else if (conversionInfo.IsMulticastDelegate)
                {
                    _delegateData._multicastTargetCount = (int)_delegateData._extraFunctionPointerOrData;
                }
            }

            //
            // Setup output argument iterator for the callee
            //
            _calleeArgs = new ArgIterator(conversionInfo.ArgIteratorData,
                                          (conversionInfo.ArgIteratorData.HasThis() && !conversionInfo.IsStaticDelegateThunk) ?
                                          CallingConvention.ManagedInstance :
                                          CallingConvention.ManagedStatic,
                                          forceCalleeHasParamType || conversionInfo.CalleeHasParamType,
                                          false,
                                          conversionInfo.CalleeForcedByRefData,
                                          conversionInfo.IsOpenInstanceDelegateThunk,
                                          conversionInfo.IsClosedStaticDelegate);

            // The function pointer, 'hasParamType', and 'hasThis' flags for the callee arg iterator need to be computed/read from the caller's
            // input arguments in the case of a reflection invoker thunk (the target method pointer and 'hasThis' flags are
            // passed in as parameters from the caller, not loaded from a static method signature in native layout)
            if (conversionInfo.IsReflectionDynamicInvokerThunk)
            {
                ComputeCalleeFlagsAndFunctionPointerForReflectionInvokeThunk();
            }

#if CALLINGCONVENTION_CALLEE_POPS
            // Ensure that the count of bytes in the stack is available
            _callerArgs.CbStackPop();
#endif
        }
Пример #17
0
 public SessionDelegate(DelegateData delegateData)
 {
     throw new NotImplementedException();
 }
Пример #18
0
 public void Update(DelegateData delegateData)
 {
     throw new NotImplementedException();
 }
Пример #19
0
        private void btnQuery_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Cookie))
            {
                rtbTip.Text = "please  login,and get cookie,and continue";
                return;
            }
            //
            int    interval = 0;
            string inter    = txtTimeSpan.Text;

            int.TryParse(inter, out interval);
            if (interval > 0)
            {
                intervalSec = interval;
            }
            else
            {
                interval = intervalSec;
            }
            int    repeact = 0;
            string rep     = txtRepeact.Text;

            int.TryParse(rep, out repeact);
            QQDataDA das  = new QQDataDA();
            string   path = LogPrepare.GetLogPath();

            LoggerWriter.CreateLogFile(Cookie, das.GeneratePathTimeSpan(Cookie), ELogType.SessionOrCookieLog);
            Uin = das.GetUinFromCookie(Cookie);//当前登录的账户
            //useralias  这是提取账户名称的元素
            QueryQQParam             param = GetBaseQueryParam();
            ParameterizedThreadStart pth;

            if (!ckStartQuartz.Checked)
            {//不进行轮询
                JustQuery(param);
            }
            else if (!ckBackGroundCall.Checked)
            {
                #region 进行的是quartz.net轮询调度
                if (ckStartQuartz.Checked && rbGuid.Checked)
                {//开启随机轮询
                    DelegateData.BaseDelegate del = QuartzGuidForach;
                    QuartzJobParam            p   = new QuartzJobParam()
                    {
                        JobExecutionContextJobDataMap = new object[] { del, param, null },
                        StartTime        = DateTime.Now.AddSeconds(interval),
                        TriggerRepeat    = repeact,
                        TrigggerInterval = interval
                    };
                    pth = new ParameterizedThreadStart(BackstageRun <JobDelegateFunction>);
                    Thread th = new Thread(pth);
                    th.Start(p);
                    // job.CreateJobWithParam<JobDelegateFunction>(new object[] { del, param,null }, DateTime.Now.AddSeconds(interval), interval, repeact);
                }
                else if (ckStartQuartz.Checked && rbDepth.Checked)
                {//该查询结果页轮询
                    DelegateData.BaseDelegate del = QuartzForeachPage;
                    QuartzJobParam            p   = new QuartzJobParam()
                    {
                        JobExecutionContextJobDataMap = new object[] { del, null, null },
                        StartTime        = DateTime.Now.AddSeconds(interval),
                        TriggerRepeat    = repeact,
                        TrigggerInterval = interval
                    };
                    pth = new ParameterizedThreadStart(BackstageRun <JobDelegateFunction>);
                    Thread th = new Thread(pth);
                    th.Start(p);
                    //job.CreateJobWithParam<JobDelegateFunction>(new object[] { del, null,null }, DateTime.Now.AddSeconds(interval), interval, repeact);
                }
                else if (ckStartQuartz.Checked)
                {
                    DelegateData.BaseDelegate del = QuartzCallBack;
                    QuartzJobParam            p   = new QuartzJobParam()
                    {
                        JobExecutionContextJobDataMap = new object[] { Cookie, param, del },
                        StartTime        = DateTime.Now.AddSeconds(interval),
                        TriggerRepeat    = repeact,
                        TrigggerInterval = interval
                    };
                    pth = new ParameterizedThreadStart(BackstageRun <JobAction <QQDataDA> >);
                    Thread th = new Thread(pth);
                    th.Start(p);
                    // job.CreateJobWithParam<JobAction<QQDataDA>>(new object[] { Cookie, param, del }, DateTime.Now, interval, repeact);
                }
                else
                {
                    JustQuery(param);
                }
                #endregion
            }
            else if (ckBackGroundCall.Checked && ckStartQuartz.Checked)
            {//轮询但是使用的是后台进程
                #region 使用的是后台进程
                BackGrounForeachCallType(param);
                #endregion
            }
            #region 数据同步到核心库
            if (ckSyncUin.Checked)
            { //同步数据
                string key = ForachCallEvent.SyncUinToCodeDB.ToString();
                if (BackGroundCallRunEvent.ContainsKey(key))
                {
                    BackGroundCallRunEvent.Remove(key);
                }
                DelegateData del = new DelegateData()
                {
                    BaseDel = BackGrounSyncUinToCoreDB, BaseDelegateParam = null
                };
                BackGroundCallRunEvent.Add(key, del);
            }
            #endregion
            if (!backRun.IsBusy)
            {
                backRun.RunWorkerAsync();
            }
        }
        public DelegateData Serialize(MethodInfo methodInfo)
        {
            var methodBody = methodInfo.GetMethodBody();

            if (methodBody == null)
            {
                return(null);
            }

            var fieldsToLocals = new Dictionary <string, int>();
            var result         = new DelegateData();

            result.ReturnType     = typeInfoDataConverter.Build(methodInfo.ReturnType);
            result.ParametersType = methodInfo.GetParameters()
                                    .Select(info => typeInfoDataConverter.Build(info.ParameterType))
                                    .ToArray();
            result.ExceptionHandlingClauses = methodBody.ExceptionHandlingClauses
                                              .Select(c => exceptionHandlingClauseDataConverter.Build(c))
                                              .ToArray();
            result.LocalVariables = new List <LocalVariableInfoData>();
            foreach (var localVariable in methodBody.LocalVariables)
            {
                result.LocalVariables.Add(localVariableInfoDataConverter.Build(localVariable));
            }

            result.Instructions = new List <ILInstructionData>();
            foreach (var instruction in MethodReader.Read(methodInfo))
            {
                //Console.WriteLine(instruction);
                var operand = instruction.Operand;
                var code    = (OpCodeValues)(instruction.Code.Value & 0xffff);

                var il = new ILInstructionData();

                if (!methodInfo.IsStatic)
                {
                    if (code == OpCodeValues.Ldarg_0)
                    {
                        throw new DelegateSerializationException("Method reference to this");
                    }
                    if (code == OpCodeValues.Ldarg_1)
                    {
                        code = OpCodeValues.Ldarg_0;
                    }
                    else if (code == OpCodeValues.Ldarg_2)
                    {
                        code = OpCodeValues.Ldarg_1;
                    }
                    else if (code == OpCodeValues.Ldarg_3)
                    {
                        code = OpCodeValues.Ldarg_2;
                    }
                    else if (code == OpCodeValues.Ldarg_S && (byte)operand == 4)
                    {
                        code    = OpCodeValues.Ldarg_3;
                        operand = null;
                    }
                    else if (code == OpCodeValues.Ldarg_S && (byte)operand > 4)
                    {
                        operand = (byte)operand - 1;
                    }
                }
                if (code == OpCodeValues.Ldftn)
                {
                    il.OperandDelegateData = Serialize((MethodInfo)instruction.Operand);
                    operand = null;
                }
                else if (operand is FieldInfo)
                {
                    var field         = (FieldInfo)operand;
                    var fieldFullName = field.DeclaringType.FullName + "_" + field.Name;
                    if (field.Name.StartsWith("CS$<>9__CachedAnonymousMethodDelegate") || field.Name.StartsWith("<>9"))
                    {
                        int local;
                        if (!fieldsToLocals.TryGetValue(fieldFullName, out local) && field.FieldType.Name != "<>c")
                        {
                            result.LocalVariables.Add(localVariableInfoDataConverter.Build(field));
                            local = result.LocalVariables.Count - 1;
                            fieldsToLocals.Add(fieldFullName, local);
                        }


                        if (code == OpCodeValues.Ldsfld)
                        {
                            if (field.FieldType.Name == "<>c")
                            {
                                code    = OpCodeValues.Ldnull;
                                operand = null;
                            }
                            else
                            {
                                code    = OpCodeValues.Ldloc;
                                operand = local;
                            }
                        }
                        else if (code == OpCodeValues.Stsfld)
                        {
                            code    = OpCodeValues.Stloc;
                            operand = local;
                        }
                        else
                        {
                            throw new DelegateSerializationException("Unknown field operation");
                        }
                    }
                    else
                    {
                        throw new DelegateSerializationException(string.Format("Unknown field info {0}", fieldFullName));
                    }
                }
                else if (operand is ConstructorInfo)
                {
                    il.OperandConstructor = constructorInfoDataConverter.Build((ConstructorInfo)operand);
                    operand = null;
                }
                else if (operand is MethodInfo)
                {
                    il.OperandMethod = methodInfoDataConverter.Build((MethodInfo)operand);
                    operand          = null;
                }

                il.Code    = (uint)code;
                il.Offset  = instruction.Offset;
                il.Operand = operand;
                result.Instructions.Add(il);
            }
            return(result);
        }
Пример #21
0
 public void AddDelegate(DelegateData delegateData)
 {
     var sessionDelegate = new SessionDelegate(delegateData);
     delegateRepository.Insert(sessionDelegate);
     delegateRepository.Save();
 }