public override String Process()
        {
            try
            {
                BeforeProcessing();
            }
            catch (System.Exception se)
            {
                return("Extraction processing exception: " + se.Message);
            }

            try { GetDwgList(SearchOption.AllDirectories); }
            catch (System.Exception se)
            {
                _Logger.Dispose();
                return("Could not access all files in: " + _Path + " because: " + se.Message);
            }

            try
            {
                foreach (String currentFile in DwgList)
                {
                    String newFilePath = String.Concat(_Path, "\\", System.IO.Path.GetFileName(currentFile));

                    try { File.Copy(currentFile, newFilePath, false); }

                    catch (IOException ioe)
                    {
                        _Logger.Log(String.Concat("File already exists in top directory: ", currentFile, " : ", ioe.Message));
                        continue;
                    }

                    catch (System.Exception se)
                    { _Logger.Log(String.Concat("Error copying file: ", currentFile, " : ", se.Message)); continue; }

                    DwgCounter++;

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

                    if (_Bw.CancellationPending)
                    {
                        _Logger.Log("Extractor cancelled by user at dwg " + DwgCounter.ToString() + " out of " + NumDwgs);
                        break;
                    }
                }
            }
            catch (System.Exception se)
            {
                return("Error: " + se.Message);
            }
            finally
            {
                AfterProcessing();
            }

            return(String.Concat(DwgCounter.ToString(), " out of ",
                                 NumDwgs, " DWGs copied in ",
                                 TimePassed));
        }
Example #2
0
        // copnvert all layer names to lowercase
        public override String Process()
        {
            //if (!CheckDirPath()) { return "Invalid path: " + _Path; }

            //try
            //{
            //    _Logger = new Logger(String.Concat(_Path, "\\LowercaseLayerErrorLog.txt"));
            //}
            //catch (System.Exception se)
            //{
            //    return "Could not create log file in: " + _Path + " because: " + se.Message;
            //}

            try
            {
                BeforeProcessing();
            }
            catch (System.Exception se)
            {
                //_Logger.Dispose();
                return("Lowercase layer processing exception: " + se.Message);
            }

            try { GetDwgList(SearchOption.TopDirectoryOnly); }
            catch (System.Exception se)
            {
                _Logger.Log("Could not get dwg files because: " + se.Message);
                _Logger.Dispose();
                return("Could not get all dwg files");
            }

            //StartTimer();

            try
            {
                foreach (String currentDwg in DwgList)
                {
                    System.Boolean changeMade = false;

                    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(String.Concat("Can't read DWG: ", currentDwg, " because: ", se.Message));
                            continue;
                        }
                        using (Transaction acTrans = db.TransactionManager.StartTransaction())
                        {
                            using (LayerTable lt = acTrans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable)
                            {
                                foreach (ObjectId oid in lt)
                                {
                                    using (LayerTableRecord ltr = acTrans.GetObject(oid, OpenMode.ForRead) as LayerTableRecord)
                                    {
                                        String layerName      = ltr.Name.Trim();
                                        String layerNameLower = layerName.ToLower();

                                        if (!String.Equals(layerName, layerNameLower))
                                        {
                                            changeMade = true;
                                            ltr.UpgradeOpen();
                                            ltr.Name = layerNameLower;
                                        }
                                    }
                                }
                            }
                            acTrans.Commit();
                        }
                        if (changeMade)
                        {
                            db.SaveAs(currentDwg, DwgVersion.Current);
                        }
                    }

                    DwgCounter++;

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

                    if (_Bw.CancellationPending)
                    {
                        _Logger.Log("Processing cancelled by user at DWG: " + DwgCounter.ToString());
                        return("Processing cancelled at dwg " + DwgCounter.ToString() + " out of " + NumDwgs.ToString());
                    }
                }
            }
            catch (System.Exception se) { _Logger.Log(String.Concat("Error: ", se.Message)); return("Processing error: " + se.Message); }
            finally
            {
                AfterProcessing();
            }

            return(String.Concat(" ", DwgCounter.ToString(), " out of ", NumDwgs, " dwgs processed in ", TimePassed));
        }
Example #3
0
        public override String Process()
        {
            //if (!CheckDirPath()) { return "Invalid path: " + _Path; }
            try
            {
                BeforeProcessing();
            }
            catch (System.Exception se)
            {
                return("FBD Updater processing exception: " + se.Message);
            }

            if (!xmlPath.isFilePathOK())
            {
                return("Invalid XML file path: " + xmlPath);
            }

            if (!String.Equals(".xml", System.IO.Path.GetExtension(xmlPath).ToLower()))
            {
                return("XML file does not have '.xml' extension");
            }

            //try { _Logger = new Logger(_Path + "\\updatefbdsLog.txt"); }
            //catch (System.Exception se) { return "Could not create log file in: " + _Path + " because: " + se.Message; }


            XmlReaderSettings xmlRSettings = new XmlReaderSettings();

            xmlRSettings.IgnoreWhitespace = true;

            try { xmlR = XmlReader.Create(xmlPath, xmlRSettings); }
            catch (System.Exception se)
            {
                _Logger.Dispose();
                return("XML reader could not be created in: " + _Path + " because: " + se.Message);
            }

            //StartTimer();

            try
            {
                // if files are specified
                if (!filesNotSpecified)
                {
                    try
                    {
                        // Get number of file tags in xml file
                        numFiles = XDocument.Load(xmlPath).Root.Elements("file").Count();
                    }
                    catch { }

                    while (xmlR.Read())
                    {
                        if (_Bw.CancellationPending)
                        {
                            _Logger.Log("Processing cancelled by user at dwg " + DwgCounter + " out of " + numFiles);
                            break;
                        }

                        if (xmlR.NodeType == XmlNodeType.Element && String.Equals(xmlR.Name.Trim(), "file"))
                        {
                            String oldfname = xmlR.GetAttribute("oldfname");
                            String newfname = xmlR.GetAttribute("newfname");

                            Dictionary <String, Dictionary <String, String> > map = new Dictionary <String, Dictionary <String, String> >();

                            map.Add("appendix", new Dictionary <string, string>());
                            map.Add("chapter", new Dictionary <string, string>());
                            map.Add("para0", new Dictionary <string, string>());
                            map.Add("section", new Dictionary <string, string>());
                            map.Add("figure", new Dictionary <string, string>());
                            map.Add("figsheet", new Dictionary <string, string>());
                            map.Add("figzone", new Dictionary <string, string>());
                            map.Add("table", new Dictionary <string, string>());
                            map.Add("tm", new Dictionary <string, string>());
                            map.Add("wp", new Dictionary <string, string>());

                            while (xmlR.Read())
                            {
                                if (XmlNodeType.Element == xmlR.NodeType && String.Equals(xmlR.Name.Trim(), "map"))
                                {
                                    String reftype = xmlR.GetAttribute("reftype");
                                    String oldVal  = xmlR.GetAttribute("old").Trim();
                                    String newVal  = xmlR.GetAttribute("new").Trim();

                                    if (String.Equals(reftype, "wp"))
                                    {
                                        map["wp"].Add(oldVal, newVal);
                                    }
                                    if (String.Equals(reftype, "appendix"))
                                    {
                                        map["appendix"].Add(oldVal, newVal);
                                    }
                                    if (String.Equals(reftype, "chapter"))
                                    {
                                        map["chapter"].Add(oldVal, newVal);
                                    }
                                    if (String.Equals(reftype, "para0"))
                                    {
                                        map["para0"].Add(oldVal, newVal);
                                    }
                                    if (String.Equals(reftype, "section"))
                                    {
                                        map["section"].Add(oldVal, newVal);
                                    }
                                    if (String.Equals(reftype, "figure"))
                                    {
                                        map["figure"].Add(oldVal, newVal);
                                    }
                                    if (String.Equals(reftype, "figsheet"))
                                    {
                                        map["figsheet"].Add(oldVal, newVal);
                                    }
                                    if (String.Equals(reftype, "figzone"))
                                    {
                                        map["figzone"].Add(oldVal, newVal);
                                    }
                                    if (String.Equals(reftype, "table"))
                                    {
                                        map["table"].Add(oldVal, newVal);
                                    }
                                    if (String.Equals(reftype, "tm"))
                                    {
                                        map["tm"].Add(oldVal, newVal);
                                    }
                                }

                                if (XmlNodeType.EndElement == xmlR.NodeType && String.Equals(xmlR.Name.Trim(), "file"))
                                {
                                    break;
                                }
                            }

                            DwgUpdater DwgUpdater = new DwgUpdater(String.Concat(_Path, "\\", oldfname), String.Concat(_Path, "\\", newfname), map, _Logger, Coordinates);

                            try
                            {
                                DwgUpdater.Convert();
                            }
                            catch (System.IO.IOException ioe)
                            {
                                _Logger.Log("Could not convert file: " + oldfname + " because: " + ioe.Message);
                                continue;
                            }
                            catch (System.Exception se)
                            {
                                _Logger.Log("Error processing file: " + oldfname + " because: " + se.Message);
                                continue;
                            }
                            DwgCounter++;
                            _Bw.ReportProgress(Utilities.GetPercentage(DwgCounter, numFiles));
                        }
                    }
                }
                // files are not specified
                else
                {
                    // Create Converted folder
                    try { Directory.CreateDirectory(_Path + "\\Converted"); }
                    catch { return("Unable to create new directory for converted files in: " + _Path); }

                    if (XDocument.Load(xmlPath).Root.Elements("file").Count() > 0)
                    {
                        _Logger.Log("File tags are being ignored because \"files not specified\" box was checked.");
                    }

                    //List<String> dwgs = new List<String>();

                    Dictionary <String, Dictionary <String, String> > map = new Dictionary <String, Dictionary <String, String> >();

                    map.Add("appendix", new Dictionary <string, string>());
                    map.Add("chapter", new Dictionary <string, string>());
                    map.Add("para0", new Dictionary <string, string>());
                    map.Add("section", new Dictionary <string, string>());
                    map.Add("figure", new Dictionary <string, string>());
                    map.Add("figsheet", new Dictionary <string, string>());
                    map.Add("figzone", new Dictionary <string, string>());
                    map.Add("table", new Dictionary <string, string>());
                    map.Add("tm", new Dictionary <string, string>());
                    map.Add("wp", new Dictionary <string, string>());

                    while (xmlR.Read())
                    {
                        if (XmlNodeType.Element == xmlR.NodeType && String.Equals(xmlR.Name.Trim(), "map"))
                        {
                            String reftype = xmlR.GetAttribute("reftype");
                            String oldVal  = xmlR.GetAttribute("old").Trim();
                            String newVal  = xmlR.GetAttribute("new").Trim();

                            // ignore repeat keys

                            if (String.Equals(reftype, "wp"))
                            {
                                try { map["wp"].Add(oldVal, newVal); }
                                catch (ArgumentException) { }
                            }
                            if (String.Equals(reftype, "appendix"))
                            {
                                try { map["appendix"].Add(oldVal, newVal); }
                                catch (ArgumentException) { }
                            }
                            if (String.Equals(reftype, "chapter"))
                            {
                                try { map["chapter"].Add(oldVal, newVal); }
                                catch (ArgumentException) { }
                            }
                            if (String.Equals(reftype, "para0"))
                            {
                                try { map["para0"].Add(oldVal, newVal); }
                                catch (ArgumentException) { }
                            }
                            if (String.Equals(reftype, "section"))
                            {
                                try { map["section"].Add(oldVal, newVal); }
                                catch (ArgumentException) { }
                            }
                            if (String.Equals(reftype, "figure"))
                            {
                                try { map["figure"].Add(oldVal, newVal); }
                                catch (ArgumentException) { }
                            }
                            if (String.Equals(reftype, "figsheet"))
                            {
                                try { map["figsheet"].Add(oldVal, newVal); }
                                catch (ArgumentException) { }
                            }
                            if (String.Equals(reftype, "figzone"))
                            {
                                try { map["figzone"].Add(oldVal, newVal); }
                                catch (ArgumentException) { }
                            }
                            if (String.Equals(reftype, "table"))
                            {
                                try { map["table"].Add(oldVal, newVal); }
                                catch (ArgumentException) { }
                            }
                            if (String.Equals(reftype, "tm"))
                            {
                                try { map["tm"].Add(oldVal, newVal); }
                                catch (ArgumentException) { }
                            }
                        }
                    }

                    try
                    {
                        GetDwgList(SearchOption.TopDirectoryOnly);
                        //dwgs = System.IO.Directory.EnumerateFiles(_Path, "*.dwg", System.IO.SearchOption.TopDirectoryOnly)
                        //                          .Where(f => !f.Contains("_Converted"))
                        //                          .ToList<String>();
                        numFiles = NumDwgs;
                    }
                    catch (System.Exception se)
                    {
                        _Logger.Log("Could not enumerate files because: " + se.Message);
                        return("Could not access files in: " + _Path + " because: " + se.Message);
                    }

                    foreach (String currentDwg in DwgList)
                    {
                        if (_Bw.CancellationPending)
                        {
                            _Logger.Log("Processing cancelled by user at dwg " + DwgCounter + " out of " + numFiles);
                            break;
                        }

                        DwgUpdater dwgUpdater = new DwgUpdater(currentDwg,
                                                               String.Concat(_Path,
                                                                             "\\Converted\\",
                                                                             Path.GetFileName(currentDwg)),
                                                               map,
                                                               _Logger,
                                                               Coordinates);

                        try
                        {
                            dwgUpdater.Convert();
                        }
                        catch (System.IO.IOException ioe)
                        {
                            _Logger.Log("Could not convert file: " + currentDwg + " because: " + ioe.Message);
                            continue;
                        }
                        catch (System.Exception se)
                        {
                            _Logger.Log("Error processing file: " + currentDwg + " because: " + se.Message);
                            continue;
                        }

                        DwgCounter++;

                        try { _Bw.ReportProgress(Utilities.GetPercentage(DwgCounter, NumDwgs)); }
                        catch { }
                    }
                }
            }
            catch (ArgumentException ae)
            {
                _Logger.Log("Argument Exception: " + ae.Message);
            }
            catch (System.Exception se)
            {
                _Logger.Log("Unhandled exception outside of dwg conversion: " + se.Message);
            }

            finally
            {
                AfterProcessing();

                // Close XML reader
                try { xmlR.Close(); }
                catch (System.Exception se) { _Logger.Log("Error closing XML reader: " + se.Message); }
            }

            return(String.Concat(DwgCounter.ToString(),
                                 " out of ",
                                 numFiles.ToString(),
                                 " dwgs converted in ",
                                 TimePassed,
                                 ". ",
                                 (_Logger.ErrorCount > 0) ? ("Error Log: " + _Logger.Path) : ("No errors found.")));
        }
Example #4
0
        public override string Process()
        {
            List <Row> mappings = new List <Row>();

            //  Check file path
            if (!MapPath.isFilePathOK())
            {
                return("Invalid File: " + MapPath);
            }

            // Open error logger
            try
            {
                BeforeProcessing();
            }
            catch (System.Exception se)
            {
                return("Layer Copy processing exception: " + se.Message);
            }

            // Get Dwgs
            try { GetDwgList(SearchOption.TopDirectoryOnly, (s) => true); }
            catch (System.Exception se)
            {
                _Logger.Dispose();
                return("Could not access DWG files in: " + _Path + " because: " + se.Message);
            }

            // Get mappings from text file
            try
            {
                String line = String.Empty;

                using (StreamReader reader = new StreamReader(MapPath))
                {
                    while ((line = reader.ReadLine()) != null)
                    {
                        String[] substrings = line.Split(new[] { '|' }, 3);
                        mappings.Add(new Row(substrings[0], substrings[1], substrings[2]));
                    }
                }
            }
            catch
            {
                _Logger.Log("Error parsing file: " + MapPath);
                _Logger.Dispose();
                return("Error parsing file: " + MapPath);
            }

            // Process
            try
            {
                // Save current db
                Database oldDb = HostApplicationServices.WorkingDatabase;

                foreach (String dwg in DwgList)
                {
                    String justFileName     = String.Empty;
                    String oldDashNumber    = String.Empty;
                    String newDashNumber    = String.Empty;
                    Row    correspondingRow = null;

                    //Check for BackgroundWorker cancellation
                    if (_Bw.CancellationPending)
                    {
                        _Logger.Log("Layer copying cancelled by user at dwg " + DwgCounter.ToString() + " out of " + NumDwgs);
                        break;
                    }

                    justFileName = System.IO.Path.GetFileNameWithoutExtension(dwg);

                    // Find corresponding row in mapping list
                    IEnumerable <Row> correspondingRows = mappings.Where <Row>(r => String.Equals(r.col1, justFileName));

                    if (correspondingRows.Count() < 1)
                    {
                        _Logger.Log("Skipping file because no mapping was found for: " + justFileName);
                        continue;
                    }
                    if (correspondingRows.Count() > 1)
                    {
                        correspondingRow = correspondingRows.First <Row>();
                        _Logger.Log("More than one mapping entry was found for: " + justFileName + ", using: " + correspondingRow.ToString());
                    }
                    correspondingRow = correspondingRows.First <Row>();

                    // Get old and new dash numbers from corresponding row in text file
                    try
                    {
                        oldDashNumber = DashValueRegex.Match(correspondingRow.col2).Value;
                        newDashNumber = DashValueRegex.Match(correspondingRow.col3).Value;
                    }
                    catch (System.Exception se)
                    {
                        _Logger.Log(se.Message + ": Error parsing dash numbers for: " + correspondingRow.col2 + " and " + correspondingRow.col3);
                        continue;
                    }

                    if (String.IsNullOrWhiteSpace(oldDashNumber) || String.IsNullOrWhiteSpace(newDashNumber))
                    {
                        _Logger.Log("old and new dash numbers not found in: " + correspondingRow.col2 + " and " + correspondingRow.col3);
                        continue;
                    }

                    using (Database db = new Database(false, true))
                    {
                        try
                        {
                            db.ReadDwgFile(dwg, FileOpenMode.OpenForReadAndWriteNoShare, true, String.Empty);
                            db.CloseInput(true);
                        }
                        catch (Autodesk.AutoCAD.Runtime.Exception e)
                        {
                            _Logger.Log(String.Concat(dwg + ": Could not read DWG because: ", e.Message));
                            continue;
                        }

                        using (Transaction acTrans = db.TransactionManager.StartTransaction())
                        {
                            using (LayerTable lt = acTrans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable)
                            {
                                if (lt.Has(correspondingRow.col2))
                                {
                                    using (LayerTableRecord layerToCopy = acTrans.GetObject(lt[correspondingRow.col2], OpenMode.ForRead) as LayerTableRecord)
                                    {
                                        // clone layer
                                        LayerTableRecord newLayer = (LayerTableRecord)layerToCopy.Clone();

                                        // rename the new layer using third column in corresponding row
                                        newLayer.Name = correspondingRow.col3;

                                        // upgrade layertable for write and add the new layer to the layertable and db
                                        lt.UpgradeOpen();
                                        lt.Add(newLayer);
                                        acTrans.AddNewlyCreatedDBObject(newLayer, true);

                                        // Get the block table record for this drawing's model space
                                        BlockTableRecord btr = acTrans.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForWrite) as BlockTableRecord;

                                        // Go through every entity in the block table record, and check if it's on the old layer,
                                        // and if it is, clone the entity, and add the clone to the new layer
                                        foreach (ObjectId entOid in btr)
                                        {
                                            using (Entity ent = acTrans.GetObject(entOid, OpenMode.ForRead) as Entity)
                                            {
                                                // Check if entity is on col2 layer
                                                if (String.Equals(ent.Layer, correspondingRow.col2))
                                                {
                                                    // Clone entity
                                                    Entity entityClone = ent.Clone() as Entity;

                                                    // if ent used for clone is text and a prefix or ms#, change the value
                                                    // (original entity, not the clone is used here to check type cause dxfname
                                                    // is still empty for the clone at this point)
                                                    if (ent.Id.ObjectClass.DxfName == "TEXT")
                                                    {
                                                        DBText dbt = entityClone as DBText;

                                                        // Check if text is a prefix note
                                                        if (PrefixRegex.IsMatch(dbt.TextString))
                                                        {
                                                            // use new dash number for prefix note on new layer
                                                            dbt.TextString = String.Concat(dbt.TextString.Substring(0, dbt.TextString.IndexOf("WITH") + 4), " " + newDashNumber);
                                                        }

                                                        // Check if text is MS#
                                                        if (MSRegex.IsMatch(dbt.TextString))
                                                        {
                                                            // use new dash number for MS# on new layer
                                                            dbt.TextString = String.Concat(dbt.TextString.Substring(0, dbt.TextString.IndexOf('-') + 1), newDashNumber);
                                                        }

                                                        btr.AppendEntity(dbt as Entity);
                                                        acTrans.AddNewlyCreatedDBObject(dbt as Entity, true);
                                                        dbt.Layer = newLayer.Name;
                                                    }
                                                    else
                                                    {
                                                        // Entity is not text, so add cloned entity to dwg, and change layer to newly added layer
                                                        btr.AppendEntity(entityClone);
                                                        acTrans.AddNewlyCreatedDBObject(entityClone as Entity, true);
                                                        entityClone.Layer = newLayer.Name;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    _Logger.Log(correspondingRow.col2 + " layer not found in dwg: " + dwg);
                                }
                            }
                            acTrans.Commit();
                        }

                        try
                        { db.SaveAs(String.Concat(Path.GetDirectoryName(db.Filename),
                                                  "\\",
                                                  correspondingRow.col3,
                                                  ".dwg"), DwgVersion.Current); }
                        catch (System.Exception se) { _Logger.Log("Could not save processed dwg because: " + se.Message); }
                    }

                    // Increment dwg counter
                    DwgCounter++;

                    // Report current progress to progress bar
                    _Bw.ReportProgress(Utilities.GetPercentage(DwgCounter, NumDwgs));
                }
                // Put old db back
                HostApplicationServices.WorkingDatabase = oldDb;
            }
            catch (System.Exception se)
            {
                _Logger.Log("Unhandled processing exception: " + se.Message);
                return("Unhandled processing Exception: " + se.Message);
            }
            finally
            {
                AfterProcessing();
            }

            return(String.Concat(DwgCounter,
                                 " out of ",
                                 NumDwgs,
                                 " dwgs processed in ",
                                 TimePassed,
                                 ((_Logger.ErrorCount > 0) ? (". Log file: " + _Logger.Path) : ".")));
        }
Example #5
0
        public override String Process()
        {
            try
            {
                BeforeProcessing();
            }
            catch (System.Exception se)
            {
                return("Keyfile Generation processing exception: " + se.Message);
            }
            //if (!CheckDirPath()) { return "Invalid path: " + _Path; }

            //try
            //{
            //    _Logger = new Logger(String.Concat(_Path, "\\KeyfileErrors.txt"));
            //}
            //catch (System.Exception se)
            //{
            //    // FATAL ERROR
            //    return "Could not create log file in: " + _Path + " because: " + se.Message;
            //}

            //StartTimer();

            // Get all DWG files
            try
            {
                GetDwgList(SearchOption.TopDirectoryOnly, delegate(String inFile) { return((System.IO.Path.GetFileNameWithoutExtension(inFile).Length < 15)); });
            }
            catch (SystemException se)
            {
                _Logger.Log(" DWG files could not be enumerated because: " + se.Message);
                _Logger.Dispose();
                return(" DWG files could not be enumerated because: " + se.Message);
            }

            if (NumDwgs == 0)
            {
                return("No DWGs found in: " + _Path);
            }

            foreach (String currentDWG in DwgList)
            {
                DwgCounter++;

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

                if (_Bw.CancellationPending)
                {
                    _Logger.Log("Keyfile generation cancelled by user at dwg " + DwgCounter.ToString() + " out of " + DwgList.Count);
                    break;
                }

                String dwgNameNoExt = System.IO.Path.GetFileNameWithoutExtension(currentDWG);
                String dwgNameExt   = System.IO.Path.GetFileName(currentDWG);
                String ms           = String.Empty;

                using (Database db = new Database(false, true))
                {
                    try
                    {
                        db.ReadDwgFile(currentDWG, FileOpenMode.OpenForReadAndWriteNoShare, true, String.Empty);
                        db.Regenmode = true;
                        db.CloseInput(true);
                    }
                    catch (Autodesk.AutoCAD.Runtime.Exception e)
                    {
                        _Logger.Log(String.Concat("Could not read DWG: ", dwgNameNoExt, " because: ", e.Message, "...Continuing to next DWG"));
                        continue;
                    }

                    using (Transaction acTrans = db.TransactionManager.StartTransaction())
                    {
                        // Unlock and thaw all layers
                        ToEach.toEachLayer(db, acTrans, delegate(LayerTableRecord ltr)
                        {
                            if (ltr.IsLocked)
                            {
                                ltr.IsLocked = false;
                            }
                            if (ltr.IsFrozen)
                            {
                                ltr.IsFrozen = false;
                            }
                            return(false);
                        });

                        XmlWriterSettings settings = new XmlWriterSettings();
                        settings.Encoding = Encoding.ASCII;
                        settings.Indent   = true;
                        XmlWriter xmlW = XmlWriter.Create(_Path + "\\" + dwgNameNoExt + "_key.xml", settings);

                        if (xmlW == null)
                        {
                            _Logger.Log("XML writer could not be initialized.");
                            _Logger.Dispose();
                            return("XML file could not be initialized.");
                        }

                        try
                        {
                            xmlW.WriteStartDocument();
                            xmlW.WriteStartElement("rpstl_keyfile");
                            xmlW.WriteAttributeString("version", "2.0");
                            xmlW.WriteStartElement("filename");
                            xmlW.WriteAttributeString("text", dwgNameExt);
                            xmlW.WriteEndElement();

                            // Write dwg extents
                            xmlW.WriteStartElement("extents");
                            xmlW.WriteAttributeString("x1", db.Extmin.X.truncstring(3));
                            xmlW.WriteAttributeString("y1", db.Extmin.Y.truncstring(3));
                            xmlW.WriteAttributeString("x2", db.Extmax.X.truncstring(3));
                            xmlW.WriteAttributeString("y2", db.Extmax.Y.truncstring(3));

                            double height = db.Extmax.Y - db.Extmin.Y;
                            double width  = db.Extmax.X - db.Extmin.X;

                            // Write document height and width
                            xmlW.WriteAttributeString("height", height.truncstring(3));
                            xmlW.WriteAttributeString("width", width.truncstring(3));

                            xmlW.WriteEndElement();

                            // Unlock all layers
                            ToEach.toEachLayer(db, acTrans, delegate(LayerTableRecord ltr)
                            {
                                if (ltr.IsLocked)
                                {
                                    ltr.IsLocked = false;
                                }
                                return(false);
                            }
                                               );

                            db.Regenmode = true;

                            ObjectIdCollection oidc = new ObjectIdCollection();
                            ToEach.toEachEntity(db, acTrans, delegate(Entity ent) { oidc.Add(ent.Id); return(false); });
                            db.Purge(oidc);

                            //Make Dictionary to map layerIds to layer names
                            // Note neccessary because the DBText .Layer property isn't working
                            Dictionary <ObjectId, String> LayerIdToLayerName = new Dictionary <ObjectId, string>();

                            using (LayerTable lt = acTrans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable)
                            {
                                foreach (ObjectId layerOid in lt)
                                {
                                    using (LayerTableRecord ltr = acTrans.GetObject(layerOid, OpenMode.ForRead) as LayerTableRecord)
                                    {
                                        LayerIdToLayerName.Add(ltr.Id, ltr.Name);
                                    }
                                }
                            }

                            using (LayerTable lt = acTrans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable)
                            {
                                foreach (ObjectId oid in lt)
                                {
                                    List <DBText>         msNos       = new List <DBText>();
                                    List <DBText>         callouts    = new List <DBText>();
                                    List <DBText>         viewLetters = new List <DBText>();
                                    List <DBText>         miscTexts   = new List <DBText>();
                                    List <BlockReference> cards       = new List <BlockReference>();
                                    //IEnumerable<DBText> msnos = new List<DBText>();
                                    StringBuilder prefixString = new StringBuilder();

                                    using (LayerTableRecord ltr = acTrans.GetObject(oid, OpenMode.ForRead) as LayerTableRecord)
                                    {
                                        List <DBText> linesBelowDesignations = new List <DBText>();

                                        using (BlockTable bt = acTrans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable)
                                        {
                                            using (BlockTableRecord btr = acTrans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord)
                                            {
                                                foreach (ObjectId oidbtr in btr)
                                                {
                                                    Entity ent = acTrans.GetObject(oidbtr, OpenMode.ForRead) as Entity;

                                                    if (ent.LayerId == ltr.Id)
                                                    {
                                                        if (ent.GetType() == typeof(DBText))
                                                        {
                                                            DBText dbt = ent as DBText;

                                                            String layerName = LayerIdToLayerName[dbt.LayerId];
                                                            // Skip everything on "FILENAME" and "SCALE" layers
                                                            if (String.Equals(layerName, "FILENAME") || String.Equals(layerName, "SCALE"))
                                                            {
                                                                continue;
                                                            }

                                                            if (dbt.TextString.Trim().ToUpper().EndsWith("(REF)"))
                                                            {
                                                                // Skip old refdess
                                                                continue;
                                                            }

                                                            // P/0 instead of P/O
                                                            if (String.Equals(dbt.TextString.Trim(), "P/0"))
                                                            {
                                                                _Logger.Log("P/0 found instead of P/O on layer: " + dbt.Layer + " in DWG: " + dwgNameNoExt);
                                                            }

                                                            if (calloutRegex.IsMatch(dbt.TextString) && !dbt.TextString.Contains("-") && layerName.StartsWith("m"))
                                                            {
                                                                callouts.Add(dbt);
                                                                continue;
                                                            }

                                                            // Skip view letters that are on layers that aren't m layers
                                                            if (viewLetterRegex.IsMatch(dbt.TextString.Trim()) && layerName.StartsWith("m"))
                                                            {
                                                                viewLetters.Add(dbt);
                                                                continue;
                                                            }

                                                            // Skip msnos that are on layers that aren't m layers
                                                            if ((msRegex.IsMatch(dbt.TextString.ToUpper()) || letterRegex.IsMatch(dbt.TextString.ToUpper())) && layerName.StartsWith("m"))
                                                            {
                                                                msNos.Add(dbt);
                                                                continue;
                                                            }

                                                            if (refDesRegex.IsMatch(dbt.TextString.ToUpper().Trim())) //&&
                                                            {
                                                                // Do nothing
                                                                // Look for refdess on a per-callout basis because refdes
                                                                // must be within a certain range of each callout
                                                                continue;
                                                            }

                                                            // Check if text refdes
                                                            if (dbt.TextString.Contains("DESIGNATIONS"))
                                                            {
                                                                // Get prefix from line with Designations
                                                                prefixString.Append(dbt.TextString.Substring(dbt.TextString.IndexOf("WITH") + 5).Trim());

                                                                // Get each line below Designations line and add it to list
                                                                linesBelowDesignations = ToEach.toEachDBText(db,
                                                                                                             acTrans,
                                                                                                             delegate(DBText dbtUnderDes)
                                                                {
                                                                    double yDiff = dbt.Position.Y - dbtUnderDes.Position.Y;
                                                                    double xDiff = Math.Abs(dbt.Position.X - dbtUnderDes.Position.X);

                                                                    return((dbt.Id != dbtUnderDes.Id) &&
                                                                           (dbt.LayerId == dbtUnderDes.LayerId) &&
                                                                           (dbt.Position.Y > dbtUnderDes.Position.Y) &&
                                                                           (yDiff < .5) &&
                                                                           (xDiff < .02));
                                                                });

                                                                // Append each line to String and format it with spaces and commas
                                                                foreach (DBText lineBelowDes in linesBelowDesignations)
                                                                {
                                                                    if (prefixString[prefixString.Length - 1] != ',')
                                                                    {
                                                                        prefixString.Append(String.Concat(", ", lineBelowDes.TextString.Trim()));
                                                                        continue;
                                                                    }
                                                                    if (prefixString[prefixString.Length - 1] == ',')
                                                                    {
                                                                        prefixString.Append(String.Concat(" ", lineBelowDes.TextString.Trim()));
                                                                        continue;
                                                                    }
                                                                }

                                                                // Delete trailing comma if it exists
                                                                if (prefixString[prefixString.Length - 1] == ',')
                                                                {
                                                                    prefixString.Length--;
                                                                }
                                                                // TODO ?
                                                                continue;
                                                            }

                                                            miscTexts.Add(dbt);
                                                        }

                                                        if (ent.GetType() == typeof(BlockReference))
                                                        {
                                                            BlockReference br = acTrans.GetObject(oidbtr, OpenMode.ForRead) as BlockReference;

                                                            if (br.Name.Contains("PRENOTE"))
                                                            {
                                                                _Logger.Log("DWG: " + dwgNameExt + ": layer: " + LayerIdToLayerName[br.LayerId] + ": " + "block reference prefix note found");
                                                            }
                                                            if (br.Name.Contains("HCRDTBL"))
                                                            {
                                                                cards.Add(br);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        xmlW.WriteStartElement("layer");
                                        xmlW.WriteAttributeString("text", ltr.Name);

                                        if (prefixString.Length > 0)
                                        {
                                            xmlW.WriteAttributeString("refdes_prefix", prefixString.ToString());
                                        }

                                        foreach (BlockReference br in cards)
                                        {
                                            Autodesk.AutoCAD.DatabaseServices.AttributeCollection attCol = br.AttributeCollection;

                                            AttributeReference attRefRefDes = acTrans.GetObject(br.AttributeCollection[0], OpenMode.ForRead) as AttributeReference;
                                            AttributeReference attRefItem   = acTrans.GetObject(br.AttributeCollection[1], OpenMode.ForRead) as AttributeReference;

                                            xmlW.WriteStartElement("callout");
                                            xmlW.WriteAttributeString("text", (String.IsNullOrWhiteSpace(attRefItem.TextString)) ? "no_itemno_for_card_slot" : attRefItem.TextString);
                                            xmlW.writeOutAttRefMinMax(attRefItem);

                                            xmlW.WriteStartElement("refdes");
                                            xmlW.WriteAttributeString("text", attRefRefDes.TextString);
                                            xmlW.writeOutAttRefMinMax(attRefRefDes);
                                            xmlW.WriteEndElement();

                                            xmlW.WriteEndElement();
                                        }
                                        foreach (DBText viewLetter in viewLetters)
                                        {
                                            TextEntity tent = new TextEntity(viewLetter);
                                            xmlW.WriteStartElement("view_letter");
                                            xmlW.WriteAttributeString("text", tent.text);
                                            xmlW.writeOutMinMax(tent, _Logger);
                                            xmlW.WriteEndElement();
                                        }

                                        foreach (DBText msNo in msNos)
                                        {
                                            TextEntity tent = new TextEntity(msNo);
                                            xmlW.WriteStartElement("msno");
                                            xmlW.WriteAttributeString("text", tent.text);
                                            xmlW.writeOutMinMax(tent, _Logger);
                                            xmlW.WriteEndElement();
                                        }

                                        foreach (DBText callout in callouts)
                                        {
                                            TextEntity tent = new TextEntity(callout);
                                            xmlW.WriteStartElement("callout");
                                            xmlW.writeOutMinMax(tent, _Logger);
                                            List <DBText> refDess = new List <DBText>();
                                            refDess = ToEach.toEachDBText(db,
                                                                          acTrans,
                                                                          delegate(DBText possibleRefDes)
                                            {
                                                const System.Double yRange = .15;
                                                const System.Double xRange = .15;

                                                return(possibleRefDes.Id != callout.Id &&
                                                       possibleRefDes.LayerId == callout.LayerId &&
                                                       refDesRegex.IsMatch(possibleRefDes.TextString.ToUpper().Trim()) &&
                                                       //!possibleRefDes.TextString.Contains(",") &&
                                                       //!possibleRefDes.TextString.Contains("-") &&
                                                       (possibleRefDes.IsAbove(callout, .1135 /*.5*/) ||
                                                        possibleRefDes.IsInRect(callout.AlignmentPoint.X - xRange,
                                                                                callout.AlignmentPoint.Y,
                                                                                callout.AlignmentPoint.X,
                                                                                callout.AlignmentPoint.Y + yRange) ||
                                                        possibleRefDes.IsInRect(callout.AlignmentPoint.X,
                                                                                callout.AlignmentPoint.Y,
                                                                                callout.AlignmentPoint.X + xRange,
                                                                                callout.AlignmentPoint.Y + yRange)) &&
                                                       !callout.IsRefDesBetween(possibleRefDes, acTrans, db)
                                                       );
                                            });
                                            if (refDess.Count > 1)
                                            {
                                                if (callout.Justify != AttachmentPoint.MiddleCenter)
                                                {
                                                    _Logger.Log("DWG: " +
                                                                dwgNameExt +
                                                                " layer: " +
                                                                LayerIdToLayerName[tent.dbText.LayerId] +
                                                                " callout: " +
                                                                tent.text +
                                                                " has an alignment point that isn't middle center" +
                                                                " (" +
                                                                tent.dbText.Position.X.truncstring(3) +
                                                                ", " +
                                                                tent.dbText.Position.Y.truncstring(3) +
                                                                ") ");
                                                }
                                                else
                                                {
                                                    _Logger.Log("DWG: " +
                                                                dwgNameExt +
                                                                " layer: " +
                                                                LayerIdToLayerName[tent.dbText.LayerId] +
                                                                " has more than one refdes for callout: " +
                                                                tent.text +
                                                                " (" +
                                                                tent.dbText.Position.X.truncstring(3) +
                                                                ", " +
                                                                tent.dbText.Position.Y.truncstring(3) +
                                                                ") "); //tent.dbText.Layer);
                                                }
                                            }

                                            xmlW.WriteAttributeString("text", tent.text);

                                            foreach (DBText refdes in refDess)
                                            {
                                                TextEntity tentRefDes = new TextEntity(refdes);
                                                xmlW.WriteStartElement("refdes");
                                                xmlW.WriteAttributeString("text", tentRefDes.text);
                                                xmlW.writeOutMinMax(tentRefDes, _Logger);
                                                xmlW.WriteEndElement();
                                            }
                                            xmlW.WriteEndElement();
                                        }
                                        foreach (DBText otherText in miscTexts)
                                        {
                                            if (!linesBelowDesignations.Contains(otherText))
                                            {
                                                TextEntity tent = new TextEntity(otherText);
                                                xmlW.WriteStartElement("other_text");
                                                xmlW.WriteAttributeString("text", tent.text);
                                                xmlW.writeOutMinMax(tent, _Logger);
                                                xmlW.WriteEndElement();
                                            }
                                        }
                                        xmlW.WriteEndElement();
                                    }
                                }
                            }
                        }
                        catch (System.Exception se)
                        {
                            _Logger.Log("DWG: " + dwgNameExt + ": processing error of type: " + se.GetType().ToString() + " : " + se.Message);
                        }
                        finally
                        {
                            xmlW.WriteEndElement();
                            xmlW.WriteRaw(Environment.NewLine);
                            xmlW.WriteEndDocument();
                            xmlW.Flush();
                            xmlW.Close();
                        }
                        acTrans.Commit();
                    }
                }
            }

            AfterProcessing();

            return(String.Concat(DwgCounter.ToString(),
                                 " out of ",
                                 NumDwgs,
                                 " DWGs processed in ",
                                 TimePassed,
                                 ". ",
                                 (_Logger.ErrorCount > 0) ? ("Error Log: " + _Logger.Path) : ("No errors found.")));
        }
        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.")));
        }
        public override String Process()
        {
            Regex FileFormat  = new System.Text.RegularExpressions.Regex(@"^m(\d){6}([a-z]{0,2})?$");
            Regex LayerFormat = new System.Text.RegularExpressions.Regex(@"^m(\d){6}([a-z]){0,2}-(\w){1,2}$");

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

            if (String.IsNullOrWhiteSpace(Suffix))
            {
                return("Invalid Suffix");
            }

            // Get all DWG files
            try { GetDwgList(SearchOption.TopDirectoryOnly); }
            catch (SystemException se)
            {
                _Logger.Log(" DWG files could not be enumerated because: " + se.Message);
                _Logger.Dispose();
                return(" DWG files could not be enumerated because: " + se.Message);
            }

            try
            {
                foreach (String currentDWG in DwgList)
                {
                    Boolean       found0          = false;
                    Boolean       foundGType      = false;
                    Boolean       foundmx0        = false;
                    ObjectId      foundmx0Id      = new ObjectId();
                    Boolean       foundmxSuffix   = false;
                    String        newfi           = "";
                    List <String> LayersForDelete = new List <String>();

                    if (_Bw.CancellationPending)
                    {
                        _Logger.Log("Processing cancelled at dwg " + currentDWG + " out of " + NumDwgs);
                        return("Processing cancelled at dwg " + DwgCounter.ToString() + " out of " + NumDwgs);
                    }

                    DwgCounter++;

                    try { _Bw.ReportProgress(Utilities.GetPercentage(DwgCounter, NumDwgs)); }
                    catch { _Logger.Log("Progress bar report error"); }

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

                        if (!FileFormat.IsMatch(System.IO.Path.GetFileNameWithoutExtension(db.Filename)))
                        {
                            _Logger.Log("Skipping: " + db.Filename + " because of incorrect name format");
                            continue;
                        }

                        String dwgMsName = System.IO.Path.GetFileNameWithoutExtension(db.Filename).Trim();

                        using (Transaction acTrans = db.TransactionManager.StartTransaction())
                        {
                            using (LayerTable lt = acTrans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable)
                            {
                                foreach (ObjectId oid in lt)
                                {
                                    using (LayerTableRecord ltr = acTrans.GetObject(oid, OpenMode.ForWrite) as LayerTableRecord)
                                    {
                                        String layerName = ltr.Name.Trim();
                                        ltr.IsLocked = false;

                                        if (String.Equals(layerName, "0"))
                                        {
                                            found0 = true; db.Clayer = ltr.Id; ltr.Color = Autodesk.AutoCAD.Colors.Color.FromRgb(255, 255, 255); continue;
                                        }
                                        if (String.Equals(layerName, "_GTYPE_RPSTL"))
                                        {
                                            foundGType = true; LayersForDelete.Add(ltr.Name); continue;
                                        }
                                        if (Regex.IsMatch(layerName, @"^m(\d){6}([a-z]){0,2}-0") && String.Equals(layerName.Remove(layerName.LastIndexOf('-')), dwgMsName))
                                        {
                                            foundmx0 = true; ltr.IsFrozen = false; foundmx0Id = ltr.Id; ltr.Color = Autodesk.AutoCAD.Colors.Color.FromRgb(255, 255, 255); continue;
                                        }
                                        if (Regex.IsMatch(layerName, @"^m(\d){6}([a-z]){0,2}-" + Suffix + "$") && String.Equals(layerName.Remove(layerName.LastIndexOf('-')), dwgMsName))
                                        {
                                            foundmxSuffix = true; ltr.IsFrozen = false; ltr.Color = Autodesk.AutoCAD.Colors.Color.FromRgb(255, 255, 255); continue;
                                        }
                                        if (String.Equals(layerName, "FILENAME") || String.Equals(layerName, "SCALE"))
                                        {
                                            LayersForDelete.Add(ltr.Name); continue;
                                        }

                                        // myLogger.Log("Deleting Unknown layer: " + ltr.Name + " in: " + currentDWG);
                                        LayersForDelete.Add(ltr.Name);
                                    }
                                }
                            }
                            if (!foundmx0 && !foundmxSuffix)
                            {
                                _Logger.Log("Could not find mx-0 or mx-suffix layer in: " + currentDWG);
                            }
                            if (!found0)
                            {
                                _Logger.Log("0 Layer not found");
                            }
                            if (!foundGType)
                            {
                                _Logger.Log("GTYPE Layer not found");
                            }

                            using (LayerTable lt = acTrans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable)
                            {
                                foreach (ObjectId oid in lt)
                                {
                                    using (LayerTableRecord ltr = acTrans.GetObject(oid, OpenMode.ForWrite) as LayerTableRecord)
                                    {
                                        String layerName = ltr.Name.Trim();

                                        if (foundmx0 && LayerFormat.IsMatch(layerName) && ltr.Id != foundmx0Id)
                                        {
                                            LayersForDelete.Add(ltr.Name); _Logger.Log("Layer: " + layerName + " not allowed in: " + System.IO.Path.GetFileNameWithoutExtension(db.Filename)); continue;
                                        }
                                        if (!foundmx0 && foundmxSuffix && LayerFormat.IsMatch(layerName))
                                        {
                                            ltr.IsFrozen = false; ltr.Color = Autodesk.AutoCAD.Colors.Color.FromRgb(255, 255, 255); continue;
                                        }
                                    }
                                }
                            }

                            foreach (String LayerForDelete in LayersForDelete)
                            {
                                Utilities.delLayer(acTrans, db, LayerForDelete);
                            }

                            if (foundmx0)
                            {
                                newfi = String.Concat(db.Filename.Remove(db.Filename.LastIndexOf('.')), "-", "0", ".dwg");
                            }
                            if (!foundmx0)
                            {
                                newfi = String.Concat(db.Filename.Remove(db.Filename.LastIndexOf('.')), "-", Suffix.Trim(), ".dwg");
                            }

                            acTrans.Commit();
                        }
                        try { db.SaveAs(newfi, DwgVersion.Current); }
                        catch (System.Exception se) { _Logger.Log("Couldn't save Dwg: " + System.IO.Path.GetFileNameWithoutExtension(db.Filename) + " because: " + se.Message); }
                    }
                }

                //if (_Logger.ErrorCount > 0) { return "Log file: " + _Logger.Path; } else { return "No errors found"; }
            }
            catch (System.Exception e) { _Logger.Log("Unhandled exception: " + e.Message); return("Unhandled exception: " + e.Message); }
            finally
            {
                AfterProcessing();
            }

            return(String.Concat(DwgCounter,
                                 " out of ",
                                 NumDwgs,
                                 " processed in ",
                                 TimePassed,
                                 (_Logger.ErrorCount > 0) ? (". Log file: " + _Logger.Path) : (".")));
        }