Esempio n. 1
0
        private EventDefinition FindEvent(MethodDefinition eventMethod, TypeDefinition type)
        {
            if (type == null)
            {
                throw new Exception("Can't find event named \"" + GetNameOfPropertyOrEvent(eventMethod.Name) + "\" in null type");
            }

            foreach (EventDefinition @event in type.Events)
            {
                if (@event.AddMethod == eventMethod || @event.RemoveMethod == eventMethod)
                {
                    return(@event);
                }
            }
            string eventName = "";

            if (AnalysisUtils.IsMethodExplicitlyImplemented(eventMethod))
            {
                eventName += eventMethod.Name.Substring(0, eventMethod.Name.LastIndexOf('.') + 1);
            }
            eventName += GetNameOfPropertyOrEvent(eventMethod.Name);
            EventDefinition newEvent = new EventDefinition(eventName, EventAttributes.None, eventMethod.Parameters[0].ParameterType);

            if (eventMethod.Name.Contains("add_"))
            {
                newEvent.AddMethod    = eventMethod;
                newEvent.RemoveMethod = GetSecondMethodOfPropertyOrEvent(eventMethod, type);
            }
            else
            {
                newEvent.AddMethod    = GetSecondMethodOfPropertyOrEvent(eventMethod, type);
                newEvent.RemoveMethod = eventMethod;
            }
            return(newEvent);
        }
Esempio n. 2
0
        /// <summary>
        /// Check if the method is an acual method, or a member of a property or event.
        /// </summary>
        /// <param name="method"></param>
        /// <returns></returns>
        private MethodType IsMethodOrPropertyOrEvent(MethodDefinition method)
        {
            string methodName;

            if (AnalysisUtils.IsMethodExplicitlyImplemented(method))
            {
                methodName = method.Name.Substring(method.Name.LastIndexOf('.') + 1);
            }
            else
            {
                methodName = method.Name;
            }
            if (methodName.StartsWith("get_") || methodName.StartsWith("set_"))
            {
                return(MethodType.PROPERTY);
            }
            else if (methodName.StartsWith("add_") || methodName.StartsWith("remove_"))
            {
                return(MethodType.EVENT);
            }
            else
            {
                return(MethodType.METHOD);
            }
        }
Esempio n. 3
0
        /// <summary>
        /// 获取导套
        /// </summary>
        /// <param name="cylinder"></param>
        /// <returns></returns>
        public List <AbstractCylinderBody> GetGuideBushing(List <AbstractCylinderBody> cylinder)
        {
            List <AbstractCylinderBody> bush = new List <AbstractCylinderBody>();

            foreach (AbstractCylinderBody ab in cylinder)
            {
                if (ab.Radius >= 6)
                {
                    Vector3d vec1   = ab.Direction;
                    Vector3d vec2   = new Vector3d(-vec1.X, -vec1.Y, -vec1.Z);
                    int      count1 = TraceARay.AskTraceARay(this.Body, ab.StratPt, vec1);
                    int      count2 = TraceARay.AskTraceARay(this.Body, ab.StratPt, vec2);
                    if (count1 == 0 && count2 == 0)
                    {
                        List <Body> bodys = new List <Body>();
                        NXOpen.GeometricAnalysis.SimpleInterference.Result res = AnalysisUtils.SetInterferenceOutResult(this.Body, ab.Body, out bodys);
                        if (res == NXOpen.GeometricAnalysis.SimpleInterference.Result.OnlyEdgesOrFacesInterfere && bodys.Count == 0)
                        {
                            if (ab is CylinderBody)
                            {
                                ab.Name = "直司";
                            }
                            else
                            {
                                ab.Name = "托司";
                            }
                            bush.Add(ab);
                            continue;
                        }
                    }
                }
            }
            return(bush);
        }
Esempio n. 4
0
        private List <string> EleInterference(string Pich)
        {
            List <string> info    = new List <string>();
            Body          eleBody = GetOccsInBods(this.eleModel.PartTag)[0];

            foreach (Part work in this.workpiecePart)
            {
                List <Body> bodys         = new List <Body>();
                Body        workpieceBody = GetOccsInBods(work)[0];
                NXOpen.GeometricAnalysis.SimpleInterference.Result re = AnalysisUtils.SetInterferenceOutResult(eleBody, workpieceBody, out bodys);
                if (re == NXOpen.GeometricAnalysis.SimpleInterference.Result.NoInterference)
                {
                    info.Add(this.eleModel.AssembleName + "                     " + work.Name + Pich + "没有干涉!");
                }
                if (re == NXOpen.GeometricAnalysis.SimpleInterference.Result.InterferenceExists)
                {
                    info.Add(this.eleModel.AssembleName + "                     " + work.Name + Pich + "有干涉!");
                }
                if (bodys.Count > 0)
                {
                    foreach (Body body in bodys)
                    {
                        body.Layer = 252;
                    }
                }
            }
            return(info);
        }
Esempio n. 5
0
        /// <summary>
        /// Try to generate a value for a given type that is not null (by calling the constructor).
        /// It returns null only if we can't find a constructor to call or a know value to return
        /// (like 0 for an int, string.Empty for a string ...).
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public string GenerateDefaultValue(TypeReference type, bool isRecursiveCall = false)
        {
            MethodDefinition constructorIfAny;

            if (TryGetConstructor(type, out constructorIfAny))
            {
                string res          = "new " + AnalysisUtils.GetFullTypeName(type, Configuration.TypesThatNeedToBeRenamed, Configuration.TypesThatNeedFullName, _outputOptions.OutputFullTypeName) + "(";
                bool   isFirstParam = true;
                foreach (ParameterDefinition param in constructorIfAny.Parameters)
                {
                    if (!isFirstParam)
                    {
                        res += ", ";
                    }
                    else
                    {
                        isFirstParam = false;
                    }
                    res += GenerateDefaultValue(param.ParameterType, true);
                }
                res += ")";
                return(res);
            }
            else
            {
                return(AnalysisUtils.GetSafeTypeReferenceDefaultValueAsString(type, _outputOptions.OutputFullTypeName));
            }
        }
        public void refreshSmartTraceTreeView()
        {
            tvSmartTrace.Nodes.Clear();
            if (tvSmartTrace.Tag == null)
            {
                return;
            }
            var fviFindingViewItem = (FindingViewItem)tvSmartTrace.Tag;

            if (fviFindingViewItem.fFinding.Trace != null)
            {
                //String sNodeText = fviFindingViewItem.fFinding.caller_name;
                String sNodeText = "O2 Trace";
                //(fviFindingViewItem.fFinding.caller_name != null) ? fviFindingViewItem.fFinding.caller_name : o2.analysis.Analysis.getStringIndexValue(UInt32.Parse(fviFindingViewItem.fFinding.caller_name_id), fviFindingViewItem.oadO2AssessmentDataOunceV6);
                var tnRootNode = new TreeNode(sNodeText);
                tnRootNode.Tag = fviFindingViewItem.fFinding;
                AnalysisUtils.addCallsToNode_Recursive(fviFindingViewItem.fFinding.Trace, tnRootNode,
                                                       fviFindingViewItem.oadO2AssessmentDataOunceV6, stfSmartTraceFilter);
                tvSmartTrace.Nodes.Add(tnRootNode.Nodes[0]);
                tvSmartTrace.ExpandAll();
                if (ascx_SelectVisiblePanels1.getCheckBox(4).Checked)
                {
                    ascx_Glee1.setAssessmentData(fviFindingViewItem.oadO2AssessmentDataOunceV6);
                    ascx_Glee1.addTreeNodeToComboxWithNodesToPlot(tvSmartTrace.Nodes[0], fviFindingViewItem.fFinding,
                                                                  fviFindingViewItem.oadO2AssessmentDataOunceV6);
                    //   the way the Smart traces are build we want to add the 2nd child
                    ascx_Glee1.showLoadedTracesInGleeViewer();
                }
            }

            ascx_SourceCodeEditor1.gotoLine(
                fviFindingViewItem.oadO2AssessmentDataOunceV6.dFindings[fviFindingViewItem.fFinding].filename,
                (Int32)fviFindingViewItem.fFinding.line_number);
        }
Esempio n. 7
0
        /// <summary>
        /// 干涉面
        /// </summary>
        public void GetInterferenceOfFace()
        {
            List <Tag>  outFace       = new List <Tag>();
            Body        eleBody       = GetOccsInBods(this.eleModel.PartTag)[0];
            Body        workpieceBody = GetOccsInBods(this.workpiece)[0];
            List <Face> faces         = AnalysisUtils.SetInterferenceOutFace(eleBody, workpieceBody);

            for (int i = 0; i < (faces.Count) / 2 - 1; i++)
            {
                FaceData data1 = FaceUtils.AskFaceData(faces[i * 2]);
                FaceData data2 = FaceUtils.AskFaceData(faces[i * 2 + 1]);
                if (data1.Equals(data2))
                {
                    Tag face3;
                    NXOpen.Features.Feature feat1 = AssmbliesUtils.WaveFace(faces[i * 2]);
                    NXOpen.Features.Feature feat2 = AssmbliesUtils.WaveFace(faces[i * 2 + 1]);
                    Body[] bodys1 = (feat1 as NXOpen.Features.BodyFeature).GetBodies();
                    Body[] bodys2 = (feat2 as NXOpen.Features.BodyFeature).GetBodies();

                    Tag bodyTag1 = Intersect(bodys1[0], bodys2[0]);
                    if (bodyTag1 != Tag.Null)
                    {
                        outFace.Add(bodyTag1);
                    }
                }
            }
            SewSolidBody(outFace);
        }
Esempio n. 8
0
        /// <summary>
        /// Check if parent type if abstract and get abstract methods that would have not been implemented if it is the case
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private HashSet <string> GetAbstractMethodsThatWouldntBeImlemented(TypeDefinition type)
        {
            HashSet <string> res = new HashSet <string>();

            if (type.BaseType != null)
            {
                AddUsing(type.BaseType.Namespace);
                TypeDefinition baseType = AnalysisUtils.GetTypeDefinitionFromTypeReference(type.BaseType, _modules);
                if (baseType != null)
                {
                    if (baseType.IsAbstract)
                    {
                        if (baseType.HasMethods)
                        {
                            foreach (MethodDefinition method in baseType.Methods)
                            {
                                if (AnalysisUtils.IsMethodAbstract(method))
                                {
                                    if (MethodAnalyzer.IsMethodUnsupported(method) ||
                                        analyzeHelpher._coreSupportedMethods.Contains(baseType.Namespace, baseType.Name, method.Name) ||
                                        analyzeHelpher.IsMethodSupported(method))
                                    {
                                        res.Add(method.Name);
                                    }
                                }
                            }
                        }
                        res.UnionWith(GetAbstractMethodsThatWouldntBeImlemented(baseType));
                    }
                }
            }
            return(res);
        }
Esempio n. 9
0
 /// <summary>
 /// Analyze the current type and save the type generated from it.
 /// </summary>
 public void Execute()
 {
     if (AnalysisUtils.IsTypeADelegate(Element))
     {
         GetUsingsForDelegate(Element);
     }
     else if (!Element.IsEnum)
     {
         AnalyzeParentAndInterfacesType(Element);
         if (Element.HasMethods)
         {
             AddConstructorToUnsupportedMethod();
             HashSet <string> methodsFromInterfaces = GetMethodsInheritedFromInterfaces(Element);
             _unsupportedMethodsInCurrentType.UnionWith(methodsFromInterfaces);
             UpdateUnsupportedMethodsInfo(methodsFromInterfaces);
             _unsupportedMethodsInCurrentType.UnionWith(GetAbstractMethodsThatWouldntBeImlemented(Element));
             GetCustomAttributes(_unsupportedMethodsInCurrentType);
             MethodAnalyzer.SetForType(_unsupportedMethodsInCurrentType, _hasAnIndexer);
             foreach (MethodDefinition method in Element.Methods)
             {
                 MethodAnalyzer.SetForMethod(method);
                 MethodAnalyzer.Run();
             }
         }
     }
     _typeBuilder.SetAndRun(Element, GetAdditionalCodeIfAny(_assemblyName, Element.Name), _implementedInterfaces, _hasAnIndexer, _assemblyName, 0);
     //Used to make sure we don't implement twice the same type. A type could be generated once with a few methods and could be override afterward with less methods defined, but it can't be the other way.
     _alreadyImplementedTypes.Add(_assemblyName + '.' + Element.FullName);
 }
Esempio n. 10
0
        public void GetInterferenceOfArea()
        {
            Body        eleBody       = GetOccsInBods(this.eleModel.PartTag)[0];
            Body        workpieceBody = GetOccsInBods(this.workpiece)[0];
            List <Face> faces         = AnalysisUtils.SetInterferenceOutFace(eleBody, workpieceBody);
            double      minArea       = 0;

            for (int i = 0; i < (faces.Count) / 2 - 1; i++)
            {
                FaceData data1 = FaceUtils.AskFaceData(faces[i * 2]);
                FaceData data2 = FaceUtils.AskFaceData(faces[i * 2 + 1]);
                if (data1.Equals(data2))
                {
                    double area1 = FaceUtils.GetFaceArea(faces[i * 2]);
                    double area2 = FaceUtils.GetFaceArea(faces[i * 2 + 1]);
                    if (area1 > area2)
                    {
                        minArea += area2;
                    }
                    else
                    {
                        minArea += area1;
                    }
                }
            }
            AttributeUtils.AttributeOperation("Area", minArea, this.eleModel.PartTag);
        }
Esempio n. 11
0
        private bool TryGetConstructor(TypeReference type, out MethodDefinition constructor, bool returnConstructorIfAbstractType = false)
        {
            if (!returnConstructorIfAbstractType)
            {
                TypeDefinition td = AnalysisUtils.GetTypeDefinitionFromTypeReference(type, _modules);
                if (td == null || AnalysisUtils.IsTypeAbstract(td))
                {
                    constructor = null;
                    return(false);
                }
            }
            HashSet <MethodDefinition> constructors;

            if (TryGetConstructors(type, out constructors))
            {
                constructor = ConvertConstructorToGenericInstanceMethod(GetConstructorWithMinimumParameters(constructors), type);
                return(true);
            }
            // we should never be in this situation
            else
            {
                constructor = null;
                return(false);
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Analyze the current method and return a method generated from this one.
        /// </summary>
        /// <returns></returns>
        public void Run()
        {
            if (!_isInitialized)
            {
                throw new Exception("MethodAnalyzer must be initialized. Please call Init() first.");
            }

            if (CanWorkOnElement())
            {
                _isMethodOrPropertyOrEvent = IsMethodOrPropertyOrEvent(Element);
                CheckParametersAndReturnValueType();
                string dependencyPropertyNameIfAny;
                switch (_isMethodOrPropertyOrEvent)
                {
                case MethodType.PROPERTY:
                    PropertyDefinition property = FindProperty(Element, Element.DeclaringType);
                    if (AddDependencyPropertyIfDefined(property, out dependencyPropertyNameIfAny))
                    {
                        _parentClassAnalyzer.AddProperty(new Builder.PropertyInfo(property, true, dependencyPropertyNameIfAny));
                    }
                    else
                    {
                        if (!AnalysisUtils.IsMethodAbstract(property) && _outputOptions.OutputPropertyOptions == OutputPropertyOptions.OUTPUT_PRIVATE_FIELD)
                        {
                            string fieldName = property.Name.Contains(".") ? property.Name.Substring(property.Name.LastIndexOf('.') + 1) : property.Name;
                            fieldName = "_" + fieldName.Substring(0, 1).ToLower() + fieldName.Substring(1);
                            string newFieldName;
                            _parentClassAnalyzer.AddField(fieldName, property.PropertyType, false, false, AnalysisUtils.IsMethodStatic(property), null, null, out newFieldName);
                            _parentClassAnalyzer.AddProperty(new Builder.PropertyInfo(property, false, newFieldName));
                        }
                        else
                        {
                            _parentClassAnalyzer.AddProperty(new Builder.PropertyInfo(property));
                        }
                    }
                    break;

                case MethodType.METHOD:
                    if (AddDependencyPropertyIfDefined(Element, out dependencyPropertyNameIfAny))
                    {
                        _parentClassAnalyzer.AddMethod(new Builder.MethodInfo(Element, Element.Name.StartsWith("Get"), Element.Name.StartsWith("Set"), dependencyPropertyNameIfAny));
                    }
                    else
                    {
                        _parentClassAnalyzer.AddMethod(new Builder.MethodInfo(Element));
                    }
                    break;

                case MethodType.EVENT:
                    EventDefinition @event = FindEvent(Element, Element.DeclaringType);
                    _parentClassAnalyzer.AddEvent(@event);
                    break;
                }
                AddMethodToImplementedMethodsSet(Element);
            }
        }
Esempio n. 13
0
            public static void addVelocityMappings(TreeView tvRawData)
            {
                String  sFunctionSignature = "ModelMap.addAttribute";
                O2Timer tTimer             = new O2Timer("Adding Velocity Mappings : {0} ").start();
                Dictionary <AssessmentAssessmentFileFinding, O2AssessmentData_OunceV6> dMatches =
                    analyzer.getSinksFindingsThatMatchRegEx(tvRawData, sFunctionSignature);

                foreach (AssessmentAssessmentFileFinding fFinding in dMatches.Keys)
                {
                    // resolve addAddtibute name
                    String sSinkContext        = AnalysisUtils.getSinkContext(fFinding, dMatches[fFinding]);
                    var    fsFilteredSignature = new FilteredSignature(sSinkContext);
                    String sParameters         = fsFilteredSignature.sParameters.Replace("\"", "");
                    String sSpringParameter    = sParameters.Substring(0, sParameters.IndexOf(',')).Trim();

                    // create a unique name for it:
                    String sSink = AnalysisUtils.getSink(fFinding, dMatches[fFinding]);
                    // String sSinkWithAttributeName = sSink.Replace("(", "_" + sSpringParameter + "(");
                    String sVelocityMapping = String.Format("{0}            0", sSink);

                    TreeNode tnVelocityNode = tvRawData.Nodes[sSink];
                    if (tnVelocityNode != null)
                    {
                        var otbO2TraceBlockWithVelocityMappings = (O2TraceBlock_OunceV6)tnVelocityNode.Tag;

                        String sUniqueSignature = analyzer.getUniqueSignature(fFinding, TraceType.Known_Sink,
                                                                              dMatches[fFinding], true);
                        var otbO2TraceBlockToAddVelocityMappings = (O2TraceBlock_OunceV6)tvRawData.Nodes[sUniqueSignature].Tag;
                        //   sUniqueSignature = sUniqueSignature.Replace("_" + sSpringParameter + "(", "(");
                        //  O2TraceBlock_OunceV6 otbO2TraceBlockToAddVelocityMappings = (O2TraceBlock_OunceV6)tvRawData.Nodes[sUniqueSignature].Tag;

                        if (otbO2TraceBlockWithVelocityMappings.dSinks.Count > 1)
                        {
                        }

                        foreach (
                            AssessmentAssessmentFileFinding fVelocityFinding in
                            otbO2TraceBlockWithVelocityMappings.dSinks.Keys)
                        {
                            if (false == otbO2TraceBlockToAddVelocityMappings.dGluedSinks.ContainsKey(fVelocityFinding))
                            {
                                otbO2TraceBlockToAddVelocityMappings.dGluedSinks.Add(fVelocityFinding,
                                                                                     otbO2TraceBlockWithVelocityMappings
                                                                                     .dSinks[fVelocityFinding]);
                            }
                            if (false == otbO2TraceBlockToAddVelocityMappings.dSinks.ContainsKey(fVelocityFinding))
                            {
                                otbO2TraceBlockToAddVelocityMappings.dSinks.Add(fVelocityFinding,
                                                                                otbO2TraceBlockWithVelocityMappings.
                                                                                dSinks[fVelocityFinding]);
                            }
                        }
                    }
                }
            }
        public static Dictionary <AssessmentAssessmentFileFinding, O2AssessmentData_OunceV6> getSinksFindingsThatMatchRegEx(
            TreeView tvRawData, String sRegExToSearch)
        {
            var dMatches = new Dictionary <AssessmentAssessmentFileFinding, O2AssessmentData_OunceV6>();
            Dictionary <AssessmentAssessmentFileFinding, O2AssessmentData_OunceV6> dAllSinkFindings =
                getUniqueListOfSinks(tvRawData);

            foreach (AssessmentAssessmentFileFinding fFinding in dAllSinkFindings.Keys)
            {
                if (RegEx.findStringInString(AnalysisUtils.getSink(fFinding, dAllSinkFindings[fFinding]), sRegExToSearch))
                {
                    dMatches.Add(fFinding, dAllSinkFindings[fFinding]);
                }
            }
            return(dMatches);
        }
Esempio n. 15
0
 /// <summary>
 /// Initialyze the StubGenerator
 /// </summary>
 private void Init()
 {
     _outputOptions   = Configuration.OutputOptions;
     _inputAssemblies = GetAssemblies(Configuration.assembliesToAnalyzePath, true).ToArray <string>();
     _referencedAssembliesFolderPath = Configuration.ReferencedAssembliesFolderPath;
     _referencedAssembliesToLookInto = GetAssemblies(_referencedAssembliesFolderPath);
     GetModules();
     AnalysisUtils.SetModules(_modules);
     GetUnsupportedMethods();
     AddUndetectedMethodToUnsupportedMethods(Configuration.MethodsToAddManuallyBecauseTheyAreUndetected);
     _assemblyAnalyzer = new AssemblyAnalyzer(
         Configuration.SLMigrationCoreAssemblyFolderPath,
         _unsupportedMethodsInfo,
         _modules,
         _outputOptions);
 }
Esempio n. 16
0
        private MethodSignature GetSignatureOfSecondMethodOfPropertyFromFirstMethod(MethodDefinition method)
        {
            bool          isExplicitlyImplemented = AnalysisUtils.IsMethodExplicitlyImplemented(method);
            string        name          = GetNameOfPropertyOrEvent(method.Name);
            string        fromInterface = "";
            string        returnType;
            bool          hasParameters;
            List <string> parameters = new List <string>();

            if (isExplicitlyImplemented)
            {
                fromInterface = method.Name.Substring(0, method.Name.LastIndexOf('.') + 1);
            }
            string newPrefix;

            if (method.Name.Contains("get_"))
            {
                newPrefix     = "set_";
                returnType    = "System.Void";
                hasParameters = true;
                if (method.HasParameters)
                {
                    foreach (ParameterDefinition param in method.Parameters)
                    {
                        parameters.Add(param.ParameterType.FullName);
                    }
                }
                parameters.Add(method.ReturnType.FullName);
            }
            else
            {
                newPrefix     = "get_";
                returnType    = method.Parameters[method.Parameters.Count - 1].ParameterType.FullName;
                hasParameters = (method.Parameters.Count > 1);
                if (hasParameters)
                {
                    for (int i = 0; i < method.Parameters.Count - 1; i++)
                    {
                        parameters.Add(method.Parameters[i].ParameterType.FullName);
                    }
                }
            }
            string fullName = fromInterface + newPrefix + name;

            return(new MethodSignature(fullName, returnType, hasParameters, parameters));
        }
Esempio n. 17
0
        /// <summary>
        /// Resolve inheritance issues
        /// </summary>
        /// <param name="assemblyName"></param>
        /// <param name="typeName"></param>
        /// <param name="methodName"></param>
        /// <returns></returns>
        private MethodInfo GetMethodInfoResolvingInheritance(string assemblyName, string typeName, string methodName)
        {
            TypeDefinition currentType   = null;
            int            i             = 0;
            bool           keepSearching = true;

            while (i < _modules.Count && keepSearching)
            {
                ModuleDefinition module = _modules[i];
                if (module.Name.Replace(".dll", "") == assemblyName)
                {
                    if (module.HasTypes)
                    {
                        int j = 0;
                        while (j < module.Types.Count && keepSearching)
                        {
                            TypeDefinition type = module.Types[j];
                            if (type.Name == typeName)
                            {
                                currentType   = type;
                                keepSearching = false;
                            }
                            j++;
                        }
                    }
                    keepSearching = false;
                }
                i++;
            }
            while (currentType != null)
            {
                if (currentType.HasMethods)
                {
                    foreach (MethodDefinition method in currentType.Methods)
                    {
                        if (method.Name == methodName)
                        {
                            return(new MethodInfo(currentType.Scope.Name.Replace(".dll", ""), currentType.Name, methodName, true));
                        }
                    }
                }
                currentType = AnalysisUtils.GetTypeDefinitionFromTypeReference(currentType.BaseType, _modules);
            }
            return(new MethodInfo(assemblyName, typeName, methodName, true));
        }
        /// <summary>
        /// 干涉检查
        /// </summary>
        /// <param name="eleCtBody"></param>
        /// <param name="eleName"></param>
        /// <param name="post"></param>
        /// <param name="picth"></param>
        /// <param name="err"></param>
        private void Interference(Component eleCt, string eleName, string post, string picth, ref List <string> err)
        {
            Body eleCtBody = GetOccsInBods(eleCt);

            foreach (Part pt in work.GetAllWorkpiece())
            {
                Component ptCoo = GetPartInOcc(pt);
                if (ptCoo != null && !ptCoo.IsSuppressed)
                {
                    Body        by    = GetOccsInBods(ptCoo);
                    List <Body> bodys = new List <Body>();
                    if (by != null)
                    {
                        try
                        {
                            NXOpen.GeometricAnalysis.SimpleInterference.Result re = AnalysisUtils.SetInterferenceOutResult(eleCtBody, by, out bodys);
                            if (re == NXOpen.GeometricAnalysis.SimpleInterference.Result.NoInterference)
                            {
                                err.Add(eleName + "                     " + pt.Name + picth + "没有干涉!");
                            }
                            if (re == NXOpen.GeometricAnalysis.SimpleInterference.Result.InterferenceExists)
                            {
                                err.Add(eleName + "                     " + pt.Name + picth + "有干涉!");
                            }
                            if (bodys.Count > 0)
                            {
                                foreach (Body body in bodys)
                                {
                                    body.Layer = 252;
                                }
                            }
                        }
                        catch
                        {
                            ClassItem.WriteLogFile("干涉检查错误!");
                        }
                    }
                    else
                    {
                        err.Add(pt.Name + "                   无法找到工件体,请检查引用集!");
                    }
                }
            }
        }
Esempio n. 19
0
            public static void mapInterfaces(TreeView tvRawData, ICirData cdCirData, String sHardCodedInterfaceKeywork,
                                             bool bAddGluedTracesAsRealTraces)
            {
                DI.log.debug("Mapping Interfaces");
                O2Timer tTimer = new O2Timer("Interfaces mapping completed").start();
                // Int32 iItemsProcessed = 0;

                Dictionary <AssessmentAssessmentFileFinding, O2AssessmentData_OunceV6> dAllSinkFindings =
                    analyzer.getUniqueListOfSinks(tvRawData);

                foreach (AssessmentAssessmentFileFinding fFinding in dAllSinkFindings.Keys)
                {
                    String sSink = AnalysisUtils.getSink(fFinding, dAllSinkFindings[fFinding]);
                    if (sSink != "" && sSink.IndexOf(sHardCodedInterfaceKeywork) > -1)
                    {
                        if (false == cdCirData.dFunctions_bySignature.ContainsKey(sSink))
                        {
                            DI.log.error("in mapInterfaces, could not find signature in loaded CirData file: {0}",
                                         sSink);
                        }
                        else
                        {
                            ICirFunction cfCirFunction = cdCirData.dFunctions_bySignature[sSink];
                            ICirClass    ccCirClass    = cfCirFunction.ParentClass;
                            foreach (ICirClass ccIsSuperClassedBy in ccCirClass.dIsSuperClassedBy.Values)
                            {
                                String sMappedMethodName = cfCirFunction.FunctionSignature.Replace(ccCirClass.Signature,
                                                                                                   ccIsSuperClassedBy.
                                                                                                   Signature);
                                List <O2TraceBlock_OunceV6> lotdMatches =
                                    analyzer.getO2TraceBlocksThatMatchSignature(sMappedMethodName, tvRawData);
                                foreach (O2TraceBlock_OunceV6 otbO2TraceBlockWithTracesToGlue in lotdMatches)
                                {
                                    addFindingAsGlueTrace(otbO2TraceBlockWithTracesToGlue, fFinding,
                                                          dAllSinkFindings[fFinding], tvRawData,
                                                          bAddGluedTracesAsRealTraces);
                                }
                            }
                        }
                    }
                }

                tTimer.stop();
            }
Esempio n. 20
0
 /// <summary>
 /// Check if a type define both get and set for a given property.
 /// </summary>
 /// <param name="methodToLookFor"></param>
 /// <param name="typeToLookInto"></param>
 /// <returns></returns>
 private AccessModifierEnum IsPropertyMethodDefined(MethodSignature methodToLookFor, TypeDefinition typeToLookInto)
 {
     if (typeToLookInto != null)
     {
         if (typeToLookInto.HasMethods)
         {
             MethodSignature methodToCompare;
             foreach (MethodDefinition m in typeToLookInto.Methods)
             {
                 methodToCompare = new MethodSignature(m);
                 if (methodToLookFor == methodToCompare)
                 {
                     return(AnalysisUtils.GetMethodAccessModifier(m));
                 }
             }
         }
     }
     return(AccessModifierEnum.NONE);
 }
Esempio n. 21
0
        private bool PrepareForAdditionalType(TypeReference type, HashSet <string> methods)
        {
            var typeDef = AnalysisUtils.GetTypeDefinitionFromTypeReference(type, _modules);

            if (typeDef == null)
            {
                //we can't find the type.
                return(false);
            }
            bool isCoreSupported     = analyzeHelpher._coreSupportedMethods.ContainsType(type.Name, type.Namespace);
            bool isMscorlibSupported = analyzeHelpher.IsTypeSupported(type);

            if (isCoreSupported || isMscorlibSupported)
            {
                //type is already supported.
                return(false);
            }
            Set(typeDef, methods);
            return(true);
        }
        /// <summary>
        /// 获得齿最小距离
        /// </summary>
        /// <returns></returns>
        public double AskMinDim()
        {
            double min = 9999;

            double[] pt1 = new double[3];
            double[] pt2 = new double[3];
            for (int i = 0; i < this.HeadBodys.Count - 1; i++)
            {
                for (int j = i + 1; j < this.HeadBodys.Count; j++)
                {
                    double temp = AnalysisUtils.AskMinimumDist(this.HeadBodys[i].Tag, this.HeadBodys[j].Tag, out pt1, out pt2);
                    temp = Math.Round(temp, 3);
                    if (min >= temp)
                    {
                        min = temp;
                    }
                }
            }
            return(min);
        }
        /// <summary>
        /// If the member is "override", this method returns the type where the
        /// corresponding "virtual" member is defined, otherwise it returns the
        /// member declaring type.
        /// </summary>
        public static TypeReference GetDeclaringTypeResolvingOverrides(MemberReference memberReference)
        {
            if (Cache.ContainsKey(memberReference))
            {
                return(Cache[memberReference]);
            }
            else
            {
                TypeReference declaringType = memberReference.DeclaringType;
                string        memberName    = memberReference.Name;

                if (memberReference is MethodReference)
                {
                    MethodReference  methodReference  = (MethodReference)memberReference;
                    MethodDefinition methodDefinition = null;
                    try
                    {
                        methodDefinition = methodReference.Resolve();
                    }
                    catch { }
                    if (methodDefinition != null)
                    {
                        if (AnalysisUtils.IsMethodOverride(methodDefinition))
                        {
                            TypeDefinition   typeDefinition = AnalysisUtils.GetTypeDefinitionFromTypeReference(declaringType, null);
                            MethodDefinition methodIsFirstDefinitionInParentType = AnalysisUtils.LookForMethodInParents(methodDefinition, typeDefinition);
                            if (methodIsFirstDefinitionInParentType != null)
                            {
                                return(methodIsFirstDefinitionInParentType.DeclaringType);
                            }
                        }
                    }
                }

                Cache.Add(memberReference, declaringType);

                return(declaringType);
            }
        }
Esempio n. 24
0
 private bool TryGetConstructors(TypeReference type, out HashSet <MethodDefinition> constructorsIfAny)
 {
     if (Constructors.ContainsKey(type))
     {
         constructorsIfAny = Constructors[type];
         return(constructorsIfAny != null && constructorsIfAny.Count > 0);
     }
     else
     {
         bool isTypeWithNoConstructor;
         if (AnalysisUtils.TryGetConstructors(type, _modules, out constructorsIfAny, out isTypeWithNoConstructor))
         {
             Constructors.Add(type, constructorsIfAny);
             return(true);
         }
         else
         {
             constructorsIfAny = null;
             Constructors.Add(type, null);
             return(false);
         }
     }
 }
Esempio n. 25
0
        public void Run()
        {
            if (!_isInitialized)
            {
                throw new Exception("ClassAnalyzer must be initialized. Please call Init() first.");
            }

            if (CanWorkOnElement())
            {
                Stack <TypeDefinition> typesToAnalyze = new Stack <TypeDefinition>();
                // We don't directly analyze the selected type because we want to start with its "oldest" parent.
                // Sometimes, we have to update our set of unsupported methods, so we need to start with the oldest parent to make sure we don't forget to implement a method from an interface or an abstract class which has been added during the execution of the program.
                do
                {
                    typesToAnalyze.Push(Element);
                    Element = AnalysisUtils.GetTypeDefinitionFromTypeReference(Element.BaseType, _modules);
                }while (Element != null && (Element.FullName != "System.Object" || Element.FullName != "System.ValueType") && CanWorkOnElement(Element));
                while (typesToAnalyze.Count > 0)
                {
                    TypeDefinition   firstParent    = typesToAnalyze.Pop();
                    string           parentAssembly = firstParent.Scope.Name.Replace(".dll", "");
                    HashSet <string> unsupportedMethodsInParent;
                    if (_unsupportedMethods.ContainsKey(parentAssembly))
                    {
                        if (_unsupportedMethods[parentAssembly].TryGetValue(firstParent.Name, out unsupportedMethodsInParent))
                        {
                            Set(firstParent, unsupportedMethodsInParent);
                        }
                        else
                        {
                            Set(firstParent, new HashSet <string>());
                        }
                        Execute();
                    }
                }
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Executes the command.
        /// Opens the AnalysisOptionsDialog, creates the export file, sends it to the Server and waits for it to have results.
        /// </summary>
        /// <param name="services">CommandServices object to interact with the system</param>
        public override void Run(Canguro.Controller.CommandServices services)
        {
            gettingResults = false;
            System.Windows.Forms.DialogResult result = services.ShowDialog(new Canguro.Commands.Model.AnalysisOptionsDialog(services));
            string message = "";

            if (result == System.Windows.Forms.DialogResult.Cancel)
            {
                services.Model.Undo.Rollback();
            }
            else if (result == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    System.Windows.Forms.Cursor cursor = System.Windows.Forms.Cursor.Current;
                    bool isConnected;
                    bool canAnalyze = false;
                    JoinCmd.RepairJoints(services.Model);
                    new Canguro.Commands.Model.UnselectCmd().Run(services);
                    if (!(canAnalyze = AnalysisUtils.CanAnalyze(services.Model, ref message, out isConnected)))
                    {
                        if (!isConnected)
                        {
                            if (System.Windows.Forms.MessageBox.Show(message, Culture.Get("error"),
                                                                     System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Error) ==
                                System.Windows.Forms.DialogResult.Yes)
                            {
                                System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;

                                new JoinCmd().Run(services);
                                canAnalyze = AnalysisUtils.CanAnalyze(services.Model, ref message, out isConnected);

                                System.Windows.Forms.Cursor.Current = cursor;
                            }
                            else
                            {
                                return;
                            }
                        }
                    }
                    if (canAnalyze)
                    {
                        System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;

                        string modelPath = System.IO.Path.GetTempFileName();
                        System.Diagnostics.Debug.WriteLine(modelPath);
                        FixPDelta(services.Model.AbstractCases);

                        Stream stream = File.Create(modelPath);
                        new Canguro.Model.Serializer.Serializer(services.Model).Serialize(stream, false);
                        stream.Close();

                        System.Windows.Forms.Cursor.Current = cursor;

                        System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;

                        // TODO: ANALYZE STRUCTURE!!!
                        //analysisID = ws.Analyze(userNameURL, passwordURL, host, serial, file, analysisOptions, modelSize, quotation);

                        System.Windows.Forms.Cursor.Current = cursor;

                        services.Model.Results = new Canguro.Model.Results.Results(0);

                        // TODO: GET RESULTS
                        services.ReportProgress(5);
                    }
                    else // Can't analyze
                    {
                        if (!isConnected)
                        {
                            message = Culture.Get("structureIsDisconnectedWrn");
                        }

                        System.Windows.Forms.MessageBox.Show(message, Culture.Get("error"), System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    }
                }
                catch (Exception)
                {
                    System.Windows.Forms.MessageBox.Show(Culture.Get("ErrorAnalyzing"), Culture.Get("error"), System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
            }
        }
Esempio n. 27
0
        /// <summary>
        /// Executes the command.
        /// Opens the SaveTo dialog, creates the xml file, sends it to the Server and waits for it to have the manifest for the exported s2k.
        /// </summary>
        /// <param name="services">CommandServices object to interact with the system</param>
        public override void Run(Canguro.Controller.CommandServices services)
        {
            gettingResults = false;
            try
            {
                string message = "";
                System.Windows.Forms.Cursor cursor = System.Windows.Forms.Cursor.Current;
                bool isConnected;
                bool canAnalyze = false;
                new Canguro.Commands.Model.UnselectCmd().Run(services);

                // Verify model consistency for analysis (e.g. graph connectivity)
                if (!(canAnalyze = AnalysisUtils.CanAnalyze(services.Model, ref message, out isConnected)))
                {
                    if (!isConnected)
                    {
                        if (System.Windows.Forms.MessageBox.Show(message, Culture.Get("error"),
                                                                 System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Error) ==
                            System.Windows.Forms.DialogResult.Yes)
                        {
                            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;

                            new JoinCmd().Run(services);
                            canAnalyze = AnalysisUtils.CanAnalyze(services.Model, ref message, out isConnected);

                            System.Windows.Forms.Cursor.Current = cursor;
                        }
                        else
                        {
                            return;
                        }
                    }
                }

                if (canAnalyze)
                {
                    System.Windows.Forms.SaveFileDialog dlg = new System.Windows.Forms.SaveFileDialog();
                    dlg.Filter       = "S2K File (*.s2k)|*.s2k";
                    dlg.DefaultExt   = "s2k";
                    dlg.AddExtension = true;
                    dlg.Title        = Culture.Get("ExportS2KTitle");
                    if (!string.IsNullOrEmpty(services.Model.CurrentPath))
                    {
                        dlg.FileName = Path.Combine(Path.GetDirectoryName(services.Model.CurrentPath), Path.GetFileNameWithoutExtension(services.Model.CurrentPath)) + ".s2k";
                    }
                    else
                    {
                        dlg.FileName = Culture.Get("defaultModelName");
                    }
                    System.Windows.Forms.DialogResult result = (dlg).ShowDialog();

                    if (result == System.Windows.Forms.DialogResult.Cancel)
                    {
                        return;
                    }
                    string dstFile = dlg.FileName;

                    System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;

                    // Serialize the model
                    string modelPath = System.IO.Path.GetTempFileName();
                    AnalysisCmd.FixPDelta(services.Model.AbstractCases);
                    Stream stream = File.Create(modelPath);
                    new Canguro.Model.Serializer.Serializer(services.Model).Serialize(stream, false);
                    stream.Close();

                    System.Windows.Forms.Cursor.Current = cursor;
                    System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;

                    // Export to s2k
                    Export(modelPath, dstFile);

                    System.Windows.Forms.Cursor.Current = cursor;
                }
                else // Can't export
                {
                    if (!isConnected)
                    {
                        message = Culture.Get("structureIsDisconnectedWrn");
                    }
                    System.Windows.Forms.MessageBox.Show(message, Culture.Get("error"), System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
            }
            catch (Exception)
            {
                System.Windows.Forms.MessageBox.Show(Culture.Get("ErrorExporting"), Culture.Get("error"), System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
            }
        }
        /// <summary>
        ///检查体
        /// </summary>
        /// <returns></returns>
        public BodyInfo GetBodyInfoForInterference(bool extract, out List <string> err)
        {
            err = new List <string>();
            List <Face> dischargeFace = new List <Face>();
            List <Face> temp          = new List <Face>();
            List <Body> bodys         = new List <Body>();

            try
            {
                AnalysisUtils.SetInterferenceOutFace(this.eleBody, this.toolBody, out temp, out bodys);
            }
            catch (NXException ex)
            {
                err.Add("干涉检查错误!" + ex.Message);
            }
            if (bodys.Count > 0)
            {
                LayerUtils.MoveDisplayableObject(252, bodys.ToArray());
                if (extract)
                {
                    this.eleBody.Color = 186;
                }
                err.Add("电极头有过切,请检查!");
            }
            dischargeFace = temp.Where(a => a.GetBody().Equals((this.eleBody))).Distinct().ToList(); //过滤电极面
            List <Face> tt    = temp.Where(a => a.GetBody().Equals((this.toolBody))).Distinct().ToList();
            List <Face> faces = new List <Face>();

            foreach (Face fe in dischargeFace)
            {
                FaceData data1 = FaceUtils.AskFaceData(fe);
                foreach (Face fa in tt)
                {
                    FaceData fd = FaceUtils.AskFaceData(fa);
                    if (UMathUtils.SelfDis(data1.Dir) == 0)
                    {
                        if (data1.FaceType == fd.FaceType && data1.IntNorm == -fd.IntNorm)
                        {
                            faces.Add(fe);
                            break;
                        }
                    }
                    else
                    {
                        double anlge = UMathUtils.Angle(data1.Dir, fd.Dir);
                        if (data1.FaceType == fd.FaceType && data1.IntNorm == -fd.IntNorm && UMathUtils.IsEqual(anlge, Math.PI))
                        {
                            faces.Add(fe);
                            break;
                        }
                    }
                }
            }
            if (extract)
            {
                ExtractFace(this.toolBody, faces.ToArray());
            }
            BodyInfo info = new BodyInfo(eleBody, faces);

            info.SetAttribute(csys, matr);
            return(info);
        }
Esempio n. 29
0
 private MethodDefinition ConvertConstructorToGenericInstanceMethod(MethodDefinition constructor, TypeReference declaringType)
 {
     if (!declaringType.IsGenericInstance)
     {
         return(constructor);
     }
     else
     {
         GenericInstanceType type = (GenericInstanceType)declaringType;
         if (type.HasGenericArguments)
         {
             MethodAttributes attributes = MethodAttributes.RTSpecialName
                                           | MethodAttributes.SpecialName
                                           | MethodAttributes.Assembly;
             MethodDefinition newConstructor = new MethodDefinition(".ctor", attributes, InstanceOfTypeSystem.Void);
             foreach (ParameterDefinition param in constructor.Parameters)
             {
                 if (param.ParameterType.IsGenericParameter)
                 {
                     int indexOfGenericType = 0;
                     foreach (GenericParameter genericParameter in type.ElementType.GenericParameters)
                     {
                         if (genericParameter.Name == param.ParameterType.Name)
                         {
                             break;
                         }
                         else
                         {
                             indexOfGenericType++;
                         }
                     }
                     if (indexOfGenericType < type.ElementType.GenericParameters.Count)
                     {
                         newConstructor.Parameters.Add(new ParameterDefinition(param.Name, param.Attributes, type.GenericArguments[indexOfGenericType]));
                     }
                     else
                     {
                         // this should not happen and will create an error in the generated code.
                         newConstructor.Parameters.Add(new ParameterDefinition(param.Name, param.Attributes, InstanceOfTypeSystem.Void));
                     }
                 }
                 else if (param.ParameterType.HasGenericParameters)
                 {
                     newConstructor.Parameters.Add(new ParameterDefinition(param.Name, param.Attributes, AnalysisUtils.MakeInstanceTypeFromTypeReference(param.ParameterType, type.GenericArguments.ToArray())));
                 }
                 else if (param.ParameterType.IsGenericInstance)
                 {
                     TypeReference paramElementType = ((GenericInstanceType)param.ParameterType).ElementType;
                     if (paramElementType.HasGenericParameters)
                     {
                         newConstructor.Parameters.Add(new ParameterDefinition(param.Name, param.Attributes, AnalysisUtils.MakeInstanceTypeFromTypeReference(paramElementType, type.GenericArguments.ToArray())));
                     }
                     else
                     {
                         newConstructor.Parameters.Add(new ParameterDefinition(param.Name, param.Attributes, param.ParameterType));
                     }
                 }
                 else
                 {
                     newConstructor.Parameters.Add(new ParameterDefinition(param.Name, param.Attributes, param.ParameterType));
                 }
             }
             return(newConstructor);
         }
         else
         {
             return(constructor);
         }
     }
 }
Esempio n. 30
0
        public string CallBaseConstructorIfAny(MethodDefinition constructor, TypeReference declaringType = null)
        {
            MethodDefinition baseConstructor;

            if (declaringType == null)
            {
                declaringType = constructor.DeclaringType;
            }
            if (TryGetBaseConstructorMatchingBestThisContructor(constructor, out baseConstructor))
            {
                if (!baseConstructor.HasParameters)
                {
                    return("");
                }
                else
                {
                    string res = " : base(";
                    bool   isFirstParameter = true;
                    ParameterDefinition matchingParameter;
                    foreach (ParameterDefinition param in baseConstructor.Parameters)
                    {
                        matchingParameter = null;
                        if (!isFirstParameter)
                        {
                            res += ", ";
                        }
                        else
                        {
                            isFirstParameter = false;
                        }
                        if (AnalysisUtils.TryGetParameterMatchingVariableInMethodArguments(param.Name, param.ParameterType, constructor.Parameters, out matchingParameter))
                        {
                            res += "@" + matchingParameter.Name;
                        }
                        else
                        {
                            if (param.ParameterType.IsGenericParameter)
                            {
                                if (constructor.DeclaringType.BaseType.IsGenericInstance)
                                {
                                    int genericParameterIndex = -1;
                                    if (baseConstructor.DeclaringType.HasGenericParameters)
                                    {
                                        int index = 0;
                                        foreach (GenericParameter gp in baseConstructor.DeclaringType.GenericParameters)
                                        {
                                            if (gp.Name == param.ParameterType.Name)
                                            {
                                                genericParameterIndex = index;
                                                break;
                                            }
                                            index++;
                                        }
                                    }
                                    if (genericParameterIndex > -1)
                                    {
                                        res += GenerateDefaultValue(((GenericInstanceType)constructor.DeclaringType.BaseType).GenericArguments[genericParameterIndex]);
                                    }
                                }
                            }
                            else
                            {
                                res += GenerateDefaultValue(param.ParameterType);
                            }
                        }
                    }
                    res += ")";
                    return(res);
                }
            }
            else
            {
                return("");
            }
        }