Ejemplo n.º 1
0
        public Class Parse(String json, String className)
        {
            Class result = new Class(AccessModifier.Public, className);

            var oo = JsonConvert.DeserializeObject(json);
            var c = new ClassInfo(className);
            if (oo is JArray)
            {
                foreach (var jo in (JArray)oo)
                {
                    if (jo is JObject)
                    {
                        SetProperties(c, (JObject)jo);
                    }
                    else if (jo is JValue)
                    {
                        var pi = new PropertyInfo();
                        pi.Validate(jo);
                        return new Class(AccessModifier.Public, pi.GetCSharpTypeName());
                    }
                }
            }
            else if (oo is JObject)
            {
                SetProperties(c, (JObject)oo);
            }
            SetProperties(result, c);

            return result;
        }
 public GetFieldRunnable(IClassRepository repository, ClassInfo classInfo, Instruction instruction, BlockDecomposer block)
 {
     this.repository = repository;
     this.classInfo = classInfo;
     this.instruction = instruction;
     this.block = block;
 }
Ejemplo n.º 3
0
 public void AddClass(ClassInfo classInfo)
 {
     _rapidAccessForClassesByName.Add(classInfo.UnderlyingType, classInfo);
     _existingClasses.Add(classInfo.UnderlyingType);
     _rapidAccessForClassesByOid.Add(classInfo.ClassInfoId, classInfo);
     _allClassInfos.Add(classInfo);
 }
 public void AddClass(ClassInfo classInfo)
 {
     if (!classes.Contains(classInfo.Name))
     {
         classes.Add(classInfo.Name, classInfo);
     }
 }
        public ClassInfo GetClassInfo(ClassDeclarationSyntax classDeclaration)
        {
            _walker.Visit(classDeclaration);

            ClassInfo classInfo = new ClassInfo(classDeclaration, _semanticModel, _semanticModel.GetDeclaredSymbol(classDeclaration));

            classInfo.Locks.AddRange(_walker.Locks);
            classInfo.GuardedFields.AddRange(_walker.GuardedFields);
            classInfo.Members.AddRange(_walker.Members);

            foreach (LockInfo lockInfo in classInfo.Locks)
            {
                lockInfo.Parent = classInfo;
            }

            foreach (GuardedFieldInfo fieldInfo in classInfo.GuardedFields)
            {
                fieldInfo.Parent = classInfo;
            }

            foreach (MemberInfo memberInfo in classInfo.Members)
            {
                memberInfo.Parent = classInfo;
            }

            return classInfo;
        }
 private bool TryGetClass(ModuleDefinition module, string className, out ClassInfo clazz)
 {
     var visitor = new ModuleInfoVisitor(this, className);
     module.Accept(visitor);
     clazz = visitor.GetClassInfo();
     return clazz != null;
 }
        //public FieldVisitor(ClassInfo classInfo, string name, string descriptor, string signature, object value, 
        //    bool isFinal, bool isStatic, bool isPrivate)
        //{
        //    Type type = ClrType.FromDescriptor(descriptor);

        //    classInfo.AddField(new FieldInfo(classInfo, name, type, isFinal, isStatic, isPrivate));
        //}

        public FieldVisitor(ClassInfo classInfo, FieldDefinition fieldDefinition)
        {
            //classInfo.AddField();
            //Type type = ClrType.FromName(fieldDefinition.FieldType.FullName);
            Type type = ClrType.FromDescriptor(fieldDefinition.FieldType.FullName);
            classInfo.AddField(new FieldInfo(classInfo, fieldDefinition.Name, type, false, fieldDefinition.IsStatic, fieldDefinition.IsPrivate));
        }
 /// <summary>Constructor.</summary>
 /// <param name="classInfo">The test-class that this method is a member of.</param>
 /// <param name="name">The name of the method.</param>
 public MethodInfo(ClassInfo classInfo, string name)
 {
     this.classInfo = classInfo;
     this.name = name;
     displayName = FormatName(name);
     isSpecial = MethodHelper.IsSpecial(Name);
 }
        public AnalysisResult Analyze(CommonSyntaxTree tree, SemanticModel model, ClassInfo classInfo)
        {
            //TODO: Refactor this whole method later and make it more robust

            if (classInfo.GuardedFields.Count <= 1)
            {
                return AnalysisResult.Succeeded;
            }

            foreach (GuardedFieldInfo first in classInfo.GuardedFields)
            {
                foreach (GuardedFieldInfo second in classInfo.GuardedFields)
                {
                    if (first == second)
                    {
                        continue;
                    }

                    if (LockHierarchy.Conflicts(first.DeclaredLockHierarchy, second.DeclaredLockHierarchy))
                    {
                        return new AnalysisResult(new Issue(
                            ErrorCode.GUARDED_FIELD_LOCK_HIERARCHY_DECLARATION_CONFLICT,
                            second.Declaration,
                            second.Symbol));
                    }
                }
            }

            return AnalysisResult.Succeeded;
        }
 public MethodNotFoundException(ClassInfo classInfo, string methodName)
     : base("Method '" + methodName + "' not found in class '"
            + classInfo.Name + "'")
 {
     this.MethodName = methodName;
     this.ClassInfo = classInfo;
 }
        private Issue AnalyzeMember(MemberInfo memberInfo, SemanticModel model, ClassInfo classInfo)
        {
            foreach (BlockSyntax block in memberInfo.Blocks)
            {
                var identifiers = block.DescendantNodes().OfType<IdentifierNameSyntax>().ToList();

                foreach (IdentifierNameSyntax identifierName in identifiers)
                {
                    SymbolInfo identifierSymbol = model.GetSymbolInfo(identifierName);

                    //Does this symbol refer to a GuardedField?
                    GuardedFieldInfo foundGuardedField = classInfo.GuardedFields.FirstOrDefault(field => field.Symbol == identifierSymbol.Symbol);

                    if (foundGuardedField != null)
                    {
                        //We must be inside a lock statement
                        LockHierarchy controlFlowHierarchy = CreateLockHiearchyFromIdentifier(identifierName);

                        bool lockHierarchySatisfied = LockHierarchy.IsSatisfiedBy(foundGuardedField.DeclaredLockHierarchy, controlFlowHierarchy);

                        if (!lockHierarchySatisfied)
                        {
                            return new Issue(
                                ErrorCode.GUARDED_FIELD_ACCESSED_OUTSIDE_OF_LOCK,
                                identifierName,
                                identifierSymbol.Symbol);
                        }
                    }
                }
            }

            return null;
        }
Ejemplo n.º 12
0
        public IList<TeacherClass> Fill(ClassInfo classInfo)
        {
            if (classInfo == null)
            {
                return null;
            }

            IList<Core.Business.TeacherClass> teacherClasslist = new List<Core.Business.TeacherClass>();

            SqlServerUtility sql = new SqlServerUtility();

            sql.AddParameter("@ClassCode", SqlDbType.NVarChar, classInfo.ClassCode, 30);

            SqlDataReader reader = sql.ExecuteSqlReader(SqlFillTeacherClassByClassInfo);

            if (reader != null)
            {
                while (reader.Read())
                {
                    Core.Business.TeacherClass teacherClass = new Core.Business.TeacherClass();

                    if (!reader.IsDBNull(0)) teacherClass.Id = reader.GetInt32(0);
                    if (!reader.IsDBNull(1)) teacherClass.TeacherCode = reader.GetString(1);
                    if (!reader.IsDBNull(2)) teacherClass.ClassCode = reader.GetString(2);
                    if (!reader.IsDBNull(3)) teacherClass.IsState = reader.GetBoolean(3);

                    teacherClass.MarkOld();
                    teacherClasslist.Add(teacherClass);
                }
                reader.Close();
            }
            return teacherClasslist;
        }
        /// <summary>Constructor.</summary>
        /// <param name="classInfo">The test-class this node represents.</param>
        public ClassListItem(ClassInfo classInfo)
        {
            // Setup initial conditions.
            this.classInfo = classInfo;

            // Set default values.
            Text = classInfo.DisplayName;
        }
Ejemplo n.º 14
0
    protected void Page_Load(object sender, EventArgs e)
    {
       
        if (ClassID != null)
            _class = ClassroomController.GetClass((int)ClassID);

        DataBind();
    }
 /**
    * Computing the ClassCost for a ClassInfo involves tallying up all the MethodCosts contained
    * in the class. Then an overall cost is calculated, based on the {@code CostModel} the metric
    * computer is using.
    *
    * @param clazz to compute the metric for.
    * @return classCost
    */
 public ClassCost compute(ClassInfo clazz)
 {
     IList<MethodCost> methods = new ArrayList<MethodCost>();
     foreach (MethodInfo method in clazz.GetMethods())
     {
         methods.Add(compute(method));
     }
     return new ClassCost(clazz.Name, methods);
 }
Ejemplo n.º 16
0
 public FieldInfo(string fieldName, ClassInfo fieldClass, bool isPrimitive, bool isArray
     , bool isNArray)
 {
     _fieldName = fieldName;
     _fieldClass = fieldClass;
     _isPrimitive = isPrimitive;
     _isArray = isArray;
     _isNArray = isNArray;
 }
Ejemplo n.º 17
0
 public static List<Account> GetAccounts(
     string name,
     int gender,
     string bloodType,
     int birthYear,
     int birthMonth,
     int birthDate,
     City hometownCity,
     Province homwtownProvince,
     City resideCity,
     Province resideProvince,
     ClassInfo classInfo,
     Grade grade,
     Major major,
     College college,
     University university,
     string code,
     bool? hasAvatar,
     string nickName,
     bool? isProtected,
     int minViewCount,
     int maxViewCount,
     bool? isPublic,
     int minYear,
     int maxYear,
     string interest,
     PagingInfo pagingInfo)
 {
     return provider.GetAccounts(
         name,
         gender,
         bloodType,
         birthYear,
         birthMonth,
         birthDate,
         hometownCity,
         homwtownProvince,
         resideCity,
         resideProvince,
         classInfo,
         grade,
         major,
         college,
         university,
         code,
         hasAvatar,
         nickName,
         isProtected,
         minViewCount,
         maxViewCount,
         isPublic,
         minYear,
         maxYear,
         interest,
         pagingInfo);
 }
Ejemplo n.º 18
0
 public ChangedObjectInfo(ClassInfo oldCi, ClassInfo newCi, int fieldIndex, AbstractObjectInfo oldValue,
                          AbstractObjectInfo newValue, string message, int objectRecursionLevel)
 {
     _oldCi = oldCi;
     _newCi = newCi;
     _fieldIndex = fieldIndex;
     _oldValue = oldValue;
     _newValue = newValue;
     _message = message;
     _objectRecursionLevel = objectRecursionLevel;
 }
        private void CheckClass(IDictionary<Type, ClassInfo> currentCIs, ClassInfo persistedCI)
        {
            var currentCI = currentCIs[persistedCI.UnderlyingType];
            var classInfoCompareResult = persistedCI.ExtractDifferences(currentCI, true);

            if (!classInfoCompareResult.IsCompatible())
                throw new OdbRuntimeException(NDatabaseError.IncompatibleMetamodel.AddParameter(currentCI.ToString()));

            if (classInfoCompareResult.HasCompatibleChanges())
                _results.Add(classInfoCompareResult);
        }
Ejemplo n.º 20
0
        public NonNativeObjectInfo(ObjectInfoHeader oip, ClassInfo classInfo) : base(null)
        {
            _classInfo = classInfo;
            _objectHeader = oip;

            if (classInfo != null)
            {
                _maxNbattributes = classInfo.MaxAttributeId;
                _attributeValues = new AbstractObjectInfo[_maxNbattributes];
            }
        }
Ejemplo n.º 21
0
 protected NonNativeObjectInfo(ClassInfo classInfo) : base(null)
 {
     _classInfo = classInfo;
     _objectHeader = new ObjectInfoHeader(-1, null, null, (classInfo != null
                                                               ? classInfo.ClassInfoId
                                                               : null), null, null);
     if (classInfo != null)
     {
         _maxNbattributes = classInfo.MaxAttributeId;
         _attributeValues = new AbstractObjectInfo[_maxNbattributes];
     }
 }
Ejemplo n.º 22
0
    public void UpdateScore()
    {
        //checks for score things, sets them to black
        bool hasAPlus = false;
        ClassInfo[] plusCubes = new ClassInfo[]{grid[0,0]}; // or it throws an error
        int rowAt = 1;
        int colAt = 1;
        //for all center columns
        while (colAt != yMax-1 && hasAPlus == false) {
            //check for a +
            while (rowAt != xMax-1) {
                if (grid [rowAt - 1, colAt].IsColor () && grid [rowAt, colAt].IsColor () && grid [rowAt + 1, colAt].IsColor ()
                    && grid [rowAt, colAt + 1].IsColor () && grid [rowAt, colAt - 1].IsColor ()) {
                    hasAPlus = true;
                    plusCubes = new ClassInfo[]{grid [rowAt - 1, colAt], grid [rowAt, colAt], grid [rowAt + 1, colAt], grid [rowAt, colAt + 1], grid [rowAt, colAt - 1]};
                }
                if (grid [rowAt, colAt - 1].IsColor () && grid [rowAt, colAt].IsColor () && grid [rowAt, colAt + 1].IsColor ()
                    && grid [rowAt + 1, colAt].IsColor () && grid [rowAt - 1, colAt].IsColor ()) {
                    hasAPlus = true;
                    plusCubes = new ClassInfo[]{grid [rowAt, colAt - 1], grid [rowAt, colAt], grid [rowAt, colAt + 1], grid [rowAt + 1, colAt], grid [rowAt - 1, colAt]};
                }
                rowAt++;
            }
            colAt++;
            rowAt = 1;
        }

        if (hasAPlus) {
            Color baseColor = plusCubes[0].GetColor ();
            if(plusCubes[1].GetColor ()==baseColor && plusCubes[2].GetColor ()==baseColor && plusCubes[3].GetColor ()==baseColor && plusCubes[4].GetColor ()==baseColor){
                score = score + plusScoreOne;
                int changingAt=0;
                while(changingAt < 5){
                    plusCubes[changingAt].SetColor(Color.black);
                    changingAt++;
                }
            }
            else{if(
                    (plusCubes[1].GetColor () != baseColor && plusCubes[2].GetColor () != baseColor && plusCubes[3].GetColor () != baseColor && plusCubes[4].GetColor () != baseColor)
                    && (plusCubes[2].GetColor () != plusCubes[1].GetColor () && plusCubes[3].GetColor () != plusCubes[1].GetColor () && plusCubes[4].GetColor () != plusCubes[1].GetColor ())
                    && (plusCubes[3].GetColor () != plusCubes[2].GetColor () && plusCubes[4].GetColor () != plusCubes[2].GetColor ())
                    && (plusCubes[4].GetColor () != plusCubes[3].GetColor ())
                 ){
                    score = score + plusScoreMany;
                    int changingAt=0;
                    while(changingAt < 5){
                        plusCubes[changingAt].SetColor(Color.gray);
                        changingAt++;
                    }
                }
            }//if all diffrent colors
        }
    }
Ejemplo n.º 23
0
 public static void AssertProperty(ClassInfo classInfo, string propXmlName, string xmlPropType, bool isList, string propertyName, string propertyType, bool hasBindedClass)
 {
     var property = classInfo.Elements.Single(p => p.XmlName == propXmlName);
     Assert.That(property.IsList, Is.EqualTo(isList), "List or not doesn't match");
     if (hasBindedClass)
         Assert.That(property.XmlType.EndsWith("#" + xmlPropType), Is.True, "Property xml type doesn't match");
     else
         Assert.That(property.XmlType, Is.EqualTo(xmlPropType), "Property xml type doesn't match");
     Assert.That(property.GetCodeName(), Is.EqualTo(propertyName), "Property name doesn't match");
     Assert.That(property.GetCodeType(), Is.EqualTo(propertyType), "Property type doesn't match");
     Assert.That(property.BindedType != null, Is.EqualTo(hasBindedClass), "Binding not right");
 }
        public AnalysisResult Analyze(CommonSyntaxTree tree, SemanticModel model, ClassInfo classInfo)
        {
            if (classInfo.HasThreadSafeAttribute &&
                classInfo.Symbol.IsAbstract)
            {
                return new AnalysisResult(new Issue(
                    ErrorCode.CLASS_CANNOT_BE_ABSTRACT,
                    classInfo.Declaration,
                    classInfo.Symbol));
            }

            return AnalysisResult.Succeeded;
        }
        public AnalysisResult Analyze(CommonSyntaxTree tree, SemanticModel model, ClassInfo classInfo)
        {
            if (classInfo.HasThreadSafeAttribute == false &&
                classInfo.GuardedFields.Count > 0)
            {
                return new AnalysisResult(new Issue(
                    ErrorCode.GUARDED_FIELD_IN_A_NON_THREAD_SAFE_CLASS,
                    classInfo.Declaration,
                    classInfo.Symbol));
            }

            return AnalysisResult.Succeeded;
        }
        public AnalysisResult Analyze(CommonSyntaxTree tree, SemanticModel model, ClassInfo classInfo)
        {
            if (classInfo.HasThreadSafeAttribute &&
                classInfo.Declaration.Modifiers.Any(SyntaxKind.PartialKeyword))
            {
                return new AnalysisResult(new Issue(
                    ErrorCode.CLASS_CANNOT_BE_PARTIAL,
                    classInfo.Declaration,
                    classInfo.Symbol));
            }

            return AnalysisResult.Succeeded;
        }
        /// <summary>Constructor.</summary>
        /// <param name="classInfo">The test-class that is under control.</param>
        public ClassController(ClassInfo classInfo)
        {
            // Setup initial conditions.
            this.classInfo = classInfo;
            sidebarView = Common.Shell.Sidebar;
            events = Common.Events;

            // Wire up events.
            events.MethodClicked += OnMethodClicked;
            sidebarView.MethodList.RunClick += OnRunClick;
            sidebarView.MethodList.RefreshClick += OnRefreshClick;
            // Finish up.
            Reset();
        }
        public AnalysisResult Analyze(CommonSyntaxTree tree, SemanticModel model, ClassInfo classInfo)
        {
            foreach (LockInfo lockInfo in classInfo.Locks)
            {
                if (lockInfo.Symbol.Type.SpecialType != Roslyn.Compilers.SpecialType.System_Object)
                {
                    return new AnalysisResult(new Issue(
                        ErrorCode.LOCK_MUST_BE_SYSTEM_OBJECT,
                        lockInfo.Declaration,
                        lockInfo.Symbol));
                }
            }

            return AnalysisResult.Succeeded;
        }
        public AnalysisResult Analyze(CommonSyntaxTree tree, SemanticModel model, ClassInfo classInfo)
        {
            foreach (GuardedFieldInfo guardedField in classInfo.GuardedFields)
            {
                if (guardedField.DeclaredLockHierarchy.Any() == false)
                {
                    return  new AnalysisResult(new Issue(
                        ErrorCode.GUARDED_FIELD_NOT_ASSOCIATED_WITH_A_LOCK,
                        guardedField.Declaration,
                        guardedField.Symbol));
                }
            }

            return AnalysisResult.Succeeded;
        }
        public AnalysisResult Analyze(CommonSyntaxTree tree, SemanticModel model, ClassInfo classInfo)
        {
            foreach (GuardedFieldInfo guardedField in classInfo.GuardedFields)
            {
                if (guardedField.DeclaredLockHierarchy.Distinct().Count() != guardedField.DeclaredLockHierarchy.Count)
                {
                    return new AnalysisResult(new Issue(
                        ErrorCode.GUARDED_FIELD_USES_SAME_LOCK_MORE_THAN_ONCE,
                        guardedField.Declaration,
                        guardedField.Symbol));
                }
            }

            return AnalysisResult.Succeeded;
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Populates the collection.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="classInfo">The class info.</param>
        /// <param name="collection">The collection.</param>
        /// <param name="dataSet">The data set.</param>
        protected static void PopulateCollection <T>(ClassInfo classInfo, MetaStorageCollectionBase <T> collection, DataSet dataSet) where T : OrderGroup
        {
            #region ArgumentNullExceptions
            if (dataSet == null)
            {
                throw new ArgumentNullException("dataSet");
            }
            #endregion

            DataTableCollection tables = dataSet.Tables;

            if (tables == null || tables.Count == 0)
            {
                return;
            }

            // Get the collection that contains ids of all items returned
            DataRowCollection dataRowCol = tables[0].Rows;

            // No ids returned
            if (dataRowCol == null || dataRowCol.Count == 0)
            {
                return;
            }

            int   numberOfRecords = dataRowCol.Count;
            int[] idArray         = new int[numberOfRecords];

            // Populate array
            for (int index = 0; index < numberOfRecords; index++)
            {
                idArray[index] = (int)dataRowCol[index]["OrderGroupId"];
            }

            // Remove id collection
            tables.RemoveAt(0);

            // Map table names
            foreach (DataTable table in dataSet.Tables)
            {
                if (table.Rows.Count > 0)
                {
                    table.TableName = table.Rows[0]["TableName"].ToString();
                }
            }

            // Cycle through id Collection
            foreach (int id in idArray)
            {
                string filter = String.Format("OrderGroupId = '{0}'", id.ToString());

                // Populate the meta object data first
                // Meta data will be always in the second table returned
                DataView view = DataHelper.CreateDataView(dataSet.Tables["OrderGroup"], filter);

                // Only read one record, since we are populating only one object
                // reader.Read();

                // Create instance of the object specified and populate it
                T obj = (T)classInfo.CreateInstance();
                obj.Load(view[0]);
                collection.Add(obj);

                // Populate collections within object
                obj.PopulateCollections(dataSet.Tables, filter);

                /*
                 * if (dataSet.Tables.Count != 0)
                 * {
                 *  throw new ArgumentOutOfRangeException("Tables", "Stored Procedure returned too many tables");
                 * }
                 * */
            }
        }
Ejemplo n.º 32
0
        // 生成dbAccess代码
        private static void GenDbAccess(AssemblyInfo assembly, List <string> csFiles, ref int count, ref int fail, ref string failStr)
        {
            foreach (var cls in assembly.ClassList)
            {
                // 处理DbTable特性
                var attr = cls.AttributeList.FirstOrDefault(f => f.TypeFullName == typeof(DbTable).FullName);
                if (attr == null || attr.ArgumentList.Count == 0)
                {
                    continue;
                }
                if (!cls.Interfaces.Contains(typeof(IDbAccess).FullName))
                {
                    continue;
                }
                count++;

                // 文件路径处理
                if (cls.FilePath.Count > 1)
                {
                    fail++;
                    failStr += ("partial class " + cls.Name + " is not support" + Environment.NewLine);
                    continue;
                }
                if (cls.FilePath.Count == 0)
                {
                    fail++;
                    failStr += ("File of class " + cls.Name + " not found" + Environment.NewLine);
                    continue;
                }

                // 找dbmodel
                ClassInfo dbmodel = null;
                foreach (var cls2 in assembly.ClassList)
                {
                    var attr2 = cls2.AttributeList.FirstOrDefault(f => f.TypeFullName == typeof(DbTable).FullName);
                    if (attr2 == null || attr.ArgumentList.Count == 0)
                    {
                        continue;
                    }
                    if (!cls2.Interfaces.Contains(typeof(IDbModel).FullName))
                    {
                        continue;
                    }
                    // 判断同一个表
                    if (attr2.ArgumentList[0] == attr.ArgumentList[0])
                    {
                        dbmodel = cls2;
                    }
                }
                if (dbmodel == null)
                {
                    fail++;
                    failStr += ("DbModel " + attr.ArgumentList[0] + " not fount " + Environment.NewLine);
                    continue;
                }
                foreach (var method in cls.MethodList)
                {
                    // intert
                    if (method.AttributeList.Exists(f => f.TypeFullName == typeof(DbInsert).FullName))
                    {
                        string tableName = attr.ArgumentList[0];
                        var    columns   = dbmodel.PropertyList.Where(f => f.AttributeList.Exists(g => g.TypeFullName == typeof(DbColumn).FullName)).ToList();

                        StringBuilder sql = new StringBuilder();
                        sql.Append("INSERT INTO ");
                        sql.Append(tableName);
                        sql.Append(" (");
                        sql.Append(string.Join(",", columns.Select(f => f.Name)));
                        sql.Append(" ) values (");
                        sql.Append(string.Join(",", columns.Select(f => "@" + f.Name)));
                        sql.Append(")");


                        // 写入db access内容
                        List <string> newFile = new List <string>();
                        newFile.Add("        public int " + method.Name + "(" + dbmodel.Name + " obj)");
                        newFile.Add("        {");
                        newFile.Add("            /// 该方法的代码由插件自动生成,请勿修改。");
                        newFile.Add("            string sql = @\"" + sql.ToString() + "\";");
                        newFile.Add("            return Helper.ExecuteNonQuery(sql, " + string.Join(", ", columns.Select(f => "obj." + f.Name)) + ");");
                        WriteMethod(cls.FilePath[0], cls.MethodList, method.MinLine, method.MaxLine, newFile.ToArray());
                    }
                    // update
                    if (method.AttributeList.Exists(f => f.TypeFullName == typeof(DbUpdate).FullName))
                    {
                        string tableName           = attr.ArgumentList[0];
                        List <PropertyInfo> keys   = new List <PropertyInfo>();
                        List <PropertyInfo> values = new List <PropertyInfo>();
                        foreach (var item in method.AttributeList)
                        {
                            if (item.TypeFullName == typeof(SqlKey).FullName)
                            {
                                var t = dbmodel.PropertyList.FirstOrDefault(f => f.Name == item.ArgumentList[0]);
                                if (t != null)
                                {
                                    keys.Add(t);
                                }
                            }
                            if (item.TypeFullName == typeof(SqlValue).FullName)
                            {
                                var t = dbmodel.PropertyList.FirstOrDefault(f => f.Name == item.ArgumentList[0]);
                                if (t != null)
                                {
                                    values.Add(t);
                                }
                            }
                        }

                        StringBuilder sql = new StringBuilder();
                        sql.Append("UPDATE ");
                        sql.Append(tableName);
                        sql.Append(" SET ");
                        sql.Append(string.Join(",", values.Select(f => f.Name + "=@" + f.Name)));
                        if (keys.Count > 0)
                        {
                            sql.Append(" WHERE ");
                            sql.Append(string.Join(" and ", keys.Select(f => f.Name + "=@" + f.Name)));
                        }


                        // 写入db access内容
                        List <string> newFile = new List <string>();
                        newFile.Add("        public int " + method.Name + "(" + dbmodel.Name + " obj)");
                        newFile.Add("        {");
                        newFile.Add("            /// 该方法的代码由插件自动生成,请勿修改。");
                        newFile.Add("            string sql = @\"" + sql.ToString() + "\";");
                        newFile.Add("            return Helper.ExecuteNonQuery(sql, " + string.Join(", ", values.Select(f => "obj." + f.Name)) + (keys.Count > 0 ? ", " : "") + string.Join(", ", keys.Select(f => "obj." + f.Name)) + ");");
                        WriteMethod(cls.FilePath[0], cls.MethodList, method.MinLine, method.MaxLine, newFile.ToArray());
                    }
                    // delete
                    if (method.AttributeList.Exists(f => f.TypeFullName == typeof(DbDelete).FullName))
                    {
                        string tableName         = attr.ArgumentList[0];
                        List <PropertyInfo> keys = new List <PropertyInfo>();
                        foreach (var item in method.AttributeList)
                        {
                            if (item.TypeFullName == typeof(SqlKey).FullName)
                            {
                                var t = dbmodel.PropertyList.FirstOrDefault(f => f.Name == item.ArgumentList[0]);
                                if (t != null)
                                {
                                    keys.Add(t);
                                }
                            }
                        }

                        StringBuilder sql = new StringBuilder();
                        sql.Append("DELETE ");
                        sql.Append(tableName);
                        if (keys.Count > 0)
                        {
                            sql.Append(" WHERE ");
                            sql.Append(string.Join(" and ", keys.Select(f => f.Name + "=@" + f.Name)));
                        }


                        // 写入db access内容
                        List <string> newFile = new List <string>();
                        newFile.Add("        public int " + method.Name + "(" + dbmodel.Name + " obj)");
                        newFile.Add("        {");
                        newFile.Add("            /// 该方法的代码由插件自动生成,请勿修改。");
                        newFile.Add("            string sql = @\"" + sql.ToString() + "\";");
                        newFile.Add("            return Helper.ExecuteNonQuery(sql" + (keys.Count > 0 ? ", " : "") + string.Join(", ", keys.Select(f => "obj." + f.Name)) + ");");
                        WriteMethod(cls.FilePath[0], cls.MethodList, method.MinLine, method.MaxLine, newFile.ToArray());
                    }
                    // read
                    if (method.AttributeList.Exists(f => f.TypeFullName == typeof(DbRead).FullName))
                    {
                        string tableName         = attr.ArgumentList[0];
                        List <PropertyInfo> keys = new List <PropertyInfo>();
                        foreach (var item in method.AttributeList)
                        {
                            if (item.TypeFullName == typeof(SqlKey).FullName)
                            {
                                var t = dbmodel.PropertyList.FirstOrDefault(f => f.Name == item.ArgumentList[0]);
                                if (t != null)
                                {
                                    keys.Add(t);
                                }
                            }
                        }

                        StringBuilder sql = new StringBuilder();
                        sql.Append("SELECT * FROM ");
                        sql.Append(tableName);
                        if (keys.Count > 0)
                        {
                            sql.Append(" WHERE ");
                            sql.Append(string.Join(" and ", keys.Select(f => f.Name + "=@" + f.Name)));
                        }


                        // 写入db access内容
                        List <string> newFile = new List <string>();
                        newFile.Add("        public List<" + dbmodel.Name + "> " + method.Name + "()");
                        newFile.Add("        {");
                        newFile.Add("            /// 该方法的代码由插件自动生成,请勿修改。");
                        newFile.Add("            string sql = @\"" + sql.ToString() + "\";");
                        newFile.Add("            DataTable dt = Helper.Query(sql" + (keys.Count > 0 ? ", " : "") + string.Join(", ", keys.Select(f => "obj." + f.Name)) + ");");
                        newFile.Add("            List<" + dbmodel.Name + "> rst = new List<" + dbmodel.Name + ">();");
                        newFile.Add("            foreach (DataRow row in dt.Rows)");
                        newFile.Add("            {");
                        newFile.Add("                " + dbmodel.Name + " t = new " + dbmodel.Name + "();");
                        foreach (var col in dbmodel.PropertyList.Where(f => f.AttributeList.Exists(g => g.TypeFullName == typeof(DbColumn).FullName)))
                        {
                            var      colAttr = col.AttributeList.FirstOrDefault(t => t.TypeFullName == typeof(DbColumn).FullName);
                            DataType type    = (DataType)int.Parse(colAttr.ArgumentList[0]);
                            switch (type)
                            {
                            case (DataType.VARCHAR):
                            case (DataType.VARCHAR2):
                                newFile.Add("                t." + col.Name + " = row[nameof(" + dbmodel.Name + "." + col.Name + ")].TryToString();");
                                break;

                            case (DataType.NUMBER):
                                newFile.Add("                t." + col.Name + " = row[nameof(" + dbmodel.Name + "." + col.Name + ")].TryToInt();");
                                break;

                            case (DataType.FLOAT):
                                newFile.Add("                t." + col.Name + " = row[nameof(" + dbmodel.Name + "." + col.Name + ")].TryToFload();");
                                break;

                            case (DataType.DATE):
                            case (DataType.TIMESTAMP_6):
                                newFile.Add("                t." + col.Name + " = row[nameof(" + dbmodel.Name + "." + col.Name + ")].TryToDateTime();");
                                break;

                            default:
                                newFile.Add("                t." + col.Name + " = row[nameof(" + dbmodel.Name + "." + col.Name + ")].TryToString();");
                                break;
                            }
                        }
                        newFile.Add("                rst.Add(t);");
                        newFile.Add("            }");
                        newFile.Add("            return rst;");
                        WriteMethod(cls.FilePath[0], cls.MethodList, method.MinLine, method.MaxLine, newFile.ToArray());
                    }
                }
            }
        }
Ejemplo n.º 33
0
        private NonNativeObjectInfo BuildNnoi(object o, ClassInfo classInfo)
        {
            var nnoi = new NonNativeObjectInfo(o, classInfo);

            return(_classInfoProvider.EnrichWithOid(nnoi, o));
        }
Ejemplo n.º 34
0
 public IActionResult UpdateClassById([FromRoute] long classId, [FromBody] ClassInfo updated)
 {
     return(NoContent());
 }
 public static byte[] getDefaultClassValue(ME3Package pcc, string className, bool fullProps = false)
 {
     if (Structs.ContainsKey(className))
     {
         bool      immutable = isImmutable(className);
         ClassInfo info      = Structs[className];
         try
         {
             using (ME3Package importPCC = MEPackageHandler.OpenME3Package(Path.Combine(ME3Directory.gamePath, @"BIOGame\" + info.pccPath)))
             {
                 byte[] buff;
                 //Plane and CoverReference inherit from other structs, meaning they don't have default values (who knows why)
                 //thus, I have hardcoded what those default values should be
                 if (className == "Plane")
                 {
                     buff = PlaneDefault;
                 }
                 else if (className == "CoverReference")
                 {
                     buff = CoverReferenceDefault;
                 }
                 else
                 {
                     buff = importPCC.Exports[info.exportIndex].Data.Skip(0x24).ToArray();
                 }
                 List <PropertyReader.Property> Props = PropertyReader.ReadProp(importPCC, buff, 0);
                 MemoryStream m = new MemoryStream();
                 foreach (PropertyReader.Property p in Props)
                 {
                     string propName = importPCC.getNameEntry(p.Name);
                     //check if property is transient, if so, skip (neither of the structs that inherit have transient props)
                     if (info.properties.ContainsKey(propName) || propName == "None" || info.baseClass != "Class")
                     {
                         if (immutable && !fullProps)
                         {
                             PropertyReader.ImportImmutableProperty(pcc, importPCC, p, className, m, true);
                         }
                         else
                         {
                             PropertyReader.ImportProperty(pcc, importPCC, p, className, m, true);
                         }
                     }
                 }
                 return(m.ToArray());
             }
         }
         catch (Exception)
         {
             return(null);
         }
     }
     else if (Classes.ContainsKey(className))
     {
         ClassInfo info = Structs[className];
         try
         {
             using (ME3Package importPCC = MEPackageHandler.OpenME3Package(Path.Combine(ME3Directory.gamePath, @"BIOGame\" + info.pccPath)))
             {
                 IExportEntry entry = pcc.Exports[info.exportIndex + 1];
                 List <PropertyReader.Property> Props = PropertyReader.getPropList(entry);
                 MemoryStream m = new MemoryStream(entry.DataSize - 4);
                 foreach (PropertyReader.Property p in Props)
                 {
                     if (!info.properties.ContainsKey(importPCC.getNameEntry(p.Name)))
                     {
                         //property is transient
                         continue;
                     }
                     PropertyReader.ImportProperty(pcc, importPCC, p, className, m);
                 }
                 return(m.ToArray());
             }
         }
         catch (Exception)
         {
             return(null);
         }
     }
     return(null);
 }
Ejemplo n.º 36
0
        public IActionResult CreateClassByCourseId([FromRoute] long courseId, [FromBody] ClassInfo newClass)
        {
            long x = InsertClassById(User.Id, courseId, newClass);

            return(NoContent());
        }
Ejemplo n.º 37
0
        public static PropertyCollection GetSequenceObjectDefaults(IMEPackage pcc, ClassInfo info)
        {
            MEGame             game     = pcc.Game;
            PropertyCollection defaults = new PropertyCollection();

            if (info.ClassName == "Sequence")
            {
                defaults.Add(new ArrayProperty <ObjectProperty>("SequenceObjects"));
            }
            else if (!info.IsA(SequenceVariableName, game))
            {
                ArrayProperty <StructProperty> varLinksProp   = null;
                ArrayProperty <StructProperty> outLinksProp   = null;
                ArrayProperty <StructProperty> eventLinksProp = null;
                ArrayProperty <StructProperty> inLinksProp    = null;
                Dictionary <string, ClassInfo> classes        = UnrealObjectInfo.GetClasses(game);
                try
                {
                    ClassInfo classInfo = info;
                    while (classInfo != null && (varLinksProp is null || outLinksProp is null || eventLinksProp is null || game == MEGame.ME1 && inLinksProp is null))
                    {
                        string filepath   = Path.Combine(MEDirectories.GetBioGamePath(game), classInfo.pccPath);
                        Stream loadStream = null;
                        if (File.Exists(classInfo.pccPath))
                        {
                            loadStream = new MemoryStream(File.ReadAllBytes(classInfo.pccPath));
                        }
                        else if (classInfo.pccPath == UnrealObjectInfo.Me3ExplorerCustomNativeAdditionsName)
                        {
                            loadStream = ME3ExplorerCoreUtilities.GetCustomAppResourceStream(game);
                        }
                        else if (File.Exists(filepath))
                        {
                            loadStream = new MemoryStream(File.ReadAllBytes(filepath));
                        }
                        else if (game == MEGame.ME1)
                        {
                            filepath = Path.Combine(ME1Directory.DefaultGamePath, classInfo.pccPath); //for files from ME1 DLC
                            if (File.Exists(filepath))
                            {
                                loadStream = new MemoryStream(File.ReadAllBytes(filepath));
                            }
                        }
                        if (loadStream != null)
                        {
                            using IMEPackage importPCC = MEPackageHandler.OpenMEPackageFromStream(loadStream);
                            ExportEntry classExport   = importPCC.GetUExport(classInfo.exportIndex);
                            UClass      classBin      = ObjectBinary.From <UClass>(classExport);
                            ExportEntry classDefaults = importPCC.GetUExport(classBin.Defaults);

                            foreach (var prop in classDefaults.GetProperties())
                            {
                                if (varLinksProp == null && prop.Name == "VariableLinks" && prop is ArrayProperty <StructProperty> vlp)
                                {
                                    varLinksProp = vlp;
                                    //relink ExpectedType
                                    foreach (StructProperty varLink in varLinksProp)
                                    {
                                        if (varLink.GetProp <ObjectProperty>("ExpectedType") is ObjectProperty expectedTypeProp &&
                                            importPCC.TryGetEntry(expectedTypeProp.Value, out IEntry expectedVar) &&
                                            EntryImporter.EnsureClassIsInFile(pcc, expectedVar.ObjectName, RelinkResultsAvailable: EntryImporterExtended.ShowRelinkResults) is IEntry portedExpectedVar)
                                        {
                                            expectedTypeProp.Value = portedExpectedVar.UIndex;
                                        }
                                    }
                                }
                                if (outLinksProp == null && prop.Name == "OutputLinks" && prop is ArrayProperty <StructProperty> olp)
                                {
                                    outLinksProp = olp;
                                }

                                if (eventLinksProp == null && prop.Name == "EventLinks" && prop is ArrayProperty <StructProperty> elp)
                                {
                                    eventLinksProp = elp;
                                    //relink ExpectedType
                                    foreach (StructProperty eventLink in eventLinksProp)
                                    {
                                        if (eventLink.GetProp <ObjectProperty>("ExpectedType") is ObjectProperty expectedTypeProp &&
                                            importPCC.TryGetEntry(expectedTypeProp.Value, out IEntry expectedVar) &&
                                            EntryImporter.EnsureClassIsInFile(pcc, expectedVar.ObjectName, RelinkResultsAvailable: EntryImporterExtended.ShowRelinkResults) is IEntry portedExpectedVar)
                                        {
                                            expectedTypeProp.Value = portedExpectedVar.UIndex;
                                        }
                                    }
                                }

                                // Jan 31 2021 change by Mgamerz: Not sure why it only adds input links if it's ME1
                                // I removed it to let other games work too
                                //if (game == MEGame.ME1 && inLinksProp is null && prop.Name == "InputLinks" && prop is ArrayProperty<StructProperty> ilp)
                                if (inLinksProp is null && prop.Name == "InputLinks" && prop is ArrayProperty <StructProperty> ilp)
                                {
                                    inLinksProp = ilp;
                                }
                            }
                        }
                        classes.TryGetValue(classInfo.baseClass, out classInfo);
                    }
                }
                catch
                {
                    // ignored
                }
                if (varLinksProp != null)
                {
                    defaults.Add(varLinksProp);
                }
                if (outLinksProp != null)
                {
                    defaults.Add(outLinksProp);
                }
                if (eventLinksProp != null)
                {
                    defaults.Add(eventLinksProp);
                }
                if (inLinksProp != null)
                {
                    defaults.Add(inLinksProp);
                }

                //remove links if empty
                if (defaults.GetProp <ArrayProperty <StructProperty> >("OutputLinks") is { } outLinks&& outLinks.IsEmpty())
                {
                    defaults.Remove(outLinks);
                }
                if (defaults.GetProp <ArrayProperty <StructProperty> >("VariableLinks") is { } varLinks&& varLinks.IsEmpty())
                {
                    defaults.Remove(varLinks);
                }
                if (defaults.GetProp <ArrayProperty <StructProperty> >("EventLinks") is { } eventLinks&& eventLinks.IsEmpty())
                {
                    defaults.Remove(eventLinks);
                }
                if (defaults.GetProp <ArrayProperty <StructProperty> >("InputLinks") is { } inputLinks&& inputLinks.IsEmpty())
                {
                    defaults.Remove(inputLinks);
                }
            }

            int objInstanceVersion = UnrealObjectInfo.getSequenceObjectInfo(game, info.ClassName)?.ObjInstanceVersion ?? 1;

            defaults.Add(new IntProperty(objInstanceVersion, "ObjInstanceVersion"));

            return(defaults);
        }
Ejemplo n.º 38
0
        /// <summary>
        /// Writes a class which structs class diagram into <paramref name="writer"/>.
        /// And if the class is excluded target and it contains inner classes, adds the inner classes into <paramref name="excludedClasses"/>.
        /// <para>If <paramref name="accessFilter"/> is specified,
        /// contents that do not correspond to the filter are not described.</para>
        /// </summary>
        /// <param name="writer"><see cref="CodeWriter"/> into which a class diagram is written</param>
        /// <param name="classInfo"><see cref="ClassInfo"/> to be written</param>
        /// <param name="accessFilter">Access level filter</param>
        /// <param name="excludedClasses">A collection of class names not to be written to a class diagram</param>
        private static void WriteClassAndUpdateExcludedClasses(CodeWriter writer, ClassInfo classInfo, Modifier accessFilter, ref IEnumerable <string> excludedClasses)
        {
            if (classInfo == null)
            {
                throw new ArgumentNullException();
            }

            var isExcludedClass = excludedClasses?.Contains(classInfo.Name) ?? false;

            if (isExcludedClass)
            {
                StartCommentMode(writer);
            }

            var stereoType = (classInfo.Category == ClassCategory.Struct) ? "<<struct>> " : string.Empty;
            var modifier   = (classInfo.Modifier.HasFlag(Modifier.Abstract)) ? "abstract " : string.Empty;

            writer.Write($"{modifier}{ClassCategoryText(classInfo.Category)} {classInfo.Type} {stereoType}{{").NewLine();
            writer.IncreaseIndent();

            foreach (var field in classInfo.Fields ?? Enumerable.Empty <FieldInfo>())
            {
                if (!IsTargetAccessModifier(field.Modifier, accessFilter))
                {
                    StartCommentMode(writer);
                }

                WriteField(writer, field);

                // Ends comment mode only if this class is NOT excluded target
                if (!isExcludedClass)
                {
                    EndCommentMode(writer);
                }
            }

            foreach (var method in classInfo.Methods ?? Enumerable.Empty <MethodInfo>())
            {
                if (!IsTargetAccessModifier(method.Modifier, accessFilter))
                {
                    StartCommentMode(writer);
                }

                WriteMethod(writer, method);

                // Ends comment mode only if this class is NOT excluded target
                if (!isExcludedClass)
                {
                    EndCommentMode(writer);
                }
            }

            writer.DecreaseIndent();
            writer.Write("}").NewLine().NewLine();

            EndCommentMode(writer);

            // Writes inner classes in this class
            foreach (var innerClass in classInfo.InnerClasses)
            {
                // If an outer class is excluded target, its inner class is also excluded.
                excludedClasses = isExcludedClass ? excludedClasses.Concat(new[] { innerClass.Name }) : excludedClasses;
                WriteClassAndUpdateExcludedClasses(writer, innerClass, accessFilter, ref excludedClasses);
            }
        }
Ejemplo n.º 39
0
        private ConstantPoolInfo[] ParseConstantPool(ref ReadOnlySpan <byte> fileData)
        {
            ushort poolCount = fileData.ReadTwoBytes();

            var infos = new ConstantPoolInfo[poolCount];

            for (int i = 1; i < poolCount; i++)
            {
                var tag = (ConstantPoolTag)fileData.ReadOneByte();
                switch (tag)
                {
                case ConstantPoolTag.Class:
                    infos[i] = new ClassInfo(ref fileData);
                    break;

                case ConstantPoolTag.Fieldref:
                    infos[i] = new FieldrefInfo(ref fileData);
                    break;

                case ConstantPoolTag.Methodref:
                    infos[i] = new MethodrefInfo(ref fileData);
                    break;

                case ConstantPoolTag.InterfaceMethodref:
                    infos[i] = new InterfaceMethodrefInfo(ref fileData);
                    break;

                case ConstantPoolTag.String:
                    infos[i] = new StringInfo(ref fileData);
                    break;

                case ConstantPoolTag.Integer:
                    infos[i] = new IntegerInfo(ref fileData);
                    break;

                case ConstantPoolTag.Float:
                    infos[i] = new FloatInfo(ref fileData);
                    break;

                case ConstantPoolTag.Long:
                    infos[i] = new LongInfo(ref fileData);
                    i++;
                    break;

                case ConstantPoolTag.Double:
                    infos[i] = new DoubleInfo(ref fileData);
                    i++;
                    break;

                case ConstantPoolTag.NameAndType:
                    infos[i] = new NameAndTypeInfo(ref fileData);
                    break;

                case ConstantPoolTag.Utf8:
                    infos[i] = new Utf8Info(ref fileData);
                    break;

                case ConstantPoolTag.MethodHandle:
                    fileData.ReadOneByte();
                    fileData.ReadTwoBytes();
                    break;

                case ConstantPoolTag.MethodType:
                    fileData.ReadTwoBytes();
                    break;

                case ConstantPoolTag.InvokeDynamic:
                    fileData.ReadFourBytes();
                    break;

                default:
                    throw new InvalidDataException();
                }
            }

            foreach (ConstantPoolInfo info in infos)
            {
                info?.Init(infos);
            }

            return(infos);
        }
        /// <summary>
        /// Build a meta representation of an object
        /// <pre>
        /// warning: When an object has two fields with the same name (a private field with the same name in a parent class, the deeper field (of the parent) is ignored!)
        /// </pre>
        /// </summary>
        /// <param name="o"></param>
        /// <param name="ci"></param>
        /// <param name="recursive"></param>
        /// <returns>The ObjectInfo</returns>
        protected virtual NeoDatis.Odb.Core.Layers.Layer2.Meta.AbstractObjectInfo GetObjectInfoInternal
            (NeoDatis.Odb.Core.Layers.Layer2.Meta.AbstractObjectInfo nnoi, object o, NeoDatis.Odb.Core.Layers.Layer2.Meta.ClassInfo
            ci, bool recursive, System.Collections.Generic.IDictionary <object, NeoDatis.Odb.Core.Layers.Layer2.Meta.NonNativeObjectInfo
                                                                        > alreadyReadObjects, NeoDatis.Odb.Core.Layers.Layer1.Introspector.IIntrospectionCallback
            callback)
        {
            object value = null;

            if (o == null)
            {
                return(NeoDatis.Odb.Core.Layers.Layer2.Meta.NullNativeObjectInfo.GetInstance());
            }
            System.Type clazz = o.GetType();
            NeoDatis.Odb.Core.Layers.Layer2.Meta.ODBType type = NeoDatis.Odb.Core.Layers.Layer2.Meta.ODBType
                                                                .GetFromClass(clazz);
            string className = OdbClassUtil.GetFullName(clazz);

            if (type.IsNative())
            {
                return(GetNativeObjectInfoInternal(type, o, recursive, alreadyReadObjects,
                                                   callback));
            }
            // sometimes the clazz.getName() may not match the ci.getClassName()
            // It happens when the attribute is an interface or superclass of the
            // real attribute class
            // In this case, ci must be updated to the real class info
            if (ci != null && !clazz.FullName.Equals(ci.GetFullClassName()))
            {
                ci   = GetClassInfo(className);
                nnoi = null;
            }
            NeoDatis.Odb.Core.Layers.Layer2.Meta.NonNativeObjectInfo mainAoi = (NeoDatis.Odb.Core.Layers.Layer2.Meta.NonNativeObjectInfo
                                                                                )nnoi;
            bool isRootObject = false;

            if (alreadyReadObjects == null)
            {
                alreadyReadObjects = new NeoDatis.Tool.Wrappers.Map.OdbHashMap <object, NeoDatis.Odb.Core.Layers.Layer2.Meta.NonNativeObjectInfo
                                                                                >();
                isRootObject = true;
            }
            if (o != null)
            {
                NonNativeObjectInfo cachedNnoi = null;
                alreadyReadObjects.TryGetValue(o, out cachedNnoi);

                if (cachedNnoi != null)
                {
                    ObjectReference or = new ObjectReference(cachedNnoi);
                    return(or);
                }
                if (callback != null)
                {
                    callback.ObjectFound(o);
                }
            }
            if (mainAoi == null)
            {
                mainAoi = BuildNnoi(o, ci, null, null, null, alreadyReadObjects);
            }
            alreadyReadObjects[o] = mainAoi;
            NeoDatis.Tool.Wrappers.List.IOdbList <System.Reflection.FieldInfo> fields = classIntrospector.GetAllFields(className);
            NeoDatis.Odb.Core.Layers.Layer2.Meta.AbstractObjectInfo            aoi    = null;
            int attributeId = -1;

            // For all fields
            for (int i = 0; i < fields.Count; i++)
            {
                System.Reflection.FieldInfo field = fields[i];
                try
                {
                    value       = field.GetValue(o);
                    attributeId = ci.GetAttributeId(field.Name);
                    if (attributeId == -1)
                    {
                        throw new ODBRuntimeException(NeoDatisError.ObjectIntrospectorNoFieldWithName.AddParameter(ci.GetFullClassName()).AddParameter(field.Name));
                    }
                    ODBType valueType = null;
                    if (value == null)
                    {
                        // If value is null, take the type from the field type
                        // declared in the class
                        valueType = ODBType.GetFromClass(field.FieldType);
                    }
                    else
                    {
                        // Else take the real attribute type!
                        valueType = ODBType.GetFromClass(value.GetType());
                    }
                    // for native fields
                    if (valueType.IsNative())
                    {
                        aoi = GetNativeObjectInfoInternal(valueType, value, recursive, alreadyReadObjects, callback);
                        mainAoi.SetAttributeValue(attributeId, aoi);
                    }
                    else
                    {
                        //callback.objectFound(value);
                        // Non Native Objects
                        if (value == null)
                        {
                            ClassInfo clai = GetClassInfo(OdbClassUtil.GetFullName(field.GetType()));

                            aoi = new NeoDatis.Odb.Core.Layers.Layer2.Meta.NonNativeNullObjectInfo(clai);
                            mainAoi.SetAttributeValue(attributeId, aoi);
                        }
                        else
                        {
                            ClassInfo clai = GetClassInfo(OdbClassUtil.GetFullName(value.GetType()));
                            if (recursive)
                            {
                                aoi = GetObjectInfoInternal(null, value, clai, recursive, alreadyReadObjects, callback
                                                            );
                                mainAoi.SetAttributeValue(attributeId, aoi);
                            }
                            else
                            {
                                // When it is not recursive, simply add the object
                                // values.add(value);
                                throw new NeoDatis.Odb.ODBRuntimeException(NeoDatis.Odb.Core.NeoDatisError.InternalError
                                                                           .AddParameter("Should not enter here - ObjectIntrospector - 'simply add the object'"
                                                                                         ));
                            }
                        }
                    }
                }
                catch (System.ArgumentException e)
                {
                    throw new NeoDatis.Odb.ODBRuntimeException(NeoDatis.Odb.Core.NeoDatisError.InternalError
                                                               .AddParameter("in getObjectInfoInternal"), e);
                }
                catch (System.MemberAccessException e)
                {
                    throw new NeoDatis.Odb.ODBRuntimeException(NeoDatis.Odb.Core.NeoDatisError.InternalError
                                                               .AddParameter("getObjectInfoInternal"), e);
                }
            }
            if (isRootObject)
            {
                alreadyReadObjects.Clear();
                alreadyReadObjects = null;
            }
            return(mainAoi);
        }
Ejemplo n.º 41
0
        public static TestCase GetSimple2LineMethodCase()
        {
            string    testMethod = @""" 
            class TestClass
            {
                void MethodA()
                {
                    int count = 0;
                    count ++;
                }
            }
            """;
            ClassInfo classInfo  = FactoryHelper.CreateClassInfo();

            classInfo.RelativeFilePath = "TestFile.cs";

            CodeRunnerInfo codeRunnerInfo = new CodeRunnerInfo();

            codeRunnerInfo.Name          = "MethodA";
            codeRunnerInfo.IsConstructor = false;

            codeRunnerInfo.blockInfo[0] = new BlockInfo();
            codeRunnerInfo.blockInfo[0].CloseBraceLineNo = 7;
            StatementInfo sInfo = new StatementInfo();

            sInfo = new StatementInfo {
                LineNo = 5
            };
            codeRunnerInfo.blockInfo[0].Add(sInfo);
            sInfo = new StatementInfo {
                LineNo = 6
            };
            codeRunnerInfo.blockInfo[0].Add(sInfo);

            classInfo.AddCodeRunnerInfo(codeRunnerInfo, 0);

            CSfileInfo cSfileInfo = new CSfileInfo();

            cSfileInfo.Classes.Add(classInfo);

            Dictionary <int, List <string> > renderingInfo = new Dictionary <int, List <string> >()
            {
            };

            renderingInfo[0] = new List <string>()
            {
                "OnMethodEnter();",
                "LogLineRun()",
                "0",
                "LogLineRun()",
                "1",
                "LogLineRun()",
            };

            List <string> expectedStatementSubStrings = new List <string>()
            {
                "OnMethodEnter",
                "LogLineRun",
                "int count",
                "LogLineRun",
                "count ++",
            };

            SyntaxNode methSyntax = Helpers.GetFirstMethodSyntax(testMethod);

            SyntaxTree root = Helpers.GetRoot(testMethod);

            return(new TestCase
            {
                Code = testMethod,
                ClassInfo = classInfo,
                ExpectedStatements = expectedStatementSubStrings,
                ExpectedStatementCount = 6,
                Node = methSyntax,
                RenderInfo = renderingInfo,
                Root = root,
                FileName = classInfo.RelativeFilePath,
                CSFileInfo = cSfileInfo,
            });
        }
Ejemplo n.º 42
0
        public static TestCase GetSingleIfMethod()
        {
            string testMethod = @""" 
            class TestClass
            {
                void MethodA()
                {
                    int b=3;
                    if(true)
                    {
                        int count = 0;
                    }
                }
            }
            """;
            MethodDeclarationSyntax methSyntax = Helpers.GetFirstMethodSyntax(testMethod);
            ClassInfo classInfo = FactoryHelper.CreateClassInfo();

            classInfo.RelativeFilePath = "TestFile.cs";

            CodeRunnerInfo codeRunnerInfo = new CodeRunnerInfo();

            codeRunnerInfo.Name          = "MethodA";
            codeRunnerInfo.IsConstructor = false;

            codeRunnerInfo.blockInfo[0] = new BlockInfo();
            codeRunnerInfo.blockInfo[0].CloseBraceLineNo = 9;
            codeRunnerInfo.blockInfo[1] = new BlockInfo();
            codeRunnerInfo.blockInfo[1].CloseBraceLineNo = 10;
            StatementInfo sInfo = new StatementInfo();

            sInfo = new StatementInfo {
                LineNo = 5
            };
            codeRunnerInfo.blockInfo[0].Add(sInfo);
            sInfo = new StatementInfo {
                LineNo = 6
            };
            codeRunnerInfo.blockInfo[0].Add(sInfo);
            sInfo = new StatementInfo {
                LineNo = 8
            };
            codeRunnerInfo.blockInfo[1].Add(sInfo);

            classInfo.AddCodeRunnerInfo(codeRunnerInfo, 0);

            CSfileInfo cSfileInfo = new CSfileInfo();

            cSfileInfo.Classes.Add(classInfo);

            SyntaxTree root = Helpers.GetRoot(testMethod);

            List <string> expectedStatementSubStrings = new List <string>()
            {
                "OnMethodEnter",
                "LogLineRun",
                "int b",
                "LogLineRun",
                "if(true)",
                "LogLineRun",
                "LogLineRun",
                "int count",
                "LogLineRun",
            };

            return(new TestCase
            {
                Code = testMethod,
                ClassInfo = classInfo,
                ExpectedStatements = expectedStatementSubStrings,
                ExpectedStatementCount = 9,
                Node = methSyntax,
                Root = root,
                CSFileInfo = cSfileInfo,
                FileName = classInfo.RelativeFilePath
            });
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Gets all the mods and patches them.
        /// </summary>
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            _errorLevel = ErrorLevel.NoError;

            //Gets the list of mods
            ItemCollection modCollection = null;

            Dispatcher.Invoke(DispatcherPriority.Input, new ThreadStart(() =>
            {
                modCollection = ModsListBox.Items;
            }));

            SetStatusLabelAsync("Gathering mods...");
            //Gets the list of mods that have been checked.
            List <LessMod> modsToPatch = new List <LessMod>();

            foreach (var x in modCollection)
            {
                CheckBox box          = (CheckBox)x;
                bool     isBoxChecked = false;
                Dispatcher.Invoke(DispatcherPriority.Input, new ThreadStart(() =>
                {
                    isBoxChecked = box.IsChecked ?? false;
                }));

                if (isBoxChecked)
                {
                    modsToPatch.Add(_lessMods[box]);
                }
            }

            string lolLocation = null;
            bool   overwrite   = true;

            Dispatcher.Invoke(DispatcherPriority.Input, new ThreadStart(() =>
            {
                lolLocation = LocationTextbox.Text;
            }));
            if (IsGarena)
            {
                MessageBox.Show("Garena detected! Please note that you must uninstall LESs before patching your LoL with Garena." + Environment.NewLine + "Otherwise, your Garena LoL patcher will complain hard and we are not responsible for it ;).");
                Uri lolRootLocation = new Uri(lolLocation);
                lolRootLocation = new Uri(lolRootLocation.LocalPath.Replace(lolRootLocation.Segments.Last(), String.Empty));
                // Get LoL latest patched date
                String versionLocation = Path.Combine(lolRootLocation.LocalPath, "lol.version");
                if (File.Exists(versionLocation))
                {
                    // Store the date in another file. It will be used in LESs removing.
                    File.Copy(versionLocation, Path.Combine(lolRootLocation.LocalPath, "LESs_recent.version"), true);
                }
                if (Directory.Exists(Path.Combine(lolLocation, "LESsBackup")))
                {
                    MessageBoxResult diagRst = MessageBox.Show("We found that you already have backup files. Overwriting it may result in you losing your original files." + Environment.NewLine + "Would you like to overwrite your old files?", "You already have backup files", MessageBoxButton.YesNo);
                    if (diagRst == MessageBoxResult.No)
                    {
                        overwrite = false;
                    }
                }
            }
            Dictionary <string, SwfFile> swfs = new Dictionary <string, SwfFile>();

            Stahpwatch = Stopwatch.StartNew();
            foreach (var lessMod in modsToPatch)
            {
                Debug.Assert(lessMod.Patches.Length > 0);
                SetStatusLabelAsync("Patching mod: " + lessMod.Name);
                foreach (var patch in lessMod.Patches)
                {
                    if (!swfs.ContainsKey(patch.Swf))
                    {
                        string fullPath = Path.Combine(lolLocation, patch.Swf);

                        //Backup the SWF
                        string   CurrentLocation = "";
                        string[] FileLocation    = patch.Swf.Split('/', '\\');
                        foreach (string s in FileLocation.Take(FileLocation.Length - 1))
                        {
                            CurrentLocation = Path.Combine(CurrentLocation, s);
                            if (IsGarena)
                            {
                                if (!Directory.Exists(Path.Combine(lolLocation, "LESsBackup", CurrentLocation)))
                                {
                                    Directory.CreateDirectory(Path.Combine(lolLocation, "LESsBackup", CurrentLocation));
                                }
                                if (!File.Exists(Path.Combine(lolLocation, "LESsBackup", patch.Swf)))
                                {
                                    if (overwrite)
                                    {
                                        File.Copy(Path.Combine(lolLocation, patch.Swf), Path.Combine(lolLocation, "LESsBackup", patch.Swf));
                                    }
                                }
                            }
                            else
                            {
                                if (!Directory.Exists(Path.Combine(lolLocation, "LESsBackup", INTENDED_VERSION, CurrentLocation)))
                                {
                                    Directory.CreateDirectory(Path.Combine(lolLocation, "LESsBackup", INTENDED_VERSION, CurrentLocation));
                                }
                                if (!File.Exists(Path.Combine(lolLocation, "LESsBackup", INTENDED_VERSION, patch.Swf)))
                                {
                                    File.Copy(Path.Combine(lolLocation, patch.Swf), Path.Combine(lolLocation, "LESsBackup", INTENDED_VERSION, patch.Swf));
                                }
                            }
                        }

                        swfs.Add(patch.Swf, SwfFile.ReadFile(fullPath));
                    }

                    SwfFile         swf        = swfs[patch.Swf];
                    List <DoAbcTag> tags       = swf.GetDoAbcTags();
                    bool            classFound = false;
                    foreach (var tag in tags)
                    {
                        //check if this tag contains our script
                        ScriptInfo si = tag.GetScriptByClassName(patch.Class);

                        //check next tag if it doesn't
                        if (si == null)
                        {
                            continue;
                        }

                        ClassInfo cls = si.GetClassByClassName(patch.Class);
                        classFound = true;

                        Assembler asm;
                        switch (patch.Action)
                        {
                        case "replace_trait":     //replace trait (method)
                            asm = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code)));
                            TraitInfo newTrait = asm.Assemble() as TraitInfo;

                            int  traitIndex = cls.Instance.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name);
                            bool classTrait = false;
                            if (traitIndex < 0)
                            {
                                traitIndex = cls.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name);
                                classTrait = true;
                            }
                            if (traitIndex < 0)
                            {
                                throw new TraitNotFoundException(String.Format("Can't find trait \"{0}\" in class \"{1}\"", newTrait.Name.Name, patch.Class));
                            }

                            if (classTrait)
                            {
                                cls.Traits[traitIndex] = newTrait;
                            }
                            else
                            {
                                cls.Instance.Traits[traitIndex] = newTrait;
                            }
                            break;

                        case "replace_cinit":    //replace class constructor
                            asm           = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code)));
                            cls.ClassInit = asm.Assemble() as MethodInfo;
                            break;

                        case "replace_iinit":    //replace instance constructor
                            asm = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code)));
                            cls.Instance.InstanceInit = asm.Assemble() as MethodInfo;
                            break;

                        case "add_class_trait":     //add new class trait (method)
                            asm        = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code)));
                            newTrait   = asm.Assemble() as TraitInfo;
                            traitIndex = cls.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name);
                            if (traitIndex < 0)
                            {
                                cls.Traits.Add(newTrait);
                            }
                            else
                            {
                                cls.Traits[traitIndex] = newTrait;
                            }
                            break;

                        case "add_instance_trait":     //add new instance trait (method)
                            asm        = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code)));
                            newTrait   = asm.Assemble() as TraitInfo;
                            traitIndex = cls.Instance.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name);
                            if (traitIndex < 0)
                            {
                                cls.Instance.Traits.Add(newTrait);
                            }
                            else
                            {
                                cls.Instance.Traits[traitIndex] = newTrait;
                            }
                            break;

                        case "remove_class_trait":
                            throw new NotImplementedException();

                        case "remove_instance_trait":
                            throw new NotImplementedException();

                        default:
                            throw new NotSupportedException("Unknown Action \"" + patch.Action + "\" in mod " + lessMod.Name);
                        }
                    }

                    if (!classFound)
                    {
                        _errorLevel = ErrorLevel.UnableToPatch;
                        throw new ClassNotFoundException(string.Format("Class {0} not found in file {1}", patch.Class, patch.Swf));
                    }
                }
            }
            //return;

            foreach (var patchedSwf in swfs)
            {
                try
                {
                    SetStatusLabelAsync("Applying mods: " + patchedSwf.Key);
                    string swfLoc = Path.Combine(lolLocation, patchedSwf.Key);
                    SwfFile.WriteFile(patchedSwf.Value, swfLoc);
                }
                catch
                {
                    _errorLevel = ErrorLevel.GoodJobYourInstallationIsProbablyCorruptedNow;
                    if (Debugger.IsAttached)
                    {
                        throw;
                    }
                }
            }
            Stahpwatch.Stop();
        }
Ejemplo n.º 44
0
    //通过字符串获取文件信息
    FileInfo ReadFileInfo(string text)
    {
        int      start    = 0;
        FileInfo fileinfo = new FileInfo();

        GetAllEnums(text, fileinfo);
        //第一遍遍历先获得所有的message类型
        while (start < text.Length)
        {
            //逐行解析
            string        lineNew  = EditorUtils.readLine(text, ref start);
            List <string> allWords = EditorUtils.splitLine(lineNew);
            if (allWords.Count > 0)
            {
                string keyWord = allWords[0];
                if (keyWord.Contains("//"))  //是注释,直接忽略
                {
                    //do nothing
                }
                else if (keyWord == "package")  //是包名
                {
                    //测试代码,防止发生跟已经生成的protobuff的文件发生冲突
                    fileinfo.nameSpace = allWords[1];
                    fileinfo.nameSpace = fileinfo.nameSpace.Replace(";", "2");
                }
                else if (keyWord == "message")  //是消息,要读取到结束
                {
                    ClassInfo classInfo = new ClassInfo();
                    classInfo.className = allWords[1];
                    fileinfo.m_allClasses.Add(classInfo.className, classInfo);
                    while (start < text.Length)
                    {
                        string        msgLine     = EditorUtils.readLine(text, ref start);
                        List <string> allMsgWords = EditorUtils.splitLine(msgLine);
                        if (allMsgWords.Count > 0)
                        {
                            string msgKeyword = allMsgWords[0];
                            if (msgKeyword.Contains("//"))  //是注释,直接忽略
                            {
                                //do nothing
                            }
                            else if (msgKeyword == "{")
                            {
                                //do nothing
                            }
                            else if (msgKeyword == "}")
                            {
                                break;
                            }
                            else //字段定义
                            {
                                //字段分析利用了protobuff里的等号的功能进行分析,
                                //如果直接对字段类型进行分析,则要考虑很多因素,例如import的支持
                                //目前做法是如果有等号,就认为是有效字段,不能识别的类型默认为class
                                for (int i = 0; i < allMsgWords.Count; ++i)
                                {
                                    string cur = allMsgWords[i];
                                    //等号前后都有空格
                                    if (cur == "=")
                                    {
                                        FieldInfo fieldInfo = new FieldInfo();
                                        fieldInfo.m_name    = allMsgWords[i - 1];
                                        fieldInfo.className = allMsgWords[i - 2];
                                        fieldInfo.m_type    = GetTypeInfo(allMsgWords[i - 2], fileinfo);
                                        if (i == 3)  //带有repeated或者optional字段
                                        {
                                            string msg0 = allMsgWords[0].Replace("\t", "");
                                            fieldInfo.isrepeat = msg0 == "repeated";
                                        }
                                        classInfo.m_allFields.Add(fieldInfo);
                                    }
                                    else if (cur.Contains("="))
                                    {
                                        //等号与前后连写有三种情况 a=2 a= 2 a =2
                                        string[] subStrings = cur.Split('=');
                                        //第一种情况,a=2
                                        if (subStrings.Length == 2)
                                        {
                                            FieldInfo fieldInfo = new FieldInfo();
                                            fieldInfo.m_name    = subStrings[0];
                                            fieldInfo.className = allMsgWords[i - 1];
                                            fieldInfo.m_type    = GetTypeInfo(allMsgWords[i - 1], fileinfo);
                                            if (i == 2)  //带有repeated或者optional字段
                                            {
                                                string msg0 = allMsgWords[0].Replace("\t", "");
                                                fieldInfo.isrepeat = msg0 == "repeated";
                                            }
                                            classInfo.m_allFields.Add(fieldInfo);
                                        }
                                        //第二三中情况,a= 2 或者 a =2
                                        else if (subStrings.Length == 1)
                                        {
                                            //根据能否转为数字决定是哪种情况
                                            int temp = 0;
                                            //这是跟后边的数字连在一起,所以名字是上个字符串 a =2
                                            if (int.TryParse(subStrings[0], out temp))
                                            {
                                                FieldInfo fieldInfo = new FieldInfo();
                                                fieldInfo.m_name    = allMsgWords[i - 1];
                                                fieldInfo.className = allMsgWords[i - 2];
                                                fieldInfo.m_type    = GetTypeInfo(allMsgWords[i - 2], fileinfo);
                                                if (i == 3)  //带有repeated或者optional字段
                                                {
                                                    string msg0 = allMsgWords[0].Replace("\t", "");
                                                    fieldInfo.isrepeat = msg0 == "repeated";
                                                }
                                                classInfo.m_allFields.Add(fieldInfo);
                                            }
                                            //剩余情况是等号与前边的变量名在一起 a= 2
                                            else
                                            {
                                                FieldInfo fieldInfo = new FieldInfo();
                                                fieldInfo.m_name    = subStrings[0];
                                                fieldInfo.className = allMsgWords[i - 2];
                                                fieldInfo.m_type    = GetTypeInfo(allMsgWords[i - 2], fileinfo);
                                                if (i == 2)  //带有repeated或者optional字段
                                                {
                                                    string msg0 = allMsgWords[0].Replace("\t", "");
                                                    fieldInfo.isrepeat = msg0 == "repeated";
                                                }
                                                classInfo.m_allFields.Add(fieldInfo);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return(fileinfo);
    }
Ejemplo n.º 45
0
        private object GetMemberValueInternal(AnalysisValue type, ModuleInfo declModule, bool isRef)
        {
            SpecializedNamespace specialCallable = type as SpecializedNamespace;

            if (specialCallable != null)
            {
                if (specialCallable.Original == null)
                {
                    return(null);
                }
                return(GetMemberValueInternal(specialCallable.Original, declModule, isRef));
            }

            switch (type.MemberType)
            {
            case PythonMemberType.Function:
                FunctionInfo fi = type as FunctionInfo;
                if (fi != null)
                {
                    if (fi.DeclaringModule.GetModuleInfo() != declModule)
                    {
                        return(GenerateFuncRef(fi));
                    }
                    else
                    {
                        return(GenerateFunction(fi));
                    }
                }

                BuiltinFunctionInfo bfi = type as BuiltinFunctionInfo;
                if (bfi != null)
                {
                    return(GenerateFuncRef(bfi));
                }

                return("function");

            case PythonMemberType.Method:
                BoundMethodInfo mi = type as BoundMethodInfo;
                if (mi != null)
                {
                    return(GenerateMethod(mi));
                }
                return("method");

            case PythonMemberType.Property:
                FunctionInfo prop = type as FunctionInfo;
                if (prop != null)
                {
                    return(GenerateProperty(prop));
                }
                break;

            case PythonMemberType.Class:
                ClassInfo ci = type as ClassInfo;
                if (ci != null)
                {
                    if (isRef || ci.DeclaringModule.GetModuleInfo() != declModule)
                    {
                        // TODO: Save qualified name so that classes defined in classes/function can be resolved
                        return(GetTypeRef(ci.DeclaringModule.ModuleName, ci.Name));
                    }
                    else
                    {
                        return(GenerateClass(ci, declModule));
                    }
                }

                BuiltinClassInfo bci = type as BuiltinClassInfo;
                if (bci != null)
                {
                    return(GetTypeRef(bci.PythonType.DeclaringModule.Name, bci.PythonType.Name));
                }
                return("type");

            case PythonMemberType.Constant:
                ConstantInfo constantInfo = type as ConstantInfo;
                if (constantInfo != null)
                {
                    return(GenerateConstant(constantInfo));
                }
                break;

            case PythonMemberType.Module:
                if (type is ModuleInfo)
                {
                    return(GetModuleName(((ModuleInfo)type).Name));
                }
                else if (type is BuiltinModule)
                {
                    return(GetModuleName(((BuiltinModule)type).Name));
                }
                break;

            case PythonMemberType.Instance:
                return(new Dictionary <string, object> {
                    { "type", GenerateTypeName(type, true) }
                });

            default:
                return(new Dictionary <string, object>()
                {
                    { "type", GenerateTypeName(type.PythonType) }
                });
            }
            return(null);
        }
Ejemplo n.º 46
0
        public static PropertyInfo getPropertyInfo(string className, string propName, bool inStruct = false, ClassInfo nonVanillaClassInfo = null)
        {
            if (className.StartsWith("Default__"))
            {
                className = className.Substring(9);
            }
            Dictionary <string, ClassInfo> temp = inStruct ? Structs : Classes;

            if (temp.ContainsKey(className)) //|| (temp = !inStruct ? Structs : Classes).ContainsKey(className))
            {
                ClassInfo info = temp[className];
                //look in class properties
                if (info.properties.ContainsKey(propName))
                {
                    return(info.properties[propName]);
                }
                //look in structs
                else
                {
                    foreach (PropertyInfo p in info.properties.Values)
                    {
                        if (p.type == PropertyType.StructProperty || p.type == PropertyType.ArrayProperty)
                        {
                            PropertyInfo val = getPropertyInfo(p.reference, propName, true);
                            if (val != null)
                            {
                                return(val);
                            }
                        }
                    }
                }
                //look in base class
                if (temp.ContainsKey(info.baseClass))
                {
                    PropertyInfo val = getPropertyInfo(info.baseClass, propName, inStruct);
                    if (val != null)
                    {
                        return(val);
                    }
                }
            }
            return(null);
        }
Ejemplo n.º 47
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            if (classNameTb.Text != "" &&
                gradeTb.Text != "" &&
                teacherNameTb.Text != "" &&
                countTb.Text != "" &&
                yearTb.Text != "")
            {
                if (!InputTester.IsAClassName(classNameTb.Text))
                {
                    iNotifierBox.Text = "Tên lớp không hợp lệ";
                    iNotifierBox.ShowDialog();
                    return;
                }

                if (!InputTester.IsAName(teacherNameTb.Text))
                {
                    iNotifierBox.Text = "Tên giáo viên không hợp lệ";
                    iNotifierBox.ShowDialog();
                    return;
                }

                if (!InputTester.IsANumber(countTb.Text, 2))
                {
                    iNotifierBox.Text = "Sĩ số không hợp lệ";
                    iNotifierBox.ShowDialog();
                    return;
                }

                if (!InputTester.IsANumber(yearTb.Text, 4))
                {
                    iNotifierBox.Text = "Năm không hợp lệ";
                    iNotifierBox.ShowDialog();
                    return;
                }

                ClassInfo classInfo = new ClassInfo()
                {
                    tenLop   = classNameTb.Text,
                    khoi     = gradeTb.Text,
                    tenGVCN  = teacherNameTb.Text,
                    siSo     = Convert.ToInt32(countTb.Text),
                    nienKhoa = yearTb.Text
                };

                bool resultYN = await Controllers.Controller.Instance.DeleteClass(classInfo.maLop);

                if (resultYN)
                {
                    this.Hide();
                    isCorrected        = true;
                    classNameTb.Text   = "";
                    gradeTb.Text       = "";
                    teacherNameTb.Text = "";
                    countTb.Text       = "";
                    yearTb.Text        = "";
                    iNotifierBox.Text  = "Xoá thành công !";
                    iNotifierBox.ShowDialog();
                }
            }
            else
            {
                iNotifierBox.Text = "Vui lòng điền đầy đủ thông tin";
                iNotifierBox.ShowDialog();
            }
        }
Ejemplo n.º 48
0
 public ClassScope(ClassInfo classInfo)
     : base(classInfo)
 {
 }
Ejemplo n.º 49
0
 public IActionResult CreateClass([FromBody] ClassInfo newClass)
 {
     return(Created("/class/1", newClass));
 }
Ejemplo n.º 50
0
        private ClassInfo <T> RegisterInternal <T>()
        {
            if (ClassInfo <T> .Instance != null)
            {
                return(ClassInfo <T> .Instance);
            }

            Type t = typeof(T);

#if NETSTANDARD2_0 || NETCOREAPP2_0
            var props = t.GetRuntimeProperties().ToArray();
#else
            var props = t.GetProperties(
                BindingFlags.Instance |
                BindingFlags.Public |
                BindingFlags.GetProperty |
                BindingFlags.SetProperty);
#endif
            int propsCount = props.Length;
            if (props == null)
            {
                throw new InvalidTypeException("Type does not contain acceptable fields");
            }

            var info = new ClassInfo <T>(propsCount);
            for (int i = 0; i < propsCount; i++)
            {
                var property     = props[i];
                var propertyType = property.PropertyType;

#if NETSTANDARD2_0 || NETCOREAPP2_0
                bool isEnum    = propertyType.GetTypeInfo().IsEnum;
                var  getMethod = property.GetMethod;
                var  setMethod = property.SetMethod;
#else
                bool isEnum    = propertyType.IsEnum;
                var  getMethod = property.GetGetMethod();
                var  setMethod = property.GetSetMethod();
#endif
                if (isEnum)
                {
                    var underlyingType = Enum.GetUnderlyingType(propertyType);
                    if (underlyingType == typeof(byte))
                    {
                        info.ReadDelegate[i] = (inf, r) =>
                        {
                            property.SetValue(inf, Enum.ToObject(propertyType, r.GetByte()), null);
                        };
                        info.WriteDelegate[i] = (inf, w) =>
                        {
                            w.Put((byte)property.GetValue(inf, null));
                        };
                    }
                    else if (underlyingType == typeof(int))
                    {
                        info.ReadDelegate[i] = (inf, r) =>
                        {
                            property.SetValue(inf, Enum.ToObject(propertyType, r.GetInt()), null);
                        };
                        info.WriteDelegate[i] = (inf, w) =>
                        {
                            w.Put((int)property.GetValue(inf, null));
                        };
                    }
                    else
                    {
                        throw new InvalidTypeException("Not supported enum underlying type: " + underlyingType.Name);
                    }
                }
                else if (propertyType == typeof(string))
                {
                    var setDelegate = ExtractSetDelegate <T, string>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, string>(getMethod);
                    if (_maxStringLength <= 0)
                    {
                        info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetString());
                        info.WriteDelegate[i] = (inf, w) => w.Put(getDelegate(inf));
                    }
                    else
                    {
                        info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetString(_maxStringLength));
                        info.WriteDelegate[i] = (inf, w) => w.Put(getDelegate(inf), _maxStringLength);
                    }
                }
                else if (propertyType == typeof(bool))
                {
                    var setDelegate = ExtractSetDelegate <T, bool>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, bool>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetBool());
                    info.WriteDelegate[i] = (inf, w) => w.Put(getDelegate(inf));
                }
                else if (propertyType == typeof(byte))
                {
                    var setDelegate = ExtractSetDelegate <T, byte>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, byte>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetByte());
                    info.WriteDelegate[i] = (inf, w) => w.Put(getDelegate(inf));
                }
                else if (propertyType == typeof(sbyte))
                {
                    var setDelegate = ExtractSetDelegate <T, sbyte>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, sbyte>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetSByte());
                    info.WriteDelegate[i] = (inf, w) => w.Put(getDelegate(inf));
                }
                else if (propertyType == typeof(short))
                {
                    var setDelegate = ExtractSetDelegate <T, short>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, short>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetShort());
                    info.WriteDelegate[i] = (inf, w) => w.Put(getDelegate(inf));
                }
                else if (propertyType == typeof(ushort))
                {
                    var setDelegate = ExtractSetDelegate <T, ushort>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, ushort>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetUShort());
                    info.WriteDelegate[i] = (inf, w) => w.Put(getDelegate(inf));
                }
                else if (propertyType == typeof(int))
                {
                    var setDelegate = ExtractSetDelegate <T, int>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, int>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetInt());
                    info.WriteDelegate[i] = (inf, w) => w.Put(getDelegate(inf));
                }
                else if (propertyType == typeof(uint))
                {
                    var setDelegate = ExtractSetDelegate <T, uint>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, uint>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetUInt());
                    info.WriteDelegate[i] = (inf, w) => w.Put(getDelegate(inf));
                }
                else if (propertyType == typeof(long))
                {
                    var setDelegate = ExtractSetDelegate <T, long>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, long>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetLong());
                    info.WriteDelegate[i] = (inf, w) => w.Put(getDelegate(inf));
                }
                else if (propertyType == typeof(ulong))
                {
                    var setDelegate = ExtractSetDelegate <T, ulong>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, ulong>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetULong());
                    info.WriteDelegate[i] = (inf, w) => w.Put(getDelegate(inf));
                }
                else if (propertyType == typeof(float))
                {
                    var setDelegate = ExtractSetDelegate <T, float>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, float>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetFloat());
                    info.WriteDelegate[i] = (inf, w) => w.Put(getDelegate(inf));
                }
                else if (propertyType == typeof(double))
                {
                    var setDelegate = ExtractSetDelegate <T, double>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, double>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetDouble());
                    info.WriteDelegate[i] = (inf, w) => w.Put(getDelegate(inf));
                }
                else if (propertyType == typeof(char))
                {
                    var setDelegate = ExtractSetDelegate <T, char>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, char>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetChar());
                    info.WriteDelegate[i] = (inf, w) => w.Put(getDelegate(inf));
                }
                else if (propertyType == typeof(IPEndPoint))
                {
                    var setDelegate = ExtractSetDelegate <T, IPEndPoint>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, IPEndPoint>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetNetEndPoint());
                    info.WriteDelegate[i] = (inf, w) => w.Put(getDelegate(inf));
                }
                // Array types
                else if (propertyType == typeof(string[]))
                {
                    var setDelegate = ExtractSetDelegate <T, string[]>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, string[]>(getMethod);
                    if (_maxStringLength <= 0)
                    {
                        info.ReadDelegate[i] =
                            (inf, r) => setDelegate(inf, r.GetStringArray());
                        info.WriteDelegate[i] =
                            (inf, w) => w.PutArray(getDelegate(inf));
                    }
                    else
                    {
                        info.ReadDelegate[i] =
                            (inf, r) => setDelegate(inf, r.GetStringArray(_maxStringLength));
                        info.WriteDelegate[i] =
                            (inf, w) => w.PutArray(getDelegate(inf), _maxStringLength);
                    }
                }
                else if (propertyType == typeof(bool[]))
                {
                    var setDelegate = ExtractSetDelegate <T, bool[]>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, bool[]>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetBoolArray());
                    info.WriteDelegate[i] = (inf, w) => w.PutArray(getDelegate(inf));
                }
                else if (propertyType == typeof(byte[]))
                {
                    var setDelegate = ExtractSetDelegate <T, byte[]>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, byte[]>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetBytesWithLength());
                    info.WriteDelegate[i] = (inf, w) => w.PutBytesWithLength(getDelegate(inf));
                }
                else if (propertyType == typeof(short[]))
                {
                    var setDelegate = ExtractSetDelegate <T, short[]>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, short[]>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetShortArray());
                    info.WriteDelegate[i] = (inf, w) => w.PutArray(getDelegate(inf));
                }
                else if (propertyType == typeof(ushort[]))
                {
                    var setDelegate = ExtractSetDelegate <T, ushort[]>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, ushort[]>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetUShortArray());
                    info.WriteDelegate[i] = (inf, w) => w.PutArray(getDelegate(inf));
                }
                else if (propertyType == typeof(int[]))
                {
                    var setDelegate = ExtractSetDelegate <T, int[]>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, int[]>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetIntArray());
                    info.WriteDelegate[i] = (inf, w) => w.PutArray(getDelegate(inf));
                }
                else if (propertyType == typeof(uint[]))
                {
                    var setDelegate = ExtractSetDelegate <T, uint[]>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, uint[]>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetUIntArray());
                    info.WriteDelegate[i] = (inf, w) => w.PutArray(getDelegate(inf));
                }
                else if (propertyType == typeof(long[]))
                {
                    var setDelegate = ExtractSetDelegate <T, long[]>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, long[]>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetLongArray());
                    info.WriteDelegate[i] = (inf, w) => w.PutArray(getDelegate(inf));
                }
                else if (propertyType == typeof(ulong[]))
                {
                    var setDelegate = ExtractSetDelegate <T, ulong[]>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, ulong[]>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetULongArray());
                    info.WriteDelegate[i] = (inf, w) => w.PutArray(getDelegate(inf));
                }
                else if (propertyType == typeof(float[]))
                {
                    var setDelegate = ExtractSetDelegate <T, float[]>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, float[]>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetFloatArray());
                    info.WriteDelegate[i] = (inf, w) => w.PutArray(getDelegate(inf));
                }
                else if (propertyType == typeof(double[]))
                {
                    var setDelegate = ExtractSetDelegate <T, double[]>(setMethod);
                    var getDelegate = ExtractGetDelegate <T, double[]>(getMethod);
                    info.ReadDelegate[i]  = (inf, r) => setDelegate(inf, r.GetDoubleArray());
                    info.WriteDelegate[i] = (inf, w) => w.PutArray(getDelegate(inf));
                }
                else
                {
                    NestedType registeredNestedType;
                    bool       array = false;

                    if (propertyType.IsArray)
                    {
                        array        = true;
                        propertyType = propertyType.GetElementType();
                    }

                    if (_registeredNestedTypes.TryGetValue(propertyType, out registeredNestedType))
                    {
                        if (array) //Array type serialize/deserialize
                        {
                            info.ReadDelegate[i]  = (inf, r) => property.SetValue(inf, registeredNestedType.ArrayReader(r), null);
                            info.WriteDelegate[i] = (inf, w) => registeredNestedType.ArrayWriter(w, property.GetValue(inf, null));
                        }
                        else //Simple
                        {
                            info.ReadDelegate[i]  = (inf, r) => property.SetValue(inf, registeredNestedType.ReadDelegate(r), null);
                            info.WriteDelegate[i] = (inf, w) => registeredNestedType.WriteDelegate(w, property.GetValue(inf, null));
                        }
                    }
                    else
                    {
                        throw new InvalidTypeException("Unknown property type: " + propertyType.FullName);
                    }
                }
            }
            ClassInfo <T> .Instance = info;
            return(info);
        }
Ejemplo n.º 51
0
        static void Main(string[] args)
        {
#if DEBUG
            DateTime start = DateTime.Now;
#endif
            try
            {
                #region Initialization

                try
                {
                    bool hasMethod = false;

                    if (args.Length < 1)
                    {
                        WriteInfo();
                        Console.WriteLine("[?] Use -help for some instructions.");
                        return;
                    }

                    for (int i = 0, n = args.Length; i < n; ++i)
                    {
                        switch (args[i])
                        {
                        case "-h":
                        case "-help":
                        case "-?":
                        case "/?":
                        case "/help":
                            WriteInfo();
                            Usage();
                            return;

                        // OPTIONS /////////////////////////////////////////////////////////////////////

                        case "-o":
                        case "-output":
                            _pathOutput = args[++i];
                            break;

                        case "-q":
                        case "-quiet":
                            _isQuiet = true;
                            break;

                        // REPLACE ////////////////////////////////////////////////////////////////////

                        case "-r":
                        case "-replace":
                            _action = Action.Replace;
                            break;

                        // REPLACE PROPERTIES ////////////////////////////////////////////////////////

                        case "-sm":
                        case "-static-method":
                            if (hasMethod)
                            {
                                throw new Exception("Two methods defined.");
                            }
                            _isMethodStatic = true;
                            _methodName     = args[++i];
                            break;

                        case "-m":
                        case "-method":
                            if (hasMethod)
                            {
                                throw new Exception("Two methods defined.");
                            }
                            _isMethodStatic = false;
                            _methodName     = args[++i];
                            break;

                        case "-co":
                        case "-constructor":
                            if (hasMethod)
                            {
                                throw new Exception("Two methods defined.");
                            }
                            _isConstructor  = true;
                            _isMethodStatic = false;
                            break;

                        case "-sc":
                        case "-static-constructor":
                            if (hasMethod)
                            {
                                throw new Exception("Two methods defined.");
                            }
                            _isConstructor  = true;
                            _isMethodStatic = true;
                            break;

                        case "-c":
                        case "-class":
                            _className = args[++i];
                            break;

                        case "-n":
                        case "-namespace":
                            _namespace = args[++i];
                            break;

                        // INLINE ///////////////////////////////////////////////////////////////////

                        case "-i":
                        case "-inline":
                            _action  = Action.Inline;
                            _pathSwf = args[++i];
                            break;

                        // PATCH ///////////////////////////////////////////////////////////////////
                        case "-optimize":
                            _action  = Action.Optimize;
                            _pathSwf = args[++i];
                            break;

                        // DASM ////////////////////////////////////////////////////////////////////

                        case "-d":
                        case "-dasm":
                            _action = Action.Dasm;
                            break;

                        // DASM PROPERTIES ////////////////////////////////////////////////////////

                        case "-a":
                        case "-as3c":
                            _dasmType = Dasm.As3c;
                            break;

                        case "-p":
                        case "-plain":
                            _dasmType = Dasm.Plain;
                            break;

                        default:
                            if (File.Exists(args[i]))
                            {
                                try
                                {
                                    BinaryReader fileHead = new BinaryReader(File.Open(args[i], FileMode.Open, FileAccess.Read));

                                    if (fileHead.BaseStream.Length < 3)
                                    {
                                        throw new Exception("Invalid file given.");
                                    }

                                    byte[] head = fileHead.ReadBytes(3);

                                    fileHead.Close();

                                    //TODO fix this ugly part...
                                    if ((head[0] == (byte)'C' || head[0] == (byte)'F') && head[1] == (byte)'W' && head[2] == (byte)'S')
                                    {
                                        if (_pathSwf != "")
                                        {
                                            throw new Exception("Two SWF files given.");
                                        }

                                        _pathSwf = args[i];
                                    }
                                    else
                                    {
                                        if ("" != _pathAsm)
                                        {
                                            throw new Exception("Two ASM files given.");
                                        }

                                        _pathAsm = args[i];
                                    }
                                }
                                catch (IOException io)
                                {
                                    WriteInfo();
                                    Console.Error.WriteLine("[-] Error: Can not open file {0}", args[i]);
#if DEBUG
                                    Console.Error.WriteLine("[-] {0}", io.Message);
#endif
                                    return;
                                }
                                catch (Exception e)
                                {
                                    WriteInfo();
                                    Console.Error.WriteLine("[-] Error: {0}", e.Message);
#if DEBUG
                                    Console.Error.WriteLine("[-] {0}", e.StackTrace);
#endif
                                    return;
                                }
                            }
                            else
                            {
                                if (args[i].IndexOf(".") != -1)
                                {
                                    WriteInfo();
                                    Console.Error.WriteLine("[-] File {0} does not exist.", args[i]);
                                    return;
                                }
                                else
                                {
                                    throw new Exception("Invalid argument given.");
                                }
                            }
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    WriteInfo();
                    Console.Error.WriteLine("[-] Error: Invalid arguments. Use -help for help ...");
#if DEBUG
                    Console.Error.WriteLine("[-] {0}", e.Message);
                    Console.Error.WriteLine("[-] {0}", e.StackTrace);
#endif
                    return;
                }

                if (!_isQuiet)
                {
                    Console.WriteLine("[i] As3c - ActionScript3 ASM compiler");
                }

                Translator.InitTable();

                #endregion

                #region Integrity scan for the Translator class (DEBUG only)

#if DEBUG
                if (Translator.CheckIntegrity())
                {
                    if (!_isQuiet)
                    {
                        Console.WriteLine("[+] Integrity scan passed!");
                    }
                }
                else
                {
                    Console.WriteLine("[-] Integrity scan failed...!");
                }
#endif

                #endregion

                FileStream fileInput;
                FileStream fileOutput;
                SwfFormat  swf;

                switch (_action)
                {
                case Action.Dasm:

                    #region Disassemble file

                    swf       = new SwfFormat();
                    fileInput = File.Open(_pathSwf, FileMode.Open, FileAccess.Read);

                    swf.Read(fileInput);

                    fileInput.Close();
                    fileInput.Dispose();

                    DisassemblerBase dasm;

                    switch (_dasmType)
                    {
                    case Dasm.As3c:
                        dasm = new DisassemblerAs3c();
                        break;

                    case Dasm.Plain:
                        dasm = new DisassemblerPlain();
                        break;

                    default:
                        throw new Exception();
                    }

                    dasm.Parse(swf);

                    if ("" == _pathOutput)
                    {
                        dasm.EmitToConsole();
                    }
                    else
                    {
                        fileOutput = File.Open(_pathOutput, FileMode.OpenOrCreate, FileAccess.Write);
                        dasm.EmitToStream(fileOutput);

                        fileOutput.Close();
                        fileOutput.Dispose();
                    }

                    #endregion

                    break;

                case Action.Optimize:

                    #region Optimize SWF

                    swf       = new SwfFormat();
                    fileInput = File.Open(_pathSwf, FileMode.Open, FileAccess.Read);

                    swf.Read(fileInput);

                    fileInput.Close();
                    fileInput.Dispose();

                    CompilerOptimize compOptimize = new CompilerOptimize(swf);

                    compOptimize.Compile();

                    fileOutput = File.Open((_pathOutput != "") ? _pathOutput : _pathSwf, FileMode.OpenOrCreate, FileAccess.Write);

                    swf.Write(fileOutput);

                    fileOutput.Close();
                    fileOutput.Dispose();

                    #endregion

                    break;

                case Action.Inline:

                    #region Compile inline instructions

                    swf       = new SwfFormat();
                    fileInput = File.Open(_pathSwf, FileMode.Open, FileAccess.Read);

                    swf.Read(fileInput);

                    fileInput.Close();
                    fileInput.Dispose();

                    CompilerInline compInline = new CompilerInline(swf);
                    compInline.Compile();

                    fileOutput = File.Open((_pathOutput != "") ? _pathOutput : _pathSwf, FileMode.OpenOrCreate, FileAccess.Write);

                    swf.Write(fileOutput);

                    fileOutput.Close();
                    fileOutput.Dispose();

                    #endregion

                    break;

                case Action.Replace:

                    #region Replace method body

                    #region Simple pre-check

                    if ("" == _pathAsm || !File.Exists(_pathAsm))
                    {
                        Console.Error.WriteLine("[-] No valid ASM input given.");
                        return;
                    }

                    if ("" == _pathSwf || !File.Exists(_pathSwf))
                    {
                        Console.Error.WriteLine("[-] No valid SWF target given.");
                        return;
                    }

                    if ("" == _className)
                    {
                        Console.Error.WriteLine("[-] No class given.");
                        return;
                    }

                    if (!_isConstructor)
                    {
                        if ("" == _methodName)
                        {
                            Console.Error.WriteLine("[-] Need method name or constructor to replace");
                            return;
                        }
                    }

                    #endregion

                    swf       = new SwfFormat();
                    fileInput = File.Open(_pathSwf, FileMode.Open, FileAccess.Read);

                    swf.Read(fileInput);

                    fileInput.Close();
                    fileInput.Dispose();

                    #region Body lookup

                    Abc46 abc = null;
                    SwfLibrary.Abc.MethodInfo method = null;
                    MethodBodyInfo            body   = null;
                    bool  instanceFound = false;
                    Abc46 currentAbc    = null;

                    string classFormat;

                    if (_className.IndexOf(".") != -1)
                    {
                        classFormat = "public::" + _className.Substring(0, _className.LastIndexOf(".")) + "::" + _className.Substring(_className.LastIndexOf(".") + 1, _className.Length - _className.LastIndexOf(".") - 1);
                    }
                    else
                    {
                        classFormat = "public::" + _className;
                    }

                    string methodFormat = _namespace + "::" + _methodName;

                    // Parse for all possibilities
                    for (int i = 0, n = swf.AbcCount; i < n; ++i)
                    {
                        currentAbc = swf.GetAbcAt(i);

                        for (int j = 0, m = currentAbc.Scripts.Count; j < m; ++j)
                        {
                            ScriptInfo script = (ScriptInfo)currentAbc.Scripts[j];

                            for (int k = 0, o = script.Traits.Count; k < o; ++k)
                            {
                                TraitInfo scriptTrait = (TraitInfo)script.Traits[k];

                                if (!(scriptTrait.Body is TraitClass))
                                {
                                    continue;
                                }

                                TraitClass   classBody    = (TraitClass)scriptTrait.Body;
                                ClassInfo    classInfo    = (ClassInfo)currentAbc.Classes[(int)classBody.ClassI];
                                InstanceInfo instanceInfo = (InstanceInfo)currentAbc.Instances[(int)classBody.ClassI];

                                string instanceName = NameUtil.ResolveMultiname(currentAbc, instanceInfo.Name);

                                if (classFormat == instanceName)
                                {
                                    instanceFound = true;

                                    if (!_isQuiet)
                                    {
                                        Console.WriteLine("[+] Found class {0}", instanceName);
                                    }

                                    if (_isMethodStatic)
                                    {
                                        if (_isConstructor)
                                        {
                                            if (null != body)
                                            {
                                                Console.Error.WriteLine("[-] Can not explicitly determine method body.");
                                                return;
                                            }

                                            method = (SwfLibrary.Abc.MethodInfo)currentAbc.Methods[(int)classInfo.CInit];

                                            body = FindBody(currentAbc, classInfo.CInit);

                                            abc = currentAbc;

                                            if (null != body)
                                            {
                                                if (!_isQuiet)
                                                {
                                                    Console.WriteLine("[+] Found static class initializer.");
                                                }
                                            }
                                        }
                                        else
                                        {
                                            Console.Error.WriteLine("[-] Sorry, static methods do not work yet ...");
                                            return;
                                            //TODO support static methods...
                                        }
                                    }
                                    else
                                    {
                                        if (_isConstructor)
                                        {
                                            if (null != body)
                                            {
                                                Console.Error.WriteLine("[-] Can not explicitly determine method body.");
                                                return;
                                            }

                                            method = (SwfLibrary.Abc.MethodInfo)currentAbc.Methods[(int)instanceInfo.IInit];

                                            body = FindBody(currentAbc, instanceInfo.IInit);

                                            abc = currentAbc;

                                            if (null != body)
                                            {
                                                if (!_isQuiet)
                                                {
                                                    Console.WriteLine("[+] Found class initializer.");
                                                }
                                            }
                                        }
                                        else
                                        {
                                            // here begins the ugly part ...
                                            for (int l = 0, p = instanceInfo.Traits.Count; l < p; ++l)
                                            {
                                                TraitInfo instanceTrait = (TraitInfo)instanceInfo.Traits[l];

                                                if (!(instanceTrait.Body is TraitMethod))
                                                {
                                                    continue;
                                                }

                                                string methodName = NameUtil.ResolveMultiname(currentAbc, instanceTrait.Name);

                                                if ("" == _namespace)
                                                {
                                                    if ("public::" + _methodName != methodName &&
                                                        "private::" + _methodName != methodName &&
                                                        "protected::" + _methodName != methodName &&
                                                        "protected$::" + _methodName != methodName &&
                                                        "internal::" + _methodName != methodName)
                                                    {
                                                        continue;
                                                    }
                                                }
                                                else
                                                {
                                                    if (methodName != methodFormat)
                                                    {
                                                        continue;
                                                    }
                                                }

                                                if (null != body)
                                                {
                                                    Console.Error.WriteLine("[-] Can not explicitly determine method body.");
                                                    return;
                                                }

                                                TraitMethod methodBody = (TraitMethod)instanceTrait.Body;

                                                method = (SwfLibrary.Abc.MethodInfo)currentAbc.Methods[(int)methodBody.Method];

                                                body = FindBody(currentAbc, methodBody.Method);

                                                abc = currentAbc;

                                                if (null != body)
                                                {
                                                    if (!_isQuiet)
                                                    {
                                                        Console.WriteLine("[+] Found method {0}", methodName);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (null == body)
                    {
                        Console.Error.WriteLine("[-] Could not find {0}.", (instanceFound) ? "method" : "class");
                        return;
                    }

                    #endregion

                    //
                    // We have valid body to replace. Start the parser.
                    //

                    ParserAs3c parser = new ParserAs3c();
                    parser.Parse(_pathAsm);

                    //
                    // Convert the parser instructions to actual bytecode for the AVM2.
                    //

                    CompilerAs3c compAs3c = new CompilerAs3c();
                    compAs3c.Compile(currentAbc, parser.Instructions, parser.Labels, false);

                    //
                    // Get body information (maxstack, localcount, maxscopedepth, initscopedepth)
                    // We keep compiler directives in respect here ...
                    //

                    #region MethodBody information

                    U30 maxStack;
                    U30 maxScopeDepth;
                    U30 localCount;
                    U30 initScopeDepth = new U30();

                    if (parser.HasMaxStack)
                    {
                        maxStack       = new U30();
                        maxStack.Value = parser.MaxStack;
                    }
                    else
                    {
                        maxStack = ByteCodeAnalyzer.CalcMaxStack(compAs3c.Code);

                        if (maxStack.Value < method.ParameterCount.Value)
                        {
                            maxStack.Value = method.ParameterCount.Value;
                        }
                    }

                    if (parser.HasLocalCount)
                    {
                        localCount       = new U30();
                        localCount.Value = parser.LocalCount;
                    }
                    else
                    {
                        localCount = ByteCodeAnalyzer.CalcLocalCount(compAs3c.Code);
                    }

                    if (parser.HasInitScopeDepth)
                    {
                        initScopeDepth.Value = parser.InitScopeDepth;
                    }
                    else
                    {
                        initScopeDepth.Value = 1;
                    }

                    if (parser.HasMaxScopeDepth)
                    {
                        maxScopeDepth       = new U30();
                        maxScopeDepth.Value = parser.MaxScopeDepth;
                    }
                    else
                    {
                        maxScopeDepth        = ByteCodeAnalyzer.CalcScopeDepth(compAs3c.Code);
                        maxScopeDepth.Value += initScopeDepth.Value;
                    }

                    if (!_isQuiet)
                    {
                        Console.WriteLine("[i] InitScopeDepth: {0}", (int)initScopeDepth);
                        Console.WriteLine("[i] MaxScopeDepth: {0}", (int)maxScopeDepth);
                        Console.WriteLine("[i] MaxStack: {0}", (int)maxStack);
                        Console.WriteLine("[i] LocalCount: {0}", (int)localCount);
                    }

                    #endregion

                    //
                    // Replace the code of the body.
                    //

                    body.Code = compAs3c.Code;

                    //
                    // Update body information
                    //

                    body.MaxStack       = maxStack;
                    body.MaxScopeDepth  = maxScopeDepth;
                    body.InitScopeDepth = initScopeDepth;
                    body.LocalCount     = localCount;

                    #region Write output

                    if ("" == _pathOutput)
                    {
                        fileOutput = File.Open(_pathSwf, FileMode.OpenOrCreate, FileAccess.Write);
                    }
                    else
                    {
                        fileOutput = File.Open(_pathOutput, FileMode.OpenOrCreate, FileAccess.Write);
                    }

                    swf.Write(fileOutput);

                    fileOutput.Close();
                    fileOutput.Dispose();

                    #endregion

                    #endregion

                    break;

                case Action.Usage:
                    Usage();
                    break;
                }

                #region Program end

                if (!_isQuiet)
                {
                    Console.WriteLine("[i] Done.");
                }
                #endregion
            }
            catch (IOException ioex)
            {
                Console.Error.WriteLine("[-] Error: {0}", ioex.Message);
            }
            catch (InstructionException iex)
            {
                #region Parser errors

                string message;

                switch (iex.ErrorType)
                {
                case InstructionException.Type.InvalidSyntax:
                    message = "Error while parsing";
                    break;

                case InstructionException.Type.NotEnoughArguments:
                    message = "Not enough arguments";
                    break;

                case InstructionException.Type.TooManyArguments:
                    message = "Too many arguments";
                    break;

                case InstructionException.Type.UnknownType:
                    message = "Unknown type";
                    break;

                case InstructionException.Type.LabelRedefined:
                    message = "Label has already been defined";
                    break;

                case InstructionException.Type.LabelMissing:
                    message = "Label has never been defined";
                    break;

                default:
                    message = "Unknown error at";
                    break;
                }

                Console.Error.WriteLine("[-] " + message + ":");

                if (null != iex.ParserInfo)
                {
                    Console.Error.WriteLine("{0}({1}): {2}", iex.ParserInfo.FilePath, iex.ParserInfo.LineNumber, iex.ParserInfo.Line);
                }

                #endregion
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("[-] Unexpected error: {0}", ex.Message);
#if DEBUG
                Console.Error.WriteLine("[-] Stacktrace: {0}", ex.StackTrace);
#endif
            }

#if DEBUG
            DateTime end   = DateTime.Now;
            TimeSpan delta = end - start;

            Console.WriteLine("[i] Total: {0}sec {1}ms", delta.Seconds, delta.Milliseconds);
#endif
        }
Ejemplo n.º 52
0
 public async Task <bool> UpdateClass(ClassInfo classInfo)
 {
     return(await APIHelper.Instance.Post <bool>(APIRoute.Class.UpdateClass, classInfo));
 }
Ejemplo n.º 53
0
 public ClassScope(ClassInfo classInfo, ClassDefinition ast, InterpreterScope outerScope)
     : base(classInfo, ast, outerScope)
 {
     classInfo.Scope = this;
 }
Ejemplo n.º 54
0
        /// <summary>
        ///   Build a meta representation of an object
        ///   <pre>warning: When an object has two fields with the same name
        ///        (a private field with the same name in a parent class, the deeper field (of the parent) is ignored!)</pre>
        /// </summary>
        /// <returns> The ObjectInfo </returns>
        private AbstractObjectInfo GetObjectInfoInternal(AbstractObjectInfo nnoi, object o, ClassInfo classInfo,
                                                         bool recursive,
                                                         IDictionary <object, NonNativeObjectInfo> alreadyReadObjects,
                                                         IIntrospectionCallback callback)
        {
            if (o == null)
            {
                return(NullNativeObjectInfo.GetInstance());
            }

            var clazz = o.GetType();
            var type  = OdbType.GetFromClass(clazz);

            if (type.IsNative())
            {
                return(GetNativeObjectInfoInternal(type, o, recursive, alreadyReadObjects, callback));
            }

            // sometimes the type.getName() may not match the ci.getClassName()
            // It happens when the attribute is an interface or superclass of the
            // real attribute class
            // In this case, ci must be updated to the real class info
            if (classInfo != null && !classInfo.FullClassName.Equals(OdbClassNameResolver.GetFullName(clazz)))
            {
                classInfo = GetClassInfo(clazz);
                nnoi      = null;
            }
            var mainAoi      = (NonNativeObjectInfo)nnoi;
            var isRootObject = false;

            if (alreadyReadObjects == null)
            {
                alreadyReadObjects = new OdbHashMap <object, NonNativeObjectInfo>();
                isRootObject       = true;
            }

            NonNativeObjectInfo cachedNnoi;

            alreadyReadObjects.TryGetValue(o, out cachedNnoi);

            if (cachedNnoi != null)
            {
                return(new ObjectReference(cachedNnoi));
            }

            if (callback != null)
            {
                callback.ObjectFound(o);
            }

            if (mainAoi == null)
            {
                mainAoi = BuildNnoi(o, classInfo);
            }

            alreadyReadObjects[o] = mainAoi;

            var fields = ClassIntrospector.GetAllFieldsFrom(clazz);

            foreach (var field in fields)
            {
                try
                {
                    var value       = field.GetValue(o);
                    var attributeId = classInfo.GetAttributeId(field.Name);
                    if (attributeId == -1)
                    {
                        throw new OdbRuntimeException(
                                  NDatabaseError.ObjectIntrospectorNoFieldWithName.AddParameter(classInfo.FullClassName).
                                  AddParameter(field.Name));
                    }

                    var valueType = OdbType.GetFromClass(value == null
                                                             ? field.FieldType
                                                             : value.GetType());
                    // for native fields
                    AbstractObjectInfo abstractObjectInfo;

                    if (valueType.IsNative())
                    {
                        abstractObjectInfo = GetNativeObjectInfoInternal(valueType, value, recursive, alreadyReadObjects,
                                                                         callback);
                        mainAoi.SetAttributeValue(attributeId, abstractObjectInfo);
                    }
                    else
                    {
                        // Non Native Objects
                        if (value == null)
                        {
                            var classInfo1 = GetClassInfo(field.GetType());

                            abstractObjectInfo = new NonNativeNullObjectInfo(classInfo1);
                            mainAoi.SetAttributeValue(attributeId, abstractObjectInfo);
                        }
                        else
                        {
                            var classInfo2 = GetClassInfo(value.GetType());
                            if (recursive)
                            {
                                abstractObjectInfo = GetObjectInfoInternal(null, value, classInfo2, true,
                                                                           alreadyReadObjects, callback);
                                mainAoi.SetAttributeValue(attributeId, abstractObjectInfo);
                            }
                            else
                            {
                                // When it is not recursive, simply add the object
                                // values.add(value);
                                throw new OdbRuntimeException(
                                          NDatabaseError.InternalError.AddParameter(
                                              "Should not enter here - ObjectIntrospector - 'simply add the object'"));
                            }
                        }
                    }
                }
                catch (ArgumentException e)
                {
                    throw new OdbRuntimeException(
                              NDatabaseError.InternalError.AddParameter("in getObjectInfoInternal"), e);
                }
                catch (MemberAccessException e)
                {
                    throw new OdbRuntimeException(NDatabaseError.InternalError.AddParameter("getObjectInfoInternal"), e);
                }
            }

            if (isRootObject)
            {
                alreadyReadObjects.Clear();
            }

            return(mainAoi);
        }
Ejemplo n.º 55
0
 private object GetClassMro(ClassInfo ci)
 {
     // TODO: return correct mro
     return(new List <object>());
 }
Ejemplo n.º 56
0
        private static object[] createInstance(ParameterInfo[] classTypeParem)
        {
            List <object> createdInstance = new List <object>();

            Debug.WriteLine("create Instance create parem");
            foreach (ParameterInfo item in classTypeParem)
            {
                Type paremType = item.ParameterType;
                if (userInputType.Contains(paremType) || userInputType.Contains(Nullable.GetUnderlyingType(paremType)) || paremType.IsEnum)
                {
                    if (paremType.IsEnum)
                    {
                        createdInstance.Add(getEnumValue(item));
                    }
                    else
                    {
                        createdInstance.Add(getTypeValue(item));
                    }
                    continue;
                }
                if (paremType.IsInterface || paremType.IsAbstract)
                {
                    string    tempTypeName = commonTypeName(paremType);
                    ClassInfo matchClass   = MainSchemaInfo.DepandancyClasses.FirstOrDefault((ClassInfo x) => x.NameSpaceAndInterfaceName == tempTypeName);

                    if (matchClass == null || string.IsNullOrWhiteSpace(matchClass.NameSpaceAndMappedClassName))
                    {
                        createdInstance.Add(findTypeFromAssebly(paremType));
                        Debug.WriteLine(tempTypeName + "->" + matchClass?.NameSpaceAndMappedClassName);
                        continue;
                    }

                    Assembly tempAssembly = findAssebly(matchClass);
                    if (tempAssembly == null)
                    {
                        createdInstance.Add(null);
                        Debug.WriteLine(tempTypeName + "-> null");
                        continue;
                    }
                    paremType = GetGenericArgumentType(paremType, matchClass, tempAssembly);
                }
                if (paremType == null)
                {
                    createdInstance.Add(null);
                    Debug.WriteLine("paremType is -> null");
                    continue;
                }
                if (!paremType.IsClass)
                {
                    createdInstance.Add(null);
                    Debug.WriteLine("paremType not IsClass set null");
                }
                else if (paremType.FullName.StartsWith("System.Lazy"))
                {
                    Type tempType = paremType.GetGenericArguments()[0];
                    if (tempType.IsInterface)
                    {
                        string    tempTypeName = commonTypeName(tempType);
                        ClassInfo matchClass   = MainSchemaInfo.DepandancyClasses.FirstOrDefault((ClassInfo x) => x.NameSpaceAndInterfaceName == tempTypeName);

                        if (matchClass == null || string.IsNullOrWhiteSpace(matchClass.NameSpaceAndMappedClassName))
                        {
                            createdInstance.Add(findTypeFromAssebly(paremType));
                            //createdInstance.Add(null);
                            Debug.WriteLine(tempTypeName + "lazy ->" + matchClass?.NameSpaceAndMappedClassName);
                            continue;
                        }
                        var tempAssebly = findAssebly(matchClass);
                        if (tempAssebly == null)
                        {
                            createdInstance.Add(null);
                            Debug.WriteLine(tempTypeName + "lazy -> null");
                            continue;
                        }
                        tempType = GetGenericArgumentType(tempType, matchClass, tempAssebly);
                    }

                    if (tempType == null)
                    {
                        createdInstance.Add(null);
                        Debug.WriteLine("paremType lazy is -> null");
                        continue;
                    }
                    ConstructorInfo[]    paremTypeConstructors2 = tempType.GetConstructors();
                    ParameterInfo[]      paremTypeParemType2    = (paremTypeConstructors2.Length != 0) ? paremTypeConstructors2[0].GetParameters() : new ParameterInfo[0];
                    lazyMapper           lazyMapper             = new lazyMapper();
                    MethodCallExpression methodCall             = Expression.Call(Expression.Constant(lazyMapper), factoryMethod, Expression.Constant(tempType), Expression.Constant(paremTypeParemType2));
                    UnaryExpression      cast   = Expression.Convert(methodCall, tempType);
                    Delegate             lambda = Expression.Lambda(cast).Compile();
                    createdInstance.Add(Activator.CreateInstance(paremType, lambda));
                }
                else
                {
                    ConstructorInfo[] paremTypeConstructors = paremType.GetConstructors();
                    ParameterInfo[]   paremTypeParemType    = (paremTypeConstructors.Length != 0) ? paremType.GetConstructors()[0].GetParameters() : new ParameterInfo[0];
                    object[]          tempCreatedInstance   = new object[0];
                    if (paremTypeParemType.Length != 0)
                    {
                        tempCreatedInstance = createInstance(paremTypeParemType);
                    }
                    Debug.WriteLine("paremType is class");

                    createdInstance.Add(Activator.CreateInstance(paremType, tempCreatedInstance));
                }
            }
            return(createdInstance.ToArray());
        }
Ejemplo n.º 57
0
 private static double Calc(double dc, double d, List <String> q, double lc, ClassInfo @class, double v)
 {
     return(Math.Log(dc / d) + q.Sum(x => Math.Log((@class.NumberOfOccurencesInTrainDocs(x) + 1) / (v + lc))));
 }
Ejemplo n.º 58
0
        internal void GenerateConstructorCode(StringBuilder sb)
        {
            // Change from camelCase to UpperCamelCase

            string origName        = TargetConstructorInfo.Name;
            string transformedName = ClassInfo.TargetNameWithoutNamespace;

            sb.AppendFormat("      public {0}(", transformedName);

            bool firstParameter = true;

            var parameters =
                TargetConstructorInfo.GetParameters().Select(pi => (new WrapperParameterInfo(this, pi))).ToArray();

            foreach (var mp in parameters)
            {
                if (Repository.TypeIsWrapped(mp.ParameterType))
                {
                    Repository.MarkUsageOfType(mp.ParameterType);
                }
            }

            foreach (var mp in parameters)
            {
                if (!firstParameter)
                {
                    sb.Append(", ");
                }
                firstParameter = false;

                sb.AppendFormat("{0} {1}", mp.ParameterTypeName, mp.ParameterName);
            }

            // Generate function call
            var functionCallSb = new StringBuilder();

            functionCallSb.Append("(");

            firstParameter = true;
            foreach (var mp in parameters)
            {
                if (!firstParameter)
                {
                    functionCallSb.Append(", ");
                }
                firstParameter = false;

                if (mp.IsWrapped)
                {
                    functionCallSb.AppendFormat("({0}){1}.WrappedObject", ClassInfo.SanitizeTypeName(mp.ParameterType.FullName), mp.ParameterName);
                }
                else
                {
                    functionCallSb.Append(mp.ParameterName);
                }
            }

            functionCallSb.Append(")");

            sb.AppendFormat(")\r\n         : this(new {0}{1}) {{}}\r\n\r\n", ClassInfo.WrappedTypeFullNameSanitized, functionCallSb);
        }
Ejemplo n.º 59
0
 /// <summary>
 ///   retrieve object data
 /// </summary>
 /// <returns> The object info </returns>
 private AbstractObjectInfo GetObjectInfo(object o, ClassInfo ci, bool recursive,
                                          IDictionary <object, NonNativeObjectInfo> alreadyReadObjects,
                                          IIntrospectionCallback callback)
 {
     return(GetObjectInfoInternal(null, o, ci, recursive, alreadyReadObjects, callback));
 }
Ejemplo n.º 60
0
        IAnalysisSet LoadComponent(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames)
        {
            if (args.Length == 2 && unit.State.Interpreter is IDotNetPythonInterpreter)
            {
                var self = args[0];
                var xaml = args[1];

                foreach (var arg in xaml)
                {
                    var strConst = arg.GetConstantValueAsString();
                    if (string.IsNullOrEmpty(strConst))
                    {
                        continue;
                    }

                    // process xaml file, add attributes to self
                    string           xamlPath = Path.Combine(Path.GetDirectoryName(unit.DeclaringModule.ProjectEntry.FilePath), strConst);
                    XamlProjectEntry xamlProject;
                    if (unit.State._xamlByFilename.TryGetValue(xamlPath, out xamlProject))
                    {
                        // TODO: Get existing analysis if it hasn't changed.
                        var analysis = xamlProject.Analysis;

                        if (analysis == null)
                        {
                            xamlProject.Analyze(CancellationToken.None);
                            analysis = xamlProject.Analysis;
                            if (analysis == null)
                            {
                                AnalysisLog.Assert(false, "No Xaml analysis");
                                return(self);
                            }
                        }

                        xamlProject.AddDependency(unit.ProjectEntry);

                        var evalUnit = unit.CopyForEval();

                        // add named objects to instance
                        foreach (var keyValue in analysis.NamedObjects)
                        {
                            var type = keyValue.Value;
                            if (type.Type.UnderlyingType != null)
                            {
                                var ns  = unit.State.GetAnalysisValueFromObjects(((IDotNetPythonInterpreter)unit.State.Interpreter).GetBuiltinType(type.Type.UnderlyingType));
                                var bci = ns as BuiltinClassInfo;
                                if (bci != null)
                                {
                                    ns = bci.Instance;
                                }
                                self.SetMember(node, evalUnit, keyValue.Key, ns.SelfSet);
                            }

                            // TODO: Better would be if SetMember took something other than a node, then we'd
                            // track references w/o this extra effort.
                            foreach (var inst in self)
                            {
                                InstanceInfo instInfo = inst as InstanceInfo;
                                if (instInfo != null && instInfo.InstanceAttributes != null)
                                {
                                    VariableDef def;
                                    if (instInfo.InstanceAttributes.TryGetValue(keyValue.Key, out def))
                                    {
                                        def.AddAssignment(
                                            new EncodedLocation(
                                                new LocationInfo(xamlProject.FilePath, xamlProject.DocumentUri, type.LineNumber, type.LineOffset),
                                                null
                                                ),
                                            xamlProject
                                            );
                                    }
                                }
                            }
                        }

                        // add references to event handlers
                        foreach (var keyValue in analysis.EventHandlers)
                        {
                            // add reference to methods...
                            var member = keyValue.Value;

                            // TODO: Better would be if SetMember took something other than a node, then we'd
                            // track references w/o this extra effort.
                            foreach (var inst in self)
                            {
                                InstanceInfo instInfo = inst as InstanceInfo;
                                if (instInfo != null)
                                {
                                    ClassInfo ci = instInfo.ClassInfo;

                                    VariableDef def;
                                    if (ci.Scope.TryGetVariable(keyValue.Key, out def))
                                    {
                                        def.AddReference(
                                            new EncodedLocation(
                                                new LocationInfo(xamlProject.FilePath, xamlProject.DocumentUri, member.LineNumber, member.LineOffset),
                                                null
                                                ),
                                            xamlProject
                                            );
                                    }
                                }
                            }
                        }
                    }
                }
                // load component returns self
                return(self);
            }

            return(AnalysisSet.Empty);
        }