Esempio n. 1
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (this.connectToSolidWorks())
            {
                // get the path to the example part
                String path = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Example.SLDPRT");

                if (File.Exists(path))
                {
                    // open the example part in solidworks
                    int       errors  = 0;
                    ModelDoc2 swModel = swApp.OpenDoc2(path, (int)swDocumentTypes_e.swDocPART, true, false, true, ref errors);
                    if (swModel != null)
                    {
                        PartDoc partDoc = (PartDoc)swModel;

                        // get the solid bodies in the part
                        var bodies = partDoc.GetBodies2((int)swBodyType_e.swSolidBody, false);

                        ModelDocExtension swModExt = (ModelDocExtension)swModel.Extension;

                        // iterate through each solid body and delete any hidden solidbodies
                        foreach (Body2 body in bodies)
                        {
                            if (!body.Visible)
                            {
                                swModExt.SelectByID2(body.Name, "SOLIDBODY", 0, 0, 0, false, 0, null, 0);
                                swModel.FeatureManager.InsertDeleteBody();
                                swModel.ClearSelection();
                            }
                        }

                        // export the result
                        String desktopPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);
                        int    warnings    = 0;

                        swModExt.SaveAs(Path.Combine(desktopPath, "Result.step"), 0, 0, null, ref errors, ref warnings);

                        swApp.CloseAllDocuments(true);
                    }
                }

                this.releaseSolidWorks();
            }
            else
            {
                MessageBox.Show("Error starting SolidWorks.");
            }
        }
Esempio n. 2
0
        public static void UpdateProperty(MaterialModel objMaterial)
        {
            //1.打开指定的SW文件
            ModelDoc2 swDoc = swAppHelper.ActiveDoc(Globals.FileName);
            //2.获取当前激活配置名
            string configName = swDoc.ConfigurationManager.ActiveConfiguration.Name;

            #region 封装所有的SolidWorks属性(配置+自定义)
            //获取属性值:图号、名称、型号规格、单位、热处理、表面处理、品牌、血液
            Dictionary <string, string> MyCustominfos = new Dictionary <string, string>();
            MyCustominfos.Add("Identification Nb", objMaterial.MaterialCode);
            MyCustominfos.Add("Description", objMaterial.MaterialName);
            MyCustominfos.Add("规格", objMaterial.MaterialSpec);
            MyCustominfos.Add("型号", objMaterial.MaterialType);
            MyCustominfos.Add("单位", objMaterial.Unit);
            MyCustominfos.Add("加工属性", objMaterial.MachiningPropertyId);
            MyCustominfos.Add("涂装颜色", objMaterial.PaintingColor);
            MyCustominfos.Add("品牌", objMaterial.BrandId);
            //遍历每个属性并赋值
            foreach (string key in MyCustominfos.Keys)
            {
                //删除,添加配置特定的属性
                swDoc.DeleteCustomInfo2(configName, key);
                swDoc.AddCustomInfo3(configName, key, (int)swCustomInfoType_e.swCustomInfoText, MyCustominfos[key]);
                //删除,添加自定义的属性
                swDoc.DeleteCustomInfo(key);
                swDoc.AddCustomInfo2(key, (int)swCustomInfoType_e.swCustomInfoText, MyCustominfos[key]);
            }
            #endregion

            #region 重建模型
            swDoc.ClearSelection();    //清除选择
            swDoc.ForceRebuild3(true); //重建模型Ctrl+Q
            //swDoc.ShowNamedView2("*等轴测", 7);//等轴测显示
            //swDoc.ViewZoomtofit2();//全屏显示
            //swDoc.Save();
            //swAppHelper.CloseDoc(objDoc.OriginalFileName);
            #endregion
        }
        /// <summary>
        /// Метод построения детали
        /// </summary>
        public void BuildCandle(CandleParametrs objParametr)
        {
            /// <summary>
            /// Экземпляру присваиваем значение объекта класса
            /// </summary>
            _parametr = objParametr;

            /// <summary>
            /// Проверка построена ли деталь
            /// </summary>
            _parametr.ExistDetail = true;

            /// <summary>
            /// Путь до рабочего стола
            /// </summary>
            var pathName = System.Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory);

            /// <summary>
            /// Присваивание параметров
            /// </summary>
            var carvingLength   = _parametr.CarvingLength;
            var nutLength       = _parametr.NutLength;
            var nutSize         = _parametr.NutSize;
            var isolatorLength  = _parametr.IsolatorLength;
            var chamferRadius   = _parametr.ChamferRadius;
            var plinthLength    = _parametr.PlinthLength;
            var headLength      = _parametr.HeadLength;
            var pitchSize       = _parametr.PitchSize;
            var carvingRadius   = _parametr.CarvingRadius;
            var textEtching     = _parametr.TextEtching;
            var electrodeLength = _parametr.ElectrodeLength;

            /// <summary>
            /// Методы класса CandleCreator
            /// </summary>
            if (_parametr.ExistHead == true)
            {
                CandleCreator.CreateHead(headLength, SwApp, SwModel, _detailNames, pathName);
            }
            CandleCreator.CreatePlinth(plinthLength, SwApp, SwModel, _detailNames, textEtching, pathName);
            CandleCreator.CreateNut(nutLength, nutSize, SwApp, SwModel, _detailNames, chamferRadius, pathName);
            CandleCreator.CreateIsolator(isolatorLength, SwApp, SwModel, _detailNames, pathName);
            CandleCreator.CreateCarving(carvingLength, SwApp, SwModel, _detailNames, pitchSize, carvingRadius, electrodeLength, pathName);

            /// <summary>
            /// Создание сборки
            /// </summary>
            AssemblyDoc swAssembly = SwApp.NewAssembly();

            SwModel = ((ModelDoc2)(SwApp.ActiveDoc));
            if (_parametr.ExistHead == true)
            {
                swAssembly.AddComponent2(_detailNames[0], 0, 0, headLength / 2);
                swAssembly.AddComponent2(_detailNames[1], 0, 0, plinthLength / 2 + headLength);
                swAssembly.AddComponent2(_detailNames[2], 0, 0, nutLength / 2 + headLength + plinthLength);
                swAssembly.AddComponent(_detailNames[3], 0, 0, isolatorLength / 2 + headLength + plinthLength + nutLength);
                swAssembly.AddComponent(_detailNames[4], 0, 0, carvingLength / 2 + headLength + plinthLength + isolatorLength + nutLength);
            }
            else
            {
                swAssembly.AddComponent2(_detailNames[0], 0, 0, plinthLength / 2 + headLength);
                swAssembly.AddComponent2(_detailNames[1], 0, 0, nutLength / 2 + headLength + plinthLength);
                swAssembly.AddComponent(_detailNames[2], 0, 0, isolatorLength / 2 + headLength + plinthLength + nutLength);
                swAssembly.AddComponent(_detailNames[3], 0, 0, carvingLength / 2 + headLength + plinthLength + isolatorLength + nutLength);
            }
            /// <summary>
            /// Выбор вида "Изометрия"
            /// </summary>
            SwModel.Extension.SelectByID2("", "FACE", 0, 0, 0, true, 0, null, 0);
            swAssembly.AddMate((int)swMateType_e.swMateCONCENTRIC, (int)swMateAlign_e.swAlignAGAINST, false, 1, 0);
            SwModel.ShowNamedView("*Изометрия");
            SwModel.ClearSelection();
            SwModel.EditRebuild3();

            /// <summary>
            /// Закрытие созданных документов
            /// </summary>
            SwApp.CloseDoc(_detailNames[0]);
            SwApp.CloseDoc(_detailNames[1]);
            SwApp.CloseDoc(_detailNames[2]);
            SwApp.CloseDoc(_detailNames[3]);
            if (_parametr.ExistHead == true)
            {
                SwApp.CloseDoc(_detailNames[4]);
            }

            /// <summary>
            /// Сохранение сборки
            /// </summary>
            string modelName = pathName + "Свеча.SLDASM";

            SwModel.SaveAs(modelName);
        }
Esempio n. 4
0
        private Feature DrawnSketchOnFace(ModelDoc2 swModel, double[] mousePoint, List <Edge> thisFaceEdgeList, Entity swSelFaceEntity, out string sketchName)
        {
            swModel.SketchManager.InsertSketch(true);

            //通过两条相邻边来标注 创建点的位置

            //1。 计算鼠标选中点到面的各边的距离。

            List <FaceEdgeInfos> faceEdgeInfor = new List <FaceEdgeInfos>();

            //Dictionary<Edge, double> pointToEdgeDim = new Dictionary<Edge, double>();

            var selMousePt = (double[])TransformPoint(swModel.IGetActiveSketch2(), mousePoint[0], mousePoint[1], mousePoint[2]);

            foreach (var item in thisFaceEdgeList)
            {
                var tStart = (Vertex)item.GetStartVertex();
                var pstart = (double[])tStart.GetPoint();

                var tEnd = (Vertex)item.GetEndVertex();
                var pend = (double[])tEnd.GetPoint();

                pstart = (double[])TransformPoint(swModel.IGetActiveSketch2(), pstart[0], pstart[1], pstart[2]);
                pend   = (double[])TransformPoint(swModel.IGetActiveSketch2(), pend[0], pend[1], pend[2]);

                var angleOfLine = Math.Atan2((pend[1] - pstart[1]), (pend[0] - pstart[0])) * 180 / Math.PI;

                double tempChuizuX = 0;
                double tempChuizuY = 0;

                //垂足的坐标位置
                var tempchuizu = Geometry2D.GetPerpendicular(selMousePt[0], selMousePt[1], pend[0], pend[1], pstart[0], pstart[1]);

                tempChuizuX = tempchuizu[0];
                tempChuizuY = tempchuizu[1];

                faceEdgeInfor.Add(new FaceEdgeInfos(item, Geometry2D.pointToLine(pstart[0], pstart[1], pend[0], pend[1], selMousePt[0], selMousePt[1]), angleOfLine, Geometry2D.lineSpace(pstart[0], pstart[1], pend[0], pend[1]), tempChuizuX, tempChuizuY));

                //pointToEdgeDim.Add(item, pointToLine(pstart[0], pstart[1], pend[0], pend[1], mousePoint[0], mousePoint[1]));
            }

            //把所有的边按距离排序
            var EdgeInfosOrderByDim = faceEdgeInfor.OrderBy(x => x.dim).ToList();

            //最近的一条边
            var minEdgeObject = EdgeInfosOrderByDim[0];

            //下一条相临的边
            FaceEdgeInfos nextMinEdga = null;

            for (int i = 1; i < EdgeInfosOrderByDim.Count; i++)
            {
                if (Math.Abs(EdgeInfosOrderByDim[i].Angle) != 180 - Math.Abs(minEdgeObject.Angle) && EdgeInfosOrderByDim[i].Angle != minEdgeObject.Angle)
                {
                    nextMinEdga = EdgeInfosOrderByDim[i];
                    break;
                }
            }

            // var eNextEdge = faceEdgeInfoses.Find(x => ((Vertex)x.edge.GetStartVertex()).GetPoint() == ((Vertex)minEdgeObject.GetEndVertex()).GetPoint());

            var minEdge = (Entity)minEdgeObject.edge;

            var nextminEdge = (Entity)nextMinEdga.edge;

            swModel.ClearSelection();

            //MessageBox.Show("done");

            swSelFaceEntity.Select(false);

            // var actSketch = swModel.SketchManager.ActiveSketch;

            ////把鼠标点坐标转换到草图中

            //var selMousePt = (double[])TransformPoint(swModel.IGetActiveSketch2(), mousePoint[0], mousePoint[1], mousePoint[2]);

            swModel.SketchManager.CreateCenterRectangle(selMousePt[0], selMousePt[1], selMousePt[2], selMousePt[0] + 0.03, selMousePt[1] + 0.03, selMousePt[2]);

            swModel.ClearSelection2(true);

            swModel.Extension.SelectByID2("Point1", "SKETCHPOINT", 0, 0, 0, false, 0, null, 0);
            minEdge.Select(true);

            // var thisDim = (DisplayDimension)swModel.AddDimension2(selMousePt[0], selMousePt[1], selMousePt[2]);
            var thisDim = (DisplayDimension)swModel.AddDimension2(minEdgeObject.chuizuPoint_X, minEdgeObject.chuizuPoint_Y, 0);

            thisDim.GetDimension2(0).SystemValue = Math.Round(minEdgeObject.dim * 1000, 0) / 1000;

            //第二个方向尺寸
            swModel.ClearSelection2(true);

            swModel.Extension.SelectByID2("Point1", "SKETCHPOINT", 0, 0, 0, false, 0, null, 0);
            nextminEdge.Select(true);

            //var nextthisDim = (DisplayDimension)swModel.AddDimension2(selMousePt[0], selMousePt[1], selMousePt[2]);
            var nextthisDim = (DisplayDimension)swModel.AddDimension2(nextMinEdga.chuizuPoint_X, nextMinEdga.chuizuPoint_Y, 0);

            nextthisDim.GetDimension2(0).SystemValue = Math.Round(nextMinEdga.dim * 1000, 0) / 1000;

            string featName = null;
            string featType = null;

            var skFeature = (Feature)swModel.IGetActiveSketch2();

            featName   = skFeature.GetNameForSelection(out featType);
            sketchName = featName;

            swModel.SketchManager.InsertSketch(true);

            swModel.Extension.SelectByID2(sketchName, "SKETCH", 0, 0, 0, false, 1, null, 0);

            var boolstatus = swModel.InsertPlanarRefSurface();

            ISelectionMgr swSelMgr = (ISelectionMgr)swModel.SelectionManager;

            skFeature = (Feature)swSelMgr.GetSelectedObject6(1, 0);// swModel.FeatureByPositionReverse(0);

            return(skFeature);
        }
Esempio n. 5
0
        public void AddFeature(SldWorks SwApp, ModelDoc2 SwModel, Point2D P1, Point2D P2)
        {
            if (CheckUsing() == false)
            {
                return;
            }

            SwModel.ClearSelection2(true);
            Helper         helper         = new Helper(SwModel, SwApp);
            SketchManager  sketchManager  = SwModel.SketchManager;
            FeatureManager featureManager = SwModel.FeatureManager;
            SelectionMgr   selectionMgr   = SwModel.SelectionManager;
            Feature        feature        = default(Feature);
            Entity         entity         = default(Entity);
            Face2          face2          = default(Face2);
            Array          faceArray      = default(Array);
            Array          edgeArray      = default(Array);
            Edge           swEdge         = default(Edge);

            List <double> filletedges = new List <double>();
            double        edgeL       = default(double);

            double[] TNormal = { 0, 1, 0 };  // Y up normal
            double[] LNormal = { 0, 0, 1 };  // +Z normal
            double[] RNormal = { 0, 0, -1 }; // -Z normal

            CurveParamData curveParamData = default(CurveParamData);

            double LStage = P2.x - P1.x;

            #region // add features

            helper.select_feature("RefPlane", 0, false, 0);
            SwModel.InsertSketch();

            if (splinedMethod == (object)"From Start")
            {
                sketchManager.CreateLine(P1.x, P1.y, 0, (P1.x + splinedLength), P1.y, 0); // top line
                sketchManager.CreateLine(P1.x, splinedR, 0, ((P1.x + splinedLength) - splinedArcL), splinedR, 0);
                // bottom line
                sketchManager.CreateLine(P1.x, P1.y, 0, P1.x, splinedR, 0); //left line
                sketchManager.CreateTangentArc((P1.x + (splinedLength - splinedArcL)), splinedR, 0,
                                               (P1.x + splinedLength),
                                               P1.y, 0, 1);
            }

            if (splinedMethod == (object)"From End")
            {
                sketchManager.CreateLine(P2.x, P1.y, 0, (P2.x - splinedLength), P2.y, 0); // top line
                sketchManager.CreateLine(P2.x, splinedR, 0, (P2.x - (splinedLength - splinedArcL)), splinedR, 0);
                // bottom line
                sketchManager.CreateLine(P2.x, P1.y, 0, P2.x, splinedR, 0); //left line
                sketchManager.CreateTangentArc((P2.x - (splinedLength - splinedArcL)), splinedR, 0,
                                               (P2.x - splinedLength),
                                               P1.y, 0, 0);
            }

            if (splinedMethod == (object)"Through")
            {
                sketchManager.CreateCenterRectangle((P1.x + (LStage / 2)), (splinedR + (P1.y - splinedR) / 2), 0,
                                                    P1.x, P1.y, 0);
            }


            SwModel.FeatureManager.FeatureCut3(true, false, false, 6, 0, splinedWidth, 0,
                                               false, false, false, false, 0, 0, false, false, false, false, false, true, true, true, true,
                                               false, 0, 0, false); //cut from mide plane

            #endregion

            feature   = (Feature)selectionMgr.GetSelectedObject6(1, -1);
            faceArray = feature.GetFaces() as Array;

            #region // edge filleting, 0 - pass

            if (splinedFillet != 0)

            {
                for (int j = 0; j < faceArray.Length; j++) // get face by normal 0,1,0
                {
                    face2 = faceArray.GetValue(j) as Face2;
                    var normal = face2.Normal;
                    if (TNormal.SequenceEqual(normal as double[]))
                    {
                        entity = faceArray.GetValue(j) as Entity;
                        entity.Select4(false, null);
                        //                                MessageBox.Show(j.ToString());
                        break;
                    }
                }

                face2     = selectionMgr.GetSelectedObject6(1, -1);
                edgeArray = face2.GetEdges() as Array;
                //                     MessageBox.Show(""+face2.GetEdgeCount().ToString());
                SwModel.ClearSelection();

                for (int j = 0; j < face2.GetEdgeCount(); j++) // finding of edge length
                {
                    swEdge         = edgeArray.GetValue(j) as Edge;
                    curveParamData = swEdge.GetCurveParams3();
                    edgeL          = Math.Abs(curveParamData.UMaxValue - curveParamData.UMinValue);
                    filletedges.Add(edgeL);
                }


                double max = filletedges.Max();
                for (int j = 0; j < filletedges.Count; j++) // select edges for filleting
                {
                    if (filletedges[j] == max)
                    {
                        entity = edgeArray.GetValue(j) as Entity;
                        entity.Select4(true, null);
                    }
                }

                featureManager.FeatureFillet(194, splinedFillet, 0, 0, null, null, null);
                // edges fillet 194 - target propagate off
                SwModel.ClearSelection2(true);
            }

            #endregion

            #region // edge chamfering, 0 - pass

            if (splinedChamfer != 0)
            {
                List <Face2> facesList = new List <Face2>();
                facesList.Add(default(Face2));             // empty element
                facesList.Add(default(Face2));             // empty element

                for (int j = 0; j < faceArray.Length; j++) // select faces by normal
                {
                    face2 = faceArray.GetValue(j) as Face2;
                    var normal = face2.Normal;
                    if (LNormal.SequenceEqual(normal as double[]))
                    {
                        facesList[0] = face2;
                    }
                    if (RNormal.SequenceEqual(normal as double[]))
                    {
                        facesList[1] = face2;
                    }
                }

                faceArray = facesList.ToArray() as Array; // refill array of neded face's
                int index_f0 = 0;                         // index of top edge L
                int index_f1 = 0;                         // index of top edge R

                for (int j = 0; j < faceArray.Length; j++)
                {
                    face2     = faceArray.GetValue(j) as Face2;
                    edgeArray = face2.GetEdges() as Array;
                    swEdge    = edgeArray.GetValue(0) as Edge;

                    CurveParamData cData = swEdge.GetCurveParams3() as CurveParamData;

                    var Spoint = (double[])cData.StartPoint;
                    var Epoint = (double[])cData.EndPoint;


                    for (int k = 0; k < edgeArray.Length; k++)
                    {
                        swEdge = edgeArray.GetValue(k) as Edge;
                        cData  = swEdge.GetCurveParams3() as CurveParamData;
                        var SP = (double[])cData.StartPoint;
                        var EP = (double[])cData.EndPoint;

                        if ((SP[1] >= Spoint[1]) && (EP[1] >= Epoint[1])) // check max y cordinats of the edge
                        {
                            if (Spoint[1] == Spoint[1])                   // horisontal line always have same y cordinats
                            {
                                Epoint = EP;
                                Spoint = SP;
                                if (j == 0)
                                {
                                    index_f0 = k;
                                }
                                else
                                {
                                    index_f1 = k;
                                }
                            }
                        }
                    }
                }


                // finally selecy top up edges
                face2     = faceArray.GetValue(0) as Face2;
                edgeArray = face2.GetEdges() as Array;
                entity    = edgeArray.GetValue(index_f0) as Entity;
                entity.Select4(false, null);


                face2     = faceArray.GetValue(1) as Face2;
                edgeArray = face2.GetEdges() as Array;
                entity    = edgeArray.GetValue(index_f1) as Entity;
                entity.Select4(true, null);

                int chamferOpt = 4; // target propagate by default

                if (splinedMethod == (object)"From Start" ||
                    splinedMethod == (object)"From End")
                {
                    chamferOpt = 1; // flip direction
                }
                featureManager.InsertFeatureChamfer(chamferOpt, 1, splinedChamfer, helper.ToRad(45), 0, 0, 0, 0);
                SwModel.ClearSelection2(true);
            }

            #endregion

            #region //Pattern if value less then 1 pass

            if (splinedArray > 1)
            {
                helper.select_feature("Cut", (helper.get_features_count("Cut") - 1), false, 4);
                helper.select_feature("RefAxis", 0, true, 1);

                if (splinedChamfer > 0)
                {
                    helper.select_feature("Chamfer", (helper.get_features_count("Chamfer") - 1), true, 4);
                }

                if (splinedFillet > 0)
                {
                    helper.select_feature("Fillet", (helper.get_features_count("Fillet") - 1), true, 4);
                }

                featureManager.FeatureCircularPattern4(splinedArray, helper.ToRad(360), false, "null", false, true,
                                                       false);
            }

            #endregion
            helper.HidePlanes();
        }
Esempio n. 6
0
        private void AutoDimensionDrawing2(ModelDoc2 swModel, bool many )
        {
            bool del3List = false;
            var thrdList = new List<string>();
            int shi = 0;
            isValidXml = true;

            var swDrawing = (DrawingDoc)swModel;
            if (swModel.GetCustomInfoValue("", "AutoDim") == "No")
            {
                if (many)
                {
                    MessageBox.Show(@"Если хотите образмерить чертеж, смените No на Yes в поле 'AutoDim' свойств данного чертежа",
                        @"MrDoors", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                isValidXml = false;
            }
            if (swModel.GetCustomInfoValue("", "MakeCNCprog") == "Yes")
            {
                _createProgramm = true;
            }
            if (!isValidXml && !_createProgramm) // если не надо создавать программу и авто дим = но, то образмеривать просто не нужно.
                return;
            swModel.Extension.SetUserPreferenceDouble((int)swUserPreferenceDoubleValue_e.swDetailingDimToDimOffset,
                                                      (int)swUserPreferenceOption_e.swDetailingNoOptionSpecified, 0.006);
            swModel.Extension.SetUserPreferenceDouble((int)swUserPreferenceDoubleValue_e.swDetailingObjectToDimOffset,
                                                      (int)swUserPreferenceOption_e.swDetailingNoOptionSpecified, 0.010);

            Dictionary<string, bool> listSide;
            string targetModelPath = null;
            if (!File.Exists(Path.Combine(Path.GetDirectoryName(_swAdd.RootModel.GetPathName()), "fpTime.txt")))
            {
                //MessageBox.Show("Образмеривание детали может пройти некорректно! Для корректного образмеривания детали необходимо произвести Окончательную обработку заказа.");
                throw new Exception("Образмеривание детали может пройти некорректно! Для корректного образмеривания детали необходимо произвести Окончательную обработку заказа.");
            }
            else
            {
                //просто взять Sketch Number

               string fnameWithoutExt = Path.GetFileNameWithoutExtension(swModel.GetPathName());
                fnameWithoutExt = fnameWithoutExt.Substring(fnameWithoutExt.Length - 4, 4);
                SwDMDocument8 swDoc = null;
                SwDMApplication swDocMgr = SwAddin.GetSwDmApp();
                SwDmDocumentOpenError oe;
                SwDmCustomInfoType type;
                if (!(fnameWithoutExt[0] == '#' && (fnameWithoutExt[3] == 'P' || fnameWithoutExt[3] == 'p')))
                {

                    swDoc = (SwDMDocument8) swDocMgr.GetDocument(Path.ChangeExtension(swModel.GetPathName(), "SLDASM"),SwDmDocumentType.swDmDocumentAssembly, true, out oe);

                }
                else
                {
                    object brokenRefVar;
                    SwDMSearchOption src = swDocMgr.GetSearchOptionObject();

                    var swDocDraw = (SwDMDocument8)swDocMgr.GetDocument(swModel.GetPathName(), SwDmDocumentType.swDmDocumentDrawing, true, out oe);
                    var varRef = (object[])swDocDraw.GetAllExternalReferences2(src, out brokenRefVar);
                    swDocDraw.CloseDoc();
                    targetModelPath = (string)varRef[0];
                    swDoc = (SwDMDocument8)swDocMgr.GetDocument(targetModelPath, SwDmDocumentType.swDmDocumentAssembly, true, out oe);
                }
                if (swDoc != null)
                {
                    var prop = swDoc.GetCustomProperty("Sketch Number", out type);
                    if (string.IsNullOrEmpty(prop) || prop == "0")
                        throw new Exception("Образмеривание детали прервано, т.к. может пройти некорректно ! Для корректного образмеривания детали необходимо произвести Окончательную обработку заказа.");
                    swDoc.CloseDoc();
                }
                _swAdd.SetModelProperty(swModel, "WasMesure", string.Empty, swCustomInfoType_e.swCustomInfoYesOrNo, "Yes", true);
            }
            string pathXml = WriteXmlFile(swModel, isValidXml, targetModelPath);

            bool isNeededSheetNumber = PrepareDrawingDoc(swModel, out listSide);
            bool dimOnlyNew = false;
            if (swModel.GetCustomInfoValue("", "DimOnlyNew") == "Yes")
                dimOnlyNew = true;
            var vSheetNames = (string[])swDrawing.GetSheetNames();
            var rootNode = _node;
            bool atLeastOneF1View = false;

            foreach (var vSheetName in vSheetNames)
            {
                bool iftherewasAhole = false;
                XmlElement element = null;
                XmlElement sheetNode = null;
                KeyValuePair<string,string> tableNameAttribute = new KeyValuePair<string, string>();
                if (_createProgramm && !string.IsNullOrEmpty(pathXml))
                {
                    element = _cxml.CreateElement("Sheet");
                    element.SetAttribute("Name", vSheetName);
                    _node = rootNode.AppendChild(element);
                    sheetNode = element;
                }

                double vScale = 0;
                var type = new List<string>();
                var listSize = new List<SizeForDim>();
                swDrawing.ActivateSheet(vSheetName);
                swModel.Extension.SelectByID2(vSheetName, "SHEET", 0, 0, 0, true,
                                              (int)swSelectionMarkAction_e.swSelectionMarkAppend, null, 0);
                swModel.ViewZoomToSelection();
                swModel.ClearSelection();
                var swSheet = (Sheet)swDrawing.GetCurrentSheet();
                var swViews = (object[])swSheet.GetViews();
                bool side = shi == 1;
                if (isNeededSheetNumber && listSide.ContainsKey(vSheetName.Substring(vSheetName.Length - 1)))
                    side = listSide[vSheetName.Substring(vSheetName.Length - 1)];
                if (vSheetName.ToUpper().Contains("FACE"))
                    side = true;
                if (vSheetName.ToUpper().Contains("BACK"))
                    side = false;

                if (swViews != null)
                {
                    var rootViewElement = _node;
                    if (Properties.Settings.Default.ViewsBeforeDimen)
                        ReplaceViews(swViews, swDrawing);
                    foreach (var t in swViews)
                    {
                        #region Образмеривание вида
                        var swView = (View) t;
                        swModel.ClearSelection2(true);

                        const string expr = "^F[1-6]$";

                        Match isMatch = Regex.Match(swView.Name, expr, RegexOptions.IgnoreCase);

                        if (_createProgramm && swView.Name.ToLower().Contains("const"))
                        {

                            //Logging.Log.Instance.Fatal(@"На данный чертеж программа не будет создана! " + swModel.GetPathName() + "swView.Name = " + swView.Name);
                            //MessageBox.Show(@"На данный чертеж программа не будет создана!", @"MrDoors",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
                        }

                        if (!(isMatch.Success || swView.Name.Contains("Чертежный вид")) ||
                            swView.Name.ToLower().Contains("const") ||
                            swView.Type == (int)swDrawingViewTypes_e.swDrawingDetailView) continue;

                        if (_createProgramm && !isMatch.Success)
                        {
                            _createProgramm = false;
                            //Logging.Log.Instance.Fatal(@"На данный чертеж программа не будет создана! " + swModel.GetPathName() + "swView.Name = " + swView.Name);
                            //MessageBox.Show(@"На данный чертеж программа не будет создана!", @"MrDoors",
                            //                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }

                        swDrawing.ActivateView(swView.GetName2());
                        swView.UseSheetScale = 0;

                        var list = HideUnusedComponents(swView, dimOnlyNew);

                        try
                        {
                            vScale = ((double[]) swView.ScaleRatio)[1];
                            swView.SetDisplayMode3(false, (int) swDisplayMode_e.swFACETED_HIDDEN, true, true);

                            #region Процесс образмеривания

                            using (var d = new DimensionView(_swApp, BlockPositionExtension.FromBool(side), dimOnlyNew))
                            {

                                d.DimView(side);
                                if (!iftherewasAhole)
                                    iftherewasAhole = d.IsHole;
                                if (!isNeededSheetNumber && !side && !iftherewasAhole)
                                    del3List = true;
                                else
                                {
                                    if (isNeededSheetNumber && !iftherewasAhole)
                                    {
                                        del3List = true;
                                        thrdList.Add(vSheetName);
                                    }
                                }
                                foreach (var tp in d.List)
                                {
                                    if (!type.Contains(tp))
                                        type.Add(tp);
                                }
                                listSize.Add(d.AddSize);

                                #region Запись данных в xml файл

                                if (element != null)
                                {
                                    element = _cxml.CreateElement("View");
                                    element.SetAttribute("Name", swView.Name);
                                    if (swView.Name == "F1")
                                    {
                                        atLeastOneF1View = true;

                                            SwDmDocumentOpenError oe;
                                            SwDMApplication swDocMgr = SwAddin.GetSwDmApp();
                                            var swDoc = (SwDMDocument8)swDocMgr.GetDocument(Path.ChangeExtension(swModel.GetPathName(), "SLDASM"),
                                                                                             SwDmDocumentType.swDmDocumentAssembly, true, out oe);
                                            if (swDoc != null)
                                            {
                                                var cit = new SwDmCustomInfoType();
                                                string[] names = swDoc.GetCustomPropertyNames();
                                                string extFeats = null,faner11 = null,faner12 = null,faner21 = null,faner22 = null;

                                                if (names.Contains("ExtFanerFeats"))
                                                    extFeats = swDoc.GetCustomProperty("ExtFanerFeats", out cit);
                                                double angle = 57.29577951308232*swView.Angle; //(180/П)
                                                if (Math.Abs(angle) < 0.000001 || Math.Abs(angle + 90) < 0.000001 || Math.Abs(angle - 270) < 0.000001 || Math.Abs(angle - 180) < 0.000001 || Math.Abs(angle - 90) < 0.000001) //!string.IsNullOrEmpty(extFeats) && extFeats == "Yes" &&
                                                {
                                                    if (names.Contains("Faner11"))
                                                        faner11 = swDoc.GetCustomProperty("Faner11", out cit);
                                                    if (names.Contains("Faner12"))
                                                        faner12 = swDoc.GetCustomProperty("Faner12", out cit);
                                                    if (names.Contains("Faner21"))
                                                        faner21 = swDoc.GetCustomProperty("Faner21", out cit);
                                                    if (names.Contains("Faner22"))
                                                        faner22 = swDoc.GetCustomProperty("Faner22", out cit);

                                                    var tmpElem = _cxml.CreateElement("Comment");
                                                    string comment = FrmEdge.GetCommentFromProperties(faner11,faner12,faner21,faner22, angle, _swAdd,swModel);
                                                    double angle2 = angle + 90;
                                                    double angle4 = angle + 180;
                                                    double angle3 = angle + 270;
                                                    if (angle2 > 270)
                                                        angle2 = angle2%360;
                                                    if (angle3 > 270)
                                                        angle3 = angle3 % 360;
                                                    if (angle4 > 270)
                                                        angle4 = angle4 % 360;
                                                    string comment2 = FrmEdge.GetCommentFromProperties(faner11, faner12, faner21, faner22, angle2, _swAdd, swModel);
                                                    string comment3 = FrmEdge.GetCommentFromProperties(faner11, faner12, faner21, faner22, angle3, _swAdd, swModel);
                                                    string comment4 = FrmEdge.GetCommentFromProperties(faner11, faner12, faner21, faner22, angle4, _swAdd, swModel);
                                                    tmpElem.SetAttribute("Rot270",comment3);
                                                    tmpElem.SetAttribute("Rot180",comment4);
                                                    tmpElem.SetAttribute("Rot90", comment2);
                                                    tmpElem.SetAttribute("Rot0", comment);
                                                    rootNode.PrependChild(tmpElem);
                                                }

                                            }

                                        //swDoc.CloseDoc();

                                        //int warnings = 0;
                                        //int errors = 0;
                                        //var swModelDoc = _swApp.OpenDoc6(Path.ChangeExtension(swModel.GetPathName(), "SLDASM"), (int)swDocumentTypes_e.swDocASSEMBLY,
                                        //                  (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", errors,
                                        //                  warnings);
                                        //if (!string.IsNullOrEmpty(swModelDoc.CustomInfo2["", "ExtFanerFeats"]) && swModelDoc.CustomInfo2["", "ExtFanerFeats"] == "Yes")
                                        //{
                                        //    var tmpElem = _cxml.CreateElement("Comment");
                                        //    string comment = FrmEdge.GetComment(swModelDoc, swView.Angle, _swAdd);
                                        //    tmpElem.SetAttribute("Rot270", string.Empty);
                                        //    tmpElem.SetAttribute("Rot90", string.Empty);
                                        //    tmpElem.SetAttribute("Rot0", comment);
                                        //    rootNode.PrependChild(tmpElem);
                                        //}

                                    }
                                    if (_node != null)
                                    {
                                        _node = rootViewElement.AppendChild(element);
                                        switch (d.Side)
                                        {
                                            case BlockPosition.LeftTopToRightBottom:

                                                if (swView.Name == "F1")
                                                    tableNameAttribute = new KeyValuePair<string, string>("F1","J");
                                                if (swView.Name == "F6")
                                                {
                                                    if (tableNameAttribute.Key!="F1") // F1 -  приоритетнее
                                                        tableNameAttribute = new KeyValuePair<string, string>("F6", "B");
                                                }
                                                if (string.IsNullOrEmpty(tableNameAttribute.Key))
                                                {
                                                    tableNameAttribute = new KeyValuePair<string, string>("none","J");
                                                }
                                                break;
                                            case BlockPosition.RightTopToLeftBottom:
                                                if (swView.Name == "F1")
                                                    tableNameAttribute = new KeyValuePair<string, string>("F1","B");
                                                if (swView.Name == "F6")
                                                {
                                                    if (tableNameAttribute.Key!="F1") // F1 -  приоритетнее
                                                        tableNameAttribute = new KeyValuePair<string, string>("F6", "J");
                                                }
                                                if (string.IsNullOrEmpty(tableNameAttribute.Key))
                                                {
                                                    tableNameAttribute = new KeyValuePair<string, string>("none", "B");
                                                }
                                                break;
                                            case BlockPosition.LeftBottomToRightTop:
                                            case BlockPosition.RigthBottomToLeftTop:
                                                //MessageBox.Show(
                                                //    "В этом чертеже начало координат находится внизу. Программа может быть создана некорректно!",
                                                //    @"MrDoors", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                                // element = _cxml.CreateElement("Table");
                                                // element.SetAttribute("Name", "Не удалось определить наименование стола!");
                                                //_node=_node.AppendChild(element);
                                                break;

                                        }
                                    }

                                    int i = 0;
                                    string id = "id" + i;
                                    element = _cxml.CreateElement(id);

                                    element.SetAttribute("X", Math.Round(d.X).ToString(CultureInfo.CreateSpecificCulture("ru-RU")));
                                    element.SetAttribute("Y", Math.Round(d.Y).ToString(CultureInfo.CreateSpecificCulture("ru-RU")));
                                    if (swView.Name == "F1" || swView.Name == "F6")
                                        element.SetAttribute("Z", _z.ToString(CultureInfo.CreateSpecificCulture("ru-RU")));
                                    if (_node != null)
                                        _node.AppendChild(element);

                                    foreach (var ls in d.ListSize)
                                    {
                                        i++;
                                        id = "id" + i;
                                        element = _cxml.CreateElement(id);

                                        element.SetAttribute("X", ls.X.ToString(CultureInfo.CreateSpecificCulture("ru-RU")));
                                        element.SetAttribute("Y",  ls.Y.ToString(CultureInfo.CreateSpecificCulture("ru-RU")));
                                        element.SetAttribute("Diameter",  ls.Diameter.ToString(CultureInfo.CreateSpecificCulture("ru-RU")));
                                        element.SetAttribute("Depth",ls.Depth.ToString(CultureInfo.CreateSpecificCulture("ru-RU")));

                                        if (_node != null)
                                            _node.AppendChild(element);
                                    }
                                    _node = _node.ParentNode;
                                }

                                #endregion
                            }

                            #endregion

                            swView.SetDisplayMode3(false, (int) swDisplayMode_e.swFACETED_HIDDEN_GREYED, true, true);

                            swDrawing.ActivateSheet(vSheetName);
                        }
                        catch (Exception e)
                        {
                            MessageBox.Show(@"Ошибка при образмеривании! " + e.Message, @"MrDoors",
                                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        finally
                        {
                            if (dimOnlyNew)
                                ShowHiddenComponents(list);
                        }

                        #endregion
                    }
                }
                if (type.Count != 0)
                    LegendMaker(swModel, swDrawing, type, vScale);
                if (!string.IsNullOrEmpty(tableNameAttribute.Value))
                    sheetNode.SetAttribute("TableName", tableNameAttribute.Value);
                if (Properties.Settings.Default.ScaleWhenDimen && !del3List && shi != 0)
                    AutoScaleSheet(listSize, swSheet, vScale, side);
                shi++;
                if(_node!=null)
                    _node = _node.ParentNode;
                AutoArrangeDimentions(vSheetName,dimOnlyNew);
            }
            swModel.EditRebuild3();
            if (shi == 3)
            {
                if (del3List)
                {
                    if (isNeededSheetNumber && thrdList.Count > 0)
                        foreach (var sh in thrdList)
                            swModel.Extension.SelectByID2(sh, "SHEET", 0, 0, 0, true, 0, null, 0);
                    else
                    {
                     if (!swModel.Extension.SelectByID2("Лист3", "SHEET", 0, 0, 0, false, 0, null, 0))
                     {
                         swModel.Extension.SelectByID2("Back3", "SHEET", 0, 0, 0, false, 0, null, 0);
                     }
                    }
                    swModel.DeleteSelection(true);
                }
                else
                    SheetNumering(swModel, swDrawing);
            }
            swModel.ForceRebuild3(false);
            bool writeXml = true;
            if (atLeastOneF1View)
            {
                try
                {
                    writeXml=SomeLogicChanges(swModel);
                }
                catch(Exception e)
                {
                    if (swModel.GetPathName() != null)
                        Logging.Log.Instance.Fatal(e, "Ошибка при применении логики к XML. " + swModel.GetPathName());
                    else
                        Logging.Log.Instance.Fatal(e, "Ошибка при применении логики к XML. ");

                }
                if (writeXml)
                    StopWriteXml(pathXml);
            }

            return;
        }
Esempio n. 7
0
        public Ordinate SelectVertexDatumUp(ModelDoc2 swModel, double[] boundBox, BlockPosition left, bool clear = false)
        {
            var sizeX = boundBox[2] - boundBox[0];
            if (sizeX < 0)
                sizeX = -sizeX;
            var sizeY = boundBox[3] - boundBox[1];
            if (sizeY < 0)
                sizeY = -sizeY;
            var etalon = sizeX > sizeY ? sizeY : sizeX;
            double step = etalon / 40;

            var ordinate = new Ordinate(0, 0);
            if (left.AsBoolean())
            {
                for (int iX = 0; iX <= 30; iX++)
                {
                    for (int iY = 0; iY <= 30; iY++)
                    {
                        var boolstatus = swModel.Extension.SelectByID2("", "VERTEX", boundBox[0] + step * iX,
                                                                       boundBox[3] - step * iY, 0.0, true,
                                                                       (int)
                                                                       swAutodimMark_e.swAutodimMarkOriginDatum,
                                                                       null, 0);
                        if (boolstatus)
                        {
                            ordinate.X = boundBox[0] + step * iX;
                            ordinate.Y = boundBox[3] - step * iY;
                            if (clear)
                                swModel.ClearSelection();
                            return ordinate;
                        }
                    }
                }
            }
            else
            {
                for (int iX = 0; iX <= 30; iX++)
                {
                    for (int iY = 0; iY <= 30; iY++)
                    {
                        var boolstatus = swModel.Extension.SelectByID2("", "VERTEX", boundBox[2] - step * iX,
                                                                       boundBox[3] - step * iY, 0.0, true,
                                                                       (int)
                                                                       swAutodimMark_e.swAutodimMarkOriginDatum,
                                                                       null, 0);
                        if (boolstatus)
                        {
                            ordinate.X = boundBox[2] - step * iX;
                            ordinate.Y = boundBox[3] - step * iY;
                            if (clear)
                                swModel.ClearSelection();
                            return ordinate;
                        }
                    }
                }
            }
            if (clear)
                swModel.ClearSelection();
            return ordinate;
        }
Esempio n. 8
0
        public double[] GetDimensionLineDirect(ModelDoc2 swModel, double[] boundBox, bool vertic,BlockPosition side, out double d, out Annotation annotation,out bool? blockSize,out Ordinate vertex,out Ordinate vertexS,  double[] dsDim,double[] deDim,double[] endDim,string dsName,string deName)
        {
            blockSize = null;
            var swDrawing = (DrawingDoc) swModel;
            var drView = swDrawing.IActiveDrawingView;
            var scale = (double[]) drView.ScaleRatio;
            double vScaleRat = scale[1];
            double[] doubles = null;
            d = 0;
            annotation = null;

            vertex = GetVertexFromBlock(swModel, drView, vScaleRat,true);
            if(!(vertex!=null && SelectVertexDatum(swModel, vertex)))
                vertex = SelectVertexDatumUp(swModel, boundBox, side);

            if (dsDim != null && deDim != null)
            {
                vertexS = GetVertexFromBlock(swModel, drView, vScaleRat, false);
                //swModel.ClearSelection2(true);

                swDrawing.ActivateView(drView.Name);
                bool tmp = swModel.Extension.SelectByID2(@"Точка вставки/" + dsName, "SKETCHPOINT", 0, 0, 0, false, 0, null, 0);
                tmp = swModel.Extension.SelectByID2(@"Точка вставки/" + deName, "SKETCHPOINT", 0, 0, 0, true, 0, null, 0);
                DisplayDimension dim1;
                if (vertic)
                     dim1 = swModel.AddVerticalDimension2(0, 0, 0);
                else
                     dim1 = swModel.AddHorizontalDimension2(0, 0, 0);

                dim1.GetDimension().DrivenState = (int)swDimensionDrivenState_e.swDimensionDriven;
                d = dim1.GetDimension().Value;
                if (vertic)
                {
                    doubles = new double[3] { 1, 0, 0 };
                }
                else
                {
                    doubles = new double[3] {0, 1, 0};
                }
                annotation = dim1.GetAnnotation();
            }
            else
            {

                if (vertic)
                {
                    vertexS = GetVertexFromBlock(swModel, drView, vScaleRat, false);
                    if (!(vertexS != null && SelectVertexDatum(swModel, vertexS)))
                        SelectVertexDatumDown(swModel, boundBox, side);
                    else if (vertex != null)
                        blockSize = vertex.X < vertexS.X;

                    DisplayDimension dim = null;

                    dim = swModel.IAddVerticalDimension2(0, 0, 0);

                    if (dim != null)
                    {
                        d = dim.IGetDimension().Value;
                        doubles = (double[]) dim.IGetDimension().DimensionLineDirection.ArrayData;
                        if (blockSize != null)
                        {
                            vertexS.Y = vertexS.Y + (d/1000)/vScaleRat;
                        }

                        annotation = dim.IGetAnnotation();
                    }
                }
                else
                {
                    vertexS = GetVertexFromBlock(swModel, drView, vScaleRat, false);
                    if (!(vertexS != null && SelectVertexDatum(swModel, vertexS)))
                    {
                        vertexS = SelectVertexDatumUp(swModel, boundBox, side.Not());
                    }
                    else if (vertex != null)
                        blockSize = vertex.X < vertexS.X;

                    var dim = swModel.AddHorizontalDimension2(0, 0, 0);

                    if (dim != null)
                    {
                        d = dim.GetDimension().Value;
                        doubles = (double[]) dim.GetDimension().DimensionLineDirection.ArrayData;
                        annotation = dim.GetAnnotation();

                    }
                }
            }
            swModel.ClearSelection();
            return doubles;
        }
Esempio n. 9
0
 private static void DrawDottedLine(ModelDoc2 swModel, Entity ent1, Entity ent2)
 {
     swModel.SetAddToDB(true);
     if (ent1 != null && ent2 != null)
     {
         swModel.SketchManager.CreateCenterLine(1, 1, 0, 1.1, 1.1, 0);
         var objPoints = (object[])swModel.SketchManager.ActiveSketch.GetSketchPoints();
         SketchPoint swPoint1 = null, swPoint2 = null;
         foreach (var objPoint in objPoints)
         {
             var swPoint = (SketchPoint)objPoint;
             double x1 = 1 - swPoint.X;
             double x2 = 1.1 - swPoint.X;
             double y1 = 1 - swPoint.Y;
             double y2 = 1.1 - swPoint.Y;
             if (x1 < 0)
                 x1 = -x1;
             if (x2 < 0)
                 x2 = -x2;
             if (y1 < 0)
                 y1 = -y1;
             if (y2 < 0)
                 y2 = -y2;
             if (x1 < 0.0001 && y1 < 0.0001)
             {
                 swPoint1 = swPoint;
             }
             if (x2 < 0.0001 && y2 < 0.0001)
             {
                 swPoint2 = swPoint;
             }
         }
         if (swPoint1 != null && swPoint2 != null)
         {
             if (swPoint1.Select(false) && ent1.Select(true))
             {
                 swModel.SketchAddConstraints("sgCONCENTRIC");
             }
             if (swPoint2.Select(false) && ent2.Select(true))
             {
                 swModel.SketchAddConstraints("sgCONCENTRIC");
             }
         }
     }
     swModel.SetAddToDB(false);
     swModel.GraphicsRedraw2();
     swModel.ClearSelection();
     //swModel.ClearUndoList();
 }
Esempio n. 10
0
        private bool PrepareDrawingDoc(ModelDoc2 swModel, out Dictionary<string, bool> list)
        {
            list = new Dictionary<string, bool>();
            bool ret = false;
            //LinkedList<ModelDoc2> outModels;
            // if (_swAdd.GetAllUniqueModels(_swAdd.RootModel, out outModels))
            //{
            /*
                ModelDoc2 swAsmModel = null;
                SwDmDocumentOpenError oe;
                SwDMApplication swDocMgr = SwAddin.GetSwDmApp();
                var swDoc = (SwDMDocument8)swDocMgr.GetDocument(swModel.GetPathName(),
                    SwDmDocumentType.swDmDocumentDrawing, true, out oe);
                if (swDoc != null)
                {
                    SwDMSearchOption src = swDocMgr.GetSearchOptionObject();
                    object brokenRefVar;
                    var varRef = (object[])swDoc.GetAllExternalReferences2(src, out brokenRefVar);
                    var name = (string)varRef[0];
                    swAsmModel = outModels.FirstOrDefault(modelDoc2 => modelDoc2.GetPathName() == name);
                }
            */
            ModelDoc2 swAsmModel = GetCurrentAsmModel(swModel);

            OleDbConnection oleDb;
            if (swAsmModel != null)
            {
                if (_createProgramm)
                {
                    var matName = swAsmModel.get_CustomInfo2("", "Material");
                    if (matName == "" && swAsmModel.GetConfigurationCount() > 1)
                    {
                        string val, resolvedVal;
                        if (
                            swAsmModel.Extension.get_CustomPropertyManager(swAsmModel.IGetActiveConfiguration().Name).
                                Get4(
                                    "Material", false, out val, out resolvedVal))
                            matName = val;
                    }
                    _z = ParseMaterialName(matName);
                }

                if (_swAdd.OpenModelDatabase(swAsmModel, out oleDb))
                {
                    bool isPropName, isStdSketchNum, isSheetNames;
                    if (IsNeededColumnInDbFile(oleDb, out isPropName, out isStdSketchNum, out isSheetNames))
                    {
                        var objNames = _namesOfColumnNameFromDimLimits.Where(x => x.Contains("obj"));
                        var listId = new List<int>();
                        foreach (var objName in objNames)
                        {
                            int id = FrmSetParameters.GetIdFromColumnName(objName);
                            if (!listId.Contains(id))
                                listId.Add(id);
                        }
                        var dictIdSize = new Dictionary<int, double>();
                        var cm = new OleDbCommand("SELECT * FROM objects", oleDb);
                        var rd = cm.ExecuteReader();
                        while (rd.Read())
                        {
                            if (listId.Contains((int) rd["id"]))
                            {
                                double val;
                                if (_swAdd.GetObjectValue(swAsmModel, (string) rd["name"], 14, out val) &&
                                    !dictIdSize.ContainsKey((int) rd["id"]))
                                    dictIdSize.Add((int) rd["id"], val);
                            }
                        }
                        rd.Close();
                        cm = new OleDbCommand("SELECT * FROM dimlimits", oleDb);
                        rd = cm.ExecuteReader();
                        while (rd.Read())
                        {
                            var lB = (from i in listId
                                      let mn = (int) rd["obj" + i + "min"]
                                      let mx = (int) rd["obj" + i + "max"]
                                      select (mn <= dictIdSize[i]) && (dictIdSize[i] <= mx)).ToList();
                            if (lB.Aggregate(true, (current, b) => (b && current)))
                            {
                                if (isSheetNames)
                                {
                                    var needSheetsNumb = (string) rd["sheetnames"];
                                    swModel.ClearSelection();
                                    foreach (var strNum in needSheetsNumb.Split(','))
                                    {
                                        string strNm = strNum.Trim();
                                        string num = strNm.Substring(0, strNm.Length - 1);
                                        string side = strNm.Substring(strNm.Length - 1);
                                        list.Add(num, side.ToLower() == "l");
                                    }
                                    var swDrw = (DrawingDoc) swModel;
                                    var sheetnames = (string[]) swDrw.GetSheetNames();

                                    foreach (var sheetname in sheetnames)
                                    {
                                        if (sheetname.Contains("1") ||
                                            list.Keys.Contains(sheetname.Substring(sheetname.Length - 1)))
                                            continue;
                                        swModel.Extension.SelectByID2(sheetname, "SHEET", 0, 0, 0, true, 0, null, 0);
                                    }
                                    swModel.DeleteSelection(true);
                                    ret = true;
                                }
                                break;
                            }
                        }
                        rd.Close();
                    }
                    oleDb.Close();
                }
            }
            return ret;
        }
Esempio n. 11
0
        private bool HideCompAndShowCross(ModelDoc2 swModel, string f1, string f2, out string comp1Name, out string comp2Name,
            out List<Component2> list)
        {
            bool ret = false;
            Component2 swComp1, swComp2;
            list = new List<Component2>();
            comp1Name = " ";
            comp2Name = " ";
            if (GetComponentByName(swModel, f1, false, out swComp1) &&
                GetComponentByName(swModel, f2, false, out swComp2))
            {
                var swComponents = new LinkedList<Component2>();
                comp1Name = swComp1.Name;
                comp2Name = swComp2.Name;
                if (comp1Name != comp2Name)
                {
                    var swConfig = (Configuration)swModel.GetActiveConfiguration();
                    if (swConfig != null)
                    {
                        var swRootComponent = (Component2)swConfig.GetRootComponent();

                        if (GetComponents(swRootComponent,
                                          swComponents, false, false))
                        {
                            foreach (var component in swComponents)
                            {
                                if ((component.Name != swComp1.Name) && (component.Name != swComp2.Name) &&
                                    (component.Visible == 1))
                                {
                                    component.Select(false);
                                    swModel.HideComponent2();
                                    swModel.ClearSelection();
                                    list.Add(component);
                                    ret = true;
                                }
                            }
                            return ret;
                        }
                    }
                }
            }
            return false;
        }
        public void CreateHeaterCenter(string heaterPathName)
        {
            ISketchPoint       startPoint = null;
            ISketchPoint       endPoint   = null;
            List <SegmentData> list       = new List <SegmentData>();
            List <SegmentData> list2      = new List <SegmentData>();
            List <SegmentData> list3      = new List <SegmentData>();
            List <SegmentData> list4      = new List <SegmentData>();

            _swApp.ActivateDoc(_swPartModel.GetTitle());
            _swPartModel.ShowNamedView2("*Front", 1);

            ISketchArc arc;
            double     length;

            list2.Clear();
            list.Clear();
            _swPartModel.Extension.SelectByID2(heaterPathName, "SKETCH", 0.0, 0.0, 0.0, true, 0, null, 0);
            _swPartModel.ViewZoomToSelection();
            ISelectionMgr iSelectionManager = _swPartModel.ISelectionManager;

            IFeature feature = iSelectionManager.GetSelectedObject6(1, 0);

            ISketch sketch = feature.GetSpecificFeature2();

            Array array = sketch.GetSketchSegments();

            Array array2 = sketch.GetSketchPoints2();

            foreach (ISketchSegment segment in array)
            {
                ISketchSegment segment2 = segment;
                segment2.Select(true);
                if (!segment2.ConstructionGeometry)
                {
                    if (segment2.GetType() == 0)
                    {
                        ISketchLine line = (ISketchLine)segment2;
                        startPoint = line.IGetStartPoint2();
                        endPoint   = line.IGetEndPoint2();
                    }
                    if (segment2.GetType() == 1)
                    {
                        arc        = (ISketchArc)segment2;
                        startPoint = arc.IGetStartPoint2();
                        endPoint   = arc.IGetEndPoint2();
                    }
                    SegmentData item = new SegmentData(segment2, startPoint, endPoint);
                    list.Add(item);
                }
                _swPartModel.ClearSelection2(true);
            }
            for (int i = 0; i < list.Count; i++)
            {
                int num9 = 0;
                list2.Add(list[0]);
                list.Remove(list[0]);
                for (int m = 0; m < list.Count; m++)
                {
                    list2[0].Segment.Select(false);
                    list[m].Segment.Select(false);
                    if ((Math.Round(list2[0].StartPoint.X, 5) == Math.Round(list[m].StartPoint.X, 5)) && (Math.Round(list2[0].StartPoint.Y, 5) == Math.Round(list[m].StartPoint.Y, 5)))
                    {
                        num9++;
                    }
                    if ((Math.Round(list2[0].EndPoint.X, 5) == Math.Round(list[m].EndPoint.X, 5)) && (Math.Round(list2[0].EndPoint.Y, 5) == Math.Round(list[m].EndPoint.Y, 5)))
                    {
                        num9++;
                    }
                    if ((Math.Round(list2[0].EndPoint.X, 5) == Math.Round(list[m].StartPoint.X, 5)) && (Math.Round(list2[0].EndPoint.Y, 5) == Math.Round(list[m].StartPoint.Y, 5)))
                    {
                        num9++;
                    }
                    if ((Math.Round(list2[0].StartPoint.X, 5) == Math.Round(list[m].EndPoint.X, 5)) && (Math.Round(list2[0].StartPoint.Y, 5) == Math.Round(list[m].EndPoint.Y, 5)))
                    {
                        num9++;
                    }
                    _swPartModel.ClearSelection2(true);
                    if (num9 == 2)
                    {
                        list.Add(list2[0]);
                        list2.Remove(list2[0]);
                        break;
                    }
                }
                if (num9 == 1)
                {
                    list2[0].Segment.Select(true);
                    break;
                }
            }
            int num = 0;

            for (int j = 0; j < list.Count; j++)
            {
                list2[num].Segment.Select(true);
                list[j].Segment.Select(false);
                if ((Math.Round(list2[num].StartPoint.X, 5) == Math.Round(list[j].StartPoint.X, 5)) && (Math.Round(list2[num].StartPoint.Y, 5) == Math.Round(list[j].StartPoint.Y, 5)))
                {
                    list2.Add(list[j]);
                    list.Remove(list[j]);
                    num++;
                    j = -1;
                }
                else if ((Math.Round(list2[num].EndPoint.X, 5) == Math.Round(list[j].EndPoint.X, 5)) && (Math.Round(list2[num].EndPoint.Y, 5) == Math.Round(list[j].EndPoint.Y, 5)))
                {
                    list2.Add(list[j]);
                    list.Remove(list[j]);
                    num++;
                    j = -1;
                }
                else if ((Math.Round(list2[num].EndPoint.X, 5) == Math.Round(list[j].StartPoint.X, 5)) && (Math.Round(list2[num].EndPoint.Y, 5) == Math.Round(list[j].StartPoint.Y, 5)))
                {
                    list2.Add(list[j]);
                    list.Remove(list[j]);
                    num++;
                    j = -1;
                }
                else if ((Math.Round(list2[num].StartPoint.X, 5) == Math.Round(list[j].EndPoint.X, 5)) && (Math.Round(list2[num].StartPoint.Y, 5) == Math.Round(list[j].EndPoint.Y, 5)))
                {
                    list2.Add(list[j]);
                    list.Remove(list[j]);
                    num++;
                    j = -1;
                }
            }
            _swPartModel.ClearSelection();
            _swPartModel.Extension.SelectByID2(heaterPathName, "SKETCH", 0.0, 0.0, 0.0, false, 0, null, 0);
            _swPartModel.EditSketch();
            foreach (ISketchPoint point3 in array2)
            {
                point3.Select(false);
                if (point3.Type == 1)
                {
                    _swPartModel.EditDelete();
                }
            }
            double num2 = 0.0;

            foreach (SegmentData data2 in list2)
            {
                data2.Segment.Select(false);
                length = data2.Segment.GetLength();
                num2  += length;
            }
            _swPartModel.ClearSelection();
            double num4 = num2 / 2.0;

            length = 0.0;
            int    num5 = 0;
            double num6 = 0.0;

            for (int k = 0; k < list2.Count; k++)
            {
                list2[k].Segment.Select(false);
                length += list2[k].Segment.GetLength();
                if (num4 < length)
                {
                    num5 = k;
                    double num7 = Math.Abs((double)(length - num4));
                    num6 = (list2[num5].Segment.GetLength() - num7) / list2[num5].Segment.GetLength();
                    break;
                }
            }
            _swPartModel.ClearSelection();
            if (list2[num5].Segment.GetType() == 0)
            {
                double num13 = 0.0;
                double x     = list2[num5].StartPoint.X;
                double y     = list2[num5].StartPoint.Y;
                double num16 = list2[num5].EndPoint.X;
                double num17 = list2[num5].EndPoint.Y;
                if ((Math.Round(num16, 6) == Math.Round(list2[num5 - 1].StartPoint.X, 6)) && (Math.Round(num17, 6) == Math.Round(list2[num5 - 1].StartPoint.Y, 6)))
                {
                    num16 = list2[num5].StartPoint.X;
                    num17 = list2[num5].StartPoint.Y;
                    x     = list2[num5].EndPoint.X;
                    y     = list2[num5].EndPoint.Y;
                }
                else if ((Math.Round(num16, 6) == Math.Round(list2[num5 - 1].EndPoint.X, 6)) && (Math.Round(num17, 6) == Math.Round(list2[num5 - 1].EndPoint.Y, 6)))
                {
                    num16 = list2[num5].StartPoint.X;
                    num17 = list2[num5].StartPoint.Y;
                    x     = list2[num5].EndPoint.X;
                    y     = list2[num5].EndPoint.Y;
                }
                double pointX = x + ((num16 - x) * num6);
                double pointY = y + ((num17 - y) * num6);
                _swPartModel.SetAddToDB(true);
                if (_swPartModel.CreatePoint2(pointX, pointY, 0.0) != null)
                {
                    _swPartModel.SketchAddConstraints("sgFixed");
                }
                if (x == num16)
                {
                    num13 = 1.5707963267948966;
                }
                if (y == num17)
                {
                    num13 = 3.1415926535897931;
                }
                if ((x != num16) && !(y == num17))
                {
                    num13 = Math.Atan((num17 - y) / (num16 - x));
                }
                if (num13 > 3.1415926535897931)
                {
                    num13 -= 3.1415926535897931;
                }
                ISketchSegment segment3 = _swPartModel.ICreateLine2(pointX + (0.005 * Math.Cos(num13 + 1.5707963267948966)), pointY + (0.005 * Math.Sin(num13 + 1.5707963267948966)), 0.0, pointX + (0.005 * Math.Cos(num13 + 4.71238898038469)), pointY + (0.005 * Math.Sin(num13 + 4.71238898038469)), 0.0);
                _swPartModel.SketchAddConstraints("sgFIXED");
                segment3.ConstructionGeometry = true;
                _swPartModel.SetAddToDB(false);
                _swPartModel.ClearSelection2(true);
                _swPartModel.InsertSketch2(true);
            }
            if (list2[num5].Segment.GetType() == 1)
            {
                arc        = (ISketchArc)list2[num5].Segment;
                startPoint = arc.IGetStartPoint2();
                endPoint   = arc.IGetEndPoint2();
                ISketchPoint point4      = arc.IGetCenterPoint2();
                int          rotationDir = arc.GetRotationDir();
                double       num21       = 0.0;
                double       num22       = 0.0;
                double       num23       = list2[num5].Segment.GetLength();
                double       radius      = arc.GetRadius();
                double       num25       = (num6 * num23) / radius;
                double       num26       = startPoint.X;
                double       num27       = startPoint.Y;
                double       num28       = endPoint.X;
                double       num29       = endPoint.Y;
                double       num30       = point4.X;
                double       num31       = point4.Y;
                if ((Math.Round(num28, 6) == Math.Round(list2[num5 - 1].StartPoint.X, 6)) && (Math.Round(num29, 6) == Math.Round(list2[num5 - 1].StartPoint.Y, 6)))
                {
                    num26       = endPoint.X;
                    num27       = endPoint.Y;
                    rotationDir = -1 * rotationDir;
                }
                else if ((Math.Round(num28, 6) == Math.Round(list2[num5 - 1].EndPoint.X, 6)) && (Math.Round(num29, 6) == Math.Round(list2[num5 - 1].EndPoint.Y, 6)))
                {
                    num26       = endPoint.X;
                    num27       = endPoint.Y;
                    rotationDir = -1 * rotationDir;
                }
                if ((num30 != num26) && !(num31 == num27))
                {
                    num21 = Math.Atan((num31 - num27) / (num30 - num26));
                }
                if (Math.Round(num30, 8) == Math.Round(num26, 8))
                {
                    if (Math.Round(num31, 8) > Math.Round(num27, 8))
                    {
                        num21 = 4.71238898038469;
                    }
                    else if (Math.Round(num31, 8) < Math.Round(num27, 8))
                    {
                        num21 = 1.5707963267948966;
                    }
                }
                else if (Math.Round(num31, 8) == Math.Round(num27, 8))
                {
                    if (Math.Round(num30, 8) > Math.Round(num26, 8))
                    {
                        num21 = 3.1415926535897931;
                    }
                    else if (Math.Round(num30, 8) < Math.Round(num26, 8))
                    {
                        if (rotationDir > 0)
                        {
                            num21 = 0.0;
                        }
                        else
                        {
                            num21 = 6.2831853071795862;
                        }
                    }
                }
                if ((Math.Round(num30, 8) < Math.Round(num26, 8)) && (Math.Round(num31, 8) < Math.Round(num27, 8)))
                {
                    num22 = num21 + (rotationDir * num25);
                }
                else if ((Math.Round(num30, 8) < Math.Round(num26, 8)) && (Math.Round(num31, 8) > Math.Round(num27, 8)))
                {
                    num22 = (6.2831853071795862 + num21) + (rotationDir * num25);
                }
                else if ((Math.Round(num30, 8) > Math.Round(num26, 8)) && (Math.Round(num31, 8) > Math.Round(num27, 8)))
                {
                    num22 = (3.1415926535897931 + num21) + (rotationDir * num25);
                }
                else if ((Math.Round(num30, 8) > Math.Round(num26, 8)) && (Math.Round(num31, 8) < Math.Round(num27, 8)))
                {
                    num22 = (3.1415926535897931 + num21) + (rotationDir * num25);
                }
                else if (Math.Round(num30, 8) == Math.Round(num26, 8))
                {
                    num22 = num21 + (rotationDir * num25);
                }
                else if (Math.Round(num31, 8) == Math.Round(num27, 8))
                {
                    num22 = num21 + (rotationDir * num25);
                }
                num22 = Math.Round(num22, 6);
                double num32  = num30 + (radius * Math.Cos(num22));
                double num33  = num31 + (radius * Math.Sin(num22));
                bool   flag29 = true;
                if (_swPartModel.Extension.SelectByID2("", "SKETCHPOINT", num32, num33, 0.0, false, 0, null, 0))
                {
                    ISketchPoint point5 = iSelectionManager.GetSelectedObject6(0, 1);

                    if ((point5 != null) && ((Math.Round(point5.X, 6) == Math.Round(num32, 6)) && (Math.Round(point5.Y, 6) == Math.Round(num33, 6))))
                    {
                        flag29 = false;
                    }
                }
                _swPartModel.SetAddToDB(true);
                if (flag29 && (_swPartModel.CreatePoint2(num32, num33, 0.0) != null))
                {
                    _swPartModel.SketchAddConstraints("sgFIXED");
                    _swPartModel.ICreateLine2(num30, num31, 0.0, num32, num33, 0.0).ConstructionGeometry = true;
                }
                _swPartModel.SetAddToDB(false);
                _swPartModel.ClearSelection2(true);
                _swPartModel.InsertSketch2(true);
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Создание головки
        /// </summary>
        public static void CreateHead(double headLength, SldWorks swApp, ModelDoc2 swModel, List <string> detailNames, string pathName)
        {
            var cutDistance = 0.003;
            var dAng        = 0.001;
            var dAng2       = 0.35;
            var dAng3       = 0.02;

            string modelName = pathName + "Головка.sldprt";

            swApp.NewPart();
            swModel = swApp.IActiveDoc2;

            swModel.Extension.SelectByID2("Спереди", "PLANE", 0, 0, 0, false, 0, null, 0);
            swModel.SketchManager.CreateCircleByRadius(0, 0, 0, cutDistance);
            swModel.FeatureManager.FeatureExtrusion2(true, false, false, 0, 0, headLength / 3, 0, false, false, false, false, _draftAngle, _draftAngle, false, false, false, false, true, true, true, 0, 0, false);

            swModel.Extension.SelectByID2("Спереди", "PLANE", 0, 0, 0, false, 0, null, 0);
            swModel.FeatureManager.InsertRefPlane(_firstConstraint, headLength / 3, 0, 0, 0, 0);
            swModel.ClearSelection2(true);

            swModel.Extension.SelectByID2("Спереди", "PLANE", 0, 0, 0, false, 0, null, 0);
            swModel.SketchManager.CreateCircleByRadius(0, 0, 0, _distanceExtrusion);

            swModel.FeatureManager.FeatureCut3(true, true, true, 0, 0, cutDistance, cutDistance, true, false, false, false, dAng2, dAng2, false, false, false, false, false, true, true, true, true, false, 0, 0, false);

            swModel.Extension.SelectByID2("Плоскость4", "PLANE", 0, 0, 0, false, 0, null, 0);
            swModel.SketchManager.CreateCircleByRadius(0, 0, 0, cutDistance);
            swModel.FeatureManager.FeatureExtrusion2(true, false, false, 0, 0, headLength / 6, 0, false, false, false, false, _draftAngle, _draftAngle, false, false, false, false, true, true, true, 0, 0, false);
            swModel.ClearSelection2(true);

            swModel.Extension.SelectByID2("Спереди", "PLANE", 0, 0, 0, false, 0, null, 0);
            swModel.FeatureManager.InsertRefPlane(_firstConstraint, headLength / 2, 0, 0, 0, 0);
            swModel.ClearSelection2(true);

            swModel.Extension.SelectByID2("Плоскость5", "PLANE", 0, 0, 0, false, 0, null, 0);
            swModel.SketchManager.CreateCircleByRadius(0, 0, 0, _distanceExtrusion);
            swModel.FeatureManager.FeatureCut3(true, true, false, 0, 0, cutDistance, cutDistance, true, false, false, false, dAng2, dAng2, false, false, false, false, false, true, true, true, true, false, 0, 0, false);
            swModel.ClearSelection2(true);

            swModel.Extension.SelectByID2("Плоскость5", "PLANE", 0, 0, 0, false, 0, null, 0);
            swModel.SketchManager.CreateCircleByRadius(0, 0, 0, _distanceExtrusion);
            swModel.FeatureManager.FeatureExtrusion2(true, false, false, 0, 0, headLength / 2, 0, false, false, false, false, _draftAngle, _draftAngle, false, false, false, false, true, true, true, 0, 0, false);

            // Вырез по центру
            swModel.Extension.SelectByID2("Спереди", "PLANE", 0, 0, 0, false, 0, null, 0);
            swModel.SketchManager.CreateCircleByRadius(0, 0, 0, 0.001);
            swModel.FeatureManager.FeatureCut3(true, false, true, 0, 0, 0.06, 0.06, false, false, false, false, dAng3, dAng3, false, false, false, false, false, true, true, true, true, false, 0, 0, false);

            // Создание гайки для головки
            swModel.Extension.SelectByID2("Спереди", "PLANE", 0, 0, 0, false, 0, null, 0);
            swModel.FeatureManager.InsertRefPlane(_firstConstraint, headLength, 0, 0, 0, 0);
            swModel.ClearSelection2(true);

            swModel.Extension.SelectByID2("Плоскость6", "PLANE", 0, 0, 0, false, 0, null, 0);
            swModel.SketchManager.CreateCircleByRadius(0, 0, 0, 0.004);
            swModel.Extension.SelectByID2("Arc1", "SKETCHSEGMENT", 0, 0, 0, false, 0, null, 0);
            swModel.FeatureManager.FeatureExtrusion2(true, false, true, 0, 0, dAng, 0, false, false, false, false, _draftAngle, _draftAngle, false, false, false, false, true, true, true, 0, 0, false);
            swModel.ClearSelection();

            swModel.SaveAs(modelName);
            detailNames.Add(modelName);
        }
Esempio n. 14
0
        /// <summary>
        /// 当结果返回True 时 表示两个零件不一样,结果false时表示 两个零件一样
        /// </summary>
        /// <param name="sendTocustomer"></param>
        /// <param name="localModel"></param>
        /// <returns></returns>
        public bool CheckTwoParts(string sendTocustomer, string localModel)
        {
            bool different1 = false;

            bool different2 = false;

            swApp = ConnectToSolidWorks();
            // swApp = ConnectToSolidWorks();

            //加载参考关系零件
            swApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swLoadExternalReferences, (int)swLoadExternalReferences_e.swLoadExternalReferences_ChangedOnly);

            //后台模式 前台不显示界面

            swApp.EnableBackgroundProcessing = true;

            //禁止记录文件路径
            swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swLockRecentDocumentsList, true);

            swApp.OpenDoc(localModel, 1);

            swApp.OpenDoc(sendTocustomer, 1);

            ModelDoc2 swModel = (ModelDoc2)swApp.ActiveDoc;

            string LocalPath = System.IO.Directory.GetParent(swModel.GetPathName()).ToString();

            string tempAssembly = swApp.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplateAssembly);

            AssemblyDoc assemblyDoc = (AssemblyDoc)swApp.NewDocument(tempAssembly, 0, 0, 0);

            Component2 insertComponentSendtoCustomer = assemblyDoc.AddComponent5(sendTocustomer, 0, "", false, "", 0, 0, 0);
            Component2 insertComponentLocal          = assemblyDoc.AddComponent5(localModel, 0, "", false, "", 0, 0, 0);

            string sendSelect  = insertComponentSendtoCustomer.GetSelectByIDString();
            string localSelect = insertComponentLocal.GetSelectByIDString();

            swModel = (ModelDoc2)swApp.ActiveDoc;

            bool b1 = swModel.Extension.SelectByID2("Point1@Origin" + "@" + sendSelect, "EXTSKETCHPOINT", 0, 0, 0, false, 0, null, 0);
            bool b2 = swModel.Extension.SelectByID2("Point1@Origin" + "@" + localSelect, "EXTSKETCHPOINT", 0, 0, 0, true, 0, null, 0);
            int  longstatus;

            Mate2 mate2 = assemblyDoc.AddMate5(20, -1, false, 0, 0.001, 0.001, 0.001, 0.001, 0, 0, 0, false, false, 0, out longstatus);

            swModel = (ModelDoc2)swApp.ActiveDoc;

            swModel.SaveAs(LocalPath + @"\TopCheck.sldasm");

            //不显示特征树
            //swModel.Extension.HideFeatureManager(true);

            swModel.ClearSelection2(true);
            //swModel.FeatureManager.ViewFeatures = false;

            //FeatureManager featureManager = swModel.FeatureManager;

            //禁用特征树
            //featureManager.EnableFeatureTree = false;

            // swModel.FeatureManager.EnableFeatureTreeWindow = false;

            #region first join

            Component2        sendToCustomerBodies     = default(Component2);
            List <Component2> sendToCustomerBodiesList = new List <Component2>();

            object swFaceOrPlane = default(object);

            assemblyDoc.InsertNewVirtualPart(swFaceOrPlane, out sendToCustomerBodies);

            sendToCustomerBodies.Select(true);

            assemblyDoc.FixComponent();
            sendToCustomerBodies.Select(true);
            assemblyDoc.EditPart();

            insertComponentSendtoCustomer.Select(false);
            insertComponentLocal.Select(true);

            assemblyDoc.InsertJoin2(false, false);

            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModel.BreakAllExternalReferences();

            object[] splits = sendToCustomerBodies.Name2.Split('^');
            // string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + splits[0];
            string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + "localBodies-1";

            ModelDoc2 compModel = default(ModelDoc2);
            compModel = (ModelDoc2)sendToCustomerBodies.GetModelDoc();

            if (compModel.GetType() == (int)swDocumentTypes_e.swDocPART)
            {
                compName = compName + ".sldprt";
            }
            else
            {
                compName = compName + ".sldasm";
            }

            bool ret;

            ret = sendToCustomerBodies.SaveVirtualComponent(compName);

            sendToCustomerBodiesList.Add(sendToCustomerBodies);

            insertComponentSendtoCustomer.Select(false);

            swModel = (ModelDoc2)sendToCustomerBodies.GetModelDoc2();

            #region 获取所有零件中的零件,每一个实体做一次反切

            List <string> bodyNamesCustomer = new List <string>();

            PartDoc swPart = null;
            object  vBody;
            swPart = (PartDoc)swModel;
            // Solid bodies
            object[] vBodyArr = null;
            Body2    swBody   = default(Body2);

            MathTransform swMathTrans = null;
            vBodyArr = (object[])swPart.GetBodies2((int)swBodyType_e.swSolidBody, true);

            if ((vBodyArr != null))
            {
                // Debug.Print("  Number of solid bodies: " + vBodyArr.Length);

                foreach (object vBody_loopVariable in vBodyArr)
                {
                    vBody  = vBody_loopVariable;
                    swBody = (Body2)vBody;

                    string[] vConfigName = null;
                    vConfigName = (string[])swModel.GetConfigurationNames();
                    string sMatDB   = "";
                    string sMatName = swBody.GetMaterialPropertyName("", out sMatDB);

                    //bRet = swBody.RemoveMaterialProperty((int)swInConfigurationOpts_e.swAllConfiguration, (vConfigName));

                    //Debug.Print("Body--> " + swBody.Name + " " + "");

                    bodyNamesCustomer.Add(swBody.Name);
                }
            }

            //如果实体数量大于1,则继续新建对应数量的join 实体。

            OnlyKeepNamedBody(bodyNamesCustomer[0], sendToCustomerBodies.GetSelectByIDString(), assemblyDoc, sendToCustomerBodies, insertComponentSendtoCustomer, ref different1);

            if (bodyNamesCustomer.Count > 1)
            {
                assemblyDoc.EditAssembly();

                for (int i = 0; i < bodyNamesCustomer.Count - 1; i++)
                {
                    Component2 returnpart = default(Component2);
                    var        partSelect = CreateNewJoinPart(assemblyDoc, insertComponentSendtoCustomer, insertComponentLocal, swModel, "localBodies-" + (i + 2), out returnpart);
                    sendToCustomerBodiesList.Add(returnpart);

                    OnlyKeepNamedBody(bodyNamesCustomer[i + 1], partSelect, assemblyDoc, returnpart, insertComponentSendtoCustomer, ref different1);
                }
            }
            // boolstatus = Part.Extension.SelectByID2("Join1[2]@localBodies-1@TopCheck", "SOLIDBODY", 0, 0, 0, True, 0, Nothing, 0)
            //Dim myFeature As Object
            //Set myFeature = Part.FeatureManager.InsertDeleteBody2(True)

            #endregion 获取所有零件中的零件,每一个实体做一次反切

            //assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1);
            Feature theFeature;

            //theFeature = swModel.FeatureByPositionReverse(0);

            //if (theFeature.Name.Contains("Cavity"))
            //{
            //    //theFeature.Select(true);

            //    swModel = (ModelDoc2)swApp.ActiveDoc;

            //    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + sendToCustomerBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

            //    swModel.BreakAllExternalReferences();
            //    different1 = true;
            //    //JoinPart1 留下的: 发给客户的没有此部分。 而本地零件中有
            //}
            //else
            //{
            //    //无法Join时表示 全切了。
            //    swModel = (ModelDoc2)swApp.ActiveDoc;

            //    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + sendToCustomerBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

            //    swModel.EditSuppress();
            //}
            //sendToCustomerBodies.Select(true);

            assemblyDoc.EditAssembly();

            #endregion first join

            #region sercond join2

            Component2        localBodies     = default(Component2);
            List <Component2> LocalBodiesList = new List <Component2>();
            assemblyDoc.InsertNewVirtualPart(swFaceOrPlane, out localBodies);

            localBodies.Select(true);

            assemblyDoc.FixComponent();
            localBodies.Select(true);
            assemblyDoc.EditPart();

            insertComponentSendtoCustomer.Select(false);
            insertComponentLocal.Select(true);

            assemblyDoc.InsertJoin2(false, false);

            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModel.BreakAllExternalReferences();

            splits = localBodies.Name2.Split('^');
            // string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + splits[0];
            compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + "sendToCustomerBodies-1";

            compModel = default(ModelDoc2);
            compModel = (ModelDoc2)localBodies.GetModelDoc();

            if (compModel.GetType() == (int)swDocumentTypes_e.swDocPART)
            {
                compName = compName + ".sldprt";
            }
            else
            {
                compName = compName + ".sldasm";
            }

            ret = localBodies.SaveVirtualComponent(compName);
            LocalBodiesList.Add(localBodies);
            insertComponentLocal.Select(false);

            swModel = (ModelDoc2)localBodies.GetModelDoc2();

            #region 获取所有零件中的零件,每一个实体做一次反切

            List <string> bodyNamesLocal = new List <string>();

            PartDoc swPart2 = null;
            object  vBody2;
            swPart2 = (PartDoc)swModel;
            // Solid bodies
            object[] vBodyArr2 = null;
            Body2    swBody2   = default(Body2);

            MathTransform swMathTrans2 = null;
            vBodyArr2 = (object[])swPart2.GetBodies2((int)swBodyType_e.swSolidBody, true);

            if ((vBodyArr2 != null))
            {
                // Debug.Print("  Number of solid bodies: " + vBodyArr.Length);

                foreach (object vBody_loopVariable in vBodyArr2)
                {
                    vBody2  = vBody_loopVariable;
                    swBody2 = (Body2)vBody2;

                    string[] vConfigName = null;
                    vConfigName = (string[])swModel.GetConfigurationNames();
                    string sMatDB   = "";
                    string sMatName = swBody2.GetMaterialPropertyName("", out sMatDB);

                    //bRet = swBody.RemoveMaterialProperty((int)swInConfigurationOpts_e.swAllConfiguration, (vConfigName));

                    bodyNamesLocal.Add(swBody2.Name);
                }
            }

            //如果实体数量大于1,则继续新建对应数量的join 实体。

            OnlyKeepNamedBody(bodyNamesLocal[0], localBodies.GetSelectByIDString(), assemblyDoc, localBodies, insertComponentLocal, ref different2);

            if (bodyNamesLocal.Count > 1)
            {
                assemblyDoc.EditAssembly();

                for (int i = 0; i < bodyNamesLocal.Count - 1; i++)
                {
                    Component2 returnpart = default(Component2);
                    var        partSelect = CreateNewJoinPart(assemblyDoc, insertComponentSendtoCustomer, insertComponentLocal, swModel, "sendToCustomerBodies-" + (i + 2), out returnpart);
                    LocalBodiesList.Add(returnpart);
                    OnlyKeepNamedBody(bodyNamesLocal[i + 1], partSelect, assemblyDoc, returnpart, insertComponentLocal, ref different2);
                }
            }
            // boolstatus = Part.Extension.SelectByID2("Join1[2]@localBodies-1@TopCheck", "SOLIDBODY", 0, 0, 0, True, 0, Nothing, 0)
            //Dim myFeature As Object
            //Set myFeature = Part.FeatureManager.InsertDeleteBody2(True)

            #endregion 获取所有零件中的零件,每一个实体做一次反切

            //assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1);

            //theFeature = swModel.FeatureByPositionReverse(0);

            //swModel = (ModelDoc2)localBodies.GetModelDoc2();

            //theFeature = swModel.FeatureByPositionReverse(0);

            //if (theFeature.Name.Contains("Cavity"))
            //{
            //    //theFeature.Select(true);

            //    swModel = (ModelDoc2)swApp.ActiveDoc;

            //    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + localBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

            //    swModel.BreakAllExternalReferences();
            //    different2 = true;
            //    //JoinPart2 留下的: 发给客户的有此部分。 而本地零件中没有
            //}
            //else
            //{
            //    //无法Join时表示 全切了。
            //    swModel = (ModelDoc2)swApp.ActiveDoc;

            //    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + sendToCustomerBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

            //    swModel.EditSuppress();
            //}

            //localBodies.Select(true);

            //assemblyDoc.EditAssembly();

            #endregion sercond join2

            #region joinPartPublic

            Component2 publicBodies = default(Component2);

            assemblyDoc.InsertNewVirtualPart(swFaceOrPlane, out publicBodies);

            publicBodies.Select(true);

            assemblyDoc.FixComponent();
            publicBodies.Select(true);
            assemblyDoc.EditPart();

            insertComponentSendtoCustomer.Select(false);
            insertComponentLocal.Select(true);

            assemblyDoc.InsertJoin2(false, false);

            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModel.BreakAllExternalReferences();

            splits = publicBodies.Name2.Split('^');
            // string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + splits[0];
            compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + "publicBodies";

            compModel = default(ModelDoc2);
            compModel = (ModelDoc2)publicBodies.GetModelDoc();

            if (compModel.GetType() == (int)swDocumentTypes_e.swDocPART)
            {
                compName = compName + ".sldprt";
            }
            else
            {
                compName = compName + ".sldasm";
            }

            ret = publicBodies.SaveVirtualComponent(compName);

            swModel.ClearSelection();

            foreach (var item in sendToCustomerBodiesList)
            {
                item.Select(false);

                assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1);

                theFeature = (Feature)swModel.FeatureByPositionReverse(0);

                swModel    = (ModelDoc2)publicBodies.GetModelDoc2();
                theFeature = (Feature)swModel.FeatureByPositionReverse(0);

                if (theFeature.Name.Contains("Cavity"))
                {
                    //theFeature.Select(true);

                    swModel = (ModelDoc2)swApp.ActiveDoc;

                    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + publicBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

                    swModel.BreakAllExternalReferences();

                    //joinPartPublic 留下的: 发给客户的有此部分。 而本地零件中没有
                }
                else
                {
                }
            }
            foreach (var item in LocalBodiesList)
            {
                item.Select(false);

                assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1);

                theFeature = (Feature)swModel.FeatureByPositionReverse(0);

                swModel    = (ModelDoc2)publicBodies.GetModelDoc2();
                theFeature = (Feature)swModel.FeatureByPositionReverse(0);

                if (theFeature.Name.Contains("Cavity"))
                {
                    //theFeature.Select(true);

                    swModel = (ModelDoc2)swApp.ActiveDoc;

                    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + publicBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

                    swModel.BreakAllExternalReferences();

                    //joinPartPublic 留下的: 发给客户的有此部分。 而本地零件中没有
                }
                else
                {
                }
            }

            publicBodies.Select(true);

            assemblyDoc.EditAssembly();

            #endregion joinPartPublic

            foreach (var item in sendToCustomerBodiesList)
            {
                item.Select(false);
                setColour(Color.Red);
            }
            foreach (var item in LocalBodiesList)
            {
                item.Select(false);
                setColour(Color.Blue);
            }

            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModel.ClearSelection2(true);

            insertComponentLocal.Select(false);
            insertComponentSendtoCustomer.Select(true);
            swModel.HideComponent2();
            swModel.ClearSelection2(true);

            publicBodies.Select(false);
            assemblyDoc.SetComponentTransparent(true);
            setColour(Color.Green);
            swModel.EditRebuild3();
            swModel.Save();

            swModel.SaveAs3(LocalPath + @"\01_CheckResult.sldprt", 0, 0);

            swApp.CloseDoc("TopCheck.sldasm");
            swApp.CloseAllDocuments(true);
            swApp.OpenDoc(LocalPath + @"\01_CheckResult.sldprt", 1);
            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModel.ShowNamedView2("*Isometric", 7);

            swModel.ViewZoomtofit2();

            swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swLockRecentDocumentsList, false);
            try
            {
                System.IO.File.Delete(LocalPath + @"\TopCheck.sldasm");
                System.IO.File.Delete(LocalPath + @"\localBodies.sldprt");
                System.IO.File.Delete(LocalPath + @"\sendToCustomerBodies.sldprt");
                System.IO.File.Delete(LocalPath + @"\publicBodies.sldprt");
            }
            catch (Exception)
            {
            }

            //第二次反向剪切

            swApp.CloseDoc(sendTocustomer);
            swApp.CloseDoc(localModel);

            swModel.FeatureManager.EnableFeatureTree = true;

            swApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swLoadExternalReferences, 2);

            if (different1 == false && different2 == false)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
Esempio n. 15
0
        private void button1_Click_1(object sender, EventArgs e)
        {
            // preventing empty fields
            if (string.IsNullOrWhiteSpace(textBox1.Text) || string.IsNullOrWhiteSpace(textBox2.Text) ||
                string.IsNullOrWhiteSpace(textBox3.Text))
            {
                MessageBox.Show("Enter all values", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            double x1 = Convert.ToDouble(textBox1.Text);
            double x2 = Convert.ToDouble(textBox2.Text);
            double x3 = Convert.ToDouble(textBox3.Text);

            // checking detail size condition
            if (x2 >= 42 - 5)
            {
                MessageBox.Show("Width of base can not exceed or equal the diameter of the cylinder",
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (x2 < 10)
            {
                MessageBox.Show("Width of base can not be less than the width of the rib",
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (x1 <= 42)
            {
                MessageBox.Show("Length of base can not be less than or equal " +
                                "to the diameter of the cylinder!",
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (x3 <= 19)
            {
                MessageBox.Show("Height of detail can not be less than or equal " +
                                "to the length of the inner section of the cylinder!",
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // m to mm conversion
            x1 = -x1 / 1000;
            x2 = -x2 / 1000;
            x3 = -x3 / 1000;

            // Opening SW 2016
            Guid   Guid1     = new Guid("F16137AD-8EE8-4D2A-8CAC-DFF5D1F67522");
            object processSW = System.Activator.CreateInstance(System.Type.GetTypeFromCLSID(Guid1));

            swApp         = (SldWorks)processSW;
            swApp.Visible = true;

            // selection of detail modeling mode
            swApp.NewPart();

            ModelDoc2 swDoc      = null;
            bool      boolstatus = false;

            swDoc = ((ModelDoc2)(swApp.ActiveDoc));

            // selecting a sketch from above, creating a circle and extruding it
            boolstatus = swDoc.Extension.SelectByID2("Top Plane", "PLANE", 0, 0, 0, false, 0, null, 0);
            swDoc.SketchManager.InsertSketch(true);
            swDoc.ClearSelection2(true);
            SketchSegment skSegment = null;

            skSegment = ((SketchSegment)(swDoc.SketchManager.CreateCircle(0, 0, 0, -0.021, 0, 0)));
            swDoc.ShowNamedView2("*Trimetric", 8);
            swDoc.ClearSelection2(true);
            boolstatus = swDoc.Extension.SelectByID2("Arc1", "SKETCHSEGMENT", 0, 0, 0, false, 0, null, 0);
            Feature myFeature = null;

            myFeature = ((Feature)(swDoc.FeatureManager.FeatureExtrusion2(true, false, false, 0, 0, Abs(x3),
                                                                          0.01, false, false, false, false, 0.017453292519943334, 0.017453292519943334,
                                                                          false, false, false, false, true, true, true, 0, 0, false)));
            swDoc.ISelectionManager.EnableContourSelection = false;

            // selecting a sketch from above, creating a base (rectangle), adding lines of contact with a circle
            boolstatus = swDoc.Extension.SelectByID2("Top Plane", "PLANE", 0, 0, 0, false, 0, null, 0);
            swDoc.SketchManager.InsertSketch(true);
            swDoc.ClearSelection2(true);
            boolstatus = swDoc.Extension.SetUserPreferenceToggle(((int)(swUserPreferenceToggle_e.swSketchAddConstToRectEntity)),
                                                                 ((int)(swUserPreferenceOption_e.swDetailingNoOptionSpecified)), true);
            boolstatus = swDoc.Extension.SetUserPreferenceToggle(((int)(swUserPreferenceToggle_e.swSketchAddConstLineDiagonalType)),
                                                                 ((int)(swUserPreferenceOption_e.swDetailingNoOptionSpecified)), true);
            Array vSkLines = null;

            vSkLines = ((Array)(swDoc.SketchManager.CreateCenterRectangle(0, 0, 0, x1 / 2, x2 / 2, 0)));
            swDoc.ShowNamedView2("*Top", 5);
            swDoc.ClearSelection2(true);
            skSegment = ((SketchSegment)(swDoc.SketchManager.CreateLine(x1 / 2, Abs(x2 / 2), 0.000000, 0.000000, 0.021000, 0.000000)));
            skSegment = ((SketchSegment)(swDoc.SketchManager.CreateLine(0.000000, 0.021000, 0.000000, Abs(x1 / 2), Abs(x2 / 2), 0.000000)));
            skSegment = ((SketchSegment)(swDoc.SketchManager.CreateLine(x1 / 2, x2 / 2, 0.000000, 0.000000, -0.021000, 0.000000)));
            skSegment = ((SketchSegment)(swDoc.SketchManager.CreateLine(0.000000, -0.021000, 0.000000, Abs(x1 / 2), x2 / 2, 0.000000)));
            swDoc.ClearSelection2(true);

            // cutting of internal lines for extrusion
            boolstatus = swDoc.Extension.SelectByID2("Line1", "SKETCHSEGMENT", -0.0065662815082737427, 0, x2 / 2, false, 2, null, 0);
            boolstatus = swDoc.SketchManager.SketchTrim(4, 0, 0, 0);
            boolstatus = swDoc.Extension.SelectByID2("Line3", "SKETCHSEGMENT", -0.0046846865546491534, 0, Abs(x2 / 2), false, 2, null, 0);
            boolstatus = swDoc.SketchManager.SketchTrim(4, 0, 0, 0);
            swDoc.ClearSelection2(true);

            // extruding base
            myFeature = ((Feature)(swDoc.FeatureManager.FeatureExtrusion2(true, false, false, 0, 0, 0.01, Abs(x3),
                                                                          false, false, false, false, 0.017453292519943334, 0.017453292519943334,
                                                                          false, false, false, false, true, true, true, 0, 0, false)));
            swDoc.ISelectionManager.EnableContourSelection = false;

            // selecting a sketch from above, creating an edge (rectangle) and extruding it
            boolstatus = swDoc.Extension.SelectByID2("Top Plane", "PLANE", 0, 0, 0, false, 0, null, 0);
            swDoc.SketchManager.InsertSketch(true);
            swDoc.ClearSelection2(true);
            boolstatus = swDoc.Extension.SetUserPreferenceToggle(((int)(swUserPreferenceToggle_e.swSketchAddConstToRectEntity)),
                                                                 ((int)(swUserPreferenceOption_e.swDetailingNoOptionSpecified)), true);
            boolstatus = swDoc.Extension.SetUserPreferenceToggle(((int)(swUserPreferenceToggle_e.swSketchAddConstLineDiagonalType)),
                                                                 ((int)(swUserPreferenceOption_e.swDetailingNoOptionSpecified)), true);
            vSkLines = ((Array)(swDoc.SketchManager.CreateCenterRectangle(0, 0, 0, x1 / 2, -0.005, 0)));
            swDoc.ClearSelection2(true);
            boolstatus = swDoc.Extension.SelectByID2("Line5", "SKETCHSEGMENT", 0, 0, 0, false, 0, null, 0);
            boolstatus = swDoc.Extension.SelectByID2("Line6", "SKETCHSEGMENT", 0, 0, 0, true, 0, null, 0);
            boolstatus = swDoc.Extension.SelectByID2("Point1", "SKETCHPOINT", 0, 0, 0, true, 0, null, 0);
            boolstatus = swDoc.Extension.SelectByID2("Line2", "SKETCHSEGMENT", 0, 0, 0, true, 0, null, 0);
            boolstatus = swDoc.Extension.SelectByID2("Line1", "SKETCHSEGMENT", 0, 0, 0, true, 0, null, 0);
            boolstatus = swDoc.Extension.SelectByID2("Line4", "SKETCHSEGMENT", 0, 0, 0, true, 0, null, 0);
            boolstatus = swDoc.Extension.SelectByID2("Line3", "SKETCHSEGMENT", 0, 0, 0, true, 0, null, 0);
            myFeature  = ((Feature)(swDoc.FeatureManager.FeatureExtrusion2(true, false, false, 0, 0, Abs(x3), 0.01,
                                                                           false, false, false, false, 0.017453292519943334, 0.017453292519943334,
                                                                           false, false, false, false, true, true, true, 0, 0, false)));
            swDoc.ISelectionManager.EnableContourSelection = false;

            // approximation
            swDoc.ViewZoomtofit2();
            swDoc.ViewZoomtofit2();
            swDoc.ViewZoomtofit2();

            // selection of a frontal sketch, creation of lines for diagonal cutting of an edge in height
            boolstatus = swDoc.Extension.SelectByID2("Front Plane", "PLANE", 0, 0, 0, false, 0, null, 0);
            swDoc.SketchManager.InsertSketch(true);
            swDoc.ClearSelection2(true);
            skSegment = null;
            skSegment = ((SketchSegment)(swDoc.SketchManager.CreateLine(x1 / 2, 0.010000, 0.000000, -0.020396, Abs(x3), 0.000000)));
            swDoc.ClearSelection2(true);
            boolstatus = swDoc.Extension.SelectByID2("Line1", "SKETCHSEGMENT", 0, 0, 0, false, 0, null, 0);
            myFeature  = ((Feature)(swDoc.FeatureManager.FeatureCut3(false, false, false, 1, 1, +x3 - 10, +x3 - 10,
                                                                     false, false, false, false, 0.017453292519943334, 0.017453292519943334,
                                                                     false, false, false, false, false, true, true, true, true, false, 0, 0, false)));
            swDoc.ISelectionManager.EnableContourSelection = false;

            // selection of frontal view, creation of the second line for diagonal cutting of the edge in height
            boolstatus = swDoc.Extension.SelectByID2("Front Plane", "PLANE", 0, 0, 0, false, 0, null, 0);
            swDoc.SketchManager.InsertSketch(true);
            swDoc.ClearSelection2(true);
            skSegment = ((SketchSegment)(swDoc.SketchManager.CreateLine(Abs(x1 / 2), 0.010000, 0.000000, 0.020396, Abs(x3), 0.000000)));
            swDoc.ClearSelection2(true);
            boolstatus = swDoc.Extension.SelectByID2("Line1", "SKETCHSEGMENT", 0, 0, 0, false, 0, null, 0);
            myFeature  = ((Feature)(swDoc.FeatureManager.FeatureCut3(false, true, false, 1, 1, Abs(x3) - 10, Abs(x3) - 10,
                                                                     false, false, false, false, 0.017453292519943334, 0.017453292519943334,
                                                                     false, false, false, false, false, true, true, true, true, false, 0, 0, false)));
            swDoc.ISelectionManager.EnableContourSelection = false;

            // selecting top view, sketch top, creating a circle for the inner notch of the cylinder
            swDoc.ShowNamedView2("*Top", 5);
            swDoc.ClearSelection2(true);
            boolstatus = swDoc.Extension.SelectByID2("Top Plane", "PLANE", 0, 0, 0, false, 0, null, 0);
            swDoc.SketchManager.InsertSketch(true);
            swDoc.ClearSelection2(true);
            swDoc.ClearSelection(false)
            skSegment = null;
            skSegment = ((SketchSegment)(swDoc.SketchManager.CreateCircle(0.000000, 0.000000, 0.000000, -0.016, 0.000000, 0.000000)));
            swDoc.ClearSelection2(true);
            boolstatus = swDoc.Extension.SelectByID2("Arc1", "SKETCHSEGMENT", 0, 0, 0, false, 0, null, 0);
            myFeature  = null;
            myFeature  = ((Feature)(swDoc.FeatureManager.FeatureCut3(true, false, true, 1, 0, 0.01, 0.01,
                                                                     false, false, false, false, 0.017453292519943334, 0.017453292519943334,
                                                                     false, false, false, false, false, true, true, true, true, false, 0, 0, false)));
            swDoc.ISelectionManager.EnableContourSelection = false;

            // filling the circle with the same radius for the cutout 17 mm below
            boolstatus = swDoc.Extension.SelectByID2("Top Plane", "PLANE", 0, 0, 0, false, 0, null, 0);
            swDoc.SketchManager.InsertSketch(true);
            swDoc.ClearSelection2(true);
            skSegment = ((SketchSegment)(swDoc.SketchManager.CreateCircle(0.000000, 0.000000, 0.000000, -0.016, 0.000000, 0.000000)));
            swDoc.ClearSelection2(true);
            boolstatus = swDoc.Extension.SelectByID2("Arc1", "SKETCHSEGMENT", 0, 0, 0, false, 0, null, 0);
            myFeature  = ((Feature)(swDoc.FeatureManager.FeatureExtrusion2(true, false, false, 0, 0, 0.017000000000000001,
                                                                           0.01, false, false, false, false, 0.017453292519943334, 0.017453292519943334,
                                                                           false, false, false, false, true, true, true, 0, 0, false)));
            swDoc.ISelectionManager.EnableContourSelection = false;

            // creating a circle of smaller radius for another cutout
            boolstatus = swDoc.Extension.SelectByID2("Top Plane", "PLANE", 0, 0, 0, false, 0, null, 0);
            swDoc.SketchManager.InsertSketch(true);
            swDoc.ClearSelection2(true);
            skSegment = ((SketchSegment)(swDoc.SketchManager.CreateCircle(0.000000, 0.000000, 0.000000, -0.009, 0.000000, 0.000000)));
            swDoc.ClearSelection2(true);
            boolstatus = swDoc.Extension.SelectByID2("Arc1", "SKETCHSEGMENT", 0, 0, 0, false, 0, null, 0);
            myFeature  = ((Feature)(swDoc.FeatureManager.FeatureCut3(true, false, true, 1, 0, 0.017000000000000001,
                                                                     0.017000000000000001, false, false, false, false, 0.017453292519943334, 0.017453292519943334,
                                                                     false, false, false, false, false, true, true, true, true, false, 0, 0, false)));
            swDoc.ISelectionManager.EnableContourSelection = false;
        }