Beispiel #1
0
        /// <summary>
        /// Adds a new layer to the drawing.
        /// </summary>
        /// <param name="name">Name for the new layer.</param>
        /// <param name="color">Color for the new layer.</param>
        /// <remarks>The layer only gets added if it doesn't exist, there's no exception
        /// for trying to add an existing layer.</remarks>
        public static void AddLayer(string name, Color color)
        {
            Database    database    = HostApplicationServices.WorkingDatabase;
            Transaction transaction = database.TransactionManager.StartTransaction();

            LayerTable       layerTable  = (LayerTable)transaction.GetObject(database.LayerTableId, OpenMode.ForWrite);
            LayerTableRecord layerRecord = new LayerTableRecord();

            layerRecord.Name  = name;
            layerRecord.Color = color;

            try
            {
                if (!layerTable.Has(name))
                {
                    layerTable.Add(layerRecord);
                    transaction.AddNewlyCreatedDBObject(layerRecord, true);
                    transaction.Commit();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                layerRecord.Dispose();
                transaction.Dispose();
            }
        }
Beispiel #2
0
        public void LockLayer()
        {
            ObjectId         id = CreateLayerNoTrans();
            LayerTableRecord layerTableRecord = this.Transaction.GetObject(id, OpenMode.ForWrite) as LayerTableRecord;

            layerTableRecord.IsLocked = true;

            Debug.Assert(LayerManager.IsLocked(this.Database, layerTableRecord.Name));

            Debug.Assert(layerTableRecord.IsLocked);
            layerTableRecord.Dispose();
        }
Beispiel #3
0
 public void Dispose()
 {
     if (_ltr != null)
     {
         try
         {
             if (_ltr.ObjectId != Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database.Clayer)
             {
                 _ltr.IsFrozen = isfrozen;
             }
             _ltr.IsLocked = islock;
             _ltr.IsOff    = isoff;
         }
         catch (Exception ex) { throw ex; }
         finally
         {
             _ltr.Dispose();
         }
     }
 }
        public static System.Data.DataTable GetAllPolylineNums()
        {
            System.Data.DataTable table = new System.Data.DataTable("编码");
            table.Columns.Add(new System.Data.DataColumn(("多段线id"), typeof(string)));
            table.Columns.Add(new System.Data.DataColumn(("个体编码"), typeof(string)));
            table.Columns.Add(new System.Data.DataColumn(("个体要素"), typeof(string)));
            table.Columns.Add(new System.Data.DataColumn(("个体名称"), typeof(string)));
            table.Columns.Add(new System.Data.DataColumn(("数量"), typeof(string)));
            table.Columns.Add(new System.Data.DataColumn(("个体阶段"), typeof(string)));

            System.Data.DataColumn column;
            System.Data.DataRow    row;

            Document     doc            = Application.DocumentManager.MdiActiveDocument;
            Editor       ed             = doc.Editor;
            Database     db             = doc.Database;
            DocumentLock m_DocumentLock = Application.DocumentManager.MdiActiveDocument.LockDocument();

            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    foreach (ObjectId layerId in LayersToList(db))
                    {
                        LayerTableRecord layer = tr.GetObject(layerId, OpenMode.ForRead) as LayerTableRecord;

                        TypedValue[] filList = new TypedValue[1] {
                            new TypedValue((int)DxfCode.LayerName, layer.Name)
                        };
                        SelectionFilter sfilter = new SelectionFilter(filList);

                        PromptSelectionResult result = ed.SelectAll(sfilter);
                        if (result.Status == PromptStatus.OK)
                        {
                            SelectionSet acSSet = result.Value;
                            foreach (ObjectId id in acSSet.GetObjectIds())
                            {
                                DBObject obj = id.GetObject(OpenMode.ForRead); //以读的方式打开对象

                                ObjectId dictId = obj.ExtensionDictionary;     //获取对象的扩展字典的id

                                Entity ent1 = tr.GetObject(id, OpenMode.ForRead) as Entity;
                                if (ent1 is Polyline && !dictId.IsNull)
                                {
                                    DBDictionary dict = dictId.GetObject(OpenMode.ForRead) as DBDictionary;//获取对象的扩展字典
                                    if (!dict.Contains("polylineNumber"))
                                    {
                                        continue;//如果扩展字典中没有包含指定关键 字的扩展记录,则返回null;
                                    }
                                    //先要获取对象的扩展字典或图形中的有名对象字典,然后才能在字典中获取要查询的扩展记录
                                    ObjectId     xrecordId = dict.GetAt("polylineNumber");                     //获取扩展记录对象的id
                                    Xrecord      xrecord   = xrecordId.GetObject(OpenMode.ForRead) as Xrecord; //根据id获取扩展记录对象
                                    ResultBuffer resBuf    = xrecord.Data;

                                    ResultBufferEnumerator rator = resBuf.GetEnumerator();
                                    int i = 0;

                                    List <string> values = new List <string>();
                                    while (rator.MoveNext())
                                    {
                                        TypedValue re = rator.Current;
                                        values.Add((string)re.Value);
                                    }

                                    bool hasData = false;
                                    foreach (System.Data.DataRow item in table.Rows)
                                    {
                                        if ((string)item["个体编码"] == values[0] && (string)item["个体要素"] == values[1] && (string)item["个体名称"] == values[2] && (string)item["个体阶段"] == values[3])
                                        {
                                            item["多段线id"] += id.Handle.Value.ToString() + ",";
                                            int count = 0;
                                            int.TryParse((string)item["数量"], out count);
                                            item["数量"] = count + 1;
                                            hasData    = true;
                                            break;
                                        }
                                    }
                                    if (!hasData)
                                    {
                                        row          = table.NewRow();
                                        row["多段线id"] = id.Handle.Value.ToString() + ",";
                                        row["数量"]    = 1;
                                        while (rator.MoveNext())
                                        {
                                            TypedValue re = rator.Current;
                                            if (i == 0)
                                            {
                                                row["个体编码"] = re.Value;
                                            }
                                            if (i == 1)
                                            {
                                                row["个体要素"] = re.Value;
                                            }
                                            if (i == 2)
                                            {
                                                row["个体名称"] = re.Value;
                                            }
                                            if (i == 3)
                                            {
                                                row["个体阶段"] = re.Value;
                                            }
                                            i++;
                                        }
                                        table.Rows.Add(row);
                                    }
                                    resBuf.Dispose();
                                    xrecord.Dispose();
                                    dict.Dispose();
                                }
                                ent1.Dispose();
                                obj.Dispose();
                            }
                        }

                        layer.Dispose();
                    }
                    tr.Commit();
                }
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.ToString());
            }
            finally
            {
                m_DocumentLock.Dispose();
            }
            return(table);
        }
        public override String Process()
        {
            Regex pattern1 = new Regex(@"^[ACDFIJKNTVWX][0-9][0-9][0-9][0-9][0-9][0-9][A-Z]?((-|–)[0-9][0-9]?)?$");
            Regex pattern2 = new Regex(@"^[ABCDEGHKLNPRUTZ][0-9][0-9][0-9][0-9]?((-|–)[0-9][0-9]?)?$");
            Regex pattern3 = new Regex(@"^[0-9][0-9][0-9][0-9][0-9][0-9][A-Z]?((-|–)([0-9]|[A-Z]))?$");

            Int32 numErrorsPerDWG = 0, numErrorsTotal = 0;

            FileInfo textReport;

            //if (!CheckDirPath()) { return "Invalid path: " + _Path; }


            try
            {
                BeforeProcessing();
            }
            catch (System.Exception se)
            {
                return("Layer Checker processing exception: " + se.Message);
            }

            try
            {
                textReport = new FileInfo(_Path + "\\dwgsource_check_" + DateTime.Now.ToString("ddHHmmss") + ".txt");
                writer     = new StreamWriter(textReport.FullName);
            }
            catch
            {
                _Logger.Dispose();
                return("Could not open checker log file in: " + _Path);
            }
            //try { _Logger = new Logger(_Path + "\\LayerCheckerErrorLog.txt"); }
            //catch { return "Could not create error log file in: " + _Path; }

            //StartTimer();

            #region Get dwgs and create checked dir if multi dir box is checked

            if (MultiDir)
            {
                try
                {
                    IEnumerable <String> dirList = Directory.EnumerateDirectories(_Path);
                    Directory.CreateDirectory(_Path + "\\checked\\");

                    foreach (String dirToCopy in dirList)
                    {
                        if (dirToCopy.Contains("checked"))
                        {
                            continue;
                        }
                        Directory.CreateDirectory(String.Concat(_Path, "\\checked\\", dirToCopy.Substring(dirToCopy.LastIndexOf("\\") + 1)));
                    }
                }
                catch (System.Exception se)
                {
                    _Logger.Log("Error re-creating directory structure in new folder in: " + _Path + " because: " + se.Message);
                    return("Error re-creating directory structure in new folder in: " + _Path);
                }

                try { GetDwgList(SearchOption.AllDirectories, (inFileStr) => !inFileStr.Contains("\\checked\\")); }
                catch (System.Exception se)
                {
                    _Logger.Log(" Not all .dwg files could be enumerated because: " + se.Message);
                    return("Could not get all DWG files");
                }
            }
            else
            {
                try { GetDwgList(SearchOption.TopDirectoryOnly); }
                catch (System.Exception se)
                {
                    _Logger.Log(" Not all DWG files could be enumerated because: " + se.Message);
                    return("Could not get all dwg files in: " + _Path);
                }
            }
            #endregion
            try
            {
                foreach (String currentDWG in DwgList)
                {
                    Database      oldDb            = HostApplicationServices.WorkingDatabase;
                    StringBuilder currentDwgErrors = new StringBuilder();
                    numErrorsPerDWG = 0;
                    String ms = "";

                    using (Database db = new Database(false, true))
                    {
                        try
                        {
                            db.ReadDwgFile(currentDWG, FileOpenMode.OpenForReadAndWriteNoShare, true, String.Empty);
                            db.CloseInput(true);
                        }
                        catch (System.Exception se)
                        {
                            _Logger.Log("Could not read DWG: " + currentDWG + " because: " + se.Message);
                            continue;
                        }

                        using (Transaction acTrans = db.TransactionManager.StartTransaction())
                        {
                            using (LayerTable lt = acTrans.GetObject(db.LayerTableId, OpenMode.ForWrite) as LayerTable)
                            {
                                if (MakeChanges)
                                {
                                    db.Clayer = lt["0"];
                                }

                                foreach (ObjectId layerId in lt)
                                {
                                    LayerTableRecord layer = acTrans.GetObject(layerId, OpenMode.ForWrite) as LayerTableRecord;

                                    String curLayerName = layer.Name.ToUpper().Trim();

                                    if (curLayerName.Equals("FILENAME"))
                                    {
                                        ms = Utilities.msText(db, "FILENAME");
                                    }

                                    if (curLayerName.Equals("MSNUM"))
                                    {
                                        ms = Utilities.msText(db, "MSNUM");
                                    }

                                    if (MakeChanges)
                                    {
                                        layer.Color = Autodesk.AutoCAD.Colors.Color.FromRgb(255, 255, 255);
                                    }

                                    if ((String.Equals(curLayerName, "0")) ||
                                        (String.Equals(curLayerName, "DEFPOINTS")) ||
                                        (String.Equals(curLayerName, "COLUMN")) ||
                                        (String.Equals(curLayerName, "ST_TABLE_VISIBLE")) ||
                                        (String.Equals(curLayerName, "ST_TABLE_INVISIBLE")) ||
                                        (String.Equals(curLayerName, System.IO.Path.GetFileNameWithoutExtension(currentDWG).ToUpper().Trim()))
                                        )
                                    {
                                        if (MakeChanges)
                                        {
                                            layer.IsLocked = false;

                                            if (layer.IsFrozen)
                                            {
                                                layer.IsFrozen = false;
                                            }

                                            if (String.Equals(curLayerName, "ST_TABLE_INVISIBLE"))
                                            {
                                                layer.IsOff = true;
                                            }
                                            else
                                            {
                                                layer.IsOff = false;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if ((String.Equals(curLayerName, "IADS_HOTSPOTS")) ||
                                            (String.Equals(curLayerName, "TEMPLATE")) ||
                                            (String.Equals(curLayerName, "ST_AUTOCONVERT_MARKERS")) ||
                                            (String.Equals(curLayerName, "ZONE")) ||
                                            (String.Equals(curLayerName, "FILENAME")) ||
                                            (String.Equals(curLayerName, "SCALE")) ||
                                            (String.Equals(curLayerName, "MSNUM")) ||
                                            (curLayerName.StartsWith("REF_")) ||
                                            (((pattern1.IsMatch(curLayerName)) ||
                                              (pattern2.IsMatch(curLayerName)) ||
                                              (pattern3.IsMatch(curLayerName))) &&
                                             (!System.IO.Path.GetFileNameWithoutExtension(currentDWG).ToUpper().Equals(curLayerName))
                                            ))
                                        {
                                            if (MakeChanges)
                                            {
                                                layer.IsLocked = false;

                                                Utilities.delLayer(db, layer.Name, layer);
                                            }
                                        }
                                        else
                                        {
                                            currentDwgErrors.Append(layer.Name + "\t\t\t" + ms + Environment.NewLine);
                                            numErrorsPerDWG++;
                                        }
                                    }
                                    layer.Dispose();
                                }
                            }
                            acTrans.Commit();
                        }
                        if (MultiDir)
                        {
                            try
                            {
                                // Dwg is in subdir
                                if (!String.Equals(Path.GetDirectoryName(currentDWG), _Path))
                                {
                                    //Get subdir path and subdir name
                                    String subdir     = Path.GetDirectoryName(currentDWG);
                                    String subdirName = subdir.Substring(subdir.LastIndexOf("\\"));

                                    db.SaveAs(Path.GetDirectoryName(subdir) + "\\checked" + subdirName + "\\" + Path.GetFileName(currentDWG), DwgVersion.Current);
                                }

                                // Dwg is in top dir
                                else
                                {
                                    db.SaveAs(_Path + "\\" + Path.GetFileName(currentDWG), DwgVersion.Current);
                                }
                            }
                            catch (System.Exception se)
                            {
                                _Logger.Log(currentDWG + " could not be saved because: " + se.Message);
                            }
                        }
                        else
                        {
                            try
                            {
                                db.SaveAs(currentDWG, DwgVersion.Current);
                            }
                            catch (System.Exception se)
                            {
                                _Logger.Log(currentDWG + " could not be saved because: " + se.Message);
                            }
                        }
                        HostApplicationServices.WorkingDatabase = oldDb;
                    }
                    numErrorsTotal += numErrorsPerDWG;

                    if (numErrorsPerDWG > 0)
                    {
                        currentDwgErrors.Insert(0, Utilities.nl + currentDWG + Utilities.nl + "--------" + Utilities.nl);
                        writer.Write(currentDwgErrors);
                    }

                    DwgCounter++;

                    try { _Bw.ReportProgress(Utilities.GetPercentage(DwgCounter, NumDwgs)); }
                    catch { }

                    if (_Bw.CancellationPending)
                    {
                        _Logger.Log("Layer Checking cancelled by user at dwg " + DwgCounter + " out of " + NumDwgs);
                        break;
                    }
                }
            }
            catch (System.Exception se)
            {
                _Logger.Log("Processing Exception: " + se.Message);
                return("Processing Exception: " + se.Message);
            }
            finally
            {
                try { writer.Close(); }
                catch (System.Exception se) { _Logger.Log("Couldn't close layer check file because: " + se.Message); }

                if (numErrorsTotal < 1)
                {
                    try { textReport.Delete(); }
                    catch { _Logger.Log("Couldn't delete empty check file"); }
                }

                AfterProcessing();
            }

            return(String.Concat(DwgCounter.ToString(),
                                 " out of ",
                                 NumDwgs.ToString(),
                                 " dwgs processed in ",
                                 TimePassed,
                                 ". ",
                                 (_Logger.ErrorCount > 0) ? ("Error Log: " + _Logger.Path) : ("No errors found.")));
        }