Ejemplo n.º 1
0
        checkForEntityatPoint(Point3d pnt3d, ObjectId idObj, Type type)
        {
            bool match = false;

            TypedValue[] TVs = new TypedValue[1];
            TVs.SetValue(new TypedValue((int)DxfCode.Start, RXClass.GetClass(type).DxfName), 0);
            SelectionFilter FILTER = new SelectionFilter(TVs);

            PromptSelectionResult PSR = BaseObjs._editor.SelectCrossingWindow(pnt3d, pnt3d, FILTER);

            if (PSR.Status == PromptStatus.OK)
            {
                ObjectId[] ids = PSR.Value.GetObjectIds();

                foreach (ObjectId id in ids)
                {
                    if (id == idObj)
                    {
                        match = true;
                        break;
                    }
                }
            }
            return(match);
        }
Ejemplo n.º 2
0
        public static ObjectIdCollection GetAll3DFaceEntities()
        {
            Document mdiActiveDocument = Application.DocumentManager.MdiActiveDocument;
            Editor   editor            = mdiActiveDocument.Editor;

            TypedValue[] array  = new TypedValue[1];
            TypedValue[] array2 = array;
            int          num    = 0;
            TypedValue   typedValue;

            typedValue..ctor(0, "3DFACE");
            array2[num] = typedValue;
            TypedValue[]          array3                = array;
            SelectionFilter       selectionFilter       = new SelectionFilter(array3);
            PromptSelectionResult promptSelectionResult = editor.SelectAll(selectionFilter);
            ObjectIdCollection    result;

            if (promptSelectionResult.Status == 5100)
            {
                result = new ObjectIdCollection(promptSelectionResult.Value.GetObjectIds());
            }
            else
            {
                result = new ObjectIdCollection();
            }
            return(result);
        }
        public static SelectionSet Aecc_Material(string message)
        {
            Document acDoc   = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;
            Editor   ed      = acDoc.Editor;

            ed.WriteMessage(message);

            TypedValue[] acTypValAr = new TypedValue[1];
            acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "AECC_QUANTITY_TAKEOFF_MATERIAL_SECTION"), 0);

            // Assign the filter criteria to a SelectionFilter object
            SelectionFilter acSelFtr = new SelectionFilter(acTypValAr);

            // Request for objects to be selected in the drawing area
            PromptSelectionResult acSSPrompt;

            acSSPrompt = ed.GetSelection(acSelFtr);

            // If the prompt status is OK, objects were selected
            if (acSSPrompt.Status == PromptStatus.OK)
            {
                SelectionSet acSSet = acSSPrompt.Value;
                //Application.ShowAlertDialog("Number of objects selected: " + acSSet.Count.ToString());
                return(acSSet);
            }
            else
            {
                Application.ShowAlertDialog("Number of objects selected: 0");
            }
            return(null);
        }
Ejemplo n.º 4
0
        getEntityatPoint(Point3d pnt3d, string nameLayer = "*")
        {
            List <ObjectId> ids = null;

            TypedValue[] TVs = new TypedValue[6];
            TVs.SetValue(new TypedValue((int)DxfCode.Operator, "<OR"), 0);
            TVs.SetValue(new TypedValue((int)DxfCode.Start, "LINE"), 1);
            TVs.SetValue(new TypedValue((int)DxfCode.Start, "ARC"), 2);
            TVs.SetValue(new TypedValue((int)DxfCode.Start, "CIRCLE"), 3);
            TVs.SetValue(new TypedValue((int)DxfCode.Start, "POLYLINE"), 4);
            TVs.SetValue(new TypedValue((int)DxfCode.Operator, "OR>"), 5);
            //TVs.SetValue(new TypedValue((int)DxfCode.LayerName, nameLayer), 6);

            SelectionFilter       FILTER = new SelectionFilter(TVs);
            PromptSelectionResult PSR    = BaseObjs._editor.SelectCrossingWindow(pnt3d, pnt3d, FILTER);

            if (PSR.Status == PromptStatus.OK)
            {
                ObjectId[] idss = PSR.Value.GetObjectIds();
                foreach (ObjectId id in idss)
                {
                    ids.Add(id);
                }
            }
            return(ids);
        }
Ejemplo n.º 5
0
        public void TestBrepUnion()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            var tvs = new TypedValue[] { new TypedValue((int)DxfCode.Start, "LWPOLYLINE") };
            var selFilter = new SelectionFilter(tvs);
            var sel = ed.GetSelection(selFilter);
            if (sel.Status != PromptStatus.OK) return;

            using (var t = db.TransactionManager.StartTransaction())
            {
                var idsPls = sel.Value.GetObjectIds();
                List<Polyline> pls = new List<Polyline>();
                foreach (var item in idsPls)
                {
                    var pl = item.GetObject(OpenMode.ForRead) as Polyline;
                    pls.Add(pl);
                }

                Region union = BrepExtensions.Union(pls, null);

                //var cs = db.CurrentSpaceId.GetObject(OpenMode.ForWrite) as BlockTableRecord;
                //if (union != null)
                //{
                //    cs.AppendEntity(union);
                //    t.AddNewlyCreatedDBObject(union, true);
                //}

                t.Commit();
            }
        }
Ejemplo n.º 6
0
        public void MidPoint()
        {
            Document doc = GetDocument();
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            try
            {
                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    PromptSelectionOptions pso    = new PromptSelectionOptions();
                    TypedValue[]           tv     = new TypedValue[] { new TypedValue(0, "POINT") };
                    SelectionFilter        filter = new SelectionFilter(tv);

                    PromptSelectionResult psr = ed.GetSelection(filter);

                    if (psr.Status != PromptStatus.OK)
                    {
                        return;
                    }

                    var    res = psr.Value.GetObjectIds();
                    double x = 0, y = 0;
                    int    n = 0;
                    foreach (ObjectId objectId in res)
                    {
                        var pt = trans.GetObject(objectId, OpenMode.ForRead) as DBPoint;
                        if (pt != null)
                        {
                            n++;
                            x += pt.Position.X;
                            y += pt.Position.Y;
                        }
                    }
                    if (n == 0)
                    {
                        return;
                    }

                    var avgPt = new Point3d(x / n, y / n, 0);

                    BlockTable bt = trans.GetObject(db.BlockTableId
                                                    , OpenMode.ForRead) as BlockTable;

                    BlockTableRecord btr = trans.GetObject(
                        bt[BlockTableRecord.ModelSpace],
                        OpenMode.ForWrite) as BlockTableRecord;

                    DBPoint po = new DBPoint(avgPt);
                    btr.AppendEntity(po);
                    trans.AddNewlyCreatedDBObject(po, true);

                    trans.Commit();
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage(ex.Message + ex.StackTrace);
            }
        }
Ejemplo n.º 7
0
        private static ObjectId FetchFFLBlockID()
        {
            Document acDoc    = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            Database acCurrDb = acDoc.Database;
            Editor   acEditor = acDoc.Editor;

            // Create the selection filter for the FFL block
            TypedValue[] selFilterList = new TypedValue[2];
            selFilterList[0] = new TypedValue(0, "INSERT");
            selFilterList[1] = new TypedValue(2, "JPP_App_Outline*");

            SelectionFilter selFilter = new SelectionFilter(selFilterList);

            // Set prompt options and message
            PromptSelectionOptions selOptions = new PromptSelectionOptions();

            selOptions.MessageForAdding  = "Select FFL block: ";
            selOptions.SinglePickInSpace = true;
            selOptions.SingleOnly        = true;

            // Prompt user to select FFL add exposed brickwork
            PromptSelectionResult selResult = acEditor.GetSelection(selOptions, selFilter);

            ObjectId[] FFLToEditId = selResult.Value.GetObjectIds();
            ObjectId   blockId     = FFLToEditId[0];

            using (Transaction acTrans = acCurrDb.TransactionManager.StartTransaction())
            {
                try
                {
                    BlockTable       acBlkTbl    = acTrans.GetObject(acCurrDb.BlockTableId, OpenMode.ForRead) as BlockTable;
                    BlockReference   fflBlock    = acTrans.GetObject(blockId, OpenMode.ForRead) as BlockReference;
                    BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTbl[fflBlock.Name],
                                                                     OpenMode.ForRead) as BlockTableRecord;
                    if (acBlkTblRec == null)
                    {
                        acEditor.WriteMessage("\nError FFL block not found.");
                        acTrans.Commit();
                        return(ObjectId.Null);
                    }
                    // Check there is only one instance of this block reference in the drawing
                    if (acBlkTblRec.GetBlockReferenceIds(false, true).Count != 1)
                    {
                        acEditor.WriteMessage("\nError more than one instance of the block reference.");
                        acTrans.Commit();
                        return(ObjectId.Null);
                    }
                    acTrans.Commit();
                    return(fflBlock.ObjectId);
                }
                catch (Autodesk.AutoCAD.Runtime.Exception acException)
                {
                    Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog
                        ("The following exception was caught: \n" + acException.Message
                        + "\nError retrieving FFL Block Id!\n");
                    acTrans.Abort();
                    return(ObjectId.Null);
                }
            }
        }
Ejemplo n.º 8
0
        public void List()
        {
            Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            try
            {
                PromptSelectionOptions Opts = new PromptSelectionOptions();

                //Build	a filter list so that only block references	are	selected
                TypedValue[] filList = { new TypedValue((int)DxfCode.Start, "INSERT") };

                SelectionFilter       filter = new SelectionFilter(filList);
                PromptSelectionResult res    = ed.GetSelection(Opts, filter);

                //Do nothing if	selection is unsuccessful
                if (res.Status != PromptStatus.OK)
                {
                    return;
                }

                Autodesk.AutoCAD.EditorInput.SelectionSet SS = res.Value;
                ObjectId[] idArray = SS.GetObjectIds();

                //List the selection set
                EmployeeCount(idArray);
            }
            catch
            {
            }
        }
Ejemplo n.º 9
0
        buildSSetBase(TypedValue[] tvs, bool selectAll = true, string prompt = "")
        {
            SelectionFilter        filter = new SelectionFilter(tvs);
            PromptSelectionOptions pso    = new PromptSelectionOptions();

            pso.MessageForAdding  = prompt;
            pso.MessageForRemoval = "";

            PromptSelectionResult psr = null;

            if (selectAll)
            {
                psr = BaseObjs._editor.SelectAll(filter);
            }
            else
            {
                psr = BaseObjs._editor.GetSelection(pso, filter);
            }

            if (psr.Status == PromptStatus.OK)
            {
                return(psr.Value);
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 10
0
        static public void SelectDynamicBlocks()
        {
            var doc = Active.Document;
            var ed  = doc.Editor;
            var pso = new PromptStringOptions("\nName of dynamic block to search for");

            pso.AllowSpaces = true;
            var pr = ed.GetString(pso);

            if (pr.Status != PromptStatus.OK)
            {
                return;
            }
            string        blkName  = pr.StringResult;
            List <string> blkNames = new List <string>();

            blkNames.Add(blkName);
            var tr = doc.TransactionManager.StartTransaction();

            try
            {
                using (tr)
                {
                    var bt = (BlockTable)tr.GetObject(doc.Database.BlockTableId, OpenMode.ForRead);
                    // Start by getting access to our block, if it exists
                    if (!bt.Has(blkName))
                    {
                        ed.WriteMessage("\nCannot find block called \"{0}\".", blkName);
                        return;
                    }
                    // Get the anonymous block names
                    var btr = (BlockTableRecord)tr.GetObject(bt[blkName], OpenMode.ForRead);
                    if (!btr.IsDynamicBlock)
                    {
                        ed.WriteMessage("\nCannot find a dynamic block called \"{0}\".", blkName);
                        return;
                    }
                    // Get the anonymous blocks and add them to our list
                    var anonBlks = btr.GetAnonymousBlockIds();
                    foreach (ObjectId bid in anonBlks)
                    {
                        var btr2 = (BlockTableRecord)tr.GetObject(bid, OpenMode.ForRead);
                        blkNames.Add(btr2.Name);
                    }
                    tr.Commit();
                }

                // Build a conditional filter list so that only
                // entities with the specified properties are
                // selected
                SelectionFilter       sf  = new SelectionFilter(CreateFilterListForBlocks(blkNames));
                PromptSelectionResult psr = ed.SelectAll(sf);
                ed.WriteMessage("\nFound {0} entit{1}.", psr.Value.Count, (psr.Value.Count == 1 ? "y" : "ies"));
            }
            catch (Autodesk.AutoCAD.Runtime.Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
        }
Ejemplo n.º 11
0
        public ObjectIdCollection GetIdsByTypeTypeValue(params string[] types)
        {
            // Get the document
            var doc = Application.DocumentManager.MdiActiveDocument;

            // Get the editor to make the selection
            Editor oEd = doc.Editor;

            // Add our or operators so we can grab multiple types.
            IList <TypedValue> typedValueSelection = new List <TypedValue> {
                new TypedValue(Convert.ToInt32(DxfCode.Operator), "<or"),
                new TypedValue(Convert.ToInt32(DxfCode.Operator), "or>")
            };

            // We will need to insert our requested types into the collection.
            // Since we knew we would have to insert they types between the operators..
            // I used a Enumerable type which gave me that functionality. (IListf<T>)
            foreach (var type in types)
            {
                typedValueSelection.Insert(1, new TypedValue(Convert.ToInt32(DxfCode.Start), type));
            }

            SelectionFilter selectionFilter = new SelectionFilter(typedValueSelection.ToArray());

            // because we have to.. Not really sure why, I assume this is our only access point
            // to grab the entities that we want. (I am open to being corrected)
            PromptSelectionResult promptSelectionResult = oEd.SelectAll(selectionFilter);

            // return our new ObjectIdCollection that is "Hopefully" full of the types that we want.
            return(new ObjectIdCollection(promptSelectionResult.Value.GetObjectIds()));
        }
Ejemplo n.º 12
0
        /// <summary>选择多个单行或者多行文字 </summary>
        /// <param name="docMdf"></param>
        /// <returns></returns>
        private static ObjectId[] SelectTexts(DocumentModifier docMdf)
        {
            var ed = docMdf.acEditor;

            var filterType = new[]
            {
                new TypedValue((int)DxfCode.Operator, "<OR"),
                new TypedValue((int)DxfCode.Start, "TEXT"),
                new TypedValue((int)DxfCode.Start, "MTEXT"),
                new TypedValue((int)DxfCode.Operator, "OR>")
            };
            var filter = new SelectionFilter(filterType);

            // Create our options object
            var pso = new PromptSelectionOptions();
            var kws = pso.Keywords.GetDisplayString(true);

            pso.MessageForAdding  = $"\n选择单行或者多行文字";      // 当用户在命令行中输入A(或Add)时,命令行出现的提示字符。
            pso.MessageForRemoval = pso.MessageForAdding; // 当用户在命令行中输入Re(或Remove)时,命令行出现的提示字符。

            var res = ed.GetSelection(pso, filter);

            if (res.Status == PromptStatus.OK)
            {
                return(res.Value.GetObjectIds());
            }
            return(null);
        }
Ejemplo n.º 13
0
        /// <summary> 在界面中选择一行点或者一列点,用来进行表格的单元格划分 </summary>
        private Point3d GetPointsFromUI(DocumentModifier docMdf, bool forRow, out bool continueSelect)
        {
            continueSelect = false;
            // 创建一个 TypedValue 数组,用于定义过滤条件
            TypedValue[] acTypValAr = new TypedValue[]
            {
                new TypedValue((int)DxfCode.Start, "TEXT"),
            };

            // 将过滤条件赋值给SelectionFilter对象
            SelectionFilter acSelFtr = new SelectionFilter(acTypValAr);

            //获取当前文档编辑器
            Editor ed  = docMdf.acActiveDocument.Editor;
            string msg = forRow ? "选择作为 行 分隔的点(至少2个) " : "选择作为 列 分隔的点(至少2个) ";

            var pao = new PromptPointOptions(message: $"\n{msg}");

            pao.AllowNone = true; // 允许用户直接按下回车或者右键,以退出 GetPoint() 方法,此时返回的 PromptPointResult.Status 为 None。

            // 请求在图形区域选择对象。 GetSelection() 会阻塞线程,直到用户在AutoCAD界面中选择对象完成、取消或者出错。
            PromptPointResult psr = ed.GetPoint(pao);

            // 输出文本所对应的数据
            if (psr.Status == PromptStatus.OK)
            {
                continueSelect = true;
                return(psr.Value);
            }
            else
            {
                continueSelect = false;
                return(default(Point3d));
            }
        }
Ejemplo n.º 14
0
 private PromptSelectionResult GetCircles(Transaction trans)
 {
     TypedValue[] types = new TypedValue[] { new TypedValue((int)DxfCode.Start, "Circle") };
     SelectionFilter selectionFilter = new SelectionFilter(types);
     PromptSelectionResult selectedObject = editor.GetSelection(selectionFilter);
     return selectedObject;
 }
Ejemplo n.º 15
0
        private void RadioButton2_Click(object sender, EventArgs e)
        {
            TypedValue[] array  = new TypedValue[1];
            Array        array2 = array;
            TypedValue   typedValue;

            typedValue..ctor(0, "TEXT");
            array2.SetValue(typedValue, 0);
            SelectionFilter selectionFilter = new SelectionFilter(array);

            this.RadioButton2.Checked = true;
            this.Hide();
            Class36.SetFocus(Application.DocumentManager.MdiActiveDocument.Window.Handle);
            PromptSelectionResult selection = this.document_0.Editor.GetSelection(selectionFilter);

            if (selection.Status == 5100)
            {
                this.selectionSet_0 = selection.Value;
                this.long_0         = (long)this.selectionSet_0.Count;
                if (this.long_0 == 0L)
                {
                    Class36.smethod_60("没有选择任何文字对象\r\n");
                }
                else
                {
                    Class36.smethod_60("当前选择集体" + this.long_0.ToString() + "个文字对象\r\n");
                }
                this.Show();
            }
            this.Button1.Enabled = true;
            this.Button2.Enabled = true;
            this.Button3.Enabled = true;
            this.Label3.Text     = "";
        }
Ejemplo n.º 16
0
        buildSSet(TypedValue[] tvs, Point3dCollection pnts3d)
        {
            SelectionFilter       filter = new SelectionFilter(tvs);
            PromptSelectionResult psr    = BaseObjs._editor.SelectCrossingPolygon(pnts3d, filter);

            return(psr.Value);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// </summary>
        /// <param name="docMdf"></param>
        /// <returns></returns>
        private static ObjectId[] SelectDims(DocumentModifier docMdf)
        {
            var ed = docMdf.acEditor;

            var filterType = new[]
            {
                new TypedValue((int)DxfCode.Start, "DIMENSION"),
                // 将标注类型限制为转角标注与对齐标注
                new TypedValue((int)DxfCode.Operator, "<OR"),
                new TypedValue(100, "AcDbAlignedDimension)"),
                new TypedValue(100, "AcDbRotatedDimension))"),
                new TypedValue((int)DxfCode.Operator, "OR>")
            };
            var filter = new SelectionFilter(filterType);

            // Create our options object
            var pso = new PromptSelectionOptions();
            var kws = pso.Keywords.GetDisplayString(true);

            pso.MessageForAdding  = $"\n选择标注对象";          // 当用户在命令行中输入A(或Add)时,命令行出现的提示字符。
            pso.MessageForRemoval = pso.MessageForAdding; // 当用户在命令行中输入Re(或Remove)时,命令行出现的提示字符。


            var res = ed.GetSelection(pso, filter);

            if (res.Status == PromptStatus.OK)
            {
                return(res.Value.GetObjectIds());
            }
            return(null);
        }
Ejemplo n.º 18
0
        static ObjectIdCollection GetSelectPolyline(bool isSingleSelect)
        {
            //过滤选择polyline
            var tvs = new[]
            {
                new TypedValue((int)DxfCode.Operator, "<or"),
                new TypedValue((int)DxfCode.Start, "LWPOLYLINE"),
                new TypedValue((int)DxfCode.Start, "POLYLINE"),
                new TypedValue((int)DxfCode.Operator, "or>")
            };
            var filter        = new SelectionFilter(tvs);
            var selectionOpts = new PromptSelectionOptions {
                SingleOnly = isSingleSelect
            };

            var currDoc = Application.DocumentManager.MdiActiveDocument;
            //选择polyline
            PromptSelectionResult result = currDoc.Editor.GetSelection(selectionOpts, filter);

            if (result.Status == PromptStatus.OK && result.Value.Count >= 1)
            {
                return(new ObjectIdCollection(result.Value.GetObjectIds()));
            }

            return(new ObjectIdCollection());
        }
Ejemplo n.º 19
0
        private SelectionSet SelectLines()
        {
            // create the typevalue (criteria what should be selected)
            TypedValue[] tvs = new TypedValue[]
            {
                new TypedValue(Convert.ToInt32(DxfCode.Operator), "<or"),
                new TypedValue(Convert.ToInt32(DxfCode.Start), "LINE"),
                new TypedValue(Convert.ToInt32(DxfCode.Start), "POLYLINE"),
                new TypedValue(Convert.ToInt32(DxfCode.Start), "LWPOLYLINE"),
                new TypedValue(Convert.ToInt32(DxfCode.Start), "POLYLINE2D"),
                new TypedValue(Convert.ToInt32(DxfCode.Start), "POLYLINE3d"),
                new TypedValue(Convert.ToInt32(DxfCode.Operator), "or>"),
            };

            SelectionFilter oSf = new SelectionFilter(tvs);

            PromptSelectionResult acPSR = AC.Editor.GetSelection(oSf);

            //acDocEd.WriteMessage("선택");
            //acDocEd.UpdateScreen();

            if (acPSR.Status != PromptStatus.OK)
            {
                AC.Editor.WriteMessage("\n선택이 취소되었습니다.");
                AC.Editor.PostCommandPrompt();
                return(null);
            }

            AC.Doc.GetAcadDocument();

            return(acPSR.Value);
        }
Ejemplo n.º 20
0
        getEntityatPoint(Point3d pnt3d, List <Type> types, string layer, double offset = 0.0)
        {
            int k = types.Count;

            TypedValue[] TVs = new TypedValue[k + 3];

            TVs.SetValue(new TypedValue((int)DxfCode.Operator, "<OR"), 0);

            for (int i = 0; i < types.Count; i++)
            {
                TVs.SetValue(new TypedValue((int)DxfCode.Start, RXClass.GetClass(types[i]).DxfName), i + 1);
            }

            TVs.SetValue(new TypedValue((int)DxfCode.Operator, "OR>"), k + 1);
            TVs.SetValue(new TypedValue((int)DxfCode.LayerName, layer), k + 2);

            SelectionFilter FILTER = new SelectionFilter(TVs);

            Point3d pnt3d1 = new Point3d(pnt3d.X - offset, pnt3d.Y - offset, 0.0);
            Point3d pnt3d2 = new Point3d(pnt3d.X + offset, pnt3d.Y + offset, 0.0);

            PromptSelectionResult PSR = BaseObjs._editor.SelectCrossingWindow(pnt3d1, pnt3d2, FILTER);

            if (PSR.Status == PromptStatus.OK)
            {
                return(PSR.Value.GetObjectIds());
            }
            return(null);
        }
Ejemplo n.º 21
0
        public SelectionSet selectPoints(string message)
        {
            Document DOC = Application.DocumentManager.MdiActiveDocument;
            Database DB  = DOC.Database;
            Editor   ED  = Application.DocumentManager.MdiActiveDocument.Editor;

            TypedValue[] TVs = new TypedValue[1];
            TVs.SetValue(new TypedValue((int)DxfCode.Start, "AECC_COGO_POINT"), 0);

            SelectionFilter        FILTER = new SelectionFilter(TVs);
            PromptSelectionOptions PSO    = new PromptSelectionOptions();

            PSO.MessageForAdding = message;

            PromptSelectionResult PSR = null;

            using (Transaction TR = DB.TransactionManager.StartTransaction())
            {
                try
                {
                    PSR = ED.GetSelection(PSO, FILTER);
                }
                catch (System.Exception ex) {
                    Application.ShowAlertDialog(ex.Message + " DragLabel.cs: line: 73");
                    BaseObjs.writeDebug(ex.Message + " DragLabel.cs: line: 73");
                }
                if (PSR.Status == PromptStatus.OK)
                {
                    return(PSR.Value);
                }
            }
            return(null);
        } // selectPoints
Ejemplo n.º 22
0
        public HashSet <ObjectId> EditorSelectCrossingWindow(Editor editor, List <Point3d> pts)
        {
            TypedValue[] filterList = new TypedValue[1];
            filterList[0] = new TypedValue(0, "INSERT,LINE,LWPOLYLINE");
            SelectionFilter filter = new SelectionFilter(filterList);

            HashSet <ObjectId>    choosenIds = new HashSet <ObjectId>();
            PromptSelectionResult selRes     = editor.SelectCrossingWindow(pts[0], pts[2], filter);

            if (selRes.Status == PromptStatus.OK)
            {
                foreach (ObjectId id in selRes.Value.GetObjectIds())
                {
                    choosenIds.Add(id);
                }
            }

            PromptSelectionResult selResReversed = editor.SelectCrossingWindow(pts[2], pts[0], filter);

            if (selResReversed.Status == PromptStatus.OK)
            {
                foreach (ObjectId id in selResReversed.Value.GetObjectIds())
                {
                    choosenIds.Add(id);
                }
            }
            return(choosenIds);
        }
Ejemplo n.º 23
0
        public void Getlayer()
        {
            string dir = null;

            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string foldPath = dialog.SelectedPath;
                dir = foldPath;
            }

            if (dir == null)
            {
                return;
            }

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;

            List <string> layersName = LayersToList(db);

            TransactionControl(() =>
            {
                foreach (var layerName in layersName)
                {
                    TypedValue[] filterlist = new TypedValue[1];
                    filterlist[0]           = new TypedValue(8, layerName);
                    SelectionFilter filter  = new SelectionFilter(filterlist);

                    PromptSelectionResult selRes = ed.SelectAll(filter);
                    if (selRes.Status != PromptStatus.OK)
                    {
                        ed.WriteMessage(
                            "\nerror in getting the selectAll");
                        return;
                    }
                    ObjectId[] ids = selRes.Value.GetObjectIds();
                    ObjectIdCollection sourceIds = new ObjectIdCollection();
                    foreach (var id in ids)
                    {
                        Entity entity = (Entity)tm.GetObject(id, OpenMode.ForRead, true);
                        sourceIds.Add(id);
                    }
                    Database destDb = new Database(true, true);

                    ObjectId sourceMsId = SymbolUtilityServices.GetBlockModelSpaceId(db);

                    ObjectId destDbMsId = SymbolUtilityServices.GetBlockModelSpaceId(destDb);

                    IdMapping mapping = new IdMapping();

                    db.WblockCloneObjects(sourceIds, destDbMsId, mapping, DuplicateRecordCloning.Replace, false);

                    destDb.SaveAs(dir + "\\" + layerName + ".dwg", DwgVersion.Current);
                }
            });
        }
Ejemplo n.º 24
0
        public void TestBrepUnion()
        {
            var doc = Application.DocumentManager.MdiActiveDocument;
            var db  = doc.Database;
            var ed  = doc.Editor;

            var tvs       = new[] { new TypedValue((int)DxfCode.Start, "LWPOLYLINE") };
            var selFilter = new SelectionFilter(tvs);
            var sel       = ed.GetSelection(selFilter);

            if (sel.Status != PromptStatus.OK)
            {
                return;
            }

            using (var t = db.TransactionManager.StartTransaction())
            {
                var idsPls = sel.Value.GetObjectIds();
                var pls    = new List <Polyline>();
                foreach (var item in idsPls)
                {
                    var pl = item.GetObject(OpenMode.ForRead) as Polyline;
                    pls.Add(pl);
                }

                var union = pls.Union(null);

                t.Commit();
            }
        }
Ejemplo n.º 25
0
        /// <summary>选择多个多面网格 </summary>
        /// <param name="docMdf"></param>
        /// <returns></returns>
        private static ObjectId[] SelectPolyfacemeshes(DocumentModifier docMdf)
        {
            var ed = docMdf.acEditor;

            var filterType = new[]
            {
                new TypedValue((int)DxfCode.Start, "POLYLINE"),
                new TypedValue((int)100, "AcDbPolyFaceMesh")
            };
            var filter = new SelectionFilter(filterType);

            // Create our options object
            var pso = new PromptSelectionOptions();
            var kws = pso.Keywords.GetDisplayString(true);

            pso.MessageForAdding  = $"\n选择多面网格";          // 当用户在命令行中输入A(或Add)时,命令行出现的提示字符。
            pso.MessageForRemoval = pso.MessageForAdding; // 当用户在命令行中输入Re(或Remove)时,命令行出现的提示字符。

            var res = ed.GetSelection(pso, filter);

            if (res.Status == PromptStatus.OK)
            {
                return(res.Value.GetObjectIds());
            }
            return(null);
        }
Ejemplo n.º 26
0
        /// <summary> 选择多段线以修改其疏密 </summary>
        private static Polyline[] SelectPolylines(DocumentModifier docMdf)
        {
            var ed = docMdf.acEditor;

            var filterType = new[]
            {
                new TypedValue((int)DxfCode.Start, "LWPOLYLINE")
            };
            var filter = new SelectionFilter(filterType);

            // Create our options object
            var pso = new PromptSelectionOptions();
            var kws = pso.Keywords.GetDisplayString(true);

            pso.MessageForAdding  = $"\n选择多段线以修改其疏密";     // 当用户在命令行中输入A(或Add)时,命令行出现的提示字符。
            pso.MessageForRemoval = pso.MessageForAdding; // 当用户在命令行中输入Re(或Remove)时,命令行出现的提示字符。


            var res = ed.GetSelection(pso, filter);

            if (res.Status == PromptStatus.OK)
            {
                return
                    (res.Value.GetObjectIds().Select(id => id.GetObject(OpenMode.ForRead)).OfType <Polyline>().ToArray());
            }
            return(null);
        }
 public ObjectId[] featureClassChecker(MSCFeatureClass fc)
 {
     ObjectId[] result;
     try
     {
         ResultBuffer          fCQuery               = fc.FCQuery;
         SelectionFilter       selectionFilter       = new SelectionFilter(fCQuery.AsArray());
         PromptSelectionResult promptSelectionResult = SingletonsList.ed.SelectAll(selectionFilter);
         if (promptSelectionResult.Status == (PromptStatus)5100 && promptSelectionResult.Value.Count > 0)
         {
             ObjectId[] objectIds = promptSelectionResult.Value.GetObjectIds();
             if (objectIds.Length != 0)
             {
                 result = objectIds;
                 return(result);
             }
         }
         result = null;
     }
     catch (Exception ex)
     {
         if (SingletonsList.ed != null)
         {
             SingletonsList.ed.WriteMessage("\n" + AfaStrings.Error + " " + ex.Message);
         }
         result = null;
     }
     return(result);
 }
Ejemplo n.º 28
0
        /// <summary>
        /// 사용자가 선택한 여러 객체들을 가져오는 메소드입니다.
        /// </summary>
        /// <param name="message">선택 전, 프롬프트에 표시할 메시지</param>
        /// <param name="Filter">선택이 가능하게 할 조건</param>
        /// <returns></returns>
        public static ObjectId[] GetEntities(string message = "객체 선택", params TypedValue[] Filter)
        {
            ActivateApplication();

            Document doc = AcadApp.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            PromptSelectionOptions pso = new PromptSelectionOptions();

            pso.MessageForAdding  = "\n" + message;
            pso.MessageForRemoval = "\n" + message;

            SelectionFilter oSF = new SelectionFilter(Filter);

            PromptSelectionResult psr = ed.GetSelection(pso, oSF);

            if (psr.Status != PromptStatus.OK)
            {
                return new ObjectId[] { }
            }
            ;

            return(psr.Value.GetObjectIds());
        }
Ejemplo n.º 29
0
        selectMTextForMoving(string layer, out bool escape)
        {
            escape = true;
            ObjectId id = ObjectId.Null;

            TypedValue[] TVs = new TypedValue[2];

            TVs.SetValue(new TypedValue((int)DxfCode.Start, "MTEXT"), 0);
            TVs.SetValue(new TypedValue((int)DxfCode.LayerName, layer), 1);

            SelectionFilter filter = new SelectionFilter(TVs);

            PromptSelectionOptions pso = new PromptSelectionOptions();

            pso.MessageForAdding = "Select MText to Move";

            PromptSelectionResult PSR = BaseObjs._editor.GetSelection(pso, filter);

            if (PSR.Status == PromptStatus.OK)
            {
                id     = PSR.Value.GetObjectIds()[0];
                escape = false;
            }
            return(id);
        }
Ejemplo n.º 30
0
        /// <summary> 选择多个单行文字 </summary>
        /// <param name="docMdf"></param>
        /// <returns></returns>
        private static List <DBText> GetDbTexts(DocumentModifier docMdf)
        {
            // Create our options object
            var pso = new PromptSelectionOptions();

            // Add our keywords
            // Set our prompts to include our keywords
            string kws = pso.Keywords.GetDisplayString(true);

            pso.MessageForAdding  = "\n 选择多个单行文字" + kws; // 当用户在命令行中输入A(或Add)时,命令行出现的提示字符。
            pso.MessageForRemoval = "\n 选择多个单行文字 " + kws;
            // 当用户在命令行中输入Re(或Remove)时,命令行出现的提示字符。
            var f     = new SelectionFilter(new TypedValue[] { new TypedValue((int)DxfCode.Start, "TEXT") });
            var texts = new List <DBText>();
            var res   = docMdf.acEditor.GetSelection(pso, f);

            if (res.Status == PromptStatus.OK)
            {
                var ids = res.Value.GetObjectIds();
                foreach (var id in ids)
                {
                    var text = id.GetObject(OpenMode.ForRead) as DBText;
                    if (text != null)
                    {
                        texts.Add(text);
                    }
                }
            }
            return(texts);
        }
Ejemplo n.º 31
0
        getEntityatPoint(Point3d pnt3d, Type type, string layer, double offset = 0.0)
        {
            List <ObjectId> ids = new List <ObjectId>();

            TypedValue[] tvs = new TypedValue[2];

            tvs.SetValue(new TypedValue((int)DxfCode.Start, RXClass.GetClass(type).DxfName), 0);
            tvs.SetValue(new TypedValue((int)DxfCode.LayerName, layer), 1);

            SelectionFilter filter = new SelectionFilter(tvs);
            Point3d         pnt3d1 = new Point3d(pnt3d.X - offset, pnt3d.Y - offset, 0.0);
            Point3d         pnt3d2 = new Point3d(pnt3d.X + offset, pnt3d.Y + offset, 0.0);

            //Draw.addLine(pnt3d1, pnt3d2);

            PromptSelectionResult psr = BaseObjs._editor.SelectCrossingWindow(pnt3d2, pnt3d1, filter);

            if (psr.Status == PromptStatus.OK)
            {
                ObjectId[] idss = psr.Value.GetObjectIds();
                foreach (ObjectId id in idss)
                {
                    ids.Add(id);
                }
            }
            return(ids);
        }
Ejemplo n.º 32
0
        private SelectionFilter CreateFilter(SearchFilterTransferObject data)
        {
            var customerRepository = ObjectFactory.GetInstance <ICustomerRepository>();
            var projectRepository  = ObjectFactory.GetInstance <IProjectRepository>();
            var taskRepository     = ObjectFactory.GetInstance <ITaskRepository>();
            var userRepository     = ObjectFactory.GetInstance <IUserRepository>();
            var filter             = new SelectionFilter();

            foreach (var customerId in data.Customers)
            {
                filter.AddCustomer(customerRepository.GetByID(customerId));
            }

            foreach (var projectId in data.Projects)
            {
                filter.AddProject(projectRepository.GetByID(projectId));
            }

            foreach (var taskId in data.Tasks)
            {
                filter.AddTask(taskRepository.GetById(taskId));
            }

            if (data.Users != null)
            {
                filter.Users = data.Users.Select(u => userRepository.GetByUserID(u)).ToList();
            }

            filter.DateFrom = data.DateFrom;
            filter.DateTo   = data.DateTo;


            return(filter);
        }
Ejemplo n.º 33
0
        public static void SelectEnt2()
        {
            //��ȡEditor����
               Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

                // ����ѡ��ѡ��
               PromptSelectionOptions selectionOp = new PromptSelectionOptions();
                 //����ѡ�񼯹�������ֻѡ������
                TypedValue[] filList = new TypedValue[1];
                filList[0] = new TypedValue((int)DxfCode.Start, "INSERT");
               SelectionFilter filter = new SelectionFilter(filList);

               PromptSelectionResult ssRes = ed.GetSelection(selectionOp, filter);
               if (ssRes.Status == PromptStatus.OK)
               {
                   SelectionSet SS = ssRes.Value;
                   int nCount = SS.Count;
                   ed.WriteMessage("ѡ����{0}����"  , nCount);
               }
        }
Ejemplo n.º 34
0
 public void AddLinesToGroup()
 {
     Editor editor = dwg.Editor;
     using (Transaction acadTrans = CurrentDatabase.TransactionManager.StartTransaction())
     {
         GroupsInformation groupsEntities = new GroupsInformation(acadTrans, CurrentDatabase);
         //Спрашиваем имя группы
         string GroupName = AskForGroup(true, groupsEntities.GroupList);
         if (GroupName != null)
         {
             // Готовим опции для запроса элементов группы
             PromptSelectionOptions acadSelectionOptions = new PromptSelectionOptions();
             acadSelectionOptions.MessageForAdding = "\nУкажите объекты группы " + GroupName;
             //Выделять будем только линии и полилинии. Создаем фильтр
             TypedValue[] acadFilterValues = new TypedValue[4];
             acadFilterValues.SetValue(new TypedValue((int)DxfCode.Operator, "<OR"),0);
             acadFilterValues.SetValue(new TypedValue((int)DxfCode.Start, "LINE"),1);
             acadFilterValues.SetValue(new TypedValue((int)DxfCode.Start, "LWPOLYLINE"),2);
             acadFilterValues.SetValue(new TypedValue((int)DxfCode.Operator, "OR>"),3);
             SelectionFilter acadSelFilter = new SelectionFilter(acadFilterValues);
             //Используем фильтр для выделения
             PromptSelectionResult acadSelSetPrompt = dwg.Editor.GetSelection(acadSelectionOptions, acadSelFilter);
             //Если выбраны объекты - едем дальше
             if (acadSelSetPrompt.Status == PromptStatus.OK)
             {
                 // Формируем коллекцию выделенных объектов
                 SelectionSet acadSelectedObjects = acadSelSetPrompt.Value;
                 // Проходим по каждому объекту в выделении
                 foreach (SelectedObject selectedObj in acadSelectedObjects)
                 {
                     if (selectedObj!=null)
                     {
                         groupsEntities.AppendGroupToObject(selectedObj.ObjectId, GroupName);
                     }
                 }
             }
         }
         acadTrans.Commit();
     }
 }
        private SelectionFilter GetSelectionFilter()
        {
            TypedValue[] acTypeValAr = new TypedValue[1] {
                                new TypedValue((int)DxfCode.Start, "INSERT")
                                };

            // the instantiating of a selection filter which selects on certain layers and which selects only lines
            SelectionFilter sf = new SelectionFilter(acTypeValAr);

            return sf;
        }
Ejemplo n.º 36
0
        private void btnSelectShapes_Click(object sender, EventArgs e)
        {
            PosShape copy = GetSelected();
            if (copy == null || copy.IsBuiltIn) return;

            // Select shapes
            Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            using (EditorUserInteraction UI = ed.StartUserInteraction(this))
            {
                TypedValue[] tvs = new TypedValue[] {
                    new TypedValue((int)DxfCode.Operator, "<OR"),
                    new TypedValue((int)DxfCode.Start, "LINE"),
                    new TypedValue((int)DxfCode.Start, "ARC"),
                    new TypedValue((int)DxfCode.Start, "CIRCLE"),
                    new TypedValue((int)DxfCode.Start, "TEXT"),
                    new TypedValue((int)DxfCode.Operator, "OR>")
                };
                SelectionFilter filter = new SelectionFilter(tvs);
                PromptSelectionResult result = ed.GetSelection(filter);

                if (result.Status != PromptStatus.OK || result.Value.Count == 0) return;

                int fieldCount = 1;
                copy.Items.Clear();
                Database db = HostApplicationServices.WorkingDatabase;
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    try
                    {
                        foreach (SelectedObject sel in result.Value)
                        {
                            DBObject obj = tr.GetObject(sel.ObjectId, OpenMode.ForRead);

                            bool visible = true;
                            Entity en = obj as Entity;
                            if (en != null)
                            {
                                LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(en.LayerId, OpenMode.ForRead);

                                if (ltr != null)
                                {
                                    visible = ltr.IsPlottable;
                                }
                            }

                            if (obj is Line)
                            {
                                Line line = obj as Line;

                                copy.Items.Add(new PosShape.ShapeLine(line.Color, line.StartPoint.X, line.StartPoint.Y, line.EndPoint.X, line.EndPoint.Y, visible));
                            }
                            else if (obj is Arc)
                            {
                                Arc arc = obj as Arc;
                                copy.Items.Add(new PosShape.ShapeArc(arc.Color, arc.Center.X, arc.Center.Y, arc.Radius, arc.StartAngle, arc.EndAngle, visible));
                            }
                            else if (obj is Circle)
                            {
                                Circle circle = obj as Circle;
                                copy.Items.Add(new PosShape.ShapeCircle(circle.Color, circle.Center.X, circle.Center.Y, circle.Radius, visible));
                            }
                            else if (obj is DBText)
                            {
                                DBText text = obj as DBText;
                                if (text.TextString == "A" && fieldCount < 1) fieldCount = 1;
                                if (text.TextString == "B" && fieldCount < 2) fieldCount = 2;
                                if (text.TextString == "C" && fieldCount < 3) fieldCount = 3;
                                if (text.TextString == "D" && fieldCount < 4) fieldCount = 4;
                                if (text.TextString == "E" && fieldCount < 5) fieldCount = 5;
                                if (text.TextString == "F" && fieldCount < 6) fieldCount = 6;
                                double x = text.Position.X;
                                double y = text.Position.Y;
                                if (text.AlignmentPoint.X != 0.0 || text.AlignmentPoint.Y != 0.0)
                                {
                                    x = text.AlignmentPoint.X;
                                    y = text.AlignmentPoint.Y;
                                }
                                copy.Items.Add(new PosShape.ShapeText(text.Color, x, y, text.Height, text.WidthFactor, text.TextString, "romans.shx", text.HorizontalMode, text.VerticalMode, visible));
                            }
                        }
                    }
                    catch (System.Exception ex)
                    {
                        System.Windows.Forms.MessageBox.Show("Error: " + ex.Message, "RebarPos", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    }
                }

                udFields.Value = fieldCount;
            }

            SetShape();
        }
Ejemplo n.º 37
0
        public static void FilterSelectionSet()
        {

            Editor acDocEd = AcadApp.Application.DocumentManager.MdiActiveDocument.Editor;

            //使用选择过滤器定义选择集规则

            //选择过滤器由TypedValue形式的一对参数构成。TypedValue的第一个参数表明过滤器的类型(例如对象),第二个参数为要过滤的值(例如圆)。过滤器类型是一个DXF组码,用来指定使用哪种过滤器。一些常用过滤器类型列表如下。


            //选择过滤器可以包含过滤多个属性或对象的条件。可以通过声明一个包含足够数量元素的数组来定义总的过滤条件,数组的每个元素代表一个过滤条件。

            TypedValue[] acTypValAr = new TypedValue[1]; // 创建一个TypedValue数组来定义过滤器条件

            acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "CIRCLE"), 0);

            //**************
            // 创建TypedValue数组定义过滤条件

            //TypedValue[] acTypValAr = new TypedValue[3];

            //acTypValAr.SetValue(new TypedValue((int)DxfCode.Color, 5), 0);

            //acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "CIRCLE"), 1);

            //acTypValAr.SetValue(new TypedValue((int)DxfCode.LayerName, "0"), 2);
            //**************


            // 将过滤器条件赋值给SelectionFilter对象

            SelectionFilter acSelFtr = new SelectionFilter(acTypValAr);

            PromptSelectionResult acSSPrompt;

            acSSPrompt = acDocEd.GetSelection(acSelFtr);

            // 提示状态OK,表示用户已选完

            if (acSSPrompt.Status == PromptStatus.OK)
            {
                SelectionSet acSSet = acSSPrompt.Value;

                AcadApp.Application.ShowAlertDialog("Number of objects selected: " + acSSet.Count.ToString());
            }

            else
            {

                AcadApp.Application.ShowAlertDialog("Numberof objects selected: 0");

            }

        }
        public void GetIntersectionsRiver()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Transaction tr = db.TransactionManager.StartTransaction();

            #region For Word
            string filepath = "D:\\intersections_rivers.docx";

            using (WordprocessingDocument docX = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
            {
                try
                {
                    // Add a main document part.
                    MainDocumentPart mainPart = docX.AddMainDocumentPart();
                    StyleDefinitionsPart styleDefinitionsPart = mainPart.AddNewPart<StyleDefinitionsPart>();
                    Styles styles1 = new Styles();
                    DocDefaults docDefaults =
                        new DocDefaults(
                            new RunPropertiesDefault(new RunPropertiesBaseStyle(new RunFonts()
                            {
                                Ascii = "Times New Roman",
                                HighAnsi = "Times New Roman",
                                ComplexScript = "Times New Roman"
                            }, new FontSize() { Val = "24" },
                                new FontSizeComplexScript() { Val = "24" })),
                                new ParagraphPropertiesDefault(new SpacingBetweenLines() { After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto }));
                    styles1.AppendChild(docDefaults);
                    styleDefinitionsPart.Styles = styles1;

                    mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
                    DocumentFormat.OpenXml.Wordprocessing.Body body = mainPart.Document.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Body());
                    ParagraphProperties paragraphProperties1 = new ParagraphProperties(
                        new Justification() { Val = JustificationValues.Center },
                        new ParagraphMarkRunProperties(
                            new RunFonts()
                            {
                                Ascii = "Times New Roman",
                                HighAnsi = "Times New Roman",
                                ComplexScript = "Times New Roman"
                            },
                            new FontSize() { Val = "24" },
                            new FontSizeComplexScript() { Val = "24" }
                            ));

                    Paragraph para = body.AppendChild(new Paragraph());
                    para.AppendChild(paragraphProperties1);

                    Run run = para.AppendChild(new Run());

                    RunProperties runProperties1 = new RunProperties(
                        new Bold());

                    // String msg contains the text, "Hello, Word!"
                    run.AppendChild(runProperties1);
                    run.AppendChild(new Text("ПРИЛОЖЕНИЕ"));
                    run.AppendChild(new Break());
                    run.AppendChild(new Text("Ведомость пересечений"));
                    run.AppendChild(new Break());

                    var table = new DocumentFormat.OpenXml.Wordprocessing.Table();
                    // Create a TableProperties object and specify its border information.
                    TableProperties tblProp = new TableProperties(
                        new TableWidth() { Width = "9782", Type = TableWidthUnitValues.Dxa },
                        new TableIndentation() { Width = -318, Type = TableWidthUnitValues.Dxa },
                        new TableBorders(
                            new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }),
                        new DocumentFormat.OpenXml.Wordprocessing.TableStyle() { Val = "TableGrid" }
                        );

                    // Append the TableProperties object to the empty table.
                    table.AppendChild<TableProperties>(tblProp);

                    // Add 3 columns to the table.
                    TableGrid tg = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(),
                         new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn());
                    table.AppendChild(tg);

                    TableRow tr1 = new TableRow(
                        new TableRowProperties(new TableRowHeight() { Val = 430 }),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1709" },
                                new VerticalMerge() { Val = MergedCellValues.Restart },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Наимен. водотока")))),
                        //new TableCellProperties(new TableCellWidth() {Type = TableWidthUnitValues.Pct, Width = "500"})
                        new TableCell(
                            new TableCellProperties(
                                new GridSpan() { Val = 2 },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "3922" }),
                            new Paragraph(
                                new ParagraphProperties(new Justification() { Val = JustificationValues.Center }),
                                new Run(new Text("Пикетное положение пересечения")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(
                                new ParagraphProperties(new Justification() { Val = JustificationValues.Center }),
                                new Run(new Text("Ширина водотока в межень")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1358" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new VerticalMerge() { Val = MergedCellValues.Restart }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Глуб. водотока")))),
                        new TableCell(
                            new TableCellProperties(
                                new GridSpan() { Val = 3 },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2368" }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Горизонт воды")))),
                        new TableCell(new TableCellProperties(
                            new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "425" },
                            new VerticalMerge() { Val = MergedCellValues.Restart },
                            new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Прим."))))
                        );
                    table.AppendChild(tr1);
                    TableRow tr2 = new TableRow(
                        new TableRowProperties(new TableRowHeight() { Val = 419 }),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("От")))),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("До")))),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("половодье")))),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1260" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Дата съемки")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("На день съемки")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Макс.")))),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())));
                    table.AppendChild(tr2);

                    TableCellProperties tcp = new TableCellProperties(new GridSpan() { Val = 9 });
            #endregion

                    while (true)
                    {

                        //using (tr)
                        //{
                        try
                        {
                            #region Поиск пересечений
                            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                            PromptEntityOptions peo = new PromptEntityOptions("\nВыбери polyline  >>");
                            peo.SetRejectMessage("\nМожно только polyline >>");
                            peo.AddAllowedClass(typeof(Polyline), false);
                            PromptEntityResult res;
                            res = ed.GetEntity(peo);
                            if (res.Status != PromptStatus.OK)
                            {
                                break;
                            }
                            DBObject ent = (DBObject)tr.GetObject(res.ObjectId, OpenMode.ForRead);
                            if (ent == null) return;

                            PromptPointResult pPtRes;
                            PromptPointOptions pPtOpts = new PromptPointOptions("");
                            // Prompt for the start point
                            pPtOpts.Message = "\nВведи начало: ";
                            pPtRes = doc.Editor.GetPoint(pPtOpts);

                            PromptDoubleOptions getpik = new PromptDoubleOptions("\nВведи пикетаж (в формате числа, а не 0+00): ");
                            PromptDoubleResult getpikRes = doc.Editor.GetDouble(getpik);

                            //zoom
                            /*PromptEntityResult per = ed.GetEntity(peo);

                            if (per.Status != PromptStatus.OK)
                                return;*/

                            // Extract its extents

                            Extents3d ext;

                            Transaction trans = db.TransactionManager.StartTransaction();
                            using (trans)
                            {
                                Entity enti = (Entity)trans.GetObject(res.ObjectId, OpenMode.ForRead);
                                ext = enti.GeometricExtents;
                                trans.Commit();
                            }

                            ext.TransformBy(ed.CurrentUserCoordinateSystem.Inverse());

                            ZoomWin(ed, ext.MinPoint, ext.MaxPoint);
                            //

                            //Polyline poly = (Polyline)ent as Polyline;
                            Curve curv = ent as Curve;

                            DBObjectCollection pcurves = new DBObjectCollection();

                            curv.Explode(pcurves);
                            TypedValue[] values = new TypedValue[]
                     {
                        new TypedValue(0, "lwpolyline")
                        //might be added layer name to select curve:
                        //, new TypedValue(8, "mylayer")
                     };
                            SelectionFilter filter = new SelectionFilter(values);

                            Point3dCollection fence = new Point3dCollection();

                            double leng = curv.GetDistanceAtParameter(curv.EndParam) - curv.GetDistanceAtParameter(curv.StartParam);
                            // number of divisions along polyline to create fence selection
                            double step = leng / 256;// set number of steps to your suit

                            int num = Convert.ToInt32(leng / step);

                            for (int i = 0; i < num; i++)
                            {
                                Point3d pp = curv.GetPointAtDist(step * i);

                                fence.Add(curv.GetClosestPointTo(pp, false));
                            }

                            PromptSelectionResult selres = ed.SelectFence(fence, filter);

                            if (selres.Status != PromptStatus.OK) return;
                            Point3dCollection intpts = new Point3dCollection();

                            DBObjectCollection qcurves = new DBObjectCollection();
                            //ed.WriteMessage("\nCheck");
                            foreach (SelectedObject selobj in selres.Value)
                            {
                                DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForRead, false) as DBObject;
                                if (selobj.ObjectId != curv.ObjectId)
                                {
                                    DBObjectCollection icurves = new DBObjectCollection();
                                    Curve icurv = obj as Curve;
                                    icurv.Explode(icurves);
                                    foreach (DBObject dbo in icurves)
                                    {
                                        if (!qcurves.Contains(dbo))
                                            qcurves.Add(dbo);
                                    }
                                }

                            }
                            //ed.WriteMessage("\n{0}", qcurves.Count);

                            int j = 0;
                            Point3dCollection polypts = new Point3dCollection();

                            for (int i = 0; i < pcurves.Count; ++i)
                            {
                                for (j = 0; j < qcurves.Count; ++j)
                                {
                                    Curve curve1 = pcurves[i] as Curve;

                                    Curve curve2 = qcurves[j] as Curve;

                                    Point3dCollection pts = new Point3dCollection();

                                    curve1.IntersectWith(curve2, Intersect.OnBothOperands, pts, IntPtr.Zero, IntPtr.Zero);

                                    foreach (Point3d pt in pts)
                                    {
                                        if (!polypts.Contains(pt))
                                            polypts.Add(pt);
                                    }
                                }
                            }
                            #endregion

                            try
                            {
                                using (Transaction tran = db.TransactionManager.StartTransaction())
                                {
                                    Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead);
                                    table.AppendChild(new TableRow(
                                        new TableCell(
                                            new TableCellProperties(
                                                new GridSpan() { Val = 9 }),
                                                new Paragraph(
                                                    new ParagraphProperties(
                                                        new ParagraphMarkRunProperties(new Bold()),
                                                        new Justification() { Val = JustificationValues.Center }),
                                                        new Run(new RunProperties(
                                                            new Bold()),
                                                            new Text("ПК" + ((int)(getpikRes.Value)).ToString("F0") + "-ПК" +
                                                                ((int)(100 * getpikRes.Value + pline.Length) / 100).ToString("F0") + "+" +
                                                                ((100 * getpikRes.Value + pline.Length) % 100).ToString("F")))))));
                                }
                            }
                            catch { ed.WriteMessage("\nError."); }

                            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("osmode", 0);// optional
                            // for debug only
                            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(string.Format("\nНайдено пересечений: {0}", polypts.Count));

                            if (polypts.Count == 0)
                            {
                                try
                                {
                                    using (Transaction tran = db.TransactionManager.StartTransaction())
                                    {
                                        Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead);
                                        table.AppendChild(new TableRow(
                                            new TableCell(
                                                new TableCellProperties(
                                                    new GridSpan() { Val = 9 }),
                                                    new Paragraph(
                                                        new ParagraphProperties(
                                                            new Justification() { Val = JustificationValues.Center }),
                                                            new Run(new Text("На данном участке трассы пересечения отсутствуют"))))));
                                    }
                                }
                                catch { ed.WriteMessage("\nError."); }
                            }
                            else
                            {
                                //List<double> pik = new List<double>(polypts.Count);
                                double[] pik = new double[polypts.Count];
                                int numInter = 0;

                                foreach (Point3d inspt in polypts)
                                {
                                    double dist = 0;
                                    dist = 100 * getpikRes.Value;

                                    // test for visulization only
                                    /*Circle circ = new Circle(inspt, Vector3d.ZAxis, 10 * db.Dimtxt);
                                    circ.ColorIndex = 1;
                                    btr.AppendEntity(circ);
                                    tr.AddNewlyCreatedDBObject(circ, true);*/

                                    Point3d curr = pPtRes.Value, next = pPtRes.Value;
                                    try
                                    {
                                        using (Transaction tran = db.TransactionManager.StartTransaction())
                                        {
                                            Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead);
                                            if ((pPtRes.Value == pline.GetLineSegmentAt(0).StartPoint) || (pPtRes.Value == pline.GetLineSegmentAt(0).EndPoint))
                                                for (int i = 0; i < pline.NumberOfVertices - 2; i++)
                                                {
                                                    LineSegment3d l1 = pline.GetLineSegmentAt(i);
                                                    LineSegment3d l2 = pline.GetLineSegmentAt(i + 1);
                                                    double angle = GetPolylineShape(l1, l2, pline.Normal);
                                                    if (angle > Math.PI)
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }
                                                    else
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }

                                                    if (Math.Abs(inspt.DistanceTo(curr) + inspt.DistanceTo(next) - curr.DistanceTo(next)) < 1)
                                                    {
                                                        dist += inspt.DistanceTo(curr);
                                                        ed.WriteMessage(((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F") + "\n");
                                                        break;
                                                    }
                                                    else
                                                        dist += curr.DistanceTo(next);

                                                    curr = next;
                                                }
                                            else
                                                for (int i = pline.NumberOfVertices - 3; i >= 0; i--)
                                                {
                                                    LineSegment3d l1 = pline.GetLineSegmentAt(i);
                                                    LineSegment3d l2 = pline.GetLineSegmentAt(i + 1);
                                                    double angle = GetPolylineShape(l1, l2, pline.Normal);
                                                    if (angle > Math.PI)
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }
                                                    else
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }

                                                    if (Math.Abs(inspt.DistanceTo(curr) + inspt.DistanceTo(next) - curr.DistanceTo(next)) < 1)
                                                    {
                                                        dist += inspt.DistanceTo(curr);
                                                        ed.WriteMessage(((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F") + "\n");
                                                        break;
                                                    }
                                                    else
                                                        dist += curr.DistanceTo(next);

                                                    curr = next;
                                                }
                                        }
                                    }
                                    catch
                                    {
                                        ed.WriteMessage("\nInvalid polyline.");
                                    }
                                    pik[numInter] = dist;
                                    numInter++;
                                    //ed.WriteMessage(" {0:0.00}\n", dist);
                                }

                                //pik.Sort();

                                Array.Sort(pik);

                                for (int i = 0; i < polypts.Count; i++)
                                {
                                    tr1 = new TableRow(
                                        new TableRowProperties(new TableRowHeight() { Val = 300 }),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(
                                                new TableCellProperties(
                                                    new GridSpan() { Val = 2 }),
                                                    new Paragraph(
                                                        new ParagraphProperties(
                                                            new Justification() { Val = JustificationValues.Center }),
                                                            new Run(new Text(((int)pik[i] / 100).ToString("F0") + "+" + (pik[i] % 100).ToString("F"))))),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run()))
                                        );
                                    table.AppendChild(tr1);
                                }
                            }

                        }
                        catch
                        {
                            ed.WriteMessage("\nError");
                        }
                        //}
                    }

                    tr.Commit();

                    body.AppendChild(table);
                    body.AppendChild(
                        new SectionProperties(
                            new PageMargin()
                            {
                                Top = 1134,
                                Right = (UInt32Value)850U,
                                Bottom = 1134,
                                Left = (UInt32Value)1418U,
                                Header = (UInt32Value)708U,
                                Footer = (UInt32Value)708U,
                                Gutter = (UInt32Value)0U
                            }));
                    ed.WriteMessage("\nДокумент сохранен в D:\\intersections_rivers.docx");
                }
                catch
                {
                    ed.WriteMessage("\nError.");
                }
            }
        }
Ejemplo n.º 39
0
 private PromptSelectionResult GetBlockIds()
 {
     TypedValue[] typedValue = GetTypedValue();
     SelectionFilter filter = new SelectionFilter(typedValue);
     PromptSelectionResult selectedMarks = editor.GetSelection(filter);
     return selectedMarks;
 }
        //create layer for signature
        private ObjectId createLayer(string lyname)
        {
            Editor ed = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Editor;
            Database db = HostApplicationServices.WorkingDatabase;            

            //search the specific layer  
            TypedValue[] filList = new TypedValue[1] {
                        new TypedValue((int)DxfCode.LayerName, lyname)
                };
            SelectionFilter filter = new SelectionFilter(filList);

            PromptSelectionResult selRes = ed.SelectAll(filter);
            if (selRes.Status != PromptStatus.OK && 
                selRes.Status != PromptStatus.Error) //error means no such layer. can continue the following code
            {
                ed.WriteMessage("\nerror in getting all entities on a layer named " + lyname + " >>error:" + selRes.Status);
                return ObjectId.Null;
            }
                        
            LayerTableRecord signatureLayer = null;
            try
            {

                using (Transaction tr =
                    db.TransactionManager.StartTransaction())
                {
                    if (selRes.Status == PromptStatus.OK)
                    {
                        ed.WriteMessage("\nTo delete entities on the signature layer");

                        //delete all signatures (solids) on the old layer
                        ObjectId[] ids = selRes.Value.GetObjectIds();
                        foreach (ObjectId eachentid in ids)
                        {
                            Entity oEnt = tr.GetObject(eachentid, OpenMode.ForWrite) as Entity;
                            oEnt.Erase();
                        }
                    }

                    ed.WriteMessage("\nTo delete signature layer");
                    LayerTable layerTable = tr.GetObject(db.LayerTableId, OpenMode.ForWrite) as LayerTable;
                    if (layerTable.Has(lyname))
                    {
                        //delete the old layer
                        ObjectId LTR_id = layerTable[lyname];
                        ObjectIdCollection idCol = new ObjectIdCollection();
                        idCol.Add(LTR_id);
                        db.Purge(idCol);

                        LayerTableRecord oLTR = tr.GetObject(LTR_id, OpenMode.ForWrite) as LayerTableRecord;
                        oLTR.Erase();
                    }

                    ed.WriteMessage("\nTo create  signature layer");
                    //create new layer
                    signatureLayer = new LayerTableRecord();
                    signatureLayer.Name = lyname;
                    layerTable.Add(signatureLayer);
                    tr.AddNewlyCreatedDBObject(signatureLayer, true);

                    tr.Commit();
                }

                if (signatureLayer != null)
                    return signatureLayer.ObjectId;
                else
                    return ObjectId.Null;
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage("\nerror in create layer " + ex.ToString());
                return ObjectId.Null;
            }
        }
        public void updateTBFromFile()
        { 
            Database db = HostApplicationServices.WorkingDatabase;
            Editor ed = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Editor;

            //read external json
            PromptFileNameResult pfnr = ed.GetFileNameForOpen("\nSpecify json file");
            if (pfnr.Status != PromptStatus.OK)
            {
                ed.WriteMessage("\nerror to read external json file " + pfnr.Status.ToString());
                return;
            }

            string paramFile = pfnr.StringResult;
            string rawJsonContent  = File.ReadAllText(paramFile);     

            Transaction tr = db.TransactionManager.StartTransaction();
            // Start the transaction
            try
            {
                //convert json to json class
                jsonDrawing jsonDrawingInstance = JsonConvert.DeserializeObject<jsonDrawing>(rawJsonContent);
                if (jsonDrawingInstance == null)
                {
                    ed.WriteMessage("\nraw json file is bad!\n");
                    return;
                }

                //string tblayer = jsonDrawingInstance.tblayer;

                //create the layer for signature
                ObjectId lyId = createLayer("signature_layer");
                if (lyId.IsNull)
                {
                    ed.WriteMessage("\nlayer cannot be created");
                    return;
                }

                // Build a filter list so that only block references are selected
                TypedValue[] filList = new TypedValue[1] {
                        new TypedValue((int)DxfCode.Start, "INSERT")
                };

                SelectionFilter filter = new SelectionFilter(filList);
                PromptSelectionResult res = ed.SelectAll(filter);

                // Do nothing if selection is unsuccessful
                if (res.Status != PromptStatus.OK)
                {
                    ed.WriteMessage("\nno any Insert in this drawing!");
                    return;
                }

                SelectionSet selSet = res.Value;
                ObjectId[] idArray = selSet.GetObjectIds();
                foreach (ObjectId blkId in idArray)
                {
                    BlockReference blkRef = (BlockReference)tr.GetObject(blkId, OpenMode.ForRead);
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead);
                    ed.WriteMessage("\nBlock: " + btr.Name);
                    btr.Dispose();

                    AttributeCollection attCol = blkRef.AttributeCollection;
                    foreach (ObjectId attId in attCol)
                    {
                        AttributeReference attRef = (AttributeReference)tr.GetObject(attId, OpenMode.ForWrite);
                        //check the block ref of title block on the specific layer 
                        if (attRef.Layer == Helper.tblayer)
                        {
                            foreach (var eachAtt in jsonDrawingInstance.tbjson)
                            {
                                if (eachAtt.tag == attRef.Tag)
                                {
                                    ed.WriteMessage("\nbegin: " + eachAtt.tag + " \n");
                                    ed.WriteMessage("\nis image: " + eachAtt.isImage + " \n");
                                    if (eachAtt.isImage)
                                    { 
                                        attRef.TextString = "";
                                        //create image for signature
                                        createImages(eachAtt, tr, lyId);
                                    }
                                    else
                                    {
                                        attRef.TextString = eachAtt.content;
                                    }
                                    break;
                                    ed.WriteMessage("\nend: " + eachAtt.tag + " \n");
                                }

                            }
                        }
                    }
                }

                tr.Commit();
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage(("\nException: " + ex.Message));
            }
            finally
            {
                tr.Dispose();
            }

            db.SaveAs("newTB.dwg", DwgVersion.Newest);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isLocalTest">true: simulate an signature image to a json string. the example image is testsig.png</param>
        void GenerateTBJson(bool isLocalTest = false)
        {
            


            Editor ed = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Editor;

            Database db = HostApplicationServices.WorkingDatabase;
            Transaction tr = db.TransactionManager.StartTransaction();
            try
            {
                ed.WriteMessage("\nbegin att checking");

                // Build a filter list so that only block references are selected
                TypedValue[] filList = new TypedValue[1] {
                  new TypedValue((int)DxfCode.Start, "INSERT")
                };

                SelectionFilter filter = new SelectionFilter(filList);
                PromptSelectionResult res = ed.SelectAll(filter);

                // Do nothing if selection is unsuccessful
                if (res.Status != PromptStatus.OK)
                    return;

                SelectionSet selSet = res.Value;
                ObjectId[] idArray = selSet.GetObjectIds();

                List<jsonAttribute> jsonDataArray = new List<jsonAttribute>();

                ed.WriteMessage("\nbegin each checking");

                foreach (ObjectId blkId in idArray)
                {
                    BlockReference blkRef = (BlockReference)tr.GetObject(blkId, OpenMode.ForRead);
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead);
                    ed.WriteMessage("\nBlock: " + btr.Name);
                    btr.Dispose();

                    AttributeCollection attCol = blkRef.AttributeCollection;

                    //attribute index
                    int index = 0;

                    foreach (ObjectId attId in attCol)
                    {
                        AttributeReference attRef = (AttributeReference)tr.GetObject(attId, OpenMode.ForRead);
                        if (attRef.Layer == "AM_BOR")
                        {
                            ed.WriteMessage("\nbegin: " + attRef.Tag);
                            string _height = attRef.Height.ToString();
                            string _tag = attRef.Tag;

                            int pFrom = _tag.IndexOf("{") + 1;
                            int pTo = _tag.LastIndexOf("}");

                            string _width_radio = _tag.Substring(pFrom, pTo - pFrom);

                            string _pos = attRef.Position.X.ToString() + "," +
                            attRef.Position.Y.ToString() + "," +
                            attRef.Position.Z.ToString();

                            string _cont = attRef.TextString;
                            var jsonData = new jsonAttribute()
                            {
                                tag = _tag,
                                height = _height,
                                width_ratio = _width_radio,
                                position = _pos,
                                content = _cont,
                                isImage = false,
                                imgbase64 = ""
                            };

                            //if this is to test an image locally
                            //only simulate the attribute in even index will be an image
                            if (isLocalTest && (index%2==1))
                            {
                                jsonData.isImage = true;
                                jsonData.imgbase64 = imageToBase64();
                            }

                            jsonDataArray.Add(jsonData);
                            ed.WriteMessage("end: " + attRef.Tag);

                            index++;

                        }
                        //tag: {12.3} is the\ ratio of the defined width for the text to the text height. For example, if the text height is 5 units, and the width of the available space is 100 units, the value between the curly brackets is 20.
                        //http://knowledge.autodesk.com/support/autocad-mechanical/getting-started/caas/CloudHelp/cloudhelp/2015/ENU/AutoCAD-Mechanical/files/GUID-ADFE83F7-CE92-4996-8231-D3C5FD5A1A92-htm.html
                    }
                }

                tr.Commit();

                var jsonDrawingInstance = new jsonDrawing()
                {
                    tbjson = jsonDataArray.ToArray<jsonAttribute>()
                };

                // this is the Newtonsoft API method
                string json_data = JsonConvert.SerializeObject(jsonDrawingInstance);

                var jsonOut = Path.Combine(Helper.jsonfilename);
                FileStream fs = new FileStream(jsonOut, FileMode.Create);
                StreamWriter sw = new StreamWriter(fs);
                try
                {
                    sw.Write(json_data);
                    sw.Flush();
                }
                catch (System.Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.Message.ToString());
                }
                finally
                {
                    sw.Close();
                    fs.Close();
                }

                ed.WriteMessage("\nend att checking");
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage(("\nException: " + ex.Message));
                return;
            }
            finally
            {
                tr.Dispose();
            } 
        }
Ejemplo n.º 43
0
        public static void SelectTables(string msg)
        {
            Document acDoc = Application.DocumentManager.MdiActiveDocument; //Текущий документ.
            Editor acDocEd = acDoc.Editor; // Editor текущего документа.
            Database acDocDb = acDoc.Database; // Database текущего документа.

            Dictionary<string, string> globalVolumesNamesAndUnits = new Dictionary<string, string>(); //Наименования объемов и единиц измерения
            Dictionary<double, ObjectId> globalPKsAndObjectIds = new Dictionary<double, ObjectId>(); //ПК для подсчета объемов и соответвующие им идентификаторы определений блоков с таблицами

            using (acDoc.LockDocument()) // блокировка документа
            {
                using (Transaction acTrans = acDocDb.TransactionManager.StartTransaction()) // Начало Транзакции.
                {
                    //открываем таблицу блоков чертежа для чтения
                    BlockTable acDocDbBlockTable = (BlockTable)acTrans.GetObject(acDocDb.BlockTableId, OpenMode.ForRead);

                    // Создание TypedValue array для определение параметров фильтра.
                    var acTypedValueArray = new TypedValue[2];
                    acTypedValueArray.SetValue(new TypedValue((int)DxfCode.Start, "INSERT"), 0); // Параметр фильтра под номером 0.
                    acTypedValueArray.SetValue(new TypedValue((int)DxfCode.LayerName, "acVlm_*"), 1); // Параметр фильтра под номером 1.

                    // Assign the filter criteria to a SelectionFilter object
                    var acSelectionFilterObject = new SelectionFilter(acTypedValueArray);

                    // Задание опций выбора объектов.
                    var acSelectionSetOptions = new PromptSelectionOptions
                    {
                        AllowDuplicates = false,
                        RejectObjectsOnLockedLayers = true,
                        //SingleOnly = true,
                        MessageForAdding = msg
                    };

                    // Выбор объектов
                    var acSelectionSetPrompt = acDocEd.GetSelection(acSelectionSetOptions, acSelectionFilterObject);

                    if (acSelectionSetPrompt.Status == PromptStatus.OK)
                    {
                        var acSelectionSet = acSelectionSetPrompt.Value;
                        //MessageBox.Show("Количество выбранных объектов = " + acSelectionSet.Count.ToString(), myCommands.msgBoxCaption_acVolume);
                        // ReSharper disable once LoopCanBeConvertedToQuery

                        //Перебираем объекты и определяем количество наименований объемов, а так же количество пикетов для посчета объемов

                        foreach (SelectedObject acSelectedObject in acSelectionSet)
                        {
                            if (acSelectedObject != null)
                            {
                                Entity acEnt = acTrans.GetObject(acSelectedObject.ObjectId, OpenMode.ForWrite) as Entity;

                                if (acEnt != null)
                                {
                                    BlockReference objBlockReference = (BlockReference)acEnt;
                                    if (objBlockReference.Layer.Contains("acVlm_")) // проверяем, принадлежит ли выбранный блок к нужному слою
                                    {
                                        ObjectId btrObjectId = acDocDbBlockTable[objBlockReference.Name]; //получаем ObjectId определения блока по имени его вхождения (objBlockReference.Name)
                                        BlockTableRecord objBlockTableRecord = (BlockTableRecord)btrObjectId.GetObject(OpenMode.ForRead); //Конвертируем объект в определние блока objBlockTableRecord

                                        //определяем количество таблиц с валидными пикетами
                                        foreach (ObjectId objObjectId in objBlockReference.AttributeCollection) //для каждого объекта в коллекции атрибутов objBlockReference.AttributeCollection
                                        {
                                            AttributeReference objAttributeReference = (AttributeReference)acTrans.GetObject(objObjectId, OpenMode.ForRead); //конвертируем объект в AttributeReference
                                            if (objAttributeReference != null)
                                            {
                                                if (objAttributeReference.Tag == "ПК" & ConvertStringToDouble(objAttributeReference.TextString) >= 0) // для каждого атрибута с Тэгом="ПК" и значением >= 0
                                                {
                                                    if (!globalPKsAndObjectIds.ContainsKey(ConvertStringToDouble(objAttributeReference.TextString.Trim())))
                                                    {
                                                        globalPKsAndObjectIds.Add(ConvertStringToDouble(objAttributeReference.TextString.Trim()), btrObjectId);
                                                    }
                                                    else
                                                    {
                                                        MessageBox.Show(
                                                            "Обнаружены таблицы объемов с одиниковым значением ПК.\nВозможны ошибки в подсчете объемов.\nУдалите дублирующиеся таблицы.",
                                                            "acVolume", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                                    }
                                                    //MessageBox.Show("BlockReference.Name: " + objBlockReference.Name + "\nПК = " + objAttributeReference.TextString);
                                                }
                                            }
                                        }

                                        foreach (ObjectId objObjectIdInBtr in objBlockTableRecord) //перебираем объекты в определении блока
                                        {
                                            try //ловим таблицу
                                            {
                                                Table objTable = (Table)objObjectIdInBtr.GetObject(OpenMode.ForRead);
                                                for (int rowIndex = 1; rowIndex < objTable.Rows.Count; rowIndex++)
                                                {
                                                    string volumeName = objTable.Cells[rowIndex, 0].TextString.Trim();
                                                    string volumeUnit = objTable.Cells[rowIndex, 1].TextString.Trim();

                                                    if (!globalVolumesNamesAndUnits.ContainsKey(volumeName))
                                                    {
                                                        globalVolumesNamesAndUnits.Add(volumeName, volumeUnit);
                                                    }
                                                }
                                                //MessageBox.Show(objTable.Cells[0, 0].TextString);
                                            }
                                            catch
                                            { //throw;
                                            }

                                            //try //ловим атрибут
                                            //{
                                            //    AttributeDefinition objAttributeDefinition = (AttributeDefinition)objObjectIdInBTR.GetObject(OpenMode.ForRead);
                                            //    //MessageBox.Show(objAttributeDefinition.Tag);
                                            //}
                                            //catch
                                            //{ //throw; 
                                            //}
                                        }
                                    }
                                }
                            }
                        }
                        // определяем количество строк и столбцов в string[,] globalVolumesTable - будующей попикетной ведомости
                        int globalRowCount = 2 + (globalPKsAndObjectIds.Count - 1) * 2 + 1 + 1; // Заголовок + (Количество ПК - 1)*2 + строка с последним ПК + строка суммы
                        int globalColumnCount = 2 + globalVolumesNamesAndUnits.Count * 2; // (столбцы ПК и Длина участка) + столбцы собъемами * 2
                        string[,] globalVolumesTable = new string[globalRowCount, globalColumnCount];

                        //Заполняем заголовки и ПК в string[,] globalVolumesTable - будующей попикетной ведомости
                        globalVolumesTable[0, 0] = "ПК+";
                        globalVolumesTable[0, 1] = "Длина участка, м";
                        globalVolumesTable[globalRowCount - 1, 0] = "ВСЕГО:";
                        //Заполняем наименования объемов и единицы измерения
                        for (int i = 0; i < globalVolumesNamesAndUnits.Count; i++)
                        {
                            globalVolumesTable[0, 2 + i * 2] = globalVolumesNamesAndUnits.ElementAt(i).Key;
                            globalVolumesTable[1, 2 + i * 2] = globalVolumesNamesAndUnits.ElementAt(i).Value;
                            switch (globalVolumesNamesAndUnits.ElementAt(i).Value)
                            {
                                case "м":
                                    globalVolumesTable[1, 2 + i * 2 + 1] = "м2";
                                    break;

                                case "м2":
                                    globalVolumesTable[1, 2 + i * 2 + 1] = "м3";
                                    break;
                            }
                        }
                        //Сортируем ПК в порядке убывания
                        globalPKsAndObjectIds = globalPKsAndObjectIds.OrderBy(pair => pair.Key).ToDictionary(pair => pair.Key, pair => pair.Value);
                        // Заполняем пикеты
                        for (int i = 0; i < globalPKsAndObjectIds.Count; i++)
                        {
                            globalVolumesTable[2 + i * 2, 0] = Convert.ToString(Math.Round(globalPKsAndObjectIds.ElementAt(i).Key, 2), CultureInfo.InvariantCulture);
                        }

                        //Получаем из Dictionary globalVolumesNamesAndUnits список List<string> globalVolumesNames
                        List<string> globalVolumesNames = globalVolumesNamesAndUnits.Select(itm => itm.Key).ToList();
                        //List<double> globalPKs = globalPKsAndObjectIds.Select(itm => itm.Key).ToList();
                        List<ObjectId> globalObjectIds = globalPKsAndObjectIds.Select(itm => itm.Value).ToList();

                        //Перебираем таблицы и добавляем объемы в string[,] globalVolumesTable
                        for (int i = 0; i < globalPKsAndObjectIds.Count; i++)
                        {
                            ObjectId btrObjectId = globalPKsAndObjectIds.ElementAt(i).Value; //получаем ObjectId
                            BlockTableRecord objBlockTableRecord =
                                (BlockTableRecord)btrObjectId.GetObject(OpenMode.ForRead);
                            //Конвертируем объект в определние блока objBlockTableRecord
                            foreach (ObjectId objObjectIdInBtr in objBlockTableRecord) //перебираем объекты в определении блока
                            {
                                try //ловим таблицу
                                {
                                    Table objTable = (Table)objObjectIdInBtr.GetObject(OpenMode.ForRead);
                                    for (int rowIndex = 1; rowIndex < objTable.Rows.Count; rowIndex++)
                                    {
                                        string volumeName = objTable.Cells[rowIndex, 0].TextString.Trim();
                                        if (globalVolumesNames.Contains(volumeName) & globalPKsAndObjectIds.ContainsValue(btrObjectId))
                                        {
                                            int volumeColumn = 2 + globalVolumesNames.IndexOf(volumeName) * 2;
                                            int volumeRow = 2 + globalObjectIds.IndexOf(btrObjectId) * 2;
                                            globalVolumesTable[volumeRow, volumeColumn] = objTable.Cells[rowIndex, 2].Value.ToString();
                                        }
                                    }
                                    //MessageBox.Show(objTable.Cells[0, 0].TextString);
                                }
                                catch
                                {
                                    // ignored }
                                }
                            }
                        }

                        //считаем расстояния для предпросмотра в DataGrid

                        for (int rowIndex = 3; rowIndex < globalVolumesTable.GetLength(0) - 2; rowIndex = rowIndex + 2)
                        {
                            double nextItem = ConvertStringToDouble(globalVolumesTable[rowIndex + 1, 0]);
                            double previousItem = ConvertStringToDouble(globalVolumesTable[rowIndex - 1, 0]);
                            double lengthItem = nextItem - previousItem;
                            globalVolumesTable[rowIndex, 1] = Convert.ToString(Math.Round(lengthItem, 2), CultureInfo.InvariantCulture);
                        }

                        //считаем объемы между поперечниками для предпросмотра в DataGrid

                        for (int columnIndex = 3; columnIndex < globalVolumesTable.GetLength(1); columnIndex = columnIndex + 2)
                        {
                            for (int rowIndex = 3; rowIndex < globalVolumesTable.GetLength(0) - 2; rowIndex = rowIndex + 2)
                            {
                                double nextItem = ConvertStringToDouble(globalVolumesTable[rowIndex + 1, columnIndex - 1]);
                                double previousItem = ConvertStringToDouble(globalVolumesTable[rowIndex - 1, columnIndex - 1]);
                                double volume = (nextItem + previousItem) / 2.0d * ConvertStringToDouble(globalVolumesTable[rowIndex, 1]);
                                globalVolumesTable[rowIndex, columnIndex] = Convert.ToString(Math.Round(volume, 2), CultureInfo.InvariantCulture);
                            }
                        }

                        //считаем итоги
                        for (int columnIndex = 3; columnIndex < globalVolumesTable.GetLength(1); columnIndex = columnIndex + 2)
                        {
                            double columnVolume = 0.0d;
                            for (int rowIndex = 3; rowIndex < globalVolumesTable.GetLength(0) - 2; rowIndex = rowIndex + 2)
                            {
                                columnVolume = columnVolume + ConvertStringToDouble(globalVolumesTable[rowIndex, columnIndex]);
                            }
                            globalVolumesTable[globalVolumesTable.GetLength(0) - 1, columnIndex] = Convert.ToString(Math.Round(columnVolume, 2), CultureInfo.InvariantCulture);
                        }

                        //Отладочные сообщения
                        //MessageBox.Show("Выбрано блоков " + acSelectionSet.Count + ".\nИз них таблиц с пикетажем " + globalPKsAndObjectIds.Count);
                        //string str1 = "Перечень ПК и ObjectIds:\n";
                        //for (int i = 0; i < globalPKsAndObjectIds.Count; i++)
                        //{
                        //    str1 = str1 + "ПК " + globalPKsAndObjectIds.ElementAt(i).Key + ", " + "ObjectId: " + globalPKsAndObjectIds.ElementAt(i).Value + "\r";
                        //}
                        //MessageBox.Show(str1);
                        //string str = "Перечень наименований объемов:\n";
                        //for (int i = 0; i < globalVolumesNamesAndUnits.Count; i++)
                        //{
                        //    str = str + globalVolumesNamesAndUnits.ElementAt(i).Key + ", " + globalVolumesNamesAndUnits.ElementAt(i).Value + "\r";
                        //}
                        //MessageBox.Show(str);

                        //AcVolShowGlobalvolumesForm();

                        //Заполнение DataGrid
                        //DataGridFilling(globalVolumesTable, _globalVolumesForm.dataGridView1);

                        //Экспорт в Excel
                        ExportToExcel(globalVolumesTable);
                        
                    }
                    acTrans.Commit();
                }
            }
            AcVolShowForm();
        }
Ejemplo n.º 44
0
        private static string SelectPk(string msg) //Указание ПК поперечного профиля
        {
            DBText acDbText = new DBText();

            Document acDoc = Application.DocumentManager.MdiActiveDocument; //Текущий документ.
            Editor acDocEd = acDoc.Editor; // Editor текущего документа.
            Database acDocDb = acDoc.Database; // Database текущего документа.

            using (Transaction acTrans = acDocDb.TransactionManager.StartTransaction()) // Начало Транзакции.
            {
            ReturnIfNullOrEmpty:
                
                // Создание TypedValue array для определение параметров фильтра.
                var acTypedValueArray = new TypedValue[1];
                acTypedValueArray.SetValue(new TypedValue((int)DxfCode.Start, "TEXT"), 0); // Параметр фильтра под номером 0.
                
                // Assign the filter criteria to a SelectionFilter object
                var acSelectionFilterObject = new SelectionFilter(acTypedValueArray);

                // Задание опций выбора объектов.
                var acSelectionSetOptions = new PromptSelectionOptions
                {
                    AllowDuplicates = false,
                    RejectObjectsOnLockedLayers = true,
                    SingleOnly = true,
                    MessageForAdding = msg
                };



                // Выбор объектов
                var acSelectionSetPrompt = acDocEd.GetSelection(acSelectionSetOptions, acSelectionFilterObject);

                if (acSelectionSetPrompt.Status == PromptStatus.OK)
                {
                    var acSelectionSet = acSelectionSetPrompt.Value;
                    foreach (SelectedObject acSelectedObject in acSelectionSet)
                    {
                        if (acSelectedObject != null)
                        {
                            var acEnt = acTrans.GetObject(acSelectedObject.ObjectId, OpenMode.ForWrite) as Entity;

                            if (acEnt != null)
                            {
                                acDbText = (DBText)acEnt;
                            }
                        }
                    }
                }

                if (acSelectionSetPrompt.Status == PromptStatus.Error)
                {
                     MessageBox.Show("ПК не выбран, повторите попытку!", myCommands.msgBoxCaption_acVolume, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                     goto ReturnIfNullOrEmpty;
                }

                if (acSelectionSetPrompt.Status == PromptStatus.Cancel)
                {
                    //MessageBox.Show("Статус Cancel");
                    //MessageBox.Show("Выбор пикета отменен!\nТаблица объемов не будет привязана к пикету и не будет учитываться при экспорте объемов в Excel.", "acVolume", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    acTrans.Commit();
                    return "-1";
                }
                acTrans.Commit();
            }

            //MessageBox.Show("acDBText = " + acDBText.TextString.Trim());
            return acDbText.TextString.Trim();
        }
Ejemplo n.º 45
0
        public static decimal[] CommandAcVol() // Выбор объектов и возврат массива объемов согласно списку слоев в listBoxLayers
        {
            try
            {
                Document acDoc = Application.DocumentManager.MdiActiveDocument; //Текущий документ.
                Editor acDocEd = acDoc.Editor; // Editor текущего документа.
                Database acDocDb = acDoc.Database; // Database текущего документа.

                //int layersCount = _form.listBoxLayers.Items.Count;
                decimal[] decVolumesArray = new decimal[_form.listBoxLayers.Items.Count];

                using (acDoc.LockDocument()) // блокировка документа
                {
                    using (Transaction acTrans = acDocDb.TransactionManager.StartTransaction()) // Начало Транзакции.
                    {

                        // Создание TypedValue array для определение параметров фильтра.
                        var acTypedValueArray = new TypedValue[2];
                        acTypedValueArray.SetValue(new TypedValue((int)DxfCode.Start, "*POLYLINE"), 0); // Параметр фильтра под номером 0.
                        acTypedValueArray.SetValue(new TypedValue((int)DxfCode.LayerName, "acVlm_*"), 1); // Параметр фильтра под номером 1.
                        // Assign the filter criteria to a SelectionFilter object
                        var acSelectionFilterObject = new SelectionFilter(acTypedValueArray);

                        // Задание опций выбора объектов.
                        var acSelectionSetOptions = new PromptSelectionOptions
                        {
                            AllowDuplicates = false,
                            RejectObjectsOnLockedLayers = true,
                            MessageForAdding = "Выберите контуры для подсчета объемов:"
                        };


                        var acSelectionSetPrompt = acDocEd.GetSelection(acSelectionSetOptions, acSelectionFilterObject);

                        if (acSelectionSetPrompt.Status == PromptStatus.OK)
                        {
                            var acSelectionSet = acSelectionSetPrompt.Value;
                            //int polylineCount = 0;

                            double sclFactor = 0.0;
                            switch (_form.comboBoxScale.SelectedIndex)
                            {
                                case 0:
                                    sclFactor = 10.0;
                                    break;
                                case 1:
                                    sclFactor = 5.0;
                                    break;
                            }

                            foreach (SelectedObject acSelectedObject in acSelectionSet)
                            {
                                if (acSelectedObject != null)
                                {
                                    var acEnt = acTrans.GetObject(acSelectedObject.ObjectId, OpenMode.ForWrite) as Entity;

                                    if (acEnt != null)
                                    {
                                        var acPolyLine = (Polyline)acEnt;
                                        for (int layerNumber = 0; layerNumber < _form.listBoxLayers.Items.Count; layerNumber++)
                                        {

                                            string layerPostfix = "";
                                            switch ((string)_form.listBoxLayersUnits.Items[layerNumber])
                                            {
                                                case "м2":
                                                    layerPostfix = "_msrA";
                                                    break;
                                                case "м":
                                                    layerPostfix = "_msrL";
                                                    break;
                                            }

                                            if (acPolyLine.Layer == "acVlm_" + _form.listBoxLayers.Items[layerNumber] + layerPostfix)
                                            {
                                                if ((string)_form.listBoxLayersUnits.Items[layerNumber] == "м2")
                                                {
                                                    decVolumesArray[layerNumber] = decVolumesArray[layerNumber] + (decimal)(acPolyLine.Area / (sclFactor * sclFactor));
                                                }
                                                if ((string)_form.listBoxLayersUnits.Items[layerNumber] == "м")
                                                {
                                                    decVolumesArray[layerNumber] = decVolumesArray[layerNumber] + (decimal)(acPolyLine.Length / sclFactor);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        else
                        {
                            acTrans.Abort();
                            AcVolShowForm();
                            return null;
                        }
                        acTrans.Commit();
                        return decVolumesArray;
                    }
                }
            }

            catch (NullReferenceException)
            {
                return null;
            }
        }
        //获取圈选的楼房
        public static List<Building> getCircleBuildings()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            List<Building> buildings;
            if (currentSolutionIndex == -1)
            {
                System.Windows.Forms.MessageBox.Show("请先新建解决方案!");
                return null ;
            }
            try
            {
                //设置过滤器
                TypedValue[] tvs = new TypedValue[] {
                    new TypedValue((int)DxfCode.Operator,"<and"),
                    new TypedValue((int)DxfCode.LayerName,"our_outline_layer"),
                    new TypedValue((int)DxfCode.Operator,"and>")
                };
                SelectionFilter sf = new SelectionFilter(tvs);
                //让用户进行圈画选择

                PromptSelectionResult psr = ed.GetSelection(sf);
                if (psr.Status != PromptStatus.OK)
                {
                    ed.WriteMessage("Action releasd");
                    return null;
                }
                else
                {
                    if (psr.Value == null)
                        return null;

                    Database db = doc.Database;
                    Transaction tr = db.TransactionManager.StartTransaction();

                    //获得所选的objectId的集合
                    ObjectId[] objectIds = psr.Value.GetObjectIds();

                    ed.WriteMessage(">>>", psr.Value.Count);
                    buildings = new List<Building>();

                    using (DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument())
                    {
                        Color currColor = getNextColor();
                        foreach (ObjectId oId in objectIds)
                        {
                            if (HeatSourceLayoutApp.buildings.ContainsKey(oId))
                            {
                                Building bui = HeatSourceLayoutApp.buildings[oId];
                                buildings.Add(bui);
                            }
                            //改变选中线段的颜色
                            Entity ent = (Entity)tr.GetObject(oId, OpenMode.ForRead);
                            ent.UpgradeOpen();
                            ent.Color = currColor;
                            //保存颜色信息
                            saveColorInfo(oId, currColor);
                            //记录修改过的颜色的信息
                            changedEntityList.Add(oId);
                        }
                        //生成地区
                        //District dt = new District();
                        //dt.Buildings = buildings;
                        //加入solution
                        Solution sl = HeatSource.HeatSourceLayoutApp.currentSolution;
                        if (sl != null)
                        {
                            //sl.Districts.Add(dt);
                        }
                        tr.Commit();
                    }
                }
                return buildings;
            }
            catch (System.Exception exc)
            {
                ed.WriteMessage("Exception" + exc.ToString());
                return null;
            }
        }
Ejemplo n.º 47
0
        /// <summary>
        /// Загружает в объект свойства всех слоев проекта с привязанными 
        /// к ним фигурами типа: точка, отрезок и окружность.
        /// </summary>
        private void Load()
        {
            // Обнуляем коллекцию слоев.
            Layers = new ObservableCollection<Layer>();

            // Получаем текущий документ, доступ к командной строке и БД.
            Document doc = AcadAS.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;

            // Начинаем транзакцию.
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                // Получаем таблицу слоев документа.
                LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
                // Добавляем в нашу коллекцию все слои с требуемыми параметрами.
                foreach (ObjectId ltrId in lt)
                {
                    LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(ltrId, OpenMode.ForRead);
                    Layers.Add(new Layer(ltr));
                }
                // Получаем список фигур (точка, отрезок и окружность) каждого слоя,
                // и сохраняем требуемыме параметры фигур в коллекции каждого слоя.
                foreach (var layer in Layers)
                {
                    // Обновляем предствление пользователя.
                    if (Layers[0] == layer)
                    {
                        _selectedLayer = layer;
                        OnPropertyChanged("SelectedLayer");
                    }

                    // Задание параметров фильтра.
                    TypedValue[] filterlist = new TypedValue[8];
                    filterlist[0] = new TypedValue((int)DxfCode.Operator, "<AND");
                    filterlist[1] = new TypedValue((int)DxfCode.LayerName, layer.Name);
                    filterlist[2] = new TypedValue((int)DxfCode.Operator, "<OR");
                    filterlist[3] = new TypedValue((int)DxfCode.Start, "POINT");
                    filterlist[4] = new TypedValue((int)DxfCode.Start, "LINE");
                    filterlist[5] = new TypedValue((int)DxfCode.Start, "CIRCLE");
                    filterlist[6] = new TypedValue((int)DxfCode.Operator, "OR>");
                    filterlist[7] = new TypedValue((int)DxfCode.Operator, "AND>");

                    // Создаем фильтр.
                    SelectionFilter filter = new SelectionFilter(filterlist);
                    // пытаемся получить ссылки на объекты с учетом фильтра
                    PromptSelectionResult selRes = ed.SelectAll(filter);

                    // Получаем массив ID объектов.
                    if (selRes.Value != null)
                    {
                        ObjectId[] ids = selRes.Value.GetObjectIds();

                        foreach (ObjectId id in ids)
                        {
                            // Приводим каждый из них к типу Entity.
                            Entity entity = (Entity)tr.GetObject(id, OpenMode.ForRead);
                            // Классифицируем по группам.
                            if (entity.GetType() == typeof(AcadDS.DBPoint))
                            {
                                layer.Points.Add(new Model.Point(entity as AcadDS.DBPoint));
                            }
                            else if (entity.GetType() == typeof(AcadDS.Line))
                            {
                                layer.Lines.Add(new Model.Line(entity as AcadDS.Line));
                            }
                            else if (entity.GetType() == typeof(AcadDS.Circle))
                            {
                                layer.Circles.Add(new Model.Circle(entity as AcadDS.Circle));
                            }
                        }
                    }
                }
                tr.Commit();
            }
        }
Ejemplo n.º 48
0
 /// <summary>
 /// Un metodo de selección que busca un elemento por un punto
 /// </summary>
 /// <param name="center">El centro del punto a buscar</param>
 /// <param name="filter">El filtro de selección</param>
 /// <param name="objIds">Los ids encontrados en el área</param>
 /// <param name="crossing">Selección por crossing, otro caso window</param>
 /// <returns>El metodo de selección</returns>
 public Boolean SelectByPoint(Point3d center, SelectionFilter filter, out ObjectIdCollection objIds, Boolean crossing = true)
 {
     objIds = new ObjectIdCollection();
     Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
     Polygon2D pol = new Polygon2D(15, center, 1);
     PromptSelectionResult res =
         crossing ? ed.SelectCrossingPolygon(pol.Geometry, filter) : ed.SelectWindowPolygon(pol.Geometry, filter);
     if (res.Status == PromptStatus.OK)
         objIds = new ObjectIdCollection(res.Value.GetObjectIds());
     return objIds.Count > 0;
 }
Ejemplo n.º 49
0
        public void ConvertTable()
        {
            List<DwgLine> linelst = new List<DwgLine>();
            List<TableText> LstTableText = new List<TableText>();
            List<DwgLine> UniqueLineLSt = new List<DwgLine>();
            List<TableText> UniqueTableText = new List<TableText>();

            linelst.Clear();
            LstTableText.Clear();

            //Создание фильтров выборки элементов с экрана
            TypedValue[] FilterLine = new TypedValue[9];
            FilterLine.SetValue(new TypedValue((int)DxfCode.Operator, "<or"), 0);
            FilterLine.SetValue(new TypedValue((int)DxfCode.Start, "Line"), 1);
            FilterLine.SetValue(new TypedValue((int)DxfCode.Start, "POLYLINE"), 2);
            FilterLine.SetValue(new TypedValue((int)DxfCode.Start, "LWPOLYLINE"), 3);
            FilterLine.SetValue(new TypedValue((int)DxfCode.Start, "2DPOPYLINE"), 4);
            FilterLine.SetValue(new TypedValue((int)DxfCode.Start, "3DPOLYLINE"), 5);
            FilterLine.SetValue(new TypedValue((int)DxfCode.Start, "MText"), 6);
            FilterLine.SetValue(new TypedValue((int)DxfCode.Start, "Text"), 7);
            FilterLine.SetValue(new TypedValue((int)DxfCode.Operator, "or>"), 8);
            SelectionFilter filter = new SelectionFilter(FilterLine);
            PromptSelectionResult result;
            result = ed.GetSelection(filter);

            if (result.Status == PromptStatus.OK)
            {
                ed.WriteMessage("После проверки статуса выбора");
                using (Transaction trs = dwg.TransactionManager.StartTransaction())
                {
                    try
                    {
                       ObjectId[] objects = result.Value.GetObjectIds();
                        foreach (ObjectId ObjId in objects)
                        {
                            DBObject obj = trs.GetObject(ObjId, OpenMode.ForRead);
                            Entity ent = obj as Entity;

                            if (ent.GetType() == typeof(acLine))
                            {
                                acLine acl = (acLine)ent;
                                linelst.Add(new DwgLine((int)acl.StartPoint.X, (int)acl.StartPoint.Y, (int)acl.EndPoint.X, (int)acl.EndPoint.Y));

                            }
                            else if (ent.GetType() == typeof(Polyline2d))
                            {
                                Polyline2d pl2d = (Polyline2d)ent;
                                linelst.Add(new DwgLine((int)pl2d.StartPoint.X, (int)pl2d.StartPoint.Y, (int)pl2d.EndPoint.X, (int)pl2d.EndPoint.Y));

                            }
                            else if (ent.GetType() == typeof(Polyline3d))
                            {
                                Polyline3d pl3d = (Polyline3d)ent;
                                linelst.Add(new DwgLine((int)pl3d.StartPoint.X, (int)pl3d.StartPoint.Y, (int)pl3d.EndPoint.X, (int)pl3d.EndPoint.Y));
                            }
                            else if (ent.GetType() == typeof(Polyline))
                            {
                                Polyline pl = (Polyline)ent;
                                if (pl.NumberOfVertices > 2)
                                {
                                    for (int i = 0; i <= pl.NumberOfVertices - 2; i++)
                                    {
                                        var PlSegment = pl.GetLineSegmentAt(i);
                                        linelst.Add(new DwgLine((int)PlSegment.StartPoint.X, (int)PlSegment.StartPoint.Y, (int)PlSegment.EndPoint.X, (int)PlSegment.EndPoint.Y));
                                    }
                                }
                                else
                                {
                                    linelst.Add(new DwgLine((int)pl.StartPoint.X, (int)pl.StartPoint.Y, (int)pl.EndPoint.X, (int)pl.EndPoint.Y));
                                }
                            }
                            else if (ent.GetType() == typeof(MText))
                            {
                                MText mtx = (MText)ent;
                                LstTableText.Add(new TableText(mtx.Text, (int)mtx.Location.X, (int)mtx.Location.Y));
                            }
                            else if (ent.GetType() == typeof(DBText))
                            {
                                DBText dbtxt = (DBText)ent;
                                LstTableText.Add(new TableText(dbtxt.TextString, (int)dbtxt.Position.X, (int)dbtxt.Position.Y));
                            }
                            else
                            {
                                ed.WriteMessage("Выбраны неверные типы данных");
                            }
                       }
                    }
                    catch (Autodesk.AutoCAD.Runtime.Exception ex)
                    {
                        ed.WriteMessage(ex.Message);
                        trs.Abort();
                    }

                    UniqueLineLSt = linelst.Distinct().ToList();
                    UniqueTableText = LstTableText.Distinct().ToList();
                    GetListOfLine(UniqueLineLSt);
                    trs.Commit();
                }
                CreateTable(UniqueLineLSt, UniqueTableText);
            }
        }
Ejemplo n.º 50
0
 public void List()
 {
     Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
     try
     {
         PromptSelectionOptions Opts = new PromptSelectionOptions();
         TypedValue[] filList = new TypedValue[1];
         //Build a filter list so that only block references are selected
         filList[0] = new TypedValue((int)DxfCode.Start, "INSERT");
         SelectionFilter filter = new SelectionFilter(filList);
         PromptSelectionResult res = ed.GetSelection(Opts, filter);
         //Do nothing if selection is unsuccessful
         if (res.Status != PromptStatus.OK)
             return;
         Autodesk.AutoCAD.EditorInput.SelectionSet SS = res.Value;
         ObjectId[] idArray;
         idArray = SS.GetObjectIds();
         string[] saEmployeeList = new string[4];
         //collect all employee details in saEmployeeList array
         foreach (ObjectId employeeId in idArray)
         {
             ListEmployee(employeeId, ref saEmployeeList);
             //Print employee details to the command line
             foreach (string employeeDetail in saEmployeeList)
             {
                 ed.WriteMessage(employeeDetail);
             }
             //separator
             ed.WriteMessage("----------------------" + "\r\n");
         }
     }
     catch (System.Exception ex)
     {
         ed.WriteMessage("Error Listing Employees: " + ex.Message);
     }
 }
Ejemplo n.º 51
0
        public void aa()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;

            //setting the settings for the selection filter - we want only lines filtered
            TypedValue[] acTypeValAr = new TypedValue[1]
                                {
                                    new TypedValue((int)DxfCode.Start , "Line")
                                };

            // instantiating the selection filter and getting the selection result
            SelectionFilter sf = new SelectionFilter(acTypeValAr);
            PromptSelectionOptions psoAngledLines = new PromptSelectionOptions();
            psoAngledLines.MessageForAdding = "Please select rough area where angled lines exist";
            PromptSelectionResult psrAngledLines = ed.GetSelection(psoAngledLines, sf);

            //if the lines are above a certain angle then put it into an objectIDCollect
            if (psrAngledLines.Status == PromptStatus.OK)
            {

                using (Transaction tr = db.TransactionManager.StartTransaction() )
                {
                    ObjectIdCollection filteredLines = new ObjectIdCollection();
                    BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                    BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;

                    foreach (SelectedObject so in psrAngledLines.Value)
                    {
                        Line ln = tr.GetObject(so.ObjectId, OpenMode.ForWrite) as Line;
                                if (ln != null)
                                {

                                    try
                                    {
                                        //if it's a small line then delete asap.
                                        if (ln.Length < 0.2)
                                        { ln.Erase(true); }
                                        else
                                        {
                                                    {
                                                        if      ((ln.Angle < (((Math.PI) / 4) + ((Math.PI) / 12)) && ln.Angle > (((Math.PI) / 4) - ((Math.PI) / 12))) ||
                                                                (ln.Angle < (((Math.PI) * 3 / 4) + ((Math.PI) / 12)) && ln.Angle > (((Math.PI) * 3 / 4) - ((Math.PI) / 12))) ||
                                                                (ln.Angle < (((Math.PI) * 5 / 4) + ((Math.PI) / 12)) && ln.Angle > (((Math.PI) * 5 / 4) - ((Math.PI) / 12))) ||
                                                                (ln.Angle < (((Math.PI) * 7 / 4) + ((Math.PI) / 12)) && ln.Angle > (((Math.PI) * 7 / 4) - ((Math.PI) / 12))))
                                                                // if it meets those conditions then erase
                                                        {
                                                            filteredLines.Add(ln.ObjectId);
                                                            ln.Erase(true);
                                                        }
                                                    } //end else statement
                                         } //if erased
                                        }
                                        catch
                                        {
                                            doc.Editor.WriteMessage("\nLine already deleted, or perhaps some other type of error") ;
                                        }
                                }//end if ln!= null
                    }//end foreach
                        tr.Commit();
                }//end using transaction

                TypedValue[] acTypeValAr1 = new TypedValue[2]
                                {
                                    new TypedValue((int)DxfCode.Start , "MTEXT"),
                                    new TypedValue((int)DxfCode.Text , "*"),
                                };

                SelectionFilter sf1 = new SelectionFilter(acTypeValAr1);

                psoAngledLines.MessageForAdding = "Please select rough area where angled lines exist";
                psrAngledLines = ed.GetSelection(psoAngledLines, sf1);

                //TypedValue[] acTypeValAr1 = new TypedValue[4];

                //acTypeValAr1.SetValue(new TypedValue((int)DxfCode.Operator, "<or"), 0);
                //acTypeValAr1.SetValue(new TypedValue((int)DxfCode.Color, 5), 1);
                //acTypeValAr1.SetValue(new TypedValue((int)DxfCode.Color, 162), 2);
                //acTypeValAr1.SetValue(new TypedValue((int)DxfCode.Operator, "or>"), 3);

                //SelectionFilter sf1 = new SelectionFilter(acTypeValAr1);

                //PromptSelectionResult colourDelete             =   ed.SelectAll(sf1);

                //using (Transaction tr = doc.TransactionManager.StartTransaction())
                //{
                //    foreach (Entity en in colourDelete.Value)
                //    {
                //        Entity ent = tr.GetObject(en.ObjectId, OpenMode.ForWrite) as Entity;
                //        ent.Erase();
                //    }
                //}

                //using (Transaction tr = doc.TransactionManager.StartTransaction())
                //{
                //    BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                //    //BlockTableRecord btr = tr.GetObject( bt[]     );
                //}

                //ed.WriteMessage("there are {0} of the filtered lines here", filteredLines.Count);

              }
        }
Ejemplo n.º 52
0
        public void List()
        {
            Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            try
            {
                PromptSelectionOptions Opts = new PromptSelectionOptions();

                //Build	a filter list so that only block references	are	selected
                TypedValue[] filList =	{ new TypedValue((int)DxfCode.Start, "INSERT") };

                SelectionFilter filter = new SelectionFilter(filList);
                PromptSelectionResult res = ed.GetSelection(Opts, filter);

                //Do nothing if	selection is unsuccessful
                if (res.Status != PromptStatus.OK)
                    return;

                Autodesk.AutoCAD.EditorInput.SelectionSet SS = res.Value;
                ObjectId[] idArray = SS.GetObjectIds();

                //List the selection set
                EmployeeCount(idArray);
            }
            catch
            {
                ed.WriteMessage("Error in Listing Employees");
            }
        }
 public ObjectIdCollection GetEntitiesOnLayer(string layerName)
 {
     Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
      Editor ed = doc.Editor;
      TypedValue[] tvs = new TypedValue[1] { new TypedValue((int)DxfCode.LayerName, layerName) };
      SelectionFilter sf = new SelectionFilter(tvs);
      PromptSelectionResult psr = ed.SelectAll(sf);
      if (psr.Status == PromptStatus.OK)
     return new ObjectIdCollection(psr.Value.GetObjectIds());
      else return new ObjectIdCollection();
 }
Ejemplo n.º 54
0
        // Works!! MUST CHECK if something is selected - if not, then return null please for goddsakes!!
        public static SelectionSet GetSS(SelectionFilter sf)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;

            //clear the current selection
            ObjectId[] idarrayEmpty = new ObjectId[0];
            ed.SetImpliedSelection(idarrayEmpty);

            PromptSelectionOptions pso = new PromptSelectionOptions();
            pso.MessageForAdding = "\nSelect block(s)";

            PromptSelectionResult psr = ed.GetSelection(pso, sf);

            return psr.Value;
        }
Ejemplo n.º 55
0
 /// <summary>
 /// Pапрос выбора блоков
 /// </summary>      
 /// <param name="msg">Строка запроса</param>
 /// <exception cref="Exception">Отменено пользователем.</exception>
 /// <returns>Список выбранных блоков</returns>
 public static List<ObjectId> SelectBlRefs(this Editor ed, string msg)
 {
     var filList = new TypedValue[1] { new TypedValue((int)DxfCode.Start, "INSERT") };
     SelectionFilter filter = new SelectionFilter(filList);
     var selOpt = new PromptSelectionOptions();
     selOpt.MessageForAdding = msg;
     var selRes = ed.GetSelection(selOpt, filter);
     if (selRes.Status == PromptStatus.OK)
     {
         return selRes.Value.GetObjectIds().ToList();
     }
     else
     {
         throw new Exception("\nОтменено пользователем");
     }
 }
Ejemplo n.º 56
0
        public static void DeleteEntitiesOnLayer(string layerName, SelectionFilter sf)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            PromptSelectionResult psr = ed.SelectAll(sf);

            if (psr.Status == PromptStatus.OK)
            {
                ObjectIdCollection ids = new ObjectIdCollection(psr.Value.GetObjectIds());

                using (DocumentLock docLock = doc.LockDocument())
                {
                    using (Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        foreach (ObjectId id in ids)
                        {
                            Entity en = tr.GetObject(id, OpenMode.ForWrite) as Entity;

                            if (en!=null)
                            {
                                en.Erase();
                            }
                        }

                        tr.Commit();
                    }
                }
            }
        }
        /// <summary>
        /// Prompts the user for a selection of blocks, returns a list of block references
        /// </summary>
        /// <param name="tr"></param>
        /// <returns></returns>
        private IEnumerable<BlockReference> PromptForBlock(Transaction tr)
        {
            var blocks = new List<BlockReference>();
            var filList = new[] {new TypedValue((int) DxfCode.Start, "INSERT")};
            var filter = new SelectionFilter(filList);
            var opts = new PromptSelectionOptions {MessageForAdding = "Select block references: "};

            PromptSelectionResult res = _ed.GetSelection(opts, filter);

            if (res.Status == PromptStatus.OK)
            {
                SelectionSet selSet = res.Value;
                ObjectId[] idArray = selSet.GetObjectIds();
                blocks.AddRange(
                    idArray.Select(blkId => (BlockReference) tr.GetObject(blkId, OpenMode.ForWrite)).Where(
                        blkRef => ValidateBlock(blkRef, tr)));
            }
            return blocks;
        }
Ejemplo n.º 58
0
 private PromptSelectionResult GetHeightMarks()
 {
     string databaseBlockName = GetDatabaseBlockName();
     TypedValue[] typedValue = new TypedValue[] { new TypedValue((int)DxfCode.BlockName, databaseBlockName) };
     SelectionFilter filter = new SelectionFilter(typedValue);
     PromptSelectionResult selectedMarks = editor.GetSelection(filter);
     return selectedMarks;
 }
Ejemplo n.º 59
0
        private static SelectionFilter GetSSFilter()
        {
            // selection filter. We filter by the name of the panel and also we want only lines
            TypedValue[] acTypeValAr = new TypedValue[4] {new TypedValue((int)DxfCode.Operator, "<or"),
                                new TypedValue((int)DxfCode.LayerName, "PANELS"),
                                new TypedValue((int)DxfCode.LayerName, "0"),
                                new TypedValue((int)DxfCode.Operator, "or>")
                                };

            // the instantiating of a selection filter which selects on certain layers and which selects only lines
            SelectionFilter sf = new SelectionFilter(acTypeValAr);

            return sf;
        }