示例#1
0
		internal static EventDefinition CreateEvent()
		{
			var e = new EventDefinition(Generate.Name.ForMethod(), EventAttributes.None, TestModule.TypeSystem.Object);
			e.DeclaringType = Methodsholdertype;
			Methodsholdertype.Events.Add(e);
			return e;
		}
    void AddErrorsChanged()
    {
        var eventDefinition = new EventDefinition(NotifyDataErrorInfoFinder.InterfaceRef.FullName + ".ErrorsChanged", EventAttributes.SpecialName, NotifyDataErrorInfoFinder.ErrorsChangedEventType)
                                  {
                                      AddMethod = GetAdd(),
                                      RemoveMethod = GetRemove(),
                                  };

        TypeDefinition.Events.Add(eventDefinition);
    }
示例#3
0
 internal static CilEventDefinition Create(EventDefinition eventDefinition, int token, ref CilReaders readers, CilTypeDefinition declaringType)
 {
     CilEventDefinition eventDef = new CilEventDefinition();
     eventDef._eventDefinition = eventDefinition;
     eventDef._readers = readers;
     eventDef._typeDefinition = declaringType;
     eventDef._accessors = eventDefinition.GetAccessors();
     eventDef._isAdderInitialized = false;
     eventDef._isRemoverInitialized = false;
     eventDef._isRaiserInitialized = false;
     eventDef._isEntityInitialized = false;
     eventDef._token = token;
     return eventDef;
 }
    // Thank you to Romain Verdier
    // largely copied from http://codingly.com/2008/11/10/introduction-a-monocecil-implementer-inotifypropertychanged/
    void WeaveEvent(TypeDefinition type)
    {
        var propertyChangedField = new FieldDefinition("PropertyChanged", FieldAttributes.Private, PropChangedHandlerReference);
        type.Fields.Add(propertyChangedField);

        var eventDefinition = new EventDefinition("PropertyChanged", EventAttributes.None, PropChangedHandlerReference)
            {
                AddMethod = CreateEventMethod("add_PropertyChanged", DelegateCombineMethodRef, propertyChangedField),
                RemoveMethod = CreateEventMethod("remove_PropertyChanged", DelegateRemoveMethodRef, propertyChangedField)
            };

        type.Methods.Add(eventDefinition.AddMethod);
        type.Methods.Add(eventDefinition.RemoveMethod);
        type.Events.Add(eventDefinition);
    }
示例#5
0
    public void Execute()
    {
        var interfaces = ValidationTemplateFinder.TypeDefinition.Interfaces;
        InterfaceRef = interfaces.FirstOrDefault(x => x.Name == "INotifyDataErrorInfo");
        if (InterfaceRef == null)
        {
            Found = false;
            return;
        }
        var interfaceType = InterfaceRef.Resolve();
        InterfaceRef = ModuleDefinition.ImportReference(InterfaceRef);

        GetErrorsMethodDef = interfaceType.Methods.First(x => x.Name == "GetErrors");
        GetErrorsMethodRef = ModuleDefinition.ImportReference(GetErrorsMethodDef);
        ErrorsChangedEvent = interfaceType.Events.First(x => x.Name == "ErrorsChanged");
        ErrorsChangedEventType = ModuleDefinition.ImportReference(ErrorsChangedEvent.EventType);
        ErrorsChangedAddMethod = ModuleDefinition.ImportReference(ErrorsChangedEvent.AddMethod);
        ErrorsChangedRemoveMethod = ModuleDefinition.ImportReference(ErrorsChangedEvent.RemoveMethod);

        GetHasErrorsMethod = ModuleDefinition.ImportReference(interfaceType.Methods.First(x => x.Name == "get_HasErrors"));
    }
示例#6
0
文件: WinService.cs 项目: HTD/Woof
 /// <summary>
 /// Writes event log with spam protection
 /// </summary>
 /// <param name="ev">event object</param>
 /// <param name="data">optional data to format message text</param>
 public static void Event(EventDefinition ev, object data = null)
 {
     lock (EventLogLock) {
         if (EventLog == null) EventLog = new EventLog(Config.Company);
         var msg = data == null ? ev.Message : String.Format(ev.Message, data);
     #if NOSPAM
         if (msg != LastLogMessage) {
     #endif
         LastLogMessage = msg;
         if (Config.TestMode) {
             lock (ConsoleLock) {
                 switch (ev.Type) {
                     case EventLogEntryType.Information: Console.Write("II: "); break;
                     case EventLogEntryType.Warning: Console.Write("WW: "); break;
                     case EventLogEntryType.Error: Console.Write("EE: "); break;
                 }
                 Console.WriteLine(String.Format("({0}) {1}", ev.Id, msg));
             }
         } else EventLog.WriteEntry(msg, ev.Type, ev.Id);
     #if NOSPAM
         }
     #endif
     }
 }
示例#7
0
        private static List <CppMethodData> ProcessTypeContents(Il2CppMetadata metadata, PE.PE cppAssembly, Il2CppTypeDefinition cppTypeDefinition, TypeDefinition ilTypeDefinition)
        {
            var typeMetaText = new StringBuilder();

            typeMetaText.Append($"Type: {ilTypeDefinition.FullName}:")
            .Append($"\n\tBase Class: \n\t\t{ilTypeDefinition.BaseType}\n")
            .Append("\n\tInterfaces:\n");

            foreach (var iface in ilTypeDefinition.Interfaces)
            {
                typeMetaText.Append($"\t\t{iface.InterfaceType.FullName}\n");
            }

            //field
            var fields = new List <FieldInType>();

            var baseFields = new List <FieldDefinition>();

            var current = ilTypeDefinition;

            while (current.BaseType != null)
            {
                var targetName = current.BaseType.FullName;
                if (targetName.Contains("<"))   // types with generic parameters (Type'1<T>) are stored as Type'1, so I just removed the part that causes trouble and called it a day
                {
                    targetName = targetName.Substring(0, targetName.IndexOf("<"));
                }

                current = SharedState.AllTypeDefinitions.Find(t => t.FullName == targetName);

                if (current == null)
                {
                    typeMetaText.Append("WARN: Type " + targetName + " is not defined yet\n");
                    break;
                }

                baseFields.InsertRange(0, current.Fields.Where(f => !f.IsStatic));   // each loop we go one inheritage level deeper, so these "new" fields should be inserted before the previous ones
            }

            //Handle base fields
            var fieldOffset = baseFields.Aggregate((ulong)(ilTypeDefinition.MetadataType == MetadataType.Class ? 0x10 : 0x0), (currentOffset, baseField) => HandleField(baseField.FieldType, currentOffset, baseField.Name, baseField, ref fields, typeMetaText));

            var lastFieldIdx = cppTypeDefinition.firstFieldIdx + cppTypeDefinition.field_count;

            for (var fieldIdx = cppTypeDefinition.firstFieldIdx; fieldIdx < lastFieldIdx; ++fieldIdx)
            {
                var fieldDef     = metadata.fieldDefs[fieldIdx];
                var fieldType    = cppAssembly.types[fieldDef.typeIndex];
                var fieldName    = metadata.GetStringFromIndex(fieldDef.nameIndex);
                var fieldTypeRef = Utils.ImportTypeInto(ilTypeDefinition, fieldType, cppAssembly, metadata);

                var fieldDefinition = new FieldDefinition(fieldName, (FieldAttributes)fieldType.attrs, fieldTypeRef);
                ilTypeDefinition.Fields.Add(fieldDefinition);

                //Field default values
                if (fieldDefinition.HasDefault)
                {
                    var fieldDefault = metadata.GetFieldDefaultValueFromIndex(fieldIdx);
                    if (fieldDefault != null && fieldDefault.dataIndex != -1)
                    {
                        fieldDefinition.Constant = Utils.GetDefaultValue(fieldDefault.dataIndex,
                                                                         fieldDefault.typeIndex, metadata, cppAssembly);
                    }
                }

                if (!fieldDefinition.IsStatic)
                {
                    fieldOffset = HandleField(fieldTypeRef, fieldOffset, fieldName, fieldDefinition, ref fields, typeMetaText);
                }
            }

            fields.Sort(); //By offset
            SharedState.FieldsByType[ilTypeDefinition] = fields;

            //Methods
            var lastMethodId = cppTypeDefinition.firstMethodId + cppTypeDefinition.method_count;
            var typeMethods  = new List <CppMethodData>();
            Il2CppGenericContainer genericContainer;

            for (var methodId = cppTypeDefinition.firstMethodId; methodId < lastMethodId; ++methodId)
            {
                var methodDef        = metadata.methodDefs[methodId];
                var methodReturnType = cppAssembly.types[methodDef.returnType];
                var methodName       = metadata.GetStringFromIndex(methodDef.nameIndex);
                var methodDefinition = new MethodDefinition(methodName, (MethodAttributes)methodDef.flags,
                                                            ilTypeDefinition.Module.ImportReference(typeof(void)));

                //TODO: For Unity 2019 we'll need to fix the imageindex param from 0 to the actual index
                var offsetInRam = cppAssembly.GetMethodPointer(methodDef.methodIndex, methodId, 0, methodDef.token);


                long offsetInFile = offsetInRam == 0 ? 0 : cppAssembly.MapVirtualAddressToRaw(offsetInRam);
                typeMetaText.Append($"\n\tMethod: {methodName}:\n")
                .Append($"\t\tFile Offset 0x{offsetInFile:X8}\n")
                .Append($"\t\tRam Offset 0x{offsetInRam:x8}\n")
                .Append($"\t\tVirtual Method Slot: {methodDef.slot}\n");

                var bytes  = new List <byte>();
                var offset = offsetInFile;
                while (true)
                {
                    var b = cppAssembly.raw[offset];
                    if (b == 0xC3 && cppAssembly.raw[offset + 1] == 0xCC)
                    {
                        break;
                    }
                    if (b == 0xCC && bytes.Count > 0 && (bytes.Last() == 0xcc || bytes.Last() == 0xc3))
                    {
                        break;
                    }
                    bytes.Add(b);
                    offset++;
                }

                typeMetaText.Append($"\t\tMethod Length: {bytes.Count} bytes\n");

                typeMethods.Add(new CppMethodData
                {
                    MethodName      = methodName,
                    MethodId        = methodId,
                    MethodBytes     = bytes.ToArray(),
                    MethodOffsetRam = offsetInRam
                });


                ilTypeDefinition.Methods.Add(methodDefinition);
                methodDefinition.ReturnType = Utils.ImportTypeInto(methodDefinition, methodReturnType, cppAssembly, metadata);
                if (methodDefinition.HasBody && ilTypeDefinition.BaseType?.FullName != "System.MulticastDelegate")
                {
                    var ilprocessor = methodDefinition.Body.GetILProcessor();
                    ilprocessor.Append(ilprocessor.Create(OpCodes.Nop));
                }

                SharedState.MethodsByIndex.Add(methodId, methodDefinition);
                //Method Params
                for (var paramIdx = 0; paramIdx < methodDef.parameterCount; ++paramIdx)
                {
                    var parameterDef        = metadata.parameterDefs[methodDef.parameterStart + paramIdx];
                    var parameterName       = metadata.GetStringFromIndex(parameterDef.nameIndex);
                    var parameterType       = cppAssembly.types[parameterDef.typeIndex];
                    var parameterTypeRef    = Utils.ImportTypeInto(methodDefinition, parameterType, cppAssembly, metadata);
                    var parameterDefinition = new ParameterDefinition(parameterName, (ParameterAttributes)parameterType.attrs, parameterTypeRef);
                    methodDefinition.Parameters.Add(parameterDefinition);
                    //Default values for params
                    if (parameterDefinition.HasDefault)
                    {
                        var parameterDefault = metadata.GetParameterDefaultValueFromIndex(methodDef.parameterStart + paramIdx);
                        if (parameterDefault != null && parameterDefault.dataIndex != -1)
                        {
                            parameterDefinition.Constant = Utils.GetDefaultValue(parameterDefault.dataIndex, parameterDefault.typeIndex, metadata, cppAssembly);
                        }
                    }


                    typeMetaText.Append($"\n\t\tParameter {paramIdx}:\n")
                    .Append($"\t\t\tName: {parameterName}\n")
                    .Append($"\t\t\tType: {(parameterTypeRef.Namespace == "" ? "<None>" : parameterTypeRef.Namespace)}.{parameterTypeRef.Name}\n")
                    .Append($"\t\t\tDefault Value: {parameterDefinition.Constant}");
                }

                if (methodDef.genericContainerIndex >= 0)
                {
                    genericContainer = metadata.genericContainers[methodDef.genericContainerIndex];
                    if (genericContainer.type_argc > methodDefinition.GenericParameters.Count)
                    {
                        for (var j = 0; j < genericContainer.type_argc; j++)
                        {
                            var genericParameterIndex = genericContainer.genericParameterStart + j;
                            var param       = metadata.genericParameters[genericParameterIndex];
                            var genericName = metadata.GetStringFromIndex(param.nameIndex);
                            if (!SharedState.GenericParamsByIndex.TryGetValue(genericParameterIndex,
                                                                              out var genericParameter))
                            {
                                genericParameter = new GenericParameter(genericName, methodDefinition);
                                methodDefinition.GenericParameters.Add(genericParameter);
                                SharedState.GenericParamsByIndex.Add(genericParameterIndex, genericParameter);
                            }
                            else
                            {
                                if (!methodDefinition.GenericParameters.Contains(genericParameter))
                                {
                                    methodDefinition.GenericParameters.Add(genericParameter);
                                }
                            }
                        }
                    }
                }

                if (methodDef.slot < ushort.MaxValue)
                {
                    SharedState.VirtualMethodsBySlot[methodDef.slot] = methodDefinition;
                }

                SharedState.MethodsByAddress[offsetInRam] = methodDefinition;
            }

            //Properties
            var lastPropertyId = cppTypeDefinition.firstPropertyId + cppTypeDefinition.propertyCount;

            for (var propertyId = cppTypeDefinition.firstPropertyId; propertyId < lastPropertyId; ++propertyId)
            {
                var              propertyDef  = metadata.propertyDefs[propertyId];
                var              propertyName = metadata.GetStringFromIndex(propertyDef.nameIndex);
                TypeReference    propertyType = null;
                MethodDefinition getter       = null;
                MethodDefinition setter       = null;
                if (propertyDef.get >= 0)
                {
                    getter       = SharedState.MethodsByIndex[cppTypeDefinition.firstMethodId + propertyDef.get];
                    propertyType = getter.ReturnType;
                }

                if (propertyDef.set >= 0)
                {
                    setter = SharedState.MethodsByIndex[cppTypeDefinition.firstMethodId + propertyDef.set];
                    if (propertyType == null)
                    {
                        propertyType = setter.Parameters[0].ParameterType;
                    }
                }

                var propertyDefinition = new PropertyDefinition(propertyName, (PropertyAttributes)propertyDef.attrs, propertyType)
                {
                    GetMethod = getter,
                    SetMethod = setter
                };
                ilTypeDefinition.Properties.Add(propertyDefinition);
            }

            //Events
            var lastEventId = cppTypeDefinition.firstEventId + cppTypeDefinition.eventCount;

            for (var eventId = cppTypeDefinition.firstEventId; eventId < lastEventId; ++eventId)
            {
                var eventDef        = metadata.eventDefs[eventId];
                var eventName       = metadata.GetStringFromIndex(eventDef.nameIndex);
                var eventType       = cppAssembly.types[eventDef.typeIndex];
                var eventTypeRef    = Utils.ImportTypeInto(ilTypeDefinition, eventType, cppAssembly, metadata);
                var eventDefinition = new EventDefinition(eventName, (EventAttributes)eventType.attrs, eventTypeRef);
                if (eventDef.add >= 0)
                {
                    eventDefinition.AddMethod = SharedState.MethodsByIndex[cppTypeDefinition.firstMethodId + eventDef.add];
                }
                if (eventDef.remove >= 0)
                {
                    eventDefinition.RemoveMethod = SharedState.MethodsByIndex[cppTypeDefinition.firstMethodId + eventDef.remove];
                }
                if (eventDef.raise >= 0)
                {
                    eventDefinition.InvokeMethod = SharedState.MethodsByIndex[cppTypeDefinition.firstMethodId + eventDef.raise];
                }
                ilTypeDefinition.Events.Add(eventDefinition);
            }

            File.WriteAllText(Path.Combine(Path.GetFullPath("cpp2il_out"), "types", ilTypeDefinition.Module.Assembly.Name.Name, ilTypeDefinition.Name.Replace("<", "_").Replace(">", "_") + "_metadata.txt"), typeMetaText.ToString());

            if (cppTypeDefinition.genericContainerIndex < 0)
            {
                return(typeMethods);                                             //Finished processing if not generic
            }
            genericContainer = metadata.genericContainers[cppTypeDefinition.genericContainerIndex];
            if (genericContainer.type_argc <= ilTypeDefinition.GenericParameters.Count)
            {
                return(typeMethods);                                                                        //Finished processing
            }
            for (var i = 0; i < genericContainer.type_argc; i++)
            {
                var genericParameterIndex = genericContainer.genericParameterStart + i;
                var param       = metadata.genericParameters[genericParameterIndex];
                var genericName = metadata.GetStringFromIndex(param.nameIndex);
                if (!SharedState.GenericParamsByIndex.TryGetValue(genericParameterIndex, out var genericParameter))
                {
                    genericParameter = new GenericParameter(genericName, ilTypeDefinition);
                    ilTypeDefinition.GenericParameters.Add(genericParameter);
                    SharedState.GenericParamsByIndex.Add(genericParameterIndex, genericParameter);
                }
                else
                {
                    if (ilTypeDefinition.GenericParameters.Contains(genericParameter))
                    {
                        continue;
                    }
                    ilTypeDefinition.GenericParameters.Add(genericParameter);
                }
            }

            return(typeMethods);
        }
        /// <summary>
        /// This method returns the correct EventInstance based upon the event definion.
        /// This EventInstance can then be raised to the context bus.
        /// </summary>
        /// <param name="eventDefinition">The defintion which has the metdata describing ContentHTML Objects.</param>
        /// <param name="contentData">The newly published Ektron CMS content data object.</param>
        /// <returns></returns>
        private EventInstance CreateContentDataEventInstance(EventDefinition eventDefinition, ContentData contentData)
        {
            Log.WriteMessage(string.Format("-Begin {0}.CreateContentDataEventInstance.", CLASS_NAME), LogLevel.Verbose);
            EventInstance HTMLEventInstance = null;
            try
            {
                HTMLEventInstance = new EventInstance()
                {
                    DisplayName = eventDefinition.DisplayName,
                    Id = eventDefinition.Id
                };

                HTMLEventInstance.Payload = ConvertContentDataToIObjectInstance(eventDefinition, contentData);

            }
            catch (Exception ex)
            {
                Log.WriteError(string.Format("{0}.CreateContentDataEventInstance failed: {1}.", CLASS_NAME, ex.Message));
            }

            Log.WriteMessage(string.Format("+Finish {0}.CreateContentDataEventInstance.", CLASS_NAME), LogLevel.Verbose);
            return HTMLEventInstance;
        }
 internal IMethodDefinition/*?*/ GetEventAddOrRemoveOrFireMethod(
   EventDefinition eventDefinition,
   MethodSemanticsFlags addOrRemoveOrFireFlag
 ) {
   uint methodSemanticRowIdStart;
   uint methodSemanticRowIdEnd;
   this.GetSemanticInfoForEvent(eventDefinition.EventRowId, out methodSemanticRowIdStart, out methodSemanticRowIdEnd);
   for (uint methSemRowIdIter = methodSemanticRowIdStart; methSemRowIdIter < methodSemanticRowIdEnd; ++methSemRowIdIter) {
     MethodSemanticsRow methodSemanticRow = this.PEFileReader.MethodSemanticsTable[methSemRowIdIter];
     if (methodSemanticRow.SemanticsFlag == addOrRemoveOrFireFlag) {
       return this.GetMethodDefAtRow(methodSemanticRow.Method);
     }
   }
   return null;
 }
示例#10
0
        public void ImportItemsToFolderWithOutListDependency(string ektronConnectionId, string sharepointConnectionId, string objectDefinitionId, long folderId, ConcurrentDictionary<int, MappingTask> listIdWithMappingTask, bool isDeleteallowed, int languageid)
        {
            Log.WriteVerbose(string.Format(BeginLogMessage, CLASS_NAME, "ImportItemsToFolderWithOutListDependency(string ektronConnectionId, string sharepointConnectionId, string objectDefinitionId, long folderId, IEnumerable<int> objectsharepointIdList)"));
            foreach (var listAndMapping in listIdWithMappingTask)
            {

                List<ObjectInstance> objectinstancelist = this.GetFilteredObjectInstanceList(sharepointConnectionId, listAndMapping.Value.SourceObject, new List<int>() { listAndMapping.Key });

                TaskManagerClient taskClient = new TaskManagerClient();
                EventManagerClient eventClient = new EventManagerClient();

                foreach (ObjectInstance item in objectinstancelist)
                {

                    string id = item.Fields.Single(p => p.Id.ToLower().Equals("id")).Value.ToString();

                    string workflowName = string.Empty;
                    if (isDeleteallowed)
                        workflowName = string.Concat("SharepointDeleteAllowed|Ektron|", objectDefinitionId, "|", folderId, "|ItemDependant|" + id + ";" + languageid);
                    else
                        workflowName = string.Concat("Sharepoint|Ektron|", objectDefinitionId, "|", folderId, "|ItemDependant|" + id + ";" + languageid);

                    //check workflow and delete if it already exists.
                    DxhWorkflow workflow = taskClient.GetWorkflow(workflowName);
                    if (workflow != null)
                    {
                        taskClient.DeleteWorkflow(workflowName);
                    }

                    //1. Create workflow tasks
                    LoginTask login = taskClient.CreateLoginTask("Ektron", ektronConnectionId);
                    SaveObjectInstanceTask saveSharepointToEktron = taskClient.CreateSaveObjectTask("Ektron");
                    LogoutTask logout = taskClient.CreateLogoutTask("Ektron");

                    //2. Assemble and save workflow
                    workflow = taskClient.CreateWorkflow(workflowName);
                    ((ICollection<ContextBusTask>)workflow.Tasks).Add(login);
                    ((ICollection<ContextBusTask>)workflow.Tasks).Add(listAndMapping.Value);
                    ((ICollection<ContextBusTask>)workflow.Tasks).Add(saveSharepointToEktron);
                    ((ICollection<ContextBusTask>)workflow.Tasks).Add(logout);
                    taskClient.SaveWorkflow(workflow);
                    DxHUtils.SaveMapping(AdapterName, sharepointConnectionId, listAndMapping.Value, workflow, Ektron.Cms.Common.EkEnumeration.CMSObjectTypes.Folder, folderId, "", languageid);

                    //3. Create associated Event Defintions for workflow.
                    EventDefinition eventDef = new EventDefinition()
                    {
                        Id = workflowName,
                        Payload = listAndMapping.Value.SourceObject
                    };
                    eventClient.AssociateWorkflowsToEvent(new List<string> { workflow.WorkflowName }, eventDef);

                    if (this.GetListType(objectDefinitionId).ToLower() == "list")
                    {
                        eventDef = new EventDefinition()
                        {
                            Id = string.Concat("SP|List|SPReceiverEvent|", this.GetSiteUrlandListTitle(objectDefinitionId)),
                            Payload = listAndMapping.Value.SourceObject
                        };
                        eventClient.AssociateWorkflowsToEvent(new List<string> { workflow.WorkflowName }, eventDef);

                        eventDef = new EventDefinition()
                        {
                            Id = string.Concat("SP|ListItemAttachment|SPReceiverEvent|", this.GetSiteUrlandListTitle(objectDefinitionId)),
                            Payload = listAndMapping.Value.SourceObject
                        };
                        eventClient.AssociateWorkflowsToEvent(new List<string> { workflow.WorkflowName }, eventDef);
                    }
                    else if (this.GetListType(objectDefinitionId).ToLower() == "documentlibrary")
                    {

                        eventDef = new EventDefinition()
                        {
                            Id = string.Concat("SP|DocumentLibrary|SPReceiverEvent|", this.GetSiteUrlandListTitle(objectDefinitionId)),
                            Payload = listAndMapping.Value.SourceObject
                        };
                        eventClient.AssociateWorkflowsToEvent(new List<string> { workflow.WorkflowName }, eventDef);
                    }

                    if (isDeleteallowed)
                    {
                        string deleteworkflowname = string.Concat("SharepointDelete|Ektron|", objectDefinitionId, "|", folderId, "|ItemDependant|" + id + ";" + languageid);
                        DxhWorkflow deleteworkflow = taskClient.GetWorkflow(deleteworkflowname);
                        if (deleteworkflow != null)
                        {
                            taskClient.DeleteWorkflow(deleteworkflowname);
                        }

                        // Create Delete Workflow Tasks
                        LoginTask deletelogin = taskClient.CreateLoginTask("Ektron", ektronConnectionId);
                        DeleteObjectInstanceTask deleteObjecttask = taskClient.CreateDeleteObjectTask("Ektron");
                        LogoutTask deletelogout = taskClient.CreateLogoutTask("Ektron");

                        //Assemble the Workflow
                        deleteworkflow = taskClient.CreateWorkflow(deleteworkflowname);
                        ((ICollection<ContextBusTask>)deleteworkflow.Tasks).Add(deletelogin);
                        ((ICollection<ContextBusTask>)deleteworkflow.Tasks).Add(listAndMapping.Value);
                        ((ICollection<ContextBusTask>)deleteworkflow.Tasks).Add(deleteObjecttask);
                        ((ICollection<ContextBusTask>)deleteworkflow.Tasks).Add(deletelogout);
                        taskClient.SaveWorkflow(deleteworkflow);

                        eventDef = new EventDefinition()
                        {
                            Id = string.Concat("SPReceiverEvent|Delete|", this.GetSiteUrlandListTitle(objectDefinitionId)),
                            Payload = listAndMapping.Value.SourceObject
                        };
                        eventClient.AssociateWorkflowsToEvent(new List<string> { deleteworkflow.WorkflowName }, eventDef);
                    }

                    item.Fields.Where(p => p.Id.Equals("DxHSource")).FirstOrDefault().Value = "FromEktron";
                    EventInstance itemEvent = new EventInstance()
                    {
                        Id = workflowName,
                        Payload = item
                    };
                    eventClient.RaiseEvent(itemEvent);
                }
                Log.WriteVerbose(string.Format(FinishLogMessage, CLASS_NAME, "ImportItemsToFolderWithOutListDependency(string ektronConnectionId, string sharepointConnectionId, string objectDefinitionId, long folderId, IEnumerable<int> objectsharepointIdList)"));
            }
        }
示例#11
0
        private D.MethodDeclaration CreateAddAccessor(ILTranslator translator, VisitingEventArgs <EventDeclaration> e, D.ArrayType arrayType, EventDefinition ed)
        {
            var n  = e.Node.Variables.Single().Name;
            var fn = FIELD_PREFIX + n;

            var union = arrayType.UnionWith(arrayType.ElementType);
            var ad    = new D.MethodDeclaration()
            {
                MethodName = ADD_PREFIX + n,
                Parameters = new Collection <D.Parameter>()
                {
                    new D.Parameter()
                    {
                        ParameterName = "value",
                        ParameterType = union
                    }
                }
            };

            var mre = new MemberReferenceExpression()
            {
                Target     = new ThisReferenceExpression(),
                MemberName = fn
            };
            var ve = new IdentifierExpression("value");

            mre.AddAnnotation(new TypeInformation(ed.EventType, ed.EventType));

            ad.Statements = translator.GetStatements(new ExpressionStatement()
            {
                Expression = new AssignmentExpression()
                {
                    Operator = AssignmentOperatorType.Add,
                    Left     = mre,
                    Right    = ve
                }
            }, e.Context);

            return(ad);
        }
 public override void ProcessEvent(EventDefinition @event)
 {
 }
示例#13
0
 public virtual void ProcessEvent(EventDefinition @event)
 {
 }
 public static bool IsPropertyChangedEvent(EventDefinition eventDefinition)
 {
     return IsNamedPropertyChanged(eventDefinition) && IsPropertyChangedEventHandler(eventDefinition.EventType);
 }
示例#15
0
 public override void RewriteChildren(EventDefinition eventDefinition)
 {
     base.RewriteChildren(eventDefinition);
     MutateMember(eventDefinition, CurrentTrimElement);
 }
示例#16
0
 public override void DecompileEvent(EventDefinition ev, ITextOutput output, DecompilationOptions options)
 {
     WriteCommentLine(output, TypeToString(ev.DeclaringType, includeNamespace: true));
     AstBuilder codeDomBuilder = CreateAstBuilder(options, currentType: ev.DeclaringType, isSingleMember: true);
     codeDomBuilder.AddEvent(ev);
     RunTransformsAndGenerateCode(codeDomBuilder, output, options);
 }
示例#17
0
 public static object GetText(EventDefinition eventDef, Language language)
 {
     return HighlightSearchMatch(eventDef.Name, " : " + language.TypeToString(eventDef.EventType, false, eventDef));
 }
示例#18
0
        public EventTreeNode(EventDefinition ev)
        {
            if (ev == null)
                throw new ArgumentNullException("ev");
            this.ev = ev;

            if (ev.AddMethod != null)
                this.Children.Add(new MethodTreeNode(ev.AddMethod));
            if (ev.RemoveMethod != null)
                this.Children.Add(new MethodTreeNode(ev.RemoveMethod));
            if (ev.InvokeMethod != null)
                this.Children.Add(new MethodTreeNode(ev.InvokeMethod));
            if (ev.HasOtherMethods)
            {
                foreach (var m in ev.OtherMethods)
                    this.Children.Add(new MethodTreeNode(m));
            }
        }
示例#19
0
 public virtual void DecompileEvent(EventDefinition ev, ITextOutput output, DecompilationOptions options)
 {
     WriteCommentLine(output, TypeToString(ev.DeclaringType, true) + "." + ev.Name);
 }
示例#20
0
        protected Dictionary <string, DecompiledType> GetNestedDecompiledTypes(TypeDefinition type, ILanguage language)
        {
            Dictionary <string, DecompiledType> decompiledTypes = new Dictionary <string, DecompiledType>();

            Queue <IMemberDefinition> decompilationQueue = new Queue <IMemberDefinition>();

            decompilationQueue.Enqueue(type);
            while (decompilationQueue.Count > 0)
            {
                IMemberDefinition currentMember = decompilationQueue.Dequeue();

                if (currentMember is TypeDefinition)
                {
                    TypeDefinition currentType = (currentMember as TypeDefinition);
                    decompiledTypes.Add(currentType.FullName, new DecompiledType(currentType));

                    //List<IMemberDefinition> members = Utilities.GetTypeMembers(currentType);
                    List <IMemberDefinition> members = Utilities.GetTypeMembersToDecompile(currentType);
                    foreach (IMemberDefinition member in members)
                    {
                        decompilationQueue.Enqueue(member);
                    }
                }
                else
                {
                    TypeDefinition currentType = currentMember.DeclaringType;

                    DecompiledType decompiledType;
                    if (!decompiledTypes.TryGetValue(currentType.FullName, out decompiledType))
                    {
                        throw new Exception("Type missing from nested types decompilation cache.");
                    }

                    if (currentMember is MethodDefinition)
                    {
                        MethodDefinition method = currentMember as MethodDefinition;
                        DecompileMember(method, language, decompiledType);
                        //Utilities.AddDecompiledMethodToDecompiledType(method, language, decompiledType);
                    }
                    if (currentMember is EventDefinition)
                    {
                        EventDefinition eventDefinition = (currentMember as EventDefinition);

                        AutoImplementedEventMatcher matcher = new AutoImplementedEventMatcher(eventDefinition);
                        bool isAutoImplemented = matcher.IsAutoImplemented();

                        if (isAutoImplemented)
                        {
                            decompiledType.TypeContext.AutoImplementedEvents.Add(eventDefinition);
                        }

                        if (eventDefinition.AddMethod != null)
                        {
                            //Utilities.AddDecompiledMethodToDecompiledType(eventDefinition.AddMethod, language, decompiledType);
                            DecompileMember(eventDefinition.AddMethod, language, decompiledType);
                        }

                        if (eventDefinition.RemoveMethod != null)
                        {
                            //Utilities.AddDecompiledMethodToDecompiledType(eventDefinition.RemoveMethod, language, decompiledType);
                            DecompileMember(eventDefinition.RemoveMethod, language, decompiledType);
                        }

                        if (eventDefinition.InvokeMethod != null)
                        {
                            //Utilities.AddDecompiledMethodToDecompiledType(eventDefinition.InvokeMethod, language, decompiledType);
                            DecompileMember(eventDefinition.InvokeMethod, language, decompiledType);
                        }
                    }
                    if (currentMember is PropertyDefinition)
                    {
                        PropertyDefinition propertyDefinition = (currentMember as PropertyDefinition);

                        CachedDecompiledMember getMethod;
                        CachedDecompiledMember setMethod;
                        bool isAutoImplemented;

                        PropertyDecompiler propertyDecompiler = new PropertyDecompiler(propertyDefinition, language, renameInvalidMembers, this.cacheService, decompiledType.TypeContext);
                        propertyDecompiler.ExceptionThrown += OnExceptionThrown;
                        propertyDecompiler.Decompile(out getMethod, out setMethod, out isAutoImplemented);
                        propertyDecompiler.ExceptionThrown -= OnExceptionThrown;

                        if (isAutoImplemented)
                        {
                            decompiledType.TypeContext.AutoImplementedProperties.Add(propertyDefinition);
                        }

                        if (getMethod != null)
                        {
                            AddDecompiledMemberToDecompiledType(getMethod, decompiledType);
                        }

                        if (setMethod != null)
                        {
                            AddDecompiledMemberToDecompiledType(setMethod, decompiledType);
                        }

                        foreach (MethodDefinition exceptionWhileDecompiling in propertyDecompiler.ExceptionsWhileDecompiling)
                        {
                            this.ExceptionsWhileDecompiling.Add(exceptionWhileDecompiling);
                        }
                    }
                }
            }

            foreach (DecompiledType decompiledType in decompiledTypes.Values)
            {
                AddGeneratedFilterMethodsToDecompiledType(decompiledType, decompiledType.TypeContext, language);
            }

            return(decompiledTypes);
        }
示例#21
0
        protected virtual void VerifyPseudoAttributes(EventDefinition src, EventDefinition linked)
        {
            var expected = (EventAttributes)GetExpectedPseudoAttributeValue(src, (uint)src.Attributes);

            Assert.AreEqual(expected, linked.Attributes, $"Event `{src}' pseudo attributes did not match expected");
        }
示例#22
0
        private static int AddEvent(MyEventsContext context)
        {
            var eventDef = new EventDefinition();
            eventDef.OrganizerId = AddOrganizer(context);
            eventDef.Name = Guid.NewGuid().ToString();
            eventDef.Description = Guid.NewGuid().ToString();
            eventDef.Address = Guid.NewGuid().ToString();
            eventDef.City = Guid.NewGuid().ToString();
            eventDef.Tags = Guid.NewGuid().ToString();
            eventDef.TwitterAccount = Guid.NewGuid().ToString();
            eventDef.Rooms = 1;
            eventDef.Date = System.DateTime.Now;
            eventDef.StartTime = System.DateTime.Now;
            eventDef.EndTime = System.DateTime.Now;
            eventDef.Latitude = 0;
            eventDef.Longitude = 0;
            eventDef.Likes = 0;
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            eventDef.Logo = encoding.GetBytes("sample");

            context.EventDefinitions.Add(eventDef);
            context.SaveChanges();
            return eventDef.EventDefinitionId;
        }
示例#23
0
 public AutoImplementedEventMatcher(EventDefinition eventDef, ILanguage language)
 {
     this.eventDef = eventDef;
     this.language = language;
 }
示例#24
0
		public static MethodDefinition CreateAddMethod (EventDefinition evt)
		{
			MethodDefinition add = new MethodDefinition (
				string.Concat ("add_", evt.Name), (MethodAttributes) 0, evt.EventType);
			evt.AddMethod = add;
			return add;
		}
 public static bool IsExplicitImplementationOf(this EventDefinition self, TypeDefinition interface)
 {
     if (interface == null)
示例#26
0
		public static MethodDefinition CreateRemoveMethod (EventDefinition evt)
		{
			MethodDefinition remove = new MethodDefinition (
				string.Concat ("remove_", evt.Name), (MethodAttributes) 0, evt.EventType);
			evt.RemoveMethod = remove;
			return remove;
		}
示例#27
0
        public void ImportListToFolder(string ektronConnectionId, string sharepointConnectionId, long folderId, MappingTask map, bool isDeleteallowed, int languageid)
        {
            Log.WriteVerbose(string.Format(BeginLogMessage, CLASS_NAME, "ImportListToFolder(string ektronConnectionId, string sharepointConnectionId, string objectDefinitionId, long folderId, List<ObjectInstance> objectinstancelist, Dictionary<string, string> SharePointFieldToMetaId = null)"));
            TaskManagerClient taskClient = new TaskManagerClient();
            EventManagerClient eventClient = new EventManagerClient();

            string workflowName = string.Empty;
            if (isDeleteallowed)
                workflowName = string.Concat("SharepointDeleteAllowed|Ektron|", map.SourceObject.Id, "|", folderId, "|ListDependant;" + languageid);
            else
                workflowName = string.Concat("Sharepoint|Ektron|", map.SourceObject.Id, "|", folderId, "|ListDependant;" + languageid);

            //check workflow and delete if it already exists.
            DxhWorkflow workflow = taskClient.GetWorkflow(workflowName);
            if (workflow != null)
            {
                taskClient.DeleteWorkflow(workflowName);
            }

            //1. Create workflow tasks
            LoginTask login = taskClient.CreateLoginTask("Ektron", ektronConnectionId);
            SaveObjectInstanceTask saveSharepointToEktron = taskClient.CreateSaveObjectTask("Ektron");
            LogoutTask logout = taskClient.CreateLogoutTask("Ektron");

            //2. Assemble and save workflow
            workflow = taskClient.CreateWorkflow(workflowName);
            ((ICollection<ContextBusTask>)workflow.Tasks).Add(login);
            ((ICollection<ContextBusTask>)workflow.Tasks).Add(map);
            ((ICollection<ContextBusTask>)workflow.Tasks).Add(saveSharepointToEktron);
            ((ICollection<ContextBusTask>)workflow.Tasks).Add(logout);
            taskClient.SaveWorkflow(workflow);
            DxHUtils.SaveMapping(AdapterName, sharepointConnectionId, map, workflow, Ektron.Cms.Common.EkEnumeration.CMSObjectTypes.Folder, folderId, "", languageid);

            //3. Create associated Event Defintions for workflow.
            EventDefinition eventDef = new EventDefinition()
            {
                Id = workflowName,
                Payload = map.SourceObject
            };
            eventClient.AssociateWorkflowsToEvent(new List<string> { workflow.WorkflowName }, eventDef);

            if (this.GetListType(map.SourceObject.Id).ToLower() == "list")
            {
                eventDef = new EventDefinition()
                {
                    Id = string.Concat("SP|List|SPReceiverEvent|", this.GetSiteUrlandListTitle(map.SourceObject.Id)),
                    Payload = map.SourceObject
                };
                eventClient.AssociateWorkflowsToEvent(new List<string> { workflow.WorkflowName }, eventDef);

                eventDef = new EventDefinition()
                {
                    Id = string.Concat("SP|ListItemAttachment|SPReceiverEvent|", this.GetSiteUrlandListTitle(map.SourceObject.Id)),
                    Payload = map.SourceObject
                };
                eventClient.AssociateWorkflowsToEvent(new List<string> { workflow.WorkflowName }, eventDef);
            }
            else if (this.GetListType(map.SourceObject.Id).ToLower() == "documentlibrary")
            {

                eventDef = new EventDefinition()
                {
                    Id = string.Concat("SP|DocumentLibrary|SPReceiverEvent|", this.GetSiteUrlandListTitle(map.SourceObject.Id)),
                    Payload = map.SourceObject
                };
                eventClient.AssociateWorkflowsToEvent(new List<string> { workflow.WorkflowName }, eventDef);
            }

            if (isDeleteallowed)
            {
                string deleteworkflowname = string.Concat("SharepointDelete|Ektron|", map.SourceObject.Id, "|", folderId, "|ListDependant;" + languageid);
                DxhWorkflow deleteworkflow = taskClient.GetWorkflow(deleteworkflowname);
                if (deleteworkflow != null)
                {
                    taskClient.DeleteWorkflow(deleteworkflowname);
                }

                // Create Delete Workflow Tasks
                LoginTask deletelogin = taskClient.CreateLoginTask("Ektron", ektronConnectionId);
                DeleteObjectInstanceTask deleteObjecttask = taskClient.CreateDeleteObjectTask("Ektron");
                LogoutTask deletelogout = taskClient.CreateLogoutTask("Ektron");

                //Assemble the Workflow
                deleteworkflow = taskClient.CreateWorkflow(deleteworkflowname);
                ((ICollection<ContextBusTask>)deleteworkflow.Tasks).Add(deletelogin);
                ((ICollection<ContextBusTask>)deleteworkflow.Tasks).Add(map);
                ((ICollection<ContextBusTask>)deleteworkflow.Tasks).Add(deleteObjecttask);
                ((ICollection<ContextBusTask>)deleteworkflow.Tasks).Add(deletelogout);
                taskClient.SaveWorkflow(deleteworkflow);

                eventDef = new EventDefinition()
                {
                    Id = string.Concat("SPReceiverEvent|Delete|", this.GetSiteUrlandListTitle(map.SourceObject.Id)),
                    Payload = map.SourceObject
                };
                eventClient.AssociateWorkflowsToEvent(new List<string> { deleteworkflow.WorkflowName }, eventDef);
            }

            ////4. Retrieve Sharepoint items and raise event for each one.
            SharePointClientImportHelper.GetInstance().StartImport(sharepointConnectionId, AdapterName, workflowName, map.SourceObject);

            Log.WriteVerbose(string.Format(FinishLogMessage, CLASS_NAME, "ImportListToFolder(string ektronConnectionId, string sharepointConnectionId, string objectDefinitionId, long folderId, List<ObjectInstance> objectinstancelist, Dictionary<string, string> SharePointFieldToMetaId = null)"));
        }
示例#28
0
		public static MethodDefinition CreateInvokeMethod (EventDefinition evt)
		{
			MethodDefinition raise = new MethodDefinition (
				string.Concat ("raise_", evt.Name), (MethodAttributes) 0, evt.EventType);
			evt.InvokeMethod = raise;
			return raise;
		}
示例#29
0
 EventDefinition CreateEvent(
   uint eventDefRowId,
   TypeBase parentModuleType
 ) {
   Debug.Assert(eventDefRowId > 0 && eventDefRowId <= this.PEFileReader.EventTable.NumberOfRows);
   EventRow eventRow = this.PEFileReader.EventTable[eventDefRowId];
   IName eventName = this.GetNameFromOffset(eventRow.Name);
   EventDefinition moduleEvent = new EventDefinition(this, eventName, parentModuleType, eventDefRowId, eventRow.Flags);
   parentModuleType.AddMember(moduleEvent);
   return moduleEvent;
 }
示例#30
0
		internal static EventDefinition Clone (EventDefinition evt, ImportContext context)
		{
			EventDefinition ne = new EventDefinition (
				evt.Name,
				context.Import (evt.EventType),
				evt.Attributes);

			if (context.GenericContext.Type is TypeDefinition) {
				TypeDefinition type = context.GenericContext.Type as TypeDefinition;
				if (evt.AddMethod != null)
					ne.AddMethod = type.Methods.GetMethod (evt.AddMethod.Name) [0];
				if (evt.InvokeMethod != null)
					ne.InvokeMethod = type.Methods.GetMethod (evt.InvokeMethod.Name) [0];
				if (evt.RemoveMethod != null)
					ne.RemoveMethod = type.Methods.GetMethod (evt.RemoveMethod.Name) [0];
			}

			foreach (CustomAttribute ca in evt.CustomAttributes)
				ne.CustomAttributes.Add (CustomAttribute.Clone (ca, context));

			return ne;
		}
示例#31
0
		public virtual void ReadSemantic (EventDefinition evt)
		{
		}
 internal AssemblyEventDefinition(AssemblyTypeDefinition declaringType, EventDefinition definition)
 {
     _declaringType = declaringType;
     _definition = definition;
 }
示例#33
0
 protected virtual void ProcessEvent(EventDefinition eventDef)
 {
     ProcessCustomAttributes(eventDef.CustomAttributes, eventDef);
 }
        public static string GetFullMemberName(this IMemberDefinition self, ILanguage language)
        {
            if (self is TypeDefinition || self is FieldDefinition)
            {
                return(GenericHelper.ReplaceInvalidCharactersName(language, self.Name));
            }
            if (self is EventDefinition)
            {
                EventDefinition @event = self as EventDefinition;

                if (@event.IsExplicitImplementation())
                {
                    string[] nameParts = @event.Name.Split(new char[] { '.' });

                    var sb = new StringBuilder(nameParts.Length * 2);

                    for (int i = 0; i < nameParts.Length; i++)
                    {
                        string namePart = nameParts[i];

                        sb.Append(GenericHelper.ReplaceInvalidCharactersName(language, namePart));

                        if (i < nameParts.Length - 1)
                        {
                            sb.Append(".");
                        }
                    }
                    return(sb.ToString());
                }
                return(GenericHelper.ReplaceInvalidCharactersName(language, self.Name));
            }
            else if (self is MethodDefinition)
            {
                return((self as MethodDefinition).GetFriendlyFullMethodReferenceName(language, self.Name, false));
            }
            else if (self is PropertyDefinition)
            {
                PropertyDefinition propertyDefinition = self as PropertyDefinition;

                if (propertyDefinition.IsExplicitImplementation())
                {
                    string[] nameParts = propertyDefinition.Name.Split(new char[] { '.' });

                    var sb = new StringBuilder(nameParts.Length * 2);

                    for (int i = 0; i < nameParts.Length; i++)
                    {
                        string namePart = nameParts[i];

                        sb.Append(GenericHelper.ReplaceInvalidCharactersName(language, namePart));

                        if (i < nameParts.Length - 1)
                        {
                            sb.Append(".");
                        }
                    }
                    sb.Append("()");
                    return(sb.ToString());
                }
                else
                {
                    return((self as PropertyDefinition).GetFriendlyFullPropertyDefinitionName(language, self.Name));
                }
            }
            throw new Exception("Invalid member definition type.");
        }
示例#35
0
 public override void ProcessEvent(EventDefinition @event)
 {
     ProcessAttributeProvider(@event);
 }
示例#36
0
 static ModifierEnum TranslateModifiers(EventDefinition @event)
 {
     return(TranslateModifiers(@event.AddMethod));
 }
        /// <inheritdoc/>
        public virtual async Task <CloudEvent?> ConsumeOrBeginCorrelateEventAsync(EventDefinition eventDefinition, CancellationToken cancellationToken = default)
        {
            if (eventDefinition == null)
            {
                throw new ArgumentNullException(nameof(eventDefinition));
            }
            var e = await this.SynapseRuntimeApi.ConsumeOrBeginCorrelateEventAsync(new() { WorkflowInstanceId = this.Instance.Id, EventDefinition = eventDefinition }, cancellationToken);

            if (e == null)
            {
                return(null);
            }
            else
            {
                return(e.ToCloudEvent());
            }
        }
示例#38
0
文件: Events.cs 项目: 71/insider
 internal static void TriggerScan(EventDefinition def)
 => EventScanned?.Invoke(def);
示例#39
0
        public bool GenerateFor(TypeDefinition hookType, TypeDefinition hookILType, MethodDefinition method)
        {
            if (method.HasGenericParameters ||
                method.IsAbstract ||
                (method.IsSpecialName && !method.IsConstructor))
            {
                return(false);
            }

            if (!HookOrig && method.Name.StartsWith("orig_"))
            {
                return(false);
            }
            if (!HookPrivate && method.IsPrivate)
            {
                return(false);
            }

            string name   = GetFriendlyName(method);
            bool   suffix = true;

            if (method.Parameters.Count == 0)
            {
                suffix = false;
            }

            IEnumerable <MethodDefinition> overloads = null;

            if (suffix)
            {
                overloads = method.DeclaringType.Methods.Where(other => !other.HasGenericParameters && GetFriendlyName(other) == name && other != method);
                if (overloads.Count() == 0)
                {
                    suffix = false;
                }
            }

            if (suffix)
            {
                StringBuilder builder = new StringBuilder();
                for (int parami = 0; parami < method.Parameters.Count; parami++)
                {
                    ParameterDefinition param = method.Parameters[parami];
                    if (!TypeNameMap.TryGetValue(param.ParameterType.FullName, out string typeName))
                    {
                        typeName = GetFriendlyName(param.ParameterType, false);
                    }

                    if (overloads.Any(other => {
                        ParameterDefinition otherParam = other.Parameters.ElementAtOrDefault(parami);
                        return
                        (otherParam != null &&
                         GetFriendlyName(otherParam.ParameterType, false) == typeName &&
                         otherParam.ParameterType.Namespace != param.ParameterType.Namespace);
                    }))
                    {
                        typeName = GetFriendlyName(param.ParameterType, true);
                    }

                    builder.Append("_");
                    builder.Append(typeName.Replace(".", "").Replace("`", ""));
                }
                name += builder.ToString();
            }

            if (hookType.FindEvent(name) != null)
            {
                string nameTmp;
                for (
                    int i = 1;
                    hookType.FindEvent(nameTmp = name + "_" + i) != null;
                    i++
                    )
                {
                    ;
                }
                name = nameTmp;
            }

            // TODO: Fix possible conflict when other members with the same names exist.

            TypeDefinition delOrig = GenerateDelegateFor(method);

            delOrig.Name = "orig_" + name;
            delOrig.CustomAttributes.Add(GenerateEditorBrowsable(EditorBrowsableState.Never));
            hookType.NestedTypes.Add(delOrig);

            TypeDefinition delHook = GenerateDelegateFor(method);

            delHook.Name = "hook_" + name;
            MethodDefinition delHookInvoke = delHook.FindMethod("Invoke");

            delHookInvoke.Parameters.Insert(0, new ParameterDefinition("orig", ParameterAttributes.None, delOrig));
            MethodDefinition delHookBeginInvoke = delHook.FindMethod("BeginInvoke");

            delHookBeginInvoke.Parameters.Insert(0, new ParameterDefinition("orig", ParameterAttributes.None, delOrig));
            delHook.CustomAttributes.Add(GenerateEditorBrowsable(EditorBrowsableState.Never));
            hookType.NestedTypes.Add(delHook);

            ILProcessor           il;
            GenericInstanceMethod endpointMethod;

            MethodReference methodRef = OutputModule.ImportReference(method);

            #region Hook

            MethodDefinition addHook = new MethodDefinition(
                "add_" + name,
                MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Static,
                OutputModule.TypeSystem.Void
                );
            addHook.Parameters.Add(new ParameterDefinition(null, ParameterAttributes.None, delHook));
            addHook.Body = new MethodBody(addHook);
            il           = addHook.Body.GetILProcessor();
            il.Emit(OpCodes.Ldtoken, methodRef);
            il.Emit(OpCodes.Call, m_GetMethodFromHandle);
            il.Emit(OpCodes.Ldarg_0);
            endpointMethod = new GenericInstanceMethod(m_Add);
            endpointMethod.GenericArguments.Add(delHook);
            il.Emit(OpCodes.Call, endpointMethod);
            il.Emit(OpCodes.Ret);
            hookType.Methods.Add(addHook);

            MethodDefinition removeHook = new MethodDefinition(
                "remove_" + name,
                MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Static,
                OutputModule.TypeSystem.Void
                );
            removeHook.Parameters.Add(new ParameterDefinition(null, ParameterAttributes.None, delHook));
            removeHook.Body = new MethodBody(removeHook);
            il = removeHook.Body.GetILProcessor();
            il.Emit(OpCodes.Ldtoken, methodRef);
            il.Emit(OpCodes.Call, m_GetMethodFromHandle);
            il.Emit(OpCodes.Ldarg_0);
            endpointMethod = new GenericInstanceMethod(m_Remove);
            endpointMethod.GenericArguments.Add(delHook);
            il.Emit(OpCodes.Call, endpointMethod);
            il.Emit(OpCodes.Ret);
            hookType.Methods.Add(removeHook);

            EventDefinition evHook = new EventDefinition(name, EventAttributes.None, delHook)
            {
                AddMethod    = addHook,
                RemoveMethod = removeHook
            };
            hookType.Events.Add(evHook);

            #endregion

            #region Hook IL

            MethodDefinition addIL = new MethodDefinition(
                "add_" + name,
                MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Static,
                OutputModule.TypeSystem.Void
                );
            addIL.Parameters.Add(new ParameterDefinition(null, ParameterAttributes.None, t_ILManipulator));
            addIL.Body = new MethodBody(addIL);
            il         = addIL.Body.GetILProcessor();
            il.Emit(OpCodes.Ldtoken, methodRef);
            il.Emit(OpCodes.Call, m_GetMethodFromHandle);
            il.Emit(OpCodes.Ldarg_0);
            endpointMethod = new GenericInstanceMethod(m_Modify);
            endpointMethod.GenericArguments.Add(delHook);
            il.Emit(OpCodes.Call, endpointMethod);
            il.Emit(OpCodes.Ret);
            hookILType.Methods.Add(addIL);

            MethodDefinition removeIL = new MethodDefinition(
                "remove_" + name,
                MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Static,
                OutputModule.TypeSystem.Void
                );
            removeIL.Parameters.Add(new ParameterDefinition(null, ParameterAttributes.None, t_ILManipulator));
            removeIL.Body = new MethodBody(removeIL);
            il            = removeIL.Body.GetILProcessor();
            il.Emit(OpCodes.Ldtoken, methodRef);
            il.Emit(OpCodes.Call, m_GetMethodFromHandle);
            il.Emit(OpCodes.Ldarg_0);
            endpointMethod = new GenericInstanceMethod(m_Unmodify);
            endpointMethod.GenericArguments.Add(delHook);
            il.Emit(OpCodes.Call, endpointMethod);
            il.Emit(OpCodes.Ret);
            hookILType.Methods.Add(removeIL);

            EventDefinition evIL = new EventDefinition(name, EventAttributes.None, t_ILManipulator)
            {
                AddMethod    = addIL,
                RemoveMethod = removeIL
            };
            hookILType.Events.Add(evIL);

            #endregion

            return(true);
        }
示例#40
0
 public static IEnumerable <string> GetOverlays(EventDefinition definition)
 {
     return((definition.AddMethod != null) ? GetOverlays(definition.AddMethod) : Enumerable.Empty <string>());
 }
示例#41
0
 protected virtual void ProcessEvent(TypeDefinition type, EventDefinition @event, XPathNavigator nav, object customData)
 {
 }
示例#42
0
        MethodBody[] GetMethodBodies(MemberReference member)
        {
            if (member is MethodReference)
            {
                return(new[] { (((MethodReference)member).Resolve()).Body });
            }
            if (member is PropertyReference)
            {
                PropertyDefinition prop = (PropertyDefinition)member;
                return(new[] {
                    prop.GetMethod != null ? prop.GetMethod.Body : null,
                    prop.SetMethod != null ? prop.SetMethod.Body : null,
                });
            }
            if (member is FieldReference)
            {
                return new MethodBody[] {}
            }
            ;
            if (member is EventReference)
            {
                EventDefinition ev = (EventDefinition)member;

                return(new[] {
                    ev.AddMethod != null ? ev.AddMethod.Body : null,
                    ev.InvokeMethod != null ? ev.InvokeMethod.Body : null,
                    ev.RemoveMethod != null ? ev.RemoveMethod.Body : null,
                });
            }
            throw new NotSupportedException("Unsupported member type: " + member.GetType().FullName);
        }

        void FillExceptions(MethodBody body, Dictionary <string, ExceptionSources> exceptions)
        {
            for (int i = 0; i < body.Instructions.Count; ++i)
            {
                Instruction instruction = body.Instructions [i];
                switch (instruction.OpCode.Code)
                {
                case Code.Call:
                case Code.Callvirt: {
                    if ((locations & ExceptionLocations.Assembly) == 0 &&
                        (locations & ExceptionLocations.DependentAssemblies) == 0)
                    {
                        break;
                    }
                    MemberReference memberRef = ((MemberReference)instruction.Operand);
                    if (((locations & ExceptionLocations.Assembly) != 0 &&
                         body.Method.DeclaringType.Scope.Name == memberRef.DeclaringType.Scope.Name) ||
                        ((locations & ExceptionLocations.DependentAssemblies) != 0 &&
                         body.Method.DeclaringType.Scope.Name != memberRef.DeclaringType.Scope.Name))
                    {
                        IEnumerable <ExceptionSources> memberExceptions = this [memberRef];
                        AddExceptions(body, instruction,
                                      memberExceptions.Select(es => es.Exception),
                                      memberExceptions.SelectMany(es => es.Sources),
                                      exceptions);
                    }
                    break;
                }

                case Code.Newobj: {
                    MethodReference ctor = (MethodReference)instruction.Operand;
                    if (IsExceptionConstructor(ctor))
                    {
                        AddExceptions(body, instruction,
                                      new TypeReference[] { ctor.DeclaringType },
                                      new MemberReference[] { body.Method },
                                      exceptions);
                    }
                    break;
                }
                }
            }
        }

        void AddExceptions(MethodBody body, Instruction instruction, IEnumerable <TypeReference> add, IEnumerable <MemberReference> sources,
                           Dictionary <string, ExceptionSources> exceptions)
        {
            var handlers = body.ExceptionHandlers.Cast <ExceptionHandler> ()
                           .Where(eh => instruction.Offset >= eh.TryStart.Offset &&
                                  instruction.Offset <= eh.TryEnd.Offset);

            foreach (var ex in add)
            {
                if (!handlers.Any(h => IsExceptionCaught(ex, h.CatchType)))
                {
                    ExceptionSources s;
                    string           eName = xdoc.GetDeclaration(ex);
                    if (!exceptions.TryGetValue(eName, out s))
                    {
                        s = new ExceptionSources(ex);
                        exceptions.Add(eName, s);
                    }
                    foreach (var m in sources)
                    {
                        s.Sources.Add(m);
                    }
                }
            }
        }
示例#43
0
 public CecilEvent(CecilTypeSystem typeSystem, EventDefinition ev, TypeReference declaringType)
 {
     _declaringType = declaringType;
     TypeSystem     = typeSystem;
     Event          = ev;
 }
示例#44
0
 protected sealed override RoMethod ComputeEventRaiseMethod() => EventDefinition.GetAccessors().Raiser.ToMethodOrNull(GetRoDeclaringType(), ReflectedType);
示例#45
0
 static string GetEventSignature(EventDefinition @event)
 {
     return(@event.EventType.FullName + " " + @event.Name);
 }
 private static void VisitEvent(EventDefinition evt, StringBuilder builder)
 {
     builder.Append(EventPrefix);
     PartVisitor.Instance.VisitEvent(evt, builder);
 }
示例#47
0
 static bool IsEventUsed(EventDefinition evt)
 {
     return(evt.AddMethod != null || evt.InvokeMethod != null || evt.RemoveMethod != null);
 }
示例#48
0
        protected void Page_Load(object sender, EventArgs e)
        {
            ContextBusClient cbClient = new ContextBusClient();

            //Get Employee definition from adventure works:
            ConnectionParam[] parameters = cbClient.LoadConnection("advworks", AdvWorksConnectorId);
            cbClient.Login(parameters, AdvWorksConnectorId);
            FlyweightObjectDefinition flyweight = new FlyweightObjectDefinition()
            {
                Id = "HumanResources.Employee"
            };
            ObjectDefinition employeeObjDef = cbClient.GetObjectDefinitionList(new FlyweightObjectDefinition[] { flyweight }, AdvWorksConnectorId).First();

            //Get Team definition from Sharepoint
            parameters = cbClient.LoadConnection("Sharepoint-Team", "SharePoint");
            cbClient.Login(parameters, "SharePoint");
            flyweight = new FlyweightObjectDefinition()
            {
                Id = "SP|List|/sites/SiteCollection1|Team"
            };
            ObjectDefinition sharepointObjDef = cbClient.GetObjectDefinitionList(new FlyweightObjectDefinition[] { flyweight }, "SharePoint").First();


            //build the workflow.
            TaskManagerClient taskClient = new TaskManagerClient();

            //1. Create login task
            LoginTask login = taskClient.CreateLoginTask(AdvWorksConnectorId, "advworks");

            //2. Create Mapping Task
            MappingTask map = taskClient.CreateMappingTask(sharepointObjDef, employeeObjDef);

            MappableField field = map.TargetFields.SingleOrDefault(f => f.Id == "p.BusinessEntityID");

            field.Mapping.MappingType = MappingType.ConstMapping;
            field.Mapping.Value       = 1;

            field = map.TargetFields.SingleOrDefault(f => f.Id == "p.EmailPromotion");
            field.Mapping.MappingType = MappingType.ConstMapping;
            field.Mapping.Value       = 0;

            field = map.TargetFields.SingleOrDefault(f => f.Id == "p.Demographics");
            field.Mapping.MappingType = MappingType.ConstMapping;
            field.Mapping.Value       = "";

            field = map.TargetFields.SingleOrDefault(f => f.Id == "p.NameStyle");
            field.Mapping.MappingType = MappingType.ConstMapping;
            field.Mapping.Value       = false;

            field = map.TargetFields.SingleOrDefault(f => f.Id == "p.PersonType");
            field.Mapping.MappingType = MappingType.ConstMapping;
            field.Mapping.Value       = "EM";

            field = map.TargetFields.SingleOrDefault(f => f.Id == "p.FirstName");
            field.Mapping.MappingType = MappingType.FieldMapping;
            field.Mapping.Value       = "First_x0020_Name";

            field = map.TargetFields.SingleOrDefault(f => f.Id == "p.LastName");
            field.Mapping.MappingType = MappingType.FieldMapping;
            field.Mapping.Value       = "Last_x0020_Name";

            field = map.TargetFields.SingleOrDefault(f => f.Id == "e.JobTitle");
            field.Mapping.MappingType = MappingType.FieldMapping;
            field.Mapping.Value       = "Title";

            //3. Save Task
            SaveObjectInstanceTask saveSharepointToEktron = taskClient.CreateSaveObjectTask(AdvWorksConnectorId);

            //4. Logout Task
            LogoutTask logout = taskClient.CreateLogoutTask(AdvWorksConnectorId);

            //5. Assemble and save workflow
            string   workflowName       = string.Concat("My Test Workflow");
            Workflow workflow           = taskClient.CreateWorkflow(workflowName);
            List <ContextBusTask> tasks = new List <ContextBusTask>();

            tasks.Add(login);
            tasks.Add(map);
            tasks.Add(saveSharepointToEktron);
            tasks.Add(logout);
            workflow.Tasks = tasks.ToArray();
            taskClient.SaveWorkflow(workflow);

            //3. Create associated Event Definitions for workflow.
            EventManagerClient eventClient = new EventManagerClient();
            EventDefinition    eventDef    = new EventDefinition()
            {
                Id      = workflowName,
                Payload = map.SourceObject
            };

            eventClient.AssociateWorkflowsToEvent(new string[] { workflow.WorkflowName }, eventDef);



            //
            //Now raise the event to perform the workflow!
            //

            //first get sharpeoint item
            ObjectInstanceCriteriaFilter criteria = new ObjectInstanceCriteriaFilter();

            criteria.Filters = new CriteriaFilter[0];
            ObjectInstanceList sharepointObjInstance = cbClient.GetObjectInstanceList(sharepointObjDef, criteria, "SharePoint");

            //create event instance with sharepoint item
            EventInstance itemEvent = new EventInstance()
            {
                Id      = workflowName,
                Payload = sharepointObjInstance.Results.First()
            };

            //raise the event.
            eventClient.RaiseEvent(itemEvent);
        }
示例#49
0
 public virtual void VisitEventDefinition(EventDefinition evt)
 {
 }
示例#50
0
 public ActionResult AddEvent(EventDefinition eventDefinition)
 {
     _eventDefinitionService.Create(eventDefinition);
     return(RedirectToAction("EventDefinitions"));
 }
示例#51
0
        protected void Page_Load(object sender, EventArgs e)
        {
            ContextBusClient cbClient = new ContextBusClient();

            //Get Employee definition from adventure works:
            ConnectionParam[] parameters = cbClient.LoadConnection("advworks", AdvWorksConnectorId);
            cbClient.Login(parameters, AdvWorksConnectorId);
            FlyweightObjectDefinition flyweight = new FlyweightObjectDefinition() { Id = "HumanResources.Employee" };
            ObjectDefinition employeeObjDef = cbClient.GetObjectDefinitionList(new FlyweightObjectDefinition[] { flyweight }, AdvWorksConnectorId).First();

            //Get Team definition from Sharepoint
            parameters = cbClient.LoadConnection("Sharepoint-Team", "SharePoint");
            cbClient.Login(parameters, "SharePoint");
            flyweight = new FlyweightObjectDefinition() { Id = "SP|List|/sites/SiteCollection1|Team" };
            ObjectDefinition sharepointObjDef = cbClient.GetObjectDefinitionList(new FlyweightObjectDefinition[] { flyweight }, "SharePoint").First();

            //build the workflow.
            TaskManagerClient taskClient = new TaskManagerClient();

            //1. Create login task
            LoginTask login = taskClient.CreateLoginTask(AdvWorksConnectorId, "advworks");

            //2. Create Mapping Task
            MappingTask map = taskClient.CreateMappingTask(sharepointObjDef, employeeObjDef);

            MappableField field = map.TargetFields.SingleOrDefault(f => f.Id == "p.BusinessEntityID");
            field.Mapping.MappingType = MappingType.ConstMapping;
            field.Mapping.Value = 1;

            field = map.TargetFields.SingleOrDefault(f => f.Id == "p.EmailPromotion");
            field.Mapping.MappingType = MappingType.ConstMapping;
            field.Mapping.Value = 0;

            field = map.TargetFields.SingleOrDefault(f => f.Id == "p.Demographics");
            field.Mapping.MappingType = MappingType.ConstMapping;
            field.Mapping.Value = "";

            field = map.TargetFields.SingleOrDefault(f => f.Id == "p.NameStyle");
            field.Mapping.MappingType = MappingType.ConstMapping;
            field.Mapping.Value = false;

            field = map.TargetFields.SingleOrDefault(f => f.Id == "p.PersonType");
            field.Mapping.MappingType = MappingType.ConstMapping;
            field.Mapping.Value = "EM";

            field = map.TargetFields.SingleOrDefault(f => f.Id == "p.FirstName");
            field.Mapping.MappingType = MappingType.FieldMapping;
            field.Mapping.Value = "First_x0020_Name";

            field = map.TargetFields.SingleOrDefault(f => f.Id == "p.LastName");
            field.Mapping.MappingType = MappingType.FieldMapping;
            field.Mapping.Value = "Last_x0020_Name";

            field = map.TargetFields.SingleOrDefault(f => f.Id == "e.JobTitle");
            field.Mapping.MappingType = MappingType.FieldMapping;
            field.Mapping.Value = "Title";

            //3. Save Task
            SaveObjectInstanceTask saveSharepointToEktron = taskClient.CreateSaveObjectTask(AdvWorksConnectorId);

            //4. Logout Task
            LogoutTask logout = taskClient.CreateLogoutTask(AdvWorksConnectorId);

            //5. Assemble and save workflow
            string workflowName = string.Concat("My Test Workflow");
            Workflow workflow = taskClient.CreateWorkflow(workflowName);
            List<ContextBusTask> tasks = new List<ContextBusTask>();
            tasks.Add(login);
            tasks.Add(map);
            tasks.Add(saveSharepointToEktron);
            tasks.Add(logout);
            workflow.Tasks = tasks.ToArray();
            taskClient.SaveWorkflow(workflow);

            //3. Create associated Event Definitions for workflow.
            EventManagerClient eventClient = new EventManagerClient();
            EventDefinition eventDef = new EventDefinition()
            {
                Id = workflowName,
                Payload = map.SourceObject
            };
            eventClient.AssociateWorkflowsToEvent(new string[] { workflow.WorkflowName }, eventDef);

            //
            //Now raise the event to perform the workflow!
            //

            //first get sharpeoint item
            ObjectInstanceCriteriaFilter criteria = new ObjectInstanceCriteriaFilter();
            criteria.Filters = new CriteriaFilter[0];
            ObjectInstanceList sharepointObjInstance = cbClient.GetObjectInstanceList(sharepointObjDef, criteria, "SharePoint");

            //create event instance with sharepoint item
            EventInstance itemEvent = new EventInstance()
            {
                Id = workflowName,
                Payload = sharepointObjInstance.Results.First()
            };

            //raise the event.
            eventClient.RaiseEvent(itemEvent);
        }
示例#52
0
 protected virtual void Process(EventDefinition @event)
 {
 }
 static bool IsNamedPropertyChanged(EventDefinition eventDefinition)
 {
     return eventDefinition.Name == "PropertyChanged" ||
            eventDefinition.Name == "System.ComponentModel.INotifyPropertyChanged.PropertyChanged" ||
            eventDefinition.Name == "Windows.UI.Xaml.Data.PropertyChanged";
 }
示例#54
0
文件: ildasm.cs 项目: sesef/mono
	void EmitEvent (EventDefinition e) {
		WriteLine (".event " + StringifyTypeRef (e.EventType) + " " + EscapeName (e.Name));
		WriteLine ("{");
		indent ++;
		if (e.AddMethod != null)
			WriteLine (".addon " + StringifyMethodRef (e.AddMethod));
		if (e.RemoveMethod != null)
			WriteLine (".removeon " + StringifyMethodRef (e.RemoveMethod));
		foreach (var m in e.OtherMethods)
			WriteLine (".other " + StringifyMethodRef (m));
		indent --;
		WriteLine ("}");
	}
示例#55
0
 internal ITypeReference/*?*/ GetEventType(
   EventDefinition moduleEvent
 ) {
   uint typeToken = this.PEFileReader.EventTable.GetEventType(moduleEvent.EventRowId);
   return this.GetTypeReferenceForToken(moduleEvent, typeToken);
 }
        public void PutRoomImage(EventDefinition eventDefinition)
        {
            ValidateEventAuthorization(eventDefinition.EventDefinitionId);

            _eventDefinitionRepository.UpdateRoomImage(eventDefinition);
        }
示例#57
0
 internal IEnumerable<IMethodReference> GetEventAccessorMethods(
   EventDefinition eventDefinition
 ) {
   uint methodSemanticRowIdStart;
   uint methodSemanticRowIdEnd;
   this.GetSemanticInfoForEvent(eventDefinition.EventRowId, out methodSemanticRowIdStart, out methodSemanticRowIdEnd);
   for (uint methSemRowIdIter = methodSemanticRowIdStart; methSemRowIdIter < methodSemanticRowIdEnd; ++methSemRowIdIter) {
     MethodSemanticsRow methodSemanticRow = this.PEFileReader.MethodSemanticsTable[methSemRowIdIter];
     IMethodDefinition/*?*/ methodDef = this.GetMethodDefAtRow(methodSemanticRow.Method);
     if (methodDef != null) {
       yield return methodDef;
     } else {
       yield return Dummy.MethodReference;
     }
   }
 }
        public DummyAssemblyGenerator(Il2CppExecutor il2CppExecutor)
        {
            executor = il2CppExecutor;
            metadata = il2CppExecutor.metadata;
            il2Cpp   = il2CppExecutor.il2Cpp;

            //Il2CppDummyDll
            var il2CppDummyDll = Il2CppDummyDll.Create();

            Assemblies.Add(il2CppDummyDll);
            var addressAttribute     = il2CppDummyDll.MainModule.Types.First(x => x.Name == "AddressAttribute").Methods[0];
            var fieldOffsetAttribute = il2CppDummyDll.MainModule.Types.First(x => x.Name == "FieldOffsetAttribute").Methods[0];

            attributeAttribute = il2CppDummyDll.MainModule.Types.First(x => x.Name == "AttributeAttribute").Methods[0];
            var metadataOffsetAttribute = il2CppDummyDll.MainModule.Types.First(x => x.Name == "MetadataOffsetAttribute").Methods[0];
            var tokenAttribute          = il2CppDummyDll.MainModule.Types.First(x => x.Name == "TokenAttribute").Methods[0];

            stringType = il2CppDummyDll.MainModule.TypeSystem.String;

            var resolver         = new MyAssemblyResolver();
            var moduleParameters = new ModuleParameters
            {
                Kind             = ModuleKind.Dll,
                AssemblyResolver = resolver
            };

            resolver.Register(il2CppDummyDll);

            var fieldDefinitionDic     = new Dictionary <int, FieldDefinition>();
            var methodDefinitionDic    = new Dictionary <int, MethodDefinition>();
            var parameterDefinitionDic = new Dictionary <int, ParameterDefinition>();
            var propertyDefinitionDic  = new Dictionary <int, PropertyDefinition>();
            var eventDefinitionDic     = new Dictionary <int, EventDefinition>();

            //创建程序集,同时创建所有类
            foreach (var imageDef in metadata.imageDefs)
            {
                var imageName          = metadata.GetStringFromIndex(imageDef.nameIndex);
                var assemblyName       = new AssemblyNameDefinition(imageName.Replace(".dll", ""), new Version("3.7.1.6"));
                var assemblyDefinition = AssemblyDefinition.CreateAssembly(assemblyName, imageName, moduleParameters);
                resolver.Register(assemblyDefinition);
                Assemblies.Add(assemblyDefinition);
                var moduleDefinition = assemblyDefinition.MainModule;
                moduleDefinition.Types.Clear();//清除自动创建的<Module>类
                var typeEnd = imageDef.typeStart + imageDef.typeCount;
                for (var index = imageDef.typeStart; index < typeEnd; ++index)
                {
                    var            typeDef       = metadata.typeDefs[index];
                    var            namespaceName = metadata.GetStringFromIndex(typeDef.namespaceIndex);
                    var            typeName      = metadata.GetStringFromIndex(typeDef.nameIndex);
                    TypeDefinition typeDefinition;
                    if (typeDef.declaringTypeIndex != -1)//nested types
                    {
                        typeDefinition = typeDefinitionDic[typeDef];
                    }
                    else
                    {
                        typeDefinition = new TypeDefinition(namespaceName, typeName, (TypeAttributes)typeDef.flags);
                        moduleDefinition.Types.Add(typeDefinition);
                        typeDefinitionDic.Add(typeDef, typeDefinition);
                    }
                    //nestedtype
                    for (int i = 0; i < typeDef.nested_type_count; i++)
                    {
                        var nestedIndex          = metadata.nestedTypeIndices[typeDef.nestedTypesStart + i];
                        var nestedTypeDef        = metadata.typeDefs[nestedIndex];
                        var nestedTypeDefinition = new TypeDefinition(metadata.GetStringFromIndex(nestedTypeDef.namespaceIndex), metadata.GetStringFromIndex(nestedTypeDef.nameIndex), (TypeAttributes)nestedTypeDef.flags);
                        typeDefinition.NestedTypes.Add(nestedTypeDefinition);
                        typeDefinitionDic.Add(nestedTypeDef, nestedTypeDefinition);
                    }
                }
            }
            //提前处理
            for (var index = 0; index < metadata.typeDefs.Length; ++index)
            {
                var typeDef        = metadata.typeDefs[index];
                var typeDefinition = typeDefinitionDic[typeDef];

                var customTokenAttribute = new CustomAttribute(typeDefinition.Module.ImportReference(tokenAttribute));
                customTokenAttribute.Fields.Add(new CustomAttributeNamedArgument("Token", new CustomAttributeArgument(stringType, $"0x{typeDef.token:X}")));
                typeDefinition.CustomAttributes.Add(customTokenAttribute);

                //genericParameter
                if (typeDef.genericContainerIndex >= 0)
                {
                    var genericContainer = metadata.genericContainers[typeDef.genericContainerIndex];
                    for (int i = 0; i < genericContainer.type_argc; i++)
                    {
                        var genericParameterIndex = genericContainer.genericParameterStart + i;
                        var genericParameter      = CreateGenericParameter(genericParameterIndex, typeDefinition);
                        typeDefinition.GenericParameters.Add(genericParameter);
                    }
                }

                //parent
                if (typeDef.parentIndex >= 0)
                {
                    var parentType    = il2Cpp.types[typeDef.parentIndex];
                    var parentTypeRef = GetTypeReference(typeDefinition, parentType);
                    typeDefinition.BaseType = parentTypeRef;
                }

                //interfaces
                for (int i = 0; i < typeDef.interfaces_count; i++)
                {
                    var interfaceType    = il2Cpp.types[metadata.interfaceIndices[typeDef.interfacesStart + i]];
                    var interfaceTypeRef = GetTypeReference(typeDefinition, interfaceType);
                    typeDefinition.Interfaces.Add(new InterfaceImplementation(interfaceTypeRef));
                }
            }
            //处理field, method, property等等
            foreach (var imageDef in metadata.imageDefs)
            {
                var imageName = metadata.GetStringFromIndex(imageDef.nameIndex);
                var typeEnd   = imageDef.typeStart + imageDef.typeCount;
                for (int index = imageDef.typeStart; index < typeEnd; index++)
                {
                    var typeDef        = metadata.typeDefs[index];
                    var typeDefinition = typeDefinitionDic[typeDef];

                    //field
                    var fieldEnd = typeDef.fieldStart + typeDef.field_count;
                    for (var i = typeDef.fieldStart; i < fieldEnd; ++i)
                    {
                        var fieldDef        = metadata.fieldDefs[i];
                        var fieldType       = il2Cpp.types[fieldDef.typeIndex];
                        var fieldName       = metadata.GetStringFromIndex(fieldDef.nameIndex);
                        var fieldTypeRef    = GetTypeReference(typeDefinition, fieldType);
                        var fieldDefinition = new FieldDefinition(fieldName, (FieldAttributes)fieldType.attrs, fieldTypeRef);
                        typeDefinition.Fields.Add(fieldDefinition);
                        fieldDefinitionDic.Add(i, fieldDefinition);

                        var customTokenAttribute = new CustomAttribute(typeDefinition.Module.ImportReference(tokenAttribute));
                        customTokenAttribute.Fields.Add(new CustomAttributeNamedArgument("Token", new CustomAttributeArgument(stringType, $"0x{fieldDef.token:X}")));
                        fieldDefinition.CustomAttributes.Add(customTokenAttribute);

                        //fieldDefault
                        if (metadata.GetFieldDefaultValueFromIndex(i, out var fieldDefault) && fieldDefault.dataIndex != -1)
                        {
                            if (TryGetDefaultValue(fieldDefault.typeIndex, fieldDefault.dataIndex, out var value))
                            {
                                fieldDefinition.Constant = value;
                            }
                            else
                            {
                                var customAttribute = new CustomAttribute(typeDefinition.Module.ImportReference(metadataOffsetAttribute));
                                var offset          = new CustomAttributeNamedArgument("Offset", new CustomAttributeArgument(stringType, $"0x{value:X}"));
                                customAttribute.Fields.Add(offset);
                                fieldDefinition.CustomAttributes.Add(customAttribute);
                            }
                        }
                        //fieldOffset
                        if (!fieldDefinition.IsLiteral)
                        {
                            var fieldOffset = il2Cpp.GetFieldOffsetFromIndex(index, i - typeDef.fieldStart, i, typeDefinition.IsValueType, fieldDefinition.IsStatic);
                            if (fieldOffset >= 0)
                            {
                                var customAttribute = new CustomAttribute(typeDefinition.Module.ImportReference(fieldOffsetAttribute));
                                var offset          = new CustomAttributeNamedArgument("Offset", new CustomAttributeArgument(stringType, $"0x{fieldOffset:X}"));
                                customAttribute.Fields.Add(offset);
                                fieldDefinition.CustomAttributes.Add(customAttribute);
                            }
                        }
                    }
                    //method
                    var methodEnd = typeDef.methodStart + typeDef.method_count;
                    for (var i = typeDef.methodStart; i < methodEnd; ++i)
                    {
                        var methodDef        = metadata.methodDefs[i];
                        var methodName       = metadata.GetStringFromIndex(methodDef.nameIndex);
                        var methodDefinition = new MethodDefinition(methodName, (MethodAttributes)methodDef.flags, typeDefinition.Module.ImportReference(typeof(void)));
                        methodDefinition.ImplAttributes = (MethodImplAttributes)methodDef.iflags;
                        typeDefinition.Methods.Add(methodDefinition);
                        //genericParameter
                        if (methodDef.genericContainerIndex >= 0)
                        {
                            var genericContainer = metadata.genericContainers[methodDef.genericContainerIndex];
                            for (int j = 0; j < genericContainer.type_argc; j++)
                            {
                                var genericParameterIndex = genericContainer.genericParameterStart + j;
                                var genericParameter      = CreateGenericParameter(genericParameterIndex, methodDefinition);
                                methodDefinition.GenericParameters.Add(genericParameter);
                            }
                        }
                        var methodReturnType = il2Cpp.types[methodDef.returnType];
                        var returnType       = GetTypeReferenceWithByRef(methodDefinition, methodReturnType);
                        methodDefinition.ReturnType = returnType;

                        var customTokenAttribute = new CustomAttribute(typeDefinition.Module.ImportReference(tokenAttribute));
                        customTokenAttribute.Fields.Add(new CustomAttributeNamedArgument("Token", new CustomAttributeArgument(stringType, $"0x{methodDef.token:X}")));
                        methodDefinition.CustomAttributes.Add(customTokenAttribute);

                        if (methodDefinition.HasBody && typeDefinition.BaseType?.FullName != "System.MulticastDelegate")
                        {
                            var ilprocessor = methodDefinition.Body.GetILProcessor();
                            if (returnType.FullName == "System.Void")
                            {
                                ilprocessor.Append(ilprocessor.Create(OpCodes.Ret));
                            }
                            else if (returnType.IsValueType)
                            {
                                var variable = new VariableDefinition(returnType);
                                methodDefinition.Body.Variables.Add(variable);
                                ilprocessor.Append(ilprocessor.Create(OpCodes.Ldloca_S, variable));
                                ilprocessor.Append(ilprocessor.Create(OpCodes.Initobj, returnType));
                                ilprocessor.Append(ilprocessor.Create(OpCodes.Ldloc_0));
                                ilprocessor.Append(ilprocessor.Create(OpCodes.Ret));
                            }
                            else
                            {
                                ilprocessor.Append(ilprocessor.Create(OpCodes.Ldnull));
                                ilprocessor.Append(ilprocessor.Create(OpCodes.Ret));
                            }
                        }
                        methodDefinitionDic.Add(i, methodDefinition);
                        //method parameter
                        for (var j = 0; j < methodDef.parameterCount; ++j)
                        {
                            var parameterDef        = metadata.parameterDefs[methodDef.parameterStart + j];
                            var parameterName       = metadata.GetStringFromIndex(parameterDef.nameIndex);
                            var parameterType       = il2Cpp.types[parameterDef.typeIndex];
                            var parameterTypeRef    = GetTypeReferenceWithByRef(methodDefinition, parameterType);
                            var parameterDefinition = new ParameterDefinition(parameterName, (ParameterAttributes)parameterType.attrs, parameterTypeRef);
                            methodDefinition.Parameters.Add(parameterDefinition);
                            parameterDefinitionDic.Add(methodDef.parameterStart + j, parameterDefinition);
                            //ParameterDefault
                            if (metadata.GetParameterDefaultValueFromIndex(methodDef.parameterStart + j, out var parameterDefault) && parameterDefault.dataIndex != -1)
                            {
                                if (TryGetDefaultValue(parameterDefault.typeIndex, parameterDefault.dataIndex, out var value))
                                {
                                    parameterDefinition.Constant = value;
                                }
                                else
                                {
                                    var customAttribute = new CustomAttribute(typeDefinition.Module.ImportReference(metadataOffsetAttribute));
                                    var offset          = new CustomAttributeNamedArgument("Offset", new CustomAttributeArgument(stringType, $"0x{value:X}"));
                                    customAttribute.Fields.Add(offset);
                                    parameterDefinition.CustomAttributes.Add(customAttribute);
                                }
                            }
                        }
                        //methodAddress
                        var methodPointer = il2Cpp.GetMethodPointer(imageName, methodDef);
                        if (methodPointer > 0)
                        {
                            var customAttribute    = new CustomAttribute(typeDefinition.Module.ImportReference(addressAttribute));
                            var fixedMethodPointer = il2Cpp.GetRVA(methodPointer);
                            var rva    = new CustomAttributeNamedArgument("RVA", new CustomAttributeArgument(stringType, $"0x{fixedMethodPointer:X}"));
                            var offset = new CustomAttributeNamedArgument("Offset", new CustomAttributeArgument(stringType, $"0x{il2Cpp.MapVATR(methodPointer):X}"));
                            var va     = new CustomAttributeNamedArgument("VA", new CustomAttributeArgument(stringType, $"0x{methodPointer:X}"));
                            customAttribute.Fields.Add(rva);
                            customAttribute.Fields.Add(offset);
                            customAttribute.Fields.Add(va);
                            if (methodDef.slot != ushort.MaxValue)
                            {
                                var slot = new CustomAttributeNamedArgument("Slot", new CustomAttributeArgument(stringType, methodDef.slot.ToString()));
                                customAttribute.Fields.Add(slot);
                            }
                            methodDefinition.CustomAttributes.Add(customAttribute);
                        }
                    }
                    //property
                    var propertyEnd = typeDef.propertyStart + typeDef.property_count;
                    for (var i = typeDef.propertyStart; i < propertyEnd; ++i)
                    {
                        var              propertyDef  = metadata.propertyDefs[i];
                        var              propertyName = metadata.GetStringFromIndex(propertyDef.nameIndex);
                        TypeReference    propertyType = null;
                        MethodDefinition GetMethod    = null;
                        MethodDefinition SetMethod    = null;
                        if (propertyDef.get >= 0)
                        {
                            GetMethod    = methodDefinitionDic[typeDef.methodStart + propertyDef.get];
                            propertyType = GetMethod.ReturnType;
                        }
                        if (propertyDef.set >= 0)
                        {
                            SetMethod = methodDefinitionDic[typeDef.methodStart + propertyDef.set];
                            if (propertyType == null)
                            {
                                propertyType = SetMethod.Parameters[0].ParameterType;
                            }
                        }
                        var propertyDefinition = new PropertyDefinition(propertyName, (PropertyAttributes)propertyDef.attrs, propertyType)
                        {
                            GetMethod = GetMethod,
                            SetMethod = SetMethod
                        };
                        typeDefinition.Properties.Add(propertyDefinition);
                        propertyDefinitionDic.Add(i, propertyDefinition);

                        var customTokenAttribute = new CustomAttribute(typeDefinition.Module.ImportReference(tokenAttribute));
                        customTokenAttribute.Fields.Add(new CustomAttributeNamedArgument("Token", new CustomAttributeArgument(stringType, $"0x{propertyDef.token:X}")));
                        propertyDefinition.CustomAttributes.Add(customTokenAttribute);
                    }
                    //event
                    var eventEnd = typeDef.eventStart + typeDef.event_count;
                    for (var i = typeDef.eventStart; i < eventEnd; ++i)
                    {
                        var eventDef        = metadata.eventDefs[i];
                        var eventName       = metadata.GetStringFromIndex(eventDef.nameIndex);
                        var eventType       = il2Cpp.types[eventDef.typeIndex];
                        var eventTypeRef    = GetTypeReference(typeDefinition, eventType);
                        var eventDefinition = new EventDefinition(eventName, (EventAttributes)eventType.attrs, eventTypeRef);
                        if (eventDef.add >= 0)
                        {
                            eventDefinition.AddMethod = methodDefinitionDic[typeDef.methodStart + eventDef.add];
                        }
                        if (eventDef.remove >= 0)
                        {
                            eventDefinition.RemoveMethod = methodDefinitionDic[typeDef.methodStart + eventDef.remove];
                        }
                        if (eventDef.raise >= 0)
                        {
                            eventDefinition.InvokeMethod = methodDefinitionDic[typeDef.methodStart + eventDef.raise];
                        }
                        typeDefinition.Events.Add(eventDefinition);
                        eventDefinitionDic.Add(i, eventDefinition);

                        var customTokenAttribute = new CustomAttribute(typeDefinition.Module.ImportReference(tokenAttribute));
                        customTokenAttribute.Fields.Add(new CustomAttributeNamedArgument("Token", new CustomAttributeArgument(stringType, $"0x{eventDef.token:X}")));
                        eventDefinition.CustomAttributes.Add(customTokenAttribute);
                    }
                }
            }
            //第三遍,添加CustomAttribute
            if (il2Cpp.Version > 20)
            {
                PrepareCustomAttribute();
                foreach (var imageDef in metadata.imageDefs)
                {
                    var typeEnd = imageDef.typeStart + imageDef.typeCount;
                    for (int index = imageDef.typeStart; index < typeEnd; index++)
                    {
                        var typeDef        = metadata.typeDefs[index];
                        var typeDefinition = typeDefinitionDic[typeDef];
                        //typeAttribute
                        CreateCustomAttribute(imageDef, typeDef.customAttributeIndex, typeDef.token, typeDefinition.Module, typeDefinition.CustomAttributes);

                        //field
                        var fieldEnd = typeDef.fieldStart + typeDef.field_count;
                        for (var i = typeDef.fieldStart; i < fieldEnd; ++i)
                        {
                            var fieldDef        = metadata.fieldDefs[i];
                            var fieldDefinition = fieldDefinitionDic[i];
                            //fieldAttribute
                            CreateCustomAttribute(imageDef, fieldDef.customAttributeIndex, fieldDef.token, typeDefinition.Module, fieldDefinition.CustomAttributes);
                        }

                        //method
                        var methodEnd = typeDef.methodStart + typeDef.method_count;
                        for (var i = typeDef.methodStart; i < methodEnd; ++i)
                        {
                            var methodDef        = metadata.methodDefs[i];
                            var methodDefinition = methodDefinitionDic[i];
                            //methodAttribute
                            CreateCustomAttribute(imageDef, methodDef.customAttributeIndex, methodDef.token, typeDefinition.Module, methodDefinition.CustomAttributes);

                            //method parameter
                            for (var j = 0; j < methodDef.parameterCount; ++j)
                            {
                                var parameterDef        = metadata.parameterDefs[methodDef.parameterStart + j];
                                var parameterDefinition = parameterDefinitionDic[methodDef.parameterStart + j];
                                //parameterAttribute
                                CreateCustomAttribute(imageDef, parameterDef.customAttributeIndex, parameterDef.token, typeDefinition.Module, parameterDefinition.CustomAttributes);
                            }
                        }

                        //property
                        var propertyEnd = typeDef.propertyStart + typeDef.property_count;
                        for (var i = typeDef.propertyStart; i < propertyEnd; ++i)
                        {
                            var propertyDef        = metadata.propertyDefs[i];
                            var propertyDefinition = propertyDefinitionDic[i];
                            //propertyAttribute
                            CreateCustomAttribute(imageDef, propertyDef.customAttributeIndex, propertyDef.token, typeDefinition.Module, propertyDefinition.CustomAttributes);
                        }

                        //event
                        var eventEnd = typeDef.eventStart + typeDef.event_count;
                        for (var i = typeDef.eventStart; i < eventEnd; ++i)
                        {
                            var eventDef        = metadata.eventDefs[i];
                            var eventDefinition = eventDefinitionDic[i];
                            //eventAttribute
                            CreateCustomAttribute(imageDef, eventDef.customAttributeIndex, eventDef.token, typeDefinition.Module, eventDefinition.CustomAttributes);
                        }
                    }
                }
            }
        }
示例#59
0
 protected virtual Exception Fail(EventDefinition @event, Exception e)
 {
     return(ErrorHelper.CreateError(ErrorCode | 5, e, Errors.MX_ExceptionalSubSteps, Name, @event?.FullName));
 }
        /// <summary>
        /// This will return a context bus instance which is the payload for the Event Definition to be raised.
        /// </summary>
        /// <param name="eventDefinition">The defintion which has the metdata describing ContentHTML Objects.</param>
        /// <param name="contentData">The newly published Ektron CMS content data object.</param>
        /// <returns></returns>
        private IContextBusInstance ConvertContentDataToIObjectInstance(EventDefinition eventDefinition, ContentData contentData)
        {
            Log.WriteMessage(string.Format("-Begin {0}.ConvertContentDataToIObjectInstance.", CLASS_NAME), LogLevel.Verbose);
            IContextBusInstance htmlInstance = null;
            try
            {
                htmlInstance = new ObjectInstance(eventDefinition.Payload as ObjectDefinition);
                FillObjectInstance(htmlInstance, contentData);

            }
            catch (Exception ex)
            {
                Log.WriteError(string.Format("{0}.ConvertContentDataToIObjectInstance failed: {1}.", CLASS_NAME, ex.Message));
            }

            Log.WriteMessage(string.Format("+Finish {0}.ConvertContentDataToIObjectInstance.", CLASS_NAME), LogLevel.Verbose);
            return htmlInstance;
        }