public List<Metric> Calculate(ICodeBase codeBase)
        {
            var result = from t in codeBase.Application.Types
                         where t.IsClass
                         let lcom = t.LCOM
                         select new Metric() { Type = ElementType.Class, Value = lcom.Value, ObjectName = t.Name };

            return result.ToList();
        }
        public List<Metric> Calculate(ICodeBase codeBase)
        {
            var result = from t in codeBase.Application.Types
                         let methods = t.Methods.Where(m => !m.IsPropertyGetter && !m.IsPropertySetter && !m.IsConstructor)
                         orderby methods.Count() descending
                         select new Metric() { Type = ElementType.Class, Value = Double.Parse(methods.Count().ToString()), ObjectName = t.Name };

            return result.ToList();
        }
        public List<Metric> Calculate(ICodeBase codeBase)
        {
            var result = from m in codeBase.Application.Methods
                         where !m.IsThirdParty
                         let rfc = m.MethodsCalled.ExceptThirdParty().Count()
                         select new Metric() { Type = ElementType.Method, Value = rfc, ObjectName = m.Name };

            return result.ToList();
        }
        public List<Metric> Calculate(ICodeBase codeBase)
        {
            var result = from t in codeBase.Application.Types
                         where t.IsClass
                         let baseClasses = t.BaseClasses.ExceptThirdParty()
                         select new Metric() { Type = ElementType.Class, Value = Double.Parse(baseClasses.Count().ToString()), ObjectName = t.Name };

            return result.ToList();
        }
        public List<Metric> Calculate(ICodeBase codeBase)
        {
            var result = from t in codeBase.Application.Types
                         let typesUsed = t.TypesUsed.ExceptThirdParty()
                         orderby typesUsed.Count() descending
                         select new Metric() { Type = ElementType.Class, Value = Double.Parse(typesUsed.Count().ToString()), ObjectName = t.Name };

            return result.ToList();
        }
        public List <Metric> Calculate(ICodeBase codeBase)
        {
            var result = from t in codeBase.Application.Types
                         let typesUsed = t.TypesUsed.ExceptThirdParty()
                                         orderby typesUsed.Count() descending
                                         select new Metric()
            {
                Type = ElementType.Class, Value = Double.Parse(typesUsed.Count().ToString()), ObjectName = t.Name
            };

            return(result.ToList());
        }
Esempio n. 7
0
        public List <Metric> Calculate(ICodeBase codeBase)
        {
            var result = from t in codeBase.Application.Types
                         let methods = t.Methods.Where(m => !m.IsPropertyGetter && !m.IsPropertySetter && !m.IsConstructor)
                                       orderby methods.Count() descending
                                       select new Metric()
            {
                Type = ElementType.Class, Value = Double.Parse(methods.Count().ToString()), ObjectName = t.Name
            };

            return(result.ToList());
        }
Esempio n. 8
0
 internal static IEnumerable <IField> FindDeadFields(ICodeBase codeBase, Func <IMember, bool> funcHasAttribute)
 {
     Debug.Assert(codeBase != null);
     Debug.Assert(funcHasAttribute != null);
     return(from f in codeBase.Application.Fields where
            f.NbMethodsUsingMe == 0 &&
            !f.IsPublic &&         // Although not recommended, public fields might be used by client applications of your assemblies.
            !f.IsLiteral &&        // The IL code never explicitely uses literal fields.
            !f.IsEnumValue &&      // The IL code never explicitely uses enumeration value.
            f.Name != "value__" && // Field named 'value__' are relative to enumerations and the IL code never explicitely uses them.
            !funcHasAttribute(f)
            select f);
 }
        public List<Metric> Calculate(ICodeBase codeBase)
        {
            var result = from t in codeBase.Application.Types
                         where t.IsClass
                         let childClasses = t.DerivedTypes
                         where
                         !t.IsThirdParty
                         //t.Name == className
                            //childClasses.Count() > 0
                         orderby childClasses.Count() descending
                         select new Metric() { Type = ElementType.Class, Value = Double.Parse(childClasses.Count().ToString()), ObjectName = t.Name };

            return result.ToList();
        }
        public IEnumerable <StructuralRelation> GetStructuralRelations(ICodeBase codeBase)
        {
            _logger.Information("\tBuilding Structural Relations");
            var stopWatch = Stopwatch.StartNew();

            HashSet <IType> types = codeBase.Application.Types.ToHashSetEx();
            List <Maybe <StructuralRelation> > relations =
                (from source in types from target in types select StructuralRelation.From(source, target)).ToList();

            IEnumerable <StructuralRelation> structuralRelations = relations.Where(r => r.HasValue).Select(r => r.Value).ToList();

            stopWatch.Stop();
            _logger.Information("\tBuilt Structural Relations in {Elapsed:000} ms", stopWatch.ElapsedMilliseconds);

            return(structuralRelations);
        }
Esempio n. 11
0
        public List <Metric> Calculate(ICodeBase codeBase)
        {
            var result = from t in codeBase.Application.Types
                         where t.IsClass
                         let childClasses = t.DerivedTypes
                                            where
                                            !t.IsThirdParty
                                            //t.Name == className
                                            //childClasses.Count() > 0
                                            orderby childClasses.Count() descending
                                            select new Metric()
            {
                Type = ElementType.Class, Value = Double.Parse(childClasses.Count().ToString()), ObjectName = t.Name
            };

            return(result.ToList());
        }
Esempio n. 12
0
        private static HashSet <IMethod> GetExcludedMethod(ICodeBase codeBase)
        {
            Debug.Assert(codeBase != null);

            // method DeemAsExcludedMethodFromFileName + eventually
            // methods tagged with generatedCodeAttributeType + types tagged with generatedCodeAttributeType
            var methodsExcluded = codeBase.Application.Methods.Where(DeemAsExcludedMethodFromFileName);

            var generatedCodeAttributeType = codeBase.ThirdParty.Types.WithFullName("System.CodeDom.Compiler.GeneratedCodeAttribute").SingleOrDefault();

            if (generatedCodeAttributeType != null)
            {
                methodsExcluded = methodsExcluded.Concat(codeBase.Application.Methods.Where(m => m.HasAttribute(generatedCodeAttributeType)));
                methodsExcluded = methodsExcluded.Concat(codeBase.Application.Types.Where(t => t.HasAttribute(generatedCodeAttributeType)).ChildMethods());
            }

            return(new HashSet <IMethod>(methodsExcluded));
        }
        private IEnumerable <DesignSmell> DetectMethodDesignSmells(ICodeBase codeBase)
        {
            var methodDesignSmells = new List <DesignSmell>();
            var stopWatch          = Stopwatch.StartNew();

            _logger.Information("\tDetecting Design Smells in methods");
            foreach (var m in codeBase.Application.Methods)
            {
                _logger.Debug("\t\t" + m.FullName);

                if (string.IsNullOrWhiteSpace(m.ParentType.SourceFile()))
                {
                    continue;
                }

                if (IsGenerated(codeBase, m.ParentType))
                {
                    continue;
                }

                if (IsDefaultConstructorGeneratedByCompiler(m))
                {
                    continue;
                }

                foreach (var methodDesignSmellDetectionStrategy in _methodDesignSmellDetectionStrategies)
                {
                    Maybe <DesignSmell> designSmell = methodDesignSmellDetectionStrategy.Detect(m);
                    if (designSmell.HasValue)
                    {
                        methodDesignSmells.Add(designSmell.Value);
                    }
                }
            }

            stopWatch.Stop();
            _logger.Information(
                "\tDetected Design Smells in methods in {Elapsed:000} ms",
                stopWatch.ElapsedMilliseconds);

            IEnumerable <DesignSmell> groupedDesignSmells = GroupByDesignSmellAndSourceFile(methodDesignSmells);

            return(groupedDesignSmells);
        }
Esempio n. 14
0
    public void InitFunc()
    {
        FunctionCall func = new FunctionCall();

        NodeFuncData funcNodeData    = this.funcNodeData as NodeFuncData;
        Type         methodClassType = NodeGUIUtility.GetType(funcNodeData.funcClassType);
        MethodInfo   method          = methodClassType.GetMethod(funcNodeData.methodName);

        AccessCode access = new AccessCode();

        List <NodePointData> parameterPoint = GetPointData(ConnectionPointType.Parameter);

        if (method.IsStatic)
        {
            access.ownerObject = new Variable()
            {
                Var = methodClassType.Name
            };
            func.Access = access;
        }
        else
        {
            NodePointData ownerPoint = parameterPoint.Find((p) => p.parameterType == funcNodeData.funcClassType);
            AddMapping(ownerPoint.GUID, (c) => ((AccessCode)((FunctionCall)code).Access).ownerObject = c);
            parameterPoint.Remove(ownerPoint);
        }

        foreach (var param in parameterPoint)
        {
            AddMapping(param.GUID, (c) => ((ParameterBlock)((FunctionCall)code).Parameter).Parameters.Add(c));
        }

        access.member = new Variable()
        {
            Var = method.Name
        };
        func.Access    = access;
        func.Parameter = new ParameterBlock();

        code = func;
    }
Esempio n. 15
0
        internal static ICodeMetric <IMethod, ushort> FindDeadMethods(ICodeBase codeBase, Func <IMember, bool> funcHasAttribute)
        {
            Debug.Assert(codeBase != null);
            Debug.Assert(funcHasAttribute != null);
            // Filter function for methods that should'nt be considered as dead
            var canMethodBeConsideredAsDead = new Func <IMethod, bool>(
                m => !m.IsPublic &&             // Public methods might be used by client applications of your assemblies.
                !m.IsEntryPoint &&              // Main() method is not used by-design.
                !m.IsExplicitInterfaceImpl &&   // The IL code never explicitely calls explicit interface methods implementation.
                !m.IsClassConstructor &&        // The IL code never explicitely calls class constructors.
                !m.IsFinalizer &&               // The IL code never explicitely calls finalizers.
                !m.IsVirtual &&                 // Only check for non virtual method that are not seen as used in IL.
                !(m.IsConstructor &&            // Don't take account of protected ctor that might be call by a derived ctors.
                  m.IsProtected) &&
                !m.IsEventAdder &&              // The IL code never explicitely calls events adder/remover.
                !m.IsEventRemover &&
                !funcHasAttribute(m) &&
                !m.FullName.Contains(".Resources."));

            // Get methods unused
            var methodsUnused =
                from m in codeBase.Application.Methods where
                m.NbMethodsCallingMe == 0 &&
                canMethodBeConsideredAsDead(m)
                select m;

            // Dead methods = methods used only by unused methods (recursive)
            var deadMethodsMetric = methodsUnused.FillIterative(
                methods => {
                // Use a hashet to make Intersect calls much faster!
                var hashset = methods.ToHashSet();
                return(from m in codeBase.Application.Methods.UsedByAny(methods).Except(methods)
                       where canMethodBeConsideredAsDead(m) &&
                       // Select methods called only by methods already considered as dead
                       hashset.Intersect(m.MethodsCallingMe).Count() == m.NbMethodsCallingMe
                       select m);
            }
                );

            return(deadMethodsMetric);
        }
Esempio n. 16
0
        private object GetParameterCode(ICodeBase codeBase, DCEntityParametersModel parameterModel, EntityPropertyModel entityProperty)
        {
            e_ConvertType e_Convert = e_ConvertType.String;
            string        pn        = parameterModel.ParameterName;

            switch (this.MethodType)
            {
            case e_MethodType.Create:
                e_Convert = this.ConvertStrToType(entityProperty.DbType);
                break;

            case e_MethodType.Update:
                e_Convert = this.ConvertStrToType(entityProperty.DbType);
                break;

            case e_MethodType.Delete:
                e_Convert = this.ConvertStrToType(entityProperty.DbType);
                break;
            }
            return(parameterModel.GetRendered(codeBase, e_Convert, entityProperty.Required));
        }
Esempio n. 17
0
        internal static ICodeMetric <IType, ushort> FindDeadTypes(ICodeBase codeBase)
        {
            Debug.Assert(codeBase != null);
            // Filter function for types that should'nt be considered as dead
            var canTypeBeConsideredAsDead = new Func <IType, bool>(
                t => !t.IsPublic);

            // Select types unused
            var typesUnused =
                from t in codeBase.Application.Types where
                t.NbTypesUsingMe == 0 && canTypeBeConsideredAsDead(t)
                select t;

            // Dead types = types used only by unused types (recursive)
            var deadTypesMetric = typesUnused.FillIterative(
                types => from t in codeBase.Application.Types.UsedByAny(types).Except(types)
                where canTypeBeConsideredAsDead(t) &&
                t.TypesUsingMe.Intersect(types).Count() == t.NbTypesUsingMe
                select t);

            return(deadTypesMetric);
        }
Esempio n. 18
0
        internal static void ShowConsoleAnalysisResult(ICodeBase codeBase)
        {
            Debug.Assert(codeBase != null);
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("  # Application Projects " + codeBase.Application.Projects.Count().Format1000());
            Console.WriteLine("  # Third-Party Projects " + codeBase.ThirdParty.Projects.Count().Format1000());
            Console.WriteLine("  # Application Namespaces " + codeBase.Application.Namespaces.Count().Format1000());
            Console.WriteLine("  # Third-Party Namespaces " + codeBase.ThirdParty.Namespaces.Count().Format1000());
            ShowTypeCount("  # Types ", codeBase, t => true);
            Console.WriteLine("  # Methods " + codeBase.Methods.Count().Format1000());
            Console.WriteLine("  # Fields " + codeBase.Fields.Count().Format1000());

            Console.WriteLine("  # Line of Codes " + codeBase.Projects.Sum(asm => asm.NbLinesOfCode).Format1000());


            Console.WriteLine("  # LOC " + codeBase.Projects.Sum(asm => asm.NbLinesOfCode).Format1000());
            ShowTypeCount("  # Classes ", codeBase, t => t.IsClass);
            ShowTypeCount("  # Structures ", codeBase, t => t.IsStructure);
            ShowTypeCount("  # Interfaces ", codeBase, t => t.IsInterface);
            ShowTypeCount("  # Enumerations ", codeBase, t => t.IsEnumeration);

            ShowTypeCount("  # Exception classes ", codeBase, t => t.IsExceptionClass);
        }
        private IEnumerable <DesignSmell> DetectTypeDesignSmells(ICodeBase codeBase)
        {
            _logger.Information("\tDetecting Design Smells in types");

            var stopWatch = Stopwatch.StartNew();

            var typeDesignSmells = new List <DesignSmell>();

            foreach (var t in codeBase.Application.Types)
            {
                _logger.Debug("\t\t" + t.FullName);

                if (string.IsNullOrWhiteSpace(t.SourceFile()))
                {
                    continue;
                }

                if (IsGenerated(codeBase, t))
                {
                    continue;
                }

                foreach (var typeDesignSmellDetectionStrategy in _typeDesignSmellDetectionStrategies)
                {
                    Maybe <DesignSmell> designSmell = typeDesignSmellDetectionStrategy.Detect(t);
                    if (designSmell.HasValue)
                    {
                        typeDesignSmells.Add(designSmell.Value);
                    }
                }
            }

            stopWatch.Stop();

            _logger.Information("\tDetected Design Smells in types in {Elapsed:000} ms", stopWatch.ElapsedMilliseconds);
            return(typeDesignSmells);
        }
        public static object GetValue(ICodeBase codeBase, string value, e_ValueType valueType,
                                      DCBaseModel.e_ConvertType e_Convert, bool allowNull = true)
        {
            switch (valueType)
            {
            case e_ValueType.Static:
                return(DCBaseModel.GetConverted(value, e_Convert, allowNull));

            case e_ValueType.Control:
                return(DCBaseModel.GetConverted(codeBase.ControlHelper.GetValue(value), e_Convert, allowNull));

            case e_ValueType.Parameter:
                return(DCBaseModel.GetConverted(codeBase.UrlHelper.GetParameter(value), e_Convert, allowNull));

            case e_ValueType.Variable:
                return(DCBaseModel.GetConverted(codeBase.VariableHelper.GetValue(value), e_Convert, allowNull));

            case e_ValueType.SysParameter:
                switch (value)
                {
                case "GetCurrentUserID":
                    return(DCBaseModel.GetConverted(codeBase.GetCurrentUserID, e_Convert, allowNull));

                case "GetCurrentUserName":
                    return(DCBaseModel.GetConverted(codeBase.GetCurrentUserName, e_Convert, allowNull));

                case "GetThreadID":
                    return(DCBaseModel.GetConverted(codeBase.GetThreadID, e_Convert, allowNull));

                case "GetThreadUserID":
                    return(DCBaseModel.GetConverted(codeBase.GetThreadUserID, e_Convert, allowNull));
                }
                break;
            }
            return(null);
        }
Esempio n. 21
0
        internal static ICodeMetric <IMethod, ushort> FindDeadMethods(ICodeBase codeBase)
        {
            Debug.Assert(codeBase != null);

            // Filter function for methods that should'nt be considered as dead
            var canMethodBeConsideredAsDead = new Func <IMethod, bool>(
                m => !m.IsPublic &&             // Public methods might be used by client applications of your projects.
                !m.IsEntryPoint &&              // Main() method is not used by-design.
                !m.IsClassConstructor &&
                !m.IsVirtual &&
                !(m.IsConstructor &&            // Don't take account of protected ctor that might be call by a derived ctors.
                  m.IsProtected)
                );

            // Get methods unused
            var methodsUnused =
                from m in codeBase.Application.Methods where
                m.NbMethodsCallingMe == 0 &&
                canMethodBeConsideredAsDead(m)
                select m;

            // Dead methods = methods used only by unused methods (recursive)
            var deadMethodsMetric = methodsUnused.FillIterative(
                methods => {
                // Use a hashet to make Intersect calls much faster!
                var hashset = methods.ToHashSet();
                return(from m in codeBase.Application.Methods.UsedByAny(methods).Except(methods)
                       where canMethodBeConsideredAsDead(m) &&
                       // Select methods called only by methods already considered as dead
                       hashset.Intersect(m.MethodsCallingMe).Count() == m.NbMethodsCallingMe
                       select m);
            }
                );

            return(deadMethodsMetric);
        }
 public UserDefinedMetrics(ICodeBase codeBaseToStudy)
 {
     this.codeBaseToStudy = codeBaseToStudy;
     codeElementsManager = new CodeElementsManager(codeBaseToStudy);
 }
Esempio n. 23
0
        public IList GetMetricHistory(string codeElementName, object metricDefinition)
        {
            CodeBaseManager codeBaseManager = new CodeBaseManager(analysisResultRefsList[0].Project);

            Type   metricType;
            string codeElementType;
            Type   metricDefinitionType = metricDefinition.GetType();

            if (metricDefinitionType == typeof(NDependMetricDefinition))
            {
                metricType      = Type.GetType(((NDependMetricDefinition)metricDefinition).NDependMetricType);
                codeElementType = ((NDependMetricDefinition)metricDefinition).NDependCodeElementType;
            }
            else
            {
                metricType      = Type.GetType(((UserDefinedMetricDefinition)metricDefinition).MetricType);
                codeElementType = ((UserDefinedMetricDefinition)metricDefinition).NDependCodeElementType;
            }

            Type  nullableMetricType = typeof(Nullable <>).MakeGenericType(metricType);
            var   metricValue        = Activator.CreateInstance(nullableMetricType);
            IList metricValues       = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(nullableMetricType));

            foreach (var analysisResultRef in analysisResultRefsList)
            {
                ICodeBase           currentAnalysisResultCodeBase        = codeBaseManager.LoadCodeBase(analysisResultRef);
                CodeElementsManager currentAnalysisResultCodeBaseManager = new CodeElementsManager(currentAnalysisResultCodeBase);
                UserDefinedMetrics  userDefinedMetrics = new UserDefinedMetrics(currentAnalysisResultCodeBase);

                metricValue = null;
                switch (codeElementType)
                {
                case "NDepend.CodeModel.IAssembly":
                    IAssembly selectedAssemblyFromCurrentAnalysisResultCodebase = currentAnalysisResultCodeBaseManager.GetAssemblyByName(codeElementName);
                    if (selectedAssemblyFromCurrentAnalysisResultCodebase != null)
                    {
                        metricValue = metricDefinitionType == typeof(NDependMetricDefinition) ?
                                      currentAnalysisResultCodeBaseManager.GetCodeElementMetricValue(selectedAssemblyFromCurrentAnalysisResultCodebase, typeof(IAssembly), (NDependMetricDefinition)metricDefinition) :
                                      userDefinedMetrics.InvokeUserDefinedMetric(codeElementName, ((UserDefinedMetricDefinition)metricDefinition).MethodNameToInvoke);
                    }
                    break;

                case "NDepend.CodeModel.INamespace":
                    INamespace selectedNamespaceFromCurrentAnalysisResultCodebase = currentAnalysisResultCodeBaseManager.GetNamespaceByName(codeElementName);
                    if (selectedNamespaceFromCurrentAnalysisResultCodebase != null)
                    {
                        metricValue = metricDefinitionType == typeof(NDependMetricDefinition) ?
                                      currentAnalysisResultCodeBaseManager.GetCodeElementMetricValue(selectedNamespaceFromCurrentAnalysisResultCodebase, typeof(INamespace), (NDependMetricDefinition)metricDefinition) :
                                      userDefinedMetrics.InvokeUserDefinedMetric(codeElementName, ((UserDefinedMetricDefinition)metricDefinition).MethodNameToInvoke);
                    }
                    break;

                case "NDepend.CodeModel.IType":
                    IType selectedTypeFromCurrentAnalysisResultCodebase = currentAnalysisResultCodeBaseManager.GetTypeByName(codeElementName);
                    if (selectedTypeFromCurrentAnalysisResultCodebase != null)
                    {
                        metricValue = metricDefinitionType == typeof(NDependMetricDefinition) ?
                                      currentAnalysisResultCodeBaseManager.GetCodeElementMetricValue(selectedTypeFromCurrentAnalysisResultCodebase, typeof(IType), (NDependMetricDefinition)metricDefinition) :
                                      userDefinedMetrics.InvokeUserDefinedMetric(codeElementName, ((UserDefinedMetricDefinition)metricDefinition).MethodNameToInvoke);
                    }
                    break;

                case "NDepend.CodeModel.IMethod":
                    IMethod selectedMethodFromCurrentAnalysisResultCodebase = currentAnalysisResultCodeBaseManager.GetMethodByName(codeElementName);
                    if (selectedMethodFromCurrentAnalysisResultCodebase != null)
                    {
                        metricValue = metricDefinitionType == typeof(NDependMetricDefinition) ?
                                      currentAnalysisResultCodeBaseManager.GetCodeElementMetricValue(selectedMethodFromCurrentAnalysisResultCodebase, typeof(IMethod), (NDependMetricDefinition)metricDefinition) :
                                      userDefinedMetrics.InvokeUserDefinedMetric(codeElementName, ((UserDefinedMetricDefinition)metricDefinition).MethodNameToInvoke);
                    }
                    break;
                }
                metricValues.Add(metricValue);
            }
            return(metricValues);
        }
Esempio n. 24
0
        public IList GetMetricHistory(string codeElementName, NDependMetricDefinition metricDefinition)
        {
            CodeBaseManager codeBaseManager = new CodeBaseManager(analysisResultRefsList[0].Project);
            CodeElementsManagerReflectionHelper reflectionHelper = new CodeElementsManagerReflectionHelper();

            Type  metricType         = Type.GetType(metricDefinition.NDependMetricType);
            Type  nullableMetricType = typeof(Nullable <>).MakeGenericType(metricType);
            var   metricValue        = Activator.CreateInstance(nullableMetricType);
            IList metricValues       = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(nullableMetricType));

            foreach (var analysisResultRef in analysisResultRefsList)
            {
                ICodeBase           currentAnalysisResultCodeBase       = codeBaseManager.LoadCodeBase(analysisResultRef);
                CodeElementsManager currenAnalysisResultCodeBaseManager = new CodeElementsManager(currentAnalysisResultCodeBase);
                metricValue = null;

                switch (metricDefinition.NDependCodeElementType)
                {
                case "NDepend.CodeModel.IAssembly":
                    IAssembly selectedAssemblyFromCurrentAnalysisResultCodebase = currenAnalysisResultCodeBaseManager.GetAssemblyByName(codeElementName);
                    if (selectedAssemblyFromCurrentAnalysisResultCodebase != null)
                    {
                        metricValue = reflectionHelper.GetCodeElementMetric(
                            selectedAssemblyFromCurrentAnalysisResultCodebase,
                            typeof(IAssembly),
                            metricDefinition.InternalPropertyName,
                            metricDefinition.NDependMetricType);
                    }
                    break;

                case "NDepend.CodeModel.INamespace":
                    INamespace selectedNamespaceFromCurrentAnalysisResultCodebase = currenAnalysisResultCodeBaseManager.GetNamespaceByName(codeElementName);
                    if (selectedNamespaceFromCurrentAnalysisResultCodebase != null)
                    {
                        metricValue = reflectionHelper.GetCodeElementMetric(
                            selectedNamespaceFromCurrentAnalysisResultCodebase,
                            typeof(INamespace),
                            metricDefinition.InternalPropertyName,
                            metricDefinition.NDependMetricType);
                    }
                    break;

                case "NDepend.CodeModel.IType":
                    IType selectedTypeFromCurrentAnalysisResultCodebase = currenAnalysisResultCodeBaseManager.GetTypeByName(codeElementName);
                    if (selectedTypeFromCurrentAnalysisResultCodebase != null)
                    {
                        metricValue = reflectionHelper.GetCodeElementMetric(
                            selectedTypeFromCurrentAnalysisResultCodebase,
                            typeof(IType),
                            metricDefinition.InternalPropertyName,
                            metricDefinition.NDependMetricType);
                    }
                    break;

                case "NDepend.CodeModel.IMethod":
                    IMethod selectedMethodFromCurrentAnalysisResultCodebase = currenAnalysisResultCodeBaseManager.GetMethodByName(codeElementName);
                    if (selectedMethodFromCurrentAnalysisResultCodebase != null)
                    {
                        metricValue = (reflectionHelper.GetCodeElementMetric(
                                           selectedMethodFromCurrentAnalysisResultCodebase,
                                           typeof(IMethod),
                                           metricDefinition.InternalPropertyName,
                                           metricDefinition.NDependMetricType));
                    }
                    break;
                }
                metricValues.Add(metricValue);
            }
            return(metricValues);
        }
Esempio n. 25
0
 public object GetRendered(ICodeBase codeBase, DCBaseModel.e_ConvertType e_Convert)
 {
     return(DCBaseModel.GetValue(codeBase, this.Value, this.ValueType, e_Convert));
 }
        public override bool Execute(ICodeBase codeBase)
        {
            bool result = true;

            foreach (var item in this.Rows)
            {
                DCBaseModel.e_ConvertType e_FirstSideConvert = e_ConvertType.String;
                switch (item.FirstConditionType)
                {
                case e_ValueType.Variable:
                    e_FirstSideConvert = DCBaseModel.GetVariableConvertType(item.FirstConditionValue, codeBase.GetProcessID, codeBase.GetApplicationPageID, codeBase.GetUnitOfWork);
                    break;
                }
                object firstValue  = DCBaseModel.GetValue(codeBase, item.FirstConditionValue, item.FirstConditionType, e_FirstSideConvert);
                object SecondValue = DCBaseModel.GetValue(codeBase, item.SecondConditionValue, item.SecondConditionType, e_FirstSideConvert);

                switch (e_FirstSideConvert)
                {
                case e_ConvertType.String:
                    switch (item.OperationType)
                    {
                    case DCRowConditionModel.e_OperationType.Equal:
                        result = firstValue.ToStringObjNull() == SecondValue.ToStringObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.BiggerAndEqualThan:
                        result = (firstValue.ToStringObjNull() == SecondValue.ToStringObjNull()) || (firstValue != null && firstValue.ToStringObjNull().CompareTo(SecondValue.ToStringObjNull()) >= 0);
                        break;

                    case DCRowConditionModel.e_OperationType.LowerAndEqualThan:
                        result = firstValue == null || firstValue.ToStringObjNull().CompareTo(SecondValue.ToStringObjNull()) <= 0;
                        break;

                    case DCRowConditionModel.e_OperationType.BiggerThan:

                        result = firstValue != null && firstValue.ToStringObjNull().CompareTo(SecondValue.ToStringObjNull()) == 1;
                        break;

                    case DCRowConditionModel.e_OperationType.LowerThan:
                        result = (firstValue == null && SecondValue != null) || (firstValue != null && firstValue.ToStringObjNull().CompareTo(SecondValue.ToStringObjNull()) == -1);
                        break;

                    case DCRowConditionModel.e_OperationType.NotEqual:
                        result = firstValue.ToStringObjNull() != SecondValue.ToStringObjNull();
                        break;

                    default: break;
                    }
                    break;

                case e_ConvertType.Integer:
                    switch (item.OperationType)
                    {
                    case DCRowConditionModel.e_OperationType.Equal:
                        result = firstValue.ToIntObjNull() == SecondValue.ToIntObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.BiggerAndEqualThan:
                        result = firstValue.ToIntObjNull() >= SecondValue.ToIntObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.LowerAndEqualThan:
                        result = firstValue.ToIntObjNull() <= SecondValue.ToIntObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.BiggerThan:
                        result = firstValue.ToIntObjNull() > SecondValue.ToIntObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.LowerThan:
                        result = firstValue.ToIntObjNull() < SecondValue.ToIntObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.NotEqual:
                        result = firstValue.ToIntObjNull() != SecondValue.ToIntObjNull();
                        break;

                    default: break;
                    }
                    break;

                case e_ConvertType.Decimal:
                    switch (item.OperationType)
                    {
                    case DCRowConditionModel.e_OperationType.Equal:
                        result = firstValue.ToDecimalObjNull() == SecondValue.ToDecimalObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.BiggerAndEqualThan:
                        result = firstValue.ToDecimalObjNull() >= SecondValue.ToDecimalObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.LowerAndEqualThan:
                        result = firstValue.ToDecimalObjNull() <= SecondValue.ToDecimalObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.BiggerThan:
                        result = firstValue.ToDecimalObjNull() > SecondValue.ToDecimalObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.LowerThan:
                        result = firstValue.ToDecimalObjNull() < SecondValue.ToDecimalObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.NotEqual:
                        result = firstValue.ToDecimalObjNull() != SecondValue.ToDecimalObjNull();
                        break;

                    default: break;
                    }
                    break;

                case e_ConvertType.DateTime:
                    switch (item.OperationType)
                    {
                    case DCRowConditionModel.e_OperationType.Equal:
                        result = firstValue.ToDateTimeObjNull() == SecondValue.ToDateTimeObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.BiggerAndEqualThan:
                        result = firstValue.ToDateTimeObjNull() >= SecondValue.ToDateTimeObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.LowerAndEqualThan:
                        result = firstValue.ToDateTimeObjNull() <= SecondValue.ToDateTimeObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.BiggerThan:
                        result = firstValue.ToDateTimeObjNull() > SecondValue.ToDateTimeObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.LowerThan:
                        result = firstValue.ToDateTimeObjNull() < SecondValue.ToDateTimeObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.NotEqual:
                        result = firstValue.ToDateTimeObjNull() != SecondValue.ToDateTimeObjNull();
                        break;

                    default: break;
                    }
                    break;

                case e_ConvertType.Boolean:
                    switch (item.OperationType)
                    {
                    case DCRowConditionModel.e_OperationType.Equal:
                        result = firstValue.ToBoolObjNull() == SecondValue.ToBoolObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.NotEqual:
                        result = firstValue.ToBoolObjNull() != SecondValue.ToBoolObjNull();
                        break;

                    default: result = false; break;
                    }
                    break;

                case e_ConvertType.Uniqueidentifier:
                    switch (item.OperationType)
                    {
                    case DCRowConditionModel.e_OperationType.Equal:
                        result = firstValue.ToGuidObjNull() == SecondValue.ToGuidObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.NotEqual:
                        result = firstValue.ToGuidObjNull() != SecondValue.ToGuidObjNull();
                        break;

                    default: result = false; break;
                    }
                    break;

                case e_ConvertType.Long:
                    switch (item.OperationType)
                    {
                    case DCRowConditionModel.e_OperationType.Equal:
                        result = firstValue.ToLongObjNull() == SecondValue.ToLongObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.BiggerAndEqualThan:
                        result = firstValue.ToLongObjNull() >= SecondValue.ToLongObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.LowerAndEqualThan:
                        result = firstValue.ToLongObjNull() <= SecondValue.ToLongObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.BiggerThan:
                        result = firstValue.ToLongObjNull() > SecondValue.ToLongObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.LowerThan:
                        result = firstValue.ToLongObjNull() < SecondValue.ToLongObjNull();
                        break;

                    case DCRowConditionModel.e_OperationType.NotEqual:
                        result = firstValue.ToLongObjNull() != SecondValue.ToLongObjNull();
                        break;

                    default: break;
                    }
                    break;
                }
                if (this.EvaluateType == e_EvaluateType.And && !result)
                {
                    break;
                }
                if (this.EvaluateType == e_EvaluateType.Or && result)
                {
                    break;
                }
            }
            return(result);
        }
Esempio n. 27
0
    public void InitFunc()
    {
        FunctionCall func = new FunctionCall();

        NodeFuncData         funcNodeData    = this.funcNodeData as NodeFuncData;
        Type                 methodClassType = NodeGUIUtility.GetType(funcNodeData.funcClassType);
        List <NodePointData> parameterPoint  = GetPointData(ConnectionPointType.Parameter);

        List <Type> methodParameters = new List <Type>();

        foreach (var point in funcNodeData.parameters)
        {
            methodParameters.Add(NodeGUIUtility.GetType(point));
        }

        MethodBase method;

        if (funcNodeData.nodeType == NodeType.Constructor)
        {
            method = methodClassType.GetConstructor(methodParameters.ToArray());

            KeywordCode keyCode = new KeywordCode()
            {
                keyword = new Variable()
                {
                    Var = "new"
                },
                code = new Variable()
                {
                    Var = funcNodeData.funcClassType
                }
            };

            foreach (var param in parameterPoint)
            {
                AddMapping(param.GUID, (c) => ((ParameterBlock)((FunctionCall)code).Parameter).Parameters.Add(c));
            }

            func.Access    = keyCode;
            func.Parameter = new ParameterBlock();

            code = func;
        }
        else if (funcNodeData.nodeType == NodeType.Property)
        {
            method = methodParameters.Count != 0 ?
                     methodClassType.GetMethod(funcNodeData.methodName, methodParameters.ToArray()) :
                     methodClassType.GetMethod(funcNodeData.methodName);

            AccessCode access = new AccessCode();

            if (method.IsStatic)
            {
                access.ownerObject = new Variable()
                {
                    Var = methodClassType.Name
                };
                func.Access = access;
            }
            else
            {
                NodePointData ownerPoint = parameterPoint.Find((p) => p.parameterType == funcNodeData.funcClassType);
                AddMapping(ownerPoint.GUID, (c) =>
                {
                    if (code is OperatorBlock)
                    {
                        ((AccessCode)((OperatorBlock)code).A).ownerObject = c;
                    }
                    else
                    {
                        ((AccessCode)code).ownerObject = c;
                    }
                });
                parameterPoint.Remove(ownerPoint);
            }

            foreach (var param in parameterPoint)
            {
                AddMapping(param.GUID, (c) =>
                {
                    OperatorBlock oper = new OperatorBlock();
                    oper.Operator      = "=";
                    oper.A             = code;
                    oper.B             = c;
                    code = oper;
                });
            }

            access.member = new Variable()
            {
                Var = method.Name.Split('_')[1]
            };
            code = access;
        }
        else
        {
            method = methodParameters.Count != 0 ?
                     methodClassType.GetMethod(funcNodeData.methodName, methodParameters.ToArray()) :
                     methodClassType.GetMethod(funcNodeData.methodName);

            AccessCode access = new AccessCode();

            if (method.IsStatic)
            {
                access.ownerObject = new Variable()
                {
                    Var = methodClassType.Name
                };
                func.Access = access;
            }
            else
            {
                NodePointData ownerPoint = parameterPoint.Find((p) => p.parameterType == funcNodeData.funcClassType);
                AddMapping(ownerPoint.GUID, (c) => ((AccessCode)((FunctionCall)code).Access).ownerObject = c);
                parameterPoint.Remove(ownerPoint);
            }

            foreach (var param in parameterPoint)
            {
                AddMapping(param.GUID, (c) => ((ParameterBlock)((FunctionCall)code).Parameter).Parameters.Add(c));
            }

            access.member = new Variable()
            {
                Var = method.Name
            };
            func.Access    = access;
            func.Parameter = new ParameterBlock();

            code = func;
        }
    }
Esempio n. 28
0
        private object GetParameterCode(ICodeBase codeBase, DCMethodParaetersModel paraetersModel)
        {
            e_ConvertType e_Convert = e_ConvertType.String;
            string        pn        = paraetersModel.ParameterName;

            switch (this.MethodGroupType)
            {
            case e_MethodGroupType.User:
                switch (this.MethodID)
                {
                case nameof(IUserCodeHelper.CreateBpmsUser):
                    e_Convert = this.ConvertStrToType("userName:String,firstName:String,LastName:String,email:String,mobile:String,telePhone:String".Split(',').FirstOrDefault(c => c.Split(':')[0] == pn).Split(':')[1]);
                    break;

                case nameof(IUserCodeHelper.CreateSiteUser):
                    e_Convert = this.ConvertStrToType("userName:String,firstName:String,LastName:String,email:String,password:String,doLogin:Boolean,createBpms:Boolean".Split(',').FirstOrDefault(c => c.Split(':')[0] == pn).Split(':')[1]);
                    break;

                case nameof(IUserCodeHelper.GetUserPropertyByID):
                    e_Convert = this.ConvertStrToType("id:Guid,propertyName:String".Split(',').FirstOrDefault(c => c.Split(':')[0] == pn).Split(':')[1]);
                    break;

                case nameof(IUserCodeHelper.GetUserPropertyByUserName):
                    e_Convert = this.ConvertStrToType("userName:String,propertyName:String".Split(',').FirstOrDefault(c => c.Split(':')[0] == pn).Split(':')[1]);
                    break;
                }
                break;

            case e_MethodGroupType.Message:
                switch (this.MethodID)
                {
                case nameof(IMessageCodeHelper.AddError):
                    e_Convert = this.ConvertStrToType("message:String".Split(',').FirstOrDefault(c => c.Split(':')[0] == pn).Split(':')[1]);
                    break;

                case nameof(IMessageCodeHelper.AddInfo):
                    e_Convert = this.ConvertStrToType("message:String".Split(',').FirstOrDefault(c => c.Split(':')[0] == pn).Split(':')[1]);
                    break;

                case nameof(IMessageCodeHelper.AddSuccess):
                    e_Convert = this.ConvertStrToType("message:String".Split(',').FirstOrDefault(c => c.Split(':')[0] == pn).Split(':')[1]);
                    break;

                case nameof(IMessageCodeHelper.AddWarning):
                    e_Convert = this.ConvertStrToType("message:String".Split(',').FirstOrDefault(c => c.Split(':')[0] == pn).Split(':')[1]);
                    break;
                }
                break;

            case e_MethodGroupType.Url:
                switch (this.MethodID)
                {
                case "RedirectUrl":
                    e_Convert = this.ConvertStrToType("url:String".Split(',').FirstOrDefault(c => c.Split(':')[0] == pn).Split(':')[1]);
                    break;

                case "RedirectForm":
                    e_Convert = this.ConvertStrToType("applicationPageId:Guid".Split(',').FirstOrDefault(c => c.Split(':')[0] == pn).Split(':')[1]);
                    break;
                }
                break;

            case e_MethodGroupType.AccessRule:
                switch (this.MethodID)
                {
                case "GetDepartmentHierarchyByUserId":
                    e_Convert = this.ConvertStrToType("userID:Guid,roleCode:Integer,goUpDepartment:Boolean".Split(',').FirstOrDefault(c => c.Split(':')[0] == pn).Split(':')[1]);
                    break;

                case "GetUserID":
                    e_Convert = this.ConvertStrToType("departmentID:Guid,roleCode:Integer".Split(',').FirstOrDefault(c => c.Split(':')[0] == pn).Split(':')[1]);
                    break;

                case "GetRoleCode":
                    e_Convert = this.ConvertStrToType("userID:Guid,departmentID:Guid".Split(',').FirstOrDefault(c => c.Split(':')[0] == pn).Split(':')[1]);
                    break;

                case "GetRoleCodeList":
                    e_Convert = this.ConvertStrToType("userID:Guid,departmentID:Guid".Split(',').FirstOrDefault(c => c.Split(':')[0] == pn).Split(':')[1]);
                    break;

                case "AddRoleToUser":
                    e_Convert = this.ConvertStrToType("userID:Guid,departmentID:Guid,roleCode:Integer".Split(',').FirstOrDefault(c => c.Split(':')[0] == pn).Split(':')[1]);
                    break;

                case "RemoveRoleFromUser":
                    e_Convert = this.ConvertStrToType("userID:Guid,departmentID:Guid,roleCode:Integer".Split(',').FirstOrDefault(c => c.Split(':')[0] == pn).Split(':')[1]);
                    break;
                }
                break;
            }
            return(paraetersModel.GetRendered(codeBase, e_Convert));
        }
        internal static List <SuspectSet> Go(ICodeBase codeBase, int N)
        {
            Debug.Assert(codeBase != null);

            var suspectSetsCallerPair = new List <SuspectSet>();

            // Some methods are oo common, they could provoque a bias in result, hence we don't take account of them.
            var methodsCalledsTooCommon = codeBase.Methods.Where(IsTooCommonMethod);

            // Exclude some generated methods, that typically contains duplicated or very similar code.
            var methodsCallersExcluded = GetExcludedMethod(codeBase);

            // This hashset is used to keep track of methods called already treated.
            var calledsAlreadyTreated = new HashSet <IMethod>(methodsCalledsTooCommon);

            // This hashset is used to keep track of pairs of callers already treated.
            var pairsOfCallersAlreadyTreated = new HashSet <PairOfMethodCallers>();

            //
            // for each methods called, try to find pairs amongst its callers calling at least N same methods!
            //
            foreach (var called in codeBase.Methods.Except(methodsCalledsTooCommon))
            {
                var callers = called.MethodsCallingMe;
                Debug.Assert(callers != null);
                if (callers.Count() < 2)
                {
                    continue;
                }                                   // At least 2 callers to get an intersection


                // Compute list of callers and the methods they call (except methods called already treated)
                var callersSuspect = (from caller in callers
                                      where !methodsCallersExcluded.Contains(caller)
                                      let methodsCalled = caller.MethodsCalled
                                                          where methodsCalled.Count() >= N
                                                          // Need to call ToArray() to avoid differed query execution. Else calledsAlreadyTreated being modified later could make differed query execution problems!!
                                                          let methodsCalledExceptThoseAlreadyTreated = methodsCalled.Except(calledsAlreadyTreated).ToArray()
                                                                                                       let fieldsRead = caller.FieldsReadButNotAssigned.Where(f => !f.IsGeneratedByCompiler).ToArray()
                                                                                                                        let fieldsAssigned = caller.FieldsAssigned.Where(f => !f.IsGeneratedByCompiler).ToArray()
                                                                                                                                             // Condition for a caller to become suspect: At least N methods called, fields read, fields assigned
                                                                                                                                             where methodsCalledExceptThoseAlreadyTreated.Length + fieldsRead.Count() + fieldsAssigned.Count() >= N
                                                                                                                                             select new CallerAndMembersUsed(caller, methodsCalledExceptThoseAlreadyTreated, fieldsRead, fieldsAssigned)).ToArray();

                // Now we can add called to calledsAlreadyTreated!
                calledsAlreadyTreated.Add(called);

                // Needs at least 2 callers methods to get one or several suspect sets with 2 callers.
                if (callersSuspect.Length < 2)
                {
                    continue;
                }

                //
                // Compute pair of callers calling at least N same methods!
                //
                var suspectSetsWith2Callers = FindCallersCallingAtLeastNSameMethods(callersSuspect, pairsOfCallersAlreadyTreated, N);

                suspectSetsCallerPair.AddRange(suspectSetsWith2Callers);
            } // end foreach method called


            return(suspectSetsCallerPair);
        }
Esempio n. 30
0
 public CodeBlock(ICodeBase condition, List <ICodeBase> commandLines)
 {
     Condition    = condition;
     CommandLines = commandLines;
 }
Esempio n. 31
0
        public static void Handle(string outputDirectory, string outputFileName, ICodeBase codeBase, ILogger logger)
        {
            HandleStructuralRelations(codeBase, outputDirectory, outputFileName, logger);

            HandleDesignSmells(codeBase, outputDirectory, outputFileName, logger);
        }
 public virtual bool Execute(ICodeBase codeBase)
 {
     return(true);
 }
 public UserDefinedMetrics(ICodeBase codeBaseToStudy)
 {
     this.codeBaseToStudy = codeBaseToStudy;
     codeElementsManager  = new CodeElementsManager(codeBaseToStudy);
 }
Esempio n. 34
0
 public CodeElementsManager(ICodeBase codeBase)
 {
     this.codeBase = codeBase;
 }
Esempio n. 35
0
 private object GetParameterCode(ICodeBase codeBase, DCRowWebServiceParameterModel paraetersModel)
 {
     return(paraetersModel.GetRendered(codeBase, e_ConvertType.String));
 }
Esempio n. 36
0
        static void MainSub()
        {
            //AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolverHelper.AssemblyResolveHandler;

            //var projectFilePath = NDEPEND_PROJECT_FILE_PATH.ToAbsoluteFilePath();
            //Console.WriteLine("*** Load NDepend Project from {" + projectFilePath.ToString() + @"}***");

            // 0) Creates a NDependServicesProvider object
            var ndependServicesProvider = new NDependServicesProvider();


            // 1) obtain some VS solution or project file path
            var visualStudioManager = ndependServicesProvider.VisualStudioManager;
            ICollection <IAbsoluteFilePath> vsSlnOrProjFilePaths;
            IntPtr ownerWindowHandle = Process.GetCurrentProcess().MainWindowHandle; // get a non IntPtr.Zero owner Window Handle. If you are in a System.Console try this

            visualStudioManager.ShowDialogSelectVisualStudioSolutionsOrProjects(ownerWindowHandle, out vsSlnOrProjFilePaths);
            // Could also use:  visualStudioManager.GetMostRecentlyUsedVisualStudioSolutionOrProject() can also be used


            // 2) obtains assemblies file path to analyze
            var assembliesFilePath = (from vsSlnOrProjFilePath in vsSlnOrProjFilePaths
                                      from assembliesFilePathTmp in visualStudioManager.GetAssembliesFromVisualStudioSolutionOrProject(vsSlnOrProjFilePath)
                                      select assembliesFilePathTmp).Distinct().ToArray();

            // 3) gets or create a IProject object
            var projectManager = ndependServicesProvider.ProjectManager;
            //var path = NDepend.Path.PathHelpers.ToAbsoluteFilePath(@"C:\projetos\estudoipt\dapperdotnet\dapper-dot-net\");
            //IProject project = projectManager.CreateBlankProject(assembliesFilePath.FirstOrDefault(), "metricsproject");
            IProject project = projectManager.CreateTemporaryProject(assembliesFilePath, TemporaryProjectMode.Temporary);
            // Or, to get a IProject object, could also use
            //   projectManager.CreateBlankProject()  to create a persisten project
            //   and then project.CodeToAnalyze.SetApplicationAssemblies()
            //   and then projectManager.SaveProject(project); o save the project file
            //
            // Or, to get an existing IProject object, could also use
            //    projectManager.ShowDialogChooseAnExistingProject(out project)
            // Or programmatically list most recently used NDepend projects on this machine through
            //    projectManager.GetMostRecentlyUsedProjects()


            // 4) gets an IAnalysisResult object from the IProject object
            IAnalysisResult analysisResult = project.RunAnalysis();  // *** This particular method works only with a Build Machine license ***
                                                                     //  Or  project.RunAnalysisAndBuildReport()  // *** This particular method works only with a Build Machine license ***

            // Or, to get a IAnalysisResult object, first gets a IAnalysisResultRef object, that represents a reference to a persisted IAnalysisResult object
            //    project.TryGetMostRecentAnalysisResultRef() or project.GetAvailableAnalysisResultsRefs() or project.GetAvailableAnalysisResultsRefsGroupedPerMonth()
            // and then analysisResultRef.Load()


            // 5) gets a ICodeBase object from the IAnalysisResult object
            ICodeBase codeBase = analysisResult.CodeBase;

            // Or eventually a ICompareContext object if you wish to analyze diff
            // codeBase.CreateCompareContextWithOlder(olderCodeBase)


            Calculator.ICalculate calc = new Calculator.NumberOfChildren();
            var result = calc.Calculate(codeBase);

            IMetricPrinter m = new ExcelPrinter();

            m.Print("NumberOfChildren", result);

            calc   = new Calculator.CouplingBetweenObjectClasses();
            result = calc.Calculate(codeBase);

            m = new ExcelPrinter();
            m.Print("CouplingBetweenObject", result);

            calc   = new Calculator.DepthOfInheritanceTree();
            result = calc.Calculate(codeBase);

            m = new ExcelPrinter();
            m.Print("DepthOfInheritanceTree", result);

            calc   = new Calculator.LackOfCohesionInMethods();
            result = calc.Calculate(codeBase);

            m = new ExcelPrinter();
            m.Print("LackOfCohesionInMethods", result);

            calc   = new Calculator.ResponseForAClass();
            result = calc.Calculate(codeBase);

            m = new ExcelPrinter();
            m.Print("ResponseForAClass", result);

            calc   = new Calculator.WeightedMethodsPerClass();
            result = calc.Calculate(codeBase);

            m = new ExcelPrinter();
            m.Print("WeightedMethodsPerClass", result);
            // 6) use the code model API to query code and do develop any algorithm you need!
            // For example here we are looking for complex methods

            /*var complexMethods = (from m in codeBase.Application.Methods
             *                    where m.ILCyclomaticComplexity > 1
             *                    orderby m.ILCyclomaticComplexity descending
             *                    select m).ToArray();
             * if (complexMethods.Length == 0) { return; }
             * Console.WriteLine("Press a key to show the " + complexMethods.Length + " most complex methods");
             * Console.ReadKey();
             * foreach (var m in complexMethods)
             * {
             *  Console.WriteLine(m.FullName + " has a IL cyclomatic complexity of " + m.ILCyclomaticComplexity);
             * }
             *
             *
             * // 7) eventually lets the user opens source file declaration
             * if (complexMethods.First().SourceFileDeclAvailable)
             * {
             *  var mostComplexMethod = complexMethods.First();
             *  Console.WriteLine("Press a key to open the source code decl of the most complex method?");
             *  Console.ReadKey();
             *  mostComplexMethod.TryOpenSource();
             *  // Eventually use ExtensionMethodsTooling.TryCompareSourceWith(NDepend.CodeModel.ISourceFileLine,NDepend.CodeModel.ISourceFileLine)
             *  // to compare 2 different versions of a code element
             * }*/
        }
Esempio n. 37
0
        public override bool Execute(ICodeBase codeBase)
        {
            object result = null;

            switch (this.MethodGroupType)
            {
            case e_MethodGroupType.User:
                switch (this.MethodID)
                {
                case nameof(IUserCodeHelper.CreateBpmsUser):
                    codeBase.UserHelper.CreateBpmsUser(this.GetParameterCode(codeBase, this.Rows[0]).ToStringObj(), this.GetParameterCode(codeBase, this.Rows[1]).ToStringObj(), this.GetParameterCode(codeBase, this.Rows[2]).ToStringObj(), this.GetParameterCode(codeBase, this.Rows[3]).ToStringObj(), this.GetParameterCode(codeBase, this.Rows[4]).ToStringObj(), this.GetParameterCode(codeBase, this.Rows[5]).ToStringObj());
                    break;

                case nameof(IUserCodeHelper.CreateSiteUser):
                    codeBase.UserHelper.CreateSiteUser(this.GetParameterCode(codeBase, this.Rows[0]).ToStringObj(), this.GetParameterCode(codeBase, this.Rows[1]).ToStringObj(), this.GetParameterCode(codeBase, this.Rows[2]).ToStringObj(), this.GetParameterCode(codeBase, this.Rows[3]).ToStringObj(), this.GetParameterCode(codeBase, this.Rows[4]).ToStringObj(), this.GetParameterCode(codeBase, this.Rows[5]).ToBoolObj(), this.GetParameterCode(codeBase, this.Rows[6]).ToBoolObj());
                    break;

                case nameof(IUserCodeHelper.GetUserPropertyByID):
                    codeBase.UserHelper.GetUserPropertyByID(this.GetParameterCode(codeBase, this.Rows[0]).ToGuidObj(), this.GetParameterCode(codeBase, this.Rows[1]).ToStringObj());
                    break;

                case nameof(IUserCodeHelper.GetUserPropertyByUserName):
                    codeBase.UserHelper.GetUserPropertyByUserName(this.GetParameterCode(codeBase, this.Rows[0]).ToStringObj(), this.GetParameterCode(codeBase, this.Rows[1]).ToStringObj());
                    break;
                }
                break;

            case e_MethodGroupType.Message:
                switch (this.MethodID)
                {
                case nameof(IMessageCodeHelper.AddError):
                    codeBase.MessageHelper.AddError(this.GetParameterCode(codeBase, this.Rows[0]).ToStringObj());
                    break;

                case nameof(IMessageCodeHelper.AddInfo):
                    codeBase.MessageHelper.AddInfo(this.GetParameterCode(codeBase, this.Rows[0]).ToStringObj());
                    break;

                case nameof(IMessageCodeHelper.AddSuccess):
                    codeBase.MessageHelper.AddSuccess(this.GetParameterCode(codeBase, this.Rows[0]).ToStringObj());
                    break;

                case nameof(IMessageCodeHelper.AddWarning):
                    codeBase.MessageHelper.AddWarning(this.GetParameterCode(codeBase, this.Rows[0]).ToStringObj());
                    break;
                }
                break;

            case e_MethodGroupType.Url:
                switch (this.MethodID)
                {
                case nameof(IUrlCodeHelper.RedirectUrl):
                    codeBase.UrlHelper.RedirectUrl(this.GetParameterCode(codeBase, this.Rows[0]).ToStringObj());
                    break;

                case nameof(IUrlCodeHelper.RedirectForm):
                    codeBase.UrlHelper.RedirectForm(this.GetParameterCode(codeBase, this.Rows[0]).ToStringObj());
                    break;
                }
                break;

            case e_MethodGroupType.AccessRule:
                switch (this.MethodID)
                {
                case nameof(IAccessCodeHelper.GetDepartmentHierarchyByUserId):
                    codeBase.AccessHelper.GetDepartmentHierarchyByUserId(this.GetParameterCode(codeBase, this.Rows[0]).ToGuidObj(), this.GetParameterCode(codeBase, this.Rows[1]).ToIntObj(), this.GetParameterCode(codeBase, this.Rows[2]).ToBoolObj());
                    break;

                case nameof(IAccessCodeHelper.GetUserID):
                    codeBase.AccessHelper.GetUserID(this.GetParameterCode(codeBase, this.Rows[0]).ToGuidObj(), this.GetParameterCode(codeBase, this.Rows[1]).ToIntObj());
                    break;

                case nameof(IAccessCodeHelper.GetRoleCode):
                    codeBase.AccessHelper.GetRoleCode(this.GetParameterCode(codeBase, this.Rows[0]).ToGuidObj(), this.GetParameterCode(codeBase, this.Rows[1]).ToGuidObj());
                    break;

                case nameof(IAccessCodeHelper.GetRoleCodeList):
                    codeBase.AccessHelper.GetRoleCodeList(this.GetParameterCode(codeBase, this.Rows[0]).ToGuidObj(), this.GetParameterCode(codeBase, this.Rows[1]).ToGuidObj());
                    break;

                case nameof(IAccessCodeHelper.AddRoleToUser):
                    codeBase.AccessHelper.AddRoleToUser(this.GetParameterCode(codeBase, this.Rows[0]).ToGuidObj(), this.GetParameterCode(codeBase, this.Rows[1]).ToGuidObj(), this.GetParameterCode(codeBase, this.Rows[2]).ToIntObj());
                    break;

                case nameof(IAccessCodeHelper.RemoveRoleFromUser):
                    codeBase.AccessHelper.RemoveRoleFromUser(this.GetParameterCode(codeBase, this.Rows[0]).ToGuidObj(), this.GetParameterCode(codeBase, this.Rows[1]).ToGuidObj(), this.GetParameterCode(codeBase, this.Rows[2]).ToIntObj());
                    break;
                }
                break;
            }
            if (!string.IsNullOrWhiteSpace(this.RetVariableName))
            {
                codeBase.VariableHelper.Set(this.RetVariableName, result);
            }
            return(true);
        }