Ejemplo n.º 1
0
    //  added. list all the disp set registered.
    private void ListDisplaySets()
    {
        Autodesk.AutoCAD.EditorInput.Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
        ed.WriteMessage("===================================\n");
        ed.WriteMessage("  Currently Registerd Display Set  \n");
        ed.WriteMessage("===================================\n");

        Database    db    = Application.DocumentManager.MdiActiveDocument.Database;
        Transaction trans = db.TransactionManager.StartTransaction();

        // get the dictionary.
        DictionaryDisplaySet dictDispSet = new DictionaryDisplaySet(db, false);

        ed.WriteMessage("Current # of display set = " + dictDispSet.Records.Count.ToString() + "\n");

        try
        {
            // loop throught it and print out the name.
            foreach (ObjectId id in dictDispSet.Records)
            {
                DisplaySet dispSet = trans.GetObject(id, OpenMode.ForRead) as DisplaySet;
                ListDisplaySet(dispSet);
            }
        }
        catch (System.Exception)
        { trans.Abort(); }
        finally
        { trans.Dispose(); }
    }
Ejemplo n.º 2
0
        static public void GetEnt()
        {
            AcEd.Editor  ed = AcAp.Application.DocumentManager.MdiActiveDocument.Editor;
            PromptResult rs = ed.GetString("\nВведите метку примитива (в hex-представлении): ");

            if (rs.Status != PromptStatus.OK)
            {
                return;
            }
            System.Int64  l  = System.Int64.Parse(rs.StringResult, System.Globalization.NumberStyles.HexNumber);
            AcDb.Handle   h  = new AcDb.Handle(l);
            AcDb.Database db = AcDb.HostApplicationServices.WorkingDatabase;
            AcDb.ObjectId id = db.GetObjectId(false, h, 0);
            if (!id.IsValid)
            {
                ed.WriteMessage("\nОшибочная метка примитива {0}", h);
                return;
            }
            using (AcAp.DocumentLock doclock = ed.Document.LockDocument())
            {
                using (AcDb.Transaction tr = db.TransactionManager.StartTransaction())
                {
                    AcDb.Entity ent = tr.GetObject(id, AcDb.OpenMode.ForRead) as AcDb.Entity;
                    if (ent != null)
                    {
                        ed.WriteMessage("\nEntity Class: {0}", AcRx.RXClass.GetClass(ent.GetType()).Name);
                        // Ну и так далее - делаешь с примитивом то, что тебе нужно...
                    }
                    else
                    {
                        ed.WriteMessage("\nЭто не примитив!");
                    }
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Загрузка библиотеки
        /// http://through-the-interface.typepad.com/through_the_interface/2007/03/getting_the_lis.html
        /// </summary>
        #region
        public void Initialize()
        {
            String assemblyFileFullName = GetType().Assembly.Location;
            String assemblyName         = System.IO.Path.GetFileName(
                GetType().Assembly.Location);

            // Just get the commands for this assembly
            App.DocumentCollection dm = App.Application.DocumentManager;
            Assembly asm = Assembly.GetExecutingAssembly();

            Ed.Editor acEd = dm.MdiActiveDocument.Editor;

            // Сообщаю о том, что произведена загрузка сборки
            //и указываю полное имя файла,
            // дабы было видно, откуда она загружена
            acEd.WriteMessage(string.Format("\n{0} {1} {2}.\n{3}: {4}\n{5}\n",
                                            "Assembly", assemblyName, "Loaded",
                                            "Assembly File:", assemblyFileFullName,
                                            "Copyright © Владимир Шульжицкий, 2017"));


            //Вывожу список комманд определенных в библиотеке
            acEd.WriteMessage("\nStart list of commands: \n\n");

            string[] cmds = GetCommands(asm, false);
            foreach (string cmd in cmds)
            {
                acEd.WriteMessage(cmd + "\n");
            }

            acEd.WriteMessage("\n\nEnd list of commands.\n");
        }
Ejemplo n.º 4
0
        public static void PlotRegion()
        {
            Ap.Document doc = cad.DocumentManager.MdiActiveDocument;
            if (doc == null || doc.IsDisposed)
            {
                return;
            }

            Ed.Editor   ed = doc.Editor;
            Db.Database db = doc.Database;

            using (doc.LockDocument())
            {
                Ed.PromptEntityOptions peo = new Ed.PromptEntityOptions(
                    "\nSelect a region"
                    );

                peo.SetRejectMessage("\nIt is not a region."
                                     );
                peo.AddAllowedClass(typeof(Db.Region), false);

                Ed.PromptEntityResult per = ed.GetEntity(peo);

                if (per.Status != Ed.PromptStatus.OK)
                {
                    ed.WriteMessage("\nCommand canceled.\n");
                    return;
                }

                Db.ObjectId regionId = per.ObjectId;

                Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32
                                                                .SaveFileDialog();
                saveFileDialog.Title =
                    "PDF file name";
                saveFileDialog.Filter = "PDF-files|*.pdf";
                bool?result = saveFileDialog.ShowDialog();

                if (!result.HasValue || !result.Value)
                {
                    ed.WriteMessage("\nCommand canceled.");
                    return;
                }

                String pdfFileName = saveFileDialog.FileName;

                PlotRegion(regionId, "DWG To PDF.pc3",
                           "ISO_A4_(210.00_x_297.00_MM)", pdfFileName);

                ed.WriteMessage("\nThe \"{0}\" file created.\n", pdfFileName);
            }
        }
Ejemplo n.º 5
0
        public static void TextToConsole(List <Curve> curveDict)
        {
            SettingsParser settings = SettingsParser.getInstance();

            Ed.Editor acEd = App.Application.DocumentManager.MdiActiveDocument.Editor;
            foreach (Curve i in curveDict)
            {
                acEd.WriteMessage($"\n №{ i.Number } Area: {i.Area}");
                foreach (Point p in i.Vertixs)
                {
                    acEd.WriteMessage($"\n -  { p.Number } {p.X.ToString(settings.coordinatFormat) } {p.Y.ToString(settings.coordinatFormat)}");
                }
                acEd.WriteMessage($"\n -  { i.Vertixs.First().Number } {i.Vertixs.First().X.ToString(settings.coordinatFormat) } {i.Vertixs.First().Y.ToString(settings.coordinatFormat)}");
            }
        }
Ejemplo n.º 6
0
        public List <Db.ObjectId> GetPipeIdByName(string[] pipeNames)
        {
            Ed.Editor         ed     = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Civ.CivilDocument civDoc = Autodesk.Civil.ApplicationServices.CivilApplication.ActiveDocument;
            var pipeIds = new List <Db.ObjectId>();

            // Iterate through each pipe network
            using (Db.Transaction ts = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database.TransactionManager.StartTransaction()) {
                try {
                    foreach (Db.ObjectId networkId in civDoc.GetPipeNetworkIds())
                    {
                        CivDb.Network oNetwork = ts.GetObject(networkId, Db.OpenMode.ForWrite) as CivDb.Network;
                        foreach (Db.ObjectId pipeId in oNetwork.GetPipeIds())
                        {
                            CivDb.Pipe oPipe = ts.GetObject(pipeId, Db.OpenMode.ForRead) as CivDb.Pipe;
                            foreach (string name in pipeNames)
                            {
                                if (oPipe.Name == name)
                                {
                                    pipeIds.Add(oPipe.Id);
                                }
                            }
                        }
                    }
                    return(pipeIds);
                } catch (Autodesk.AutoCAD.Runtime.Exception ex) {
                    ed.WriteMessage("StructurePipesData: " + ex.Message);
                    return(null);
                }
            }
        }
Ejemplo n.º 7
0
    ////////////////////////////
    //// Display Rep
    ////
    //// list all the display reps for MassElem and MassGroup for the current display config.
    ////////////////////////////

    private void DisplayReps()
    {
        Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("\n====================================================\n");
        Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Get All the AecDbMassElem/Massgroup Display Reps for the current display config\n");
        Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("====================================================\n");

        Database    db    = Application.DocumentManager.MdiActiveDocument.Database;
        Transaction trans = db.TransactionManager.StartTransaction();

        Autodesk.AutoCAD.EditorInput.Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

        DisplaySet         ds  = new DisplaySet();
        ObjectIdCollection ids = DisplayRepresentationManager.GetActiveDisplayRepresentationSets(db);

        ed.WriteMessage("# of active display sets = " + ids.Count + "\n");

        DisplaySet acds = new DisplaySet();

        try
        {
            //  loop through the active disp sets (i.e., disp sets of active dis confid.)
            foreach (ObjectId id in ids)
            {
                acds = trans.GetObject(id, OpenMode.ForRead) as DisplaySet;
                foreach (ObjectId drid in acds.DisplayRepresentationIds)
                {
                    DisplayRepresentation dr = trans.GetObject(drid, OpenMode.ForRead) as DisplayRepresentation;
                    dr = trans.GetObject(drid, OpenMode.ForRead) as DisplayRepresentation;
                    RXClass rc = dr.WorksWith;
                    if (rc.Name == "AecDbMassElem" || rc.Name == "AecDbMassGroup")
                    {
                        if (ds.DisplayRepresentationIds.Contains(drid))
                        {
                            continue;
                        }
                        else
                        {
                            ds.DisplayRepresentationIds.Add(drid);
                            ListDisplayRep(dr);
                        }
                    }
                }
            }
            trans.Commit();
        }
        catch (System.Exception)
        {
            trans.Abort();
        }
        finally
        {
            trans.Dispose();
        }
        return;
    }
Ejemplo n.º 8
0
        // The CommandMethod attribute can be applied to any public  member
        // function of any public class.
        // The function should take no arguments and return nothing.
        // If the method is an instance member then the enclosing class is
        // instantiated for each document. If the member is a static member then
        // the enclosing class is NOT instantiated.
        //
        // NOTE: CommandMethod has overloads where you can provide helpid and
        // context menu.
        public MyCommands()
        {
            Autodesk.AutoCAD.EditorInput.Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            ed.PointMonitor += new PointMonitorEventHandler(ed_PointMonitor);
            MonitoredPoint   = Point3d.Origin;

            SetCurrentGroup();
            ReadUserPosShapes();
            ReadUserTableStyles();

            ShowShapes = false;

            // Load prompt
            string heading = "Donatı Pozlandırma ve Metraj Programı v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(2) + " yüklendi.";

            ed.WriteMessage("\n");
            ed.WriteMessage(heading);
            ed.WriteMessage("\n");
            ed.WriteMessage(new string('=', heading.Length));
            PosCategories();

            // License information
            CheckLicense.LicenseInformation();
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Загрузка библиотеки
        /// http://through-the-interface.typepad.com/through_the_interface/2007/03/getting_the_lis.html
        /// </summary>
        #region
        public void Initialize()
        {
            String assemblyFileFullName = GetType().Assembly.Location;
            String assemblyName         = System.IO.Path.GetFileName(
                GetType().Assembly.Location);

            // Just get the commands for this assembly
            App.DocumentCollection dm = App.Application.DocumentManager;
            Assembly asm = Assembly.GetExecutingAssembly();

            // Сообщаю о том, что произведена загрузка сборки
            //и указываю полное имя файла,
            // дабы было видно, откуда она загружена

            Ed.Editor     editor        = App.Application.DocumentManager.MdiActiveDocument.Editor;
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.AppendLine($"\n Assembly, {assemblyName}, Loaded");
            stringBuilder.AppendLine($"\nAssembly File:{ assemblyFileFullName}");
            stringBuilder.AppendLine("\nДанная программа предназначена, на данный момент,");
            stringBuilder.AppendLine("только для удаления невидимых объектов, некоей \"Siberia\"");
            stringBuilder.AppendLine("(предположительно, Autodesk СПДС, без наличия оного)");
            stringBuilder.AppendLine("\nCopyright © ООО \'НСК-Проект\' written by Владимир Шульжицкий, 01.2020");
            editor.WriteMessage(stringBuilder.ToString());

            //Вывожу список комманд определенных в библиотеке
            App.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage
                ("\nСписок команд реализованных в библиотеке: \n\n");

            string[] cmds = GetCommands(asm, false);
            foreach (string cmd in cmds)
            {
                App.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage
                    (cmd + "\n");
            }

            App.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage
                ("\n\nКонец списка.\n");
        }
Ejemplo n.º 10
0
 private bool CheckStatuseOfAccessChangeDefault()
 {
     Autodesk.AutoCAD.EditorInput.Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
     ed.WriteMessage("AccessChangeDefault={0}\n", Atend.Control.Common.AccessChangeDefault);
     if (!Atend.Control.Common.AccessChangeDefault)
     {
         if (SelectedRecloserCode == Guid.Empty && IsDefault)
         {
             MessageBox.Show("کاربر گرامی شما اجازه ثبت تجهیز به صورت پیش فرض ندارید", "خطا");
             return(false);
         }
         else
         {
             Atend.Base.Equipment.EReCloser Recloser = Atend.Base.Equipment.EReCloser.SelectByXCode(SelectedRecloserCode);
             if (Recloser.IsDefault || IsDefault)
             {
                 MessageBox.Show("کاربر گرامی شما اجازه ویرایش  تجهیز به صورت پیش فرض ندارید", "خطا");
                 return(false);
             }
         }
     }
     return(true);
 }
Ejemplo n.º 11
0
 private bool CheckStatuseOfAccessChangeDefault()
 {
     Autodesk.AutoCAD.EditorInput.Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
     ed.WriteMessage("AccessChangeDefault={0}\n", Atend.Control.Common.AccessChangeDefault);
     if (!Atend.Control.Common.AccessChangeDefault)
     {
         if (selectedmjackpanel == Guid.Empty && IsDefault)
         {
             MessageBox.Show("کاربر گرامی شما اجازه ثبت تجهیز به صورت پیش فرض ندارید", "خطا");
             return false;
         }
         else
         {
             Atend.Base.Equipment.EMeasuredJackPanel measuredJackPanel = Atend.Base.Equipment.EMeasuredJackPanel.SelectByXCode(selectedmjackpanel);
             if (measuredJackPanel.IsDefault || IsDefault)
             {
                 MessageBox.Show("کاربر گرامی شما اجازه ویرایش  تجهیز به صورت پیش فرض ندارید", "خطا");
                 return false;
             }
         }
     }
     return true;
 }
Ejemplo n.º 12
0
        /// <summary>
        /// طرح پشتیبان
        /// </summary>
        private void PoshtibanDesign(OleDbConnection aConnection, OleDbTransaction aTransaction, SqlConnection sConnection, SqlTransaction sTransaction)
        {
            Autodesk.AutoCAD.EditorInput.Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            DataTable dtWorkOrder = Atend.Base.Design.DPackage.AccessWorkOrders(aTransaction, aConnection);

            Atend.Base.Design.DDesignProfile _DDesignProfile      = Atend.Base.Design.DDesignProfile.SelectByDesignID(sTransaction, sConnection, Atend.Control.Common.DesignId);
            Atend.Base.Design.DDesign        _DDesign             = Atend.Base.Design.DDesign.SelectByID(sTransaction, sConnection, Atend.Control.Common.DesignId);
            Atend.Base.Design.DDesignFile    _DDesignFile         = Atend.Base.Design.DDesignFile.SelectByDesignId(sTransaction, sConnection, Atend.Control.Common.DesignId);
            Atend.Base.Design.DDesignProfile currentDesignProfile = Atend.Base.Design.DDesignProfile.AccessSelect(aTransaction, aConnection);

            if (_DDesignProfile.Id != -1)
            {
                if (currentDesignProfile.DesignId != -1)
                {
                    if (!currentDesignProfile.UpdateByDesignId(sTransaction, sConnection))
                    {
                        throw new System.Exception("currentDesignProfile.Update 4");
                    }
                }
                else
                {
                    throw new System.Exception("DDesignProfile access record was not found");
                }
            }
            else
            {
                if (currentDesignProfile.DesignId != -1)
                {
                    if (!currentDesignProfile.Insert(sTransaction, sConnection))
                    {
                        throw new System.Exception("currentDesignProfile.Insert 5");
                    }
                }
            }

            #region design
            _DDesign.Region = Convert.ToByte(Atend.Base.Base.BRegion.SelectByCodeLoacal(currentDesignProfile.Zone).SecondCode);
            if (!_DDesign.Update(sTransaction, sConnection))
            {
                throw new System.Exception("_DDesign.Update ");
            }
            #endregion

            #region DesignFile
            _DDesignFile.DesignId = Atend.Control.Common.DesignId;
            _DDesignFile.File     = new byte[0];

            #region ATNX file
            FileStream fs;
            fs = new FileStream(string.Format(@"{0}\{1}", Atend.Control.Common.DesignFullAddress, Atend.Control.Common.DesignName.Replace(".DWG", ".ATNX")), FileMode.Open);
            BinaryReader br = new BinaryReader(fs);
            _DDesignFile.File = br.ReadBytes((Int32)br.BaseStream.Length);
            fs.Dispose();
            #endregion

            #region PDF file
            if (txtBookAddress.Text != string.Empty)
            {
                fs = new FileStream(txtBookAddress.Text, FileMode.Open);
                br = new BinaryReader(fs);
                _DDesignFile.Book = br.ReadBytes((Int32)br.BaseStream.Length);
                fs.Dispose();
            }
            else
            {
                _DDesignFile.Book = new byte[0];
            }
            #endregion

            #region DWF file
            if (txtBookAddress.Text != string.Empty)
            {
                fs = new FileStream(txtDWFAddress.Text, FileMode.Open);
                br = new BinaryReader(fs);
                _DDesignFile.Image = br.ReadBytes((Int32)br.BaseStream.Length);
                fs.Dispose();
            }
            else
            {
                _DDesignFile.Image = new byte[0];
            }
            #endregion


            if (_DDesignFile.Id != -1)
            {
                if (!_DDesignFile.Update(sTransaction, sConnection))
                {
                    throw new System.Exception("NewDesignFile.Insert 5");
                }
            }
            else
            {
                if (!_DDesignFile.Insert(sTransaction, sConnection))
                {
                    throw new System.Exception("CurrentDesignFile.Update 4");
                }
            }
            #endregion

            #region StatusReport
            Atend.Global.Utility.UOtherOutPut Output = new Atend.Global.Utility.UOtherOutPut();
            Atend.Report.dsSagAndTension      ds     = Output.FillStatusReport();
            Atend.Base.Design.DStatusReport.DeleteByDesignId(currentDesignProfile.DesignId);
            for (int i = 0; i < ds.Tables["StatusReport"].Rows.Count; i++)
            {
                Atend.Base.Design.DStatusReport STR = new Atend.Base.Design.DStatusReport();
                STR.DesignId = currentDesignProfile.DesignId;
                if (Atend.Control.NumericValidation.Int32Converter(ds.Tables["StatusReport"].Rows[i]["Code"].ToString()))
                {
                    STR.ProductCode = Convert.ToInt32(ds.Tables["StatusReport"].Rows[i]["Code"].ToString());
                }
                else
                {
                    STR.ProductCode = 0;
                }

                DataTable ExTbl = Atend.Base.Base.BEquipStatus.SelectAllX();
                STR.Existance = Convert.ToInt32(ExTbl.Select("Name = '" + ds.Tables["StatusReport"].Rows[i]["Exist"].ToString() + "'")[0]["ACode"].ToString());
                int pc = Convert.ToInt32(ds.Tables["StatusReport"].Rows[i]["ProjectCode"]);
                //int pc = Atend.Base.Base.BProjectCode.AccessSelectByCode(Convert.ToInt32(Table.Rows[i]["ProjectCode"].ToString())).AdditionalCode;
                STR.ProjectCode = pc;
                ds.Tables["StatusReport"].Rows[i]["ProjectCode"] = pc;
                ds.Tables["StatusReport"].Rows[i]["Count"]       = Math.Round(Convert.ToDouble(ds.Tables["StatusReport"].Rows[i]["Count"].ToString()), 2);
                STR.Count = Convert.ToDouble(ds.Tables["StatusReport"].Rows[i]["Count"].ToString());
                if (!STR.Insert(sTransaction, sConnection))
                {
                    ed.WriteMessage("\nError In D_StatusReport Insertion\n");
                }
            }
            #endregion

            #region WorkOrder
            if (Atend.Base.Design.DWorkOrder.Delete(Atend.Control.Common.DesignId, sTransaction, sConnection))
            {
                foreach (DataRow drWorkOrder in dtWorkOrder.Rows)
                {
                    Atend.Base.Design.DWorkOrder WO = new Atend.Base.Design.DWorkOrder();
                    WO.DesignID  = Atend.Control.Common.DesignId;;
                    WO.WorkOrder = Convert.ToInt32(drWorkOrder["WorkOrderCode"].ToString());
                    if (!WO.Insert(sTransaction, sConnection))
                    {
                        throw new System.Exception("WorkOrder.Insert Failed 5");
                    }
                }
            }
            #endregion
        }
Ejemplo n.º 13
0
        /// <summary>
        /// طرح جدید بدون پشتیبان
        /// </summary>
        private void NewDesignWithoutPoshtiban(OleDbConnection aConnection, OleDbTransaction aTransaction, SqlConnection sConnection, SqlTransaction sTransaction)
        {
            Autodesk.AutoCAD.EditorInput.Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            //طرح کد نداره و در پشتیبان طرحی نداره پی یک طرح جدید تولید می کنیم
            ed.WriteMessage("@@@@ 1\n");
            DataTable dtWorkOrder = Atend.Base.Design.DPackage.AccessWorkOrders(aTransaction, aConnection);

            Atend.Base.Design.DDesignProfile currentDesignProfile = Atend.Base.Design.DDesignProfile.AccessSelect(aTransaction, aConnection);
            Atend.Base.Design.DDesign        currentDesign        = new Atend.Base.Design.DDesign();
            currentDesign.Title     = currentDesignProfile.DesignName;
            currentDesign.ArchiveNo = currentDesignProfile.DesignCode;
            currentDesign.PRGCode   = 0;
            ed.WriteMessage("@@@@ 2\n");
            currentDesign.RequestType = 0;
            currentDesign.Region      = Convert.ToByte(Atend.Base.Base.BRegion.SelectByCodeLoacal(currentDesignProfile.Zone).SecondCode);
            currentDesign.IsAtend     = true;
            currentDesign.Address     = currentDesignProfile.Address;
            ed.WriteMessage("@@@@ 3\n");
            if (!currentDesign.Insert(sTransaction, sConnection))
            {
                ed.WriteMessage("@@@@ 4\n");
                throw new System.Exception("currentDesign.Insert 1");
            }
            ed.WriteMessage("@@@@ 5\n");
            foreach (DataRow drWorkOrder in dtWorkOrder.Rows)
            {
                Atend.Base.Design.DWorkOrder WO = new Atend.Base.Design.DWorkOrder();
                WO.DesignID  = currentDesign.Id;
                WO.WorkOrder = Convert.ToInt32(drWorkOrder["WorkOrderCode"].ToString());
                if (!WO.Insert(sTransaction, sConnection))
                {
                    throw new System.Exception("WorkOrder.Insert Failed 1");
                }
            }

            ed.WriteMessage("@@@@ 6\n");
            currentDesignProfile.DesignId = currentDesign.Id;
            if (!currentDesignProfile.AccessUpdate(aTransaction, aConnection))
            {
                throw new System.Exception("currentDesignProfile.AccessUpdate 1");
            }

            ed.WriteMessage("@@@@ 7\n");
            Atend.Base.Design.DDesignFile currentDesignFile = new Atend.Base.Design.DDesignFile();
            currentDesignFile.DesignId = currentDesign.Id;
            currentDesignFile.File     = new byte[0];


            ed.WriteMessage("@@@@ 8\n");
            #region ATNX file
            FileStream fs;
            fs = new FileStream(string.Format(@"{0}\{1}", Atend.Control.Common.DesignFullAddress, Atend.Control.Common.DesignName.Replace(".DWG", ".ATNX")), FileMode.Open);
            BinaryReader br = new BinaryReader(fs);
            currentDesignFile.File = br.ReadBytes((Int32)br.BaseStream.Length);
            fs.Dispose();
            #endregion

            ed.WriteMessage("@@@@ 9\n");
            #region PDF file
            if (txtBookAddress.Text != string.Empty)
            {
                fs = new FileStream(txtBookAddress.Text, FileMode.Open);
                br = new BinaryReader(fs);
                currentDesignFile.Book = br.ReadBytes((Int32)br.BaseStream.Length);
                fs.Dispose();
            }
            else
            {
                currentDesignFile.Book = new byte[0];
            }
            #endregion

            ed.WriteMessage("@@@@ 10\n");
            #region DWF file
            if (txtBookAddress.Text != string.Empty)
            {
                fs = new FileStream(txtDWFAddress.Text, FileMode.Open);
                br = new BinaryReader(fs);
                currentDesignFile.Image = br.ReadBytes((Int32)br.BaseStream.Length);
                fs.Dispose();
            }
            else
            {
                currentDesignFile.Image = new byte[0];
            }
            #endregion

            ed.WriteMessage("@@@@ 11\n");

            if (!currentDesignFile.Insert(sTransaction, sConnection))
            {
                throw new System.Exception("currentDesignFile.Insert 1");
            }
            ed.WriteMessage("@@@@ 12\n");
            if (!currentDesignProfile.Insert(sTransaction, sConnection))
            {
                throw new System.Exception("currentDesignProfile.Insert 1");
            }
            ed.WriteMessage("@@@@ 13\n");
            #region StatusReport
            Atend.Global.Utility.UOtherOutPut Output = new Atend.Global.Utility.UOtherOutPut();
            ed.WriteMessage("@@@@ 13.1\n");
            Atend.Report.dsSagAndTension ds = Output.FillStatusReport();
            ed.WriteMessage("@@@@ 13.2\n");
            Atend.Base.Design.DStatusReport.DeleteByDesignId(currentDesignProfile.DesignId);
            ed.WriteMessage("@@@@ 14,{0}\n", ds.Tables["StatusReport"].Rows.Count);
            for (int i = 0; i < ds.Tables["StatusReport"].Rows.Count; i++)
            {
                Atend.Base.Design.DStatusReport STR = new Atend.Base.Design.DStatusReport();
                STR.DesignId = currentDesignProfile.DesignId;
                if (Atend.Control.NumericValidation.Int32Converter(ds.Tables["StatusReport"].Rows[i]["Code"].ToString()))
                {
                    STR.ProductCode = Convert.ToInt32(ds.Tables["StatusReport"].Rows[i]["Code"].ToString());
                }
                else
                {
                    STR.ProductCode = 0;
                }

                DataTable ExTbl = Atend.Base.Base.BEquipStatus.SelectAllX();
                STR.Existance = Convert.ToInt32(ExTbl.Select("Name = '" + ds.Tables["StatusReport"].Rows[i]["Exist"].ToString() + "'")[0]["ACode"].ToString());
                int pc = Convert.ToInt32(ds.Tables["StatusReport"].Rows[i]["ProjectCode"]);
                //int pc = Atend.Base.Base.BProjectCode.AccessSelectByCode(Convert.ToInt32(Table.Rows[i]["ProjectCode"].ToString())).AdditionalCode;
                STR.ProjectCode = pc;
                ds.Tables["StatusReport"].Rows[i]["ProjectCode"] = pc;
                ds.Tables["StatusReport"].Rows[i]["Count"]       = Math.Round(Convert.ToDouble(ds.Tables["StatusReport"].Rows[i]["Count"].ToString()), 2);
                STR.Count = Convert.ToDouble(ds.Tables["StatusReport"].Rows[i]["Count"].ToString());
                if (!STR.Insert(sTransaction, sConnection))
                {
                    ed.WriteMessage("\nError In D_StatusReport Insertion\n");
                }
                ed.WriteMessage("@@@@ 15\n");
            }
            #endregion
        }
Ejemplo n.º 14
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            Autodesk.AutoCAD.EditorInput.Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            if (Validation())
            {
                Atend.Base.Design.NodeTransaction _NodeTransaction = new Atend.Base.Design.NodeTransaction();

                SqlConnection  sConnection  = null;
                SqlTransaction sTransaction = null;

                OleDbTransaction aTransaction = null;
                OleDbConnection  aConnection  = null;

                if (_NodeTransaction.CreateTransactionAndConnection(out sTransaction, out sConnection, out aTransaction, out aConnection, false))
                {
                    Atend.Control.Common.DesignId = Atend.Base.Design.DDesignProfile.AccessSelect(aTransaction, aConnection).DesignId;
                    if (Atend.Control.Common.DesignId == 0)//یعنی طرح جدید باز شده است
                    {
                        if (MessageBox.Show("آیا طرح در پشتیبان تعریف شده است", "ذخیره سازی طرح", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                        {
                            ed.WriteMessage("_______ 1\n");
                            NewDesignWithPoshtiban(aConnection, aTransaction, sConnection, sTransaction);
                            ed.WriteMessage("_______ 1.1\n");
                        }
                        else /////////////////////////////////////////////////////////////////////////////////
                        {
                            ed.WriteMessage("_______ 2\n");
                            NewDesignWithoutPoshtiban(aConnection, aTransaction, sConnection, sTransaction);
                            ed.WriteMessage("_______ 2.2\n");
                        }
                    }
                    else////////////////////////////////////// ALL DESIGN HAVE DESIGN ID ///////////////////////////////////////
                    {
                        ed.WriteMessage("_______ 3\n");
                        PoshtibanDesign(aConnection, aTransaction, sConnection, sTransaction);
                    }
                }
                ed.WriteMessage("_______ 4\n");
                aTransaction.Commit();
                sTransaction.Commit();

                aConnection.Close();
                sConnection.Close();


                //#region DDesignProfile

                //Atend.Global.Utility.UOtherOutPut Output = new Atend.Global.Utility.UOtherOutPut();
                //Atend.Report.dsSagAndTension ds = Output.FillStatusReport();
                //Atend.Base.Design.DDesignProfile DP = Atend.Base.Design.DDesignProfile.AccessSelect();
                //if (DP.DesignId <= 0)
                //{
                //    Atend.Base.Design.DDesign Des = new Atend.Base.Design.DDesign();
                //    Des.Title = DP.DesignName;
                //    Des.ArchiveNo = DP.DesignCode;
                //    Des.PRGCode = 0;
                //    Des.RequestType = 0;
                //    Des.Region = 0;
                //    Des.IsAtend = true;
                //    Des.Address = DP.Address;

                //    if (Des.Insert())
                //    {
                //        DP.DesignId = Des.Id;
                //        if (!DP.AccessUpdate())
                //            ed.WriteMessage("\nError In D_DesignProfile Access Update\n");

                //    }
                //    else
                //        ed.WriteMessage("\nError In D_Design Server Insert\n");

                //}
                //Atend.Base.Design.DStatusReport.DeleteByDesignId(DP.DesignId);
                //for (int i = 0; i < ds.Tables["StatusReport"].Rows.Count; i++)
                //{

                //    Atend.Base.Design.DStatusReport STR = new Atend.Base.Design.DStatusReport();
                //    STR.DesignId = DP.DesignId;
                //    if (Atend.Control.NumericValidation.Int32Converter(ds.Tables["StatusReport"].Rows[i]["Code"].ToString()))
                //    {
                //        STR.ProductCode = Convert.ToInt32(ds.Tables["StatusReport"].Rows[i]["Code"].ToString());
                //    }
                //    else
                //        STR.ProductCode = 0;
                //    //MessageBox.Show(i.ToString() +"   " + );
                //    DataTable ExTbl = Atend.Base.Base.BEquipStatus.SelectAllX();
                //    STR.Existance = Convert.ToInt32(ExTbl.Select("Name = '" + ds.Tables["StatusReport"].Rows[i]["Exist"].ToString() + "'")[0]["ACode"].ToString());
                //    int pc = Convert.ToInt32(ds.Tables["StatusReport"].Rows[i]["ProjectCode"]);
                //    //int pc = Atend.Base.Base.BProjectCode.AccessSelectByCode(Convert.ToInt32(Table.Rows[i]["ProjectCode"].ToString())).AdditionalCode;
                //    STR.ProjectCode = pc;
                //    ds.Tables["StatusReport"].Rows[i]["ProjectCode"] = pc;
                //    ds.Tables["StatusReport"].Rows[i]["Count"] = Math.Round(Convert.ToDouble(ds.Tables["StatusReport"].Rows[i]["Count"].ToString()), 2);
                //    STR.Count = Convert.ToDouble(ds.Tables["StatusReport"].Rows[i]["Count"].ToString());
                //    if (!STR.Insert())
                //    {
                //        ed.WriteMessage("\nError In D_StatusReport Insertion\n");
                //    }
                //}

                //#endregion

                DataTable dt = Atend.Base.Design.DDesign.SelectAll();
                gvDesign1.AutoGenerateColumns = false;
                gvDesign1.DataSource          = dt;
            }
            else
            {
                AllowToClose = false;
            }
        }
Ejemplo n.º 15
0
        private void poleInsertionMenu_Click(object sender, EventArgs e)
        {
            Autodesk.AutoCAD.EditorInput.Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            this.Cursor = Cursors.WaitCursor;
            try
            {
                if (Validation() && gvBranches.Rows.Count > 0)
                {
                    //foreach (Autodesk.AutoCAD.DatabaseServices.Entity ent in SelectdEntities)
                    for (int i = 0; i < gvBranches.Rows.Count; i++)
                    {
                        //SelectdEntities.Clear();
                        Atend.Global.Calculation.Mechanical.CAutoPoleInstallation _AutoPoleInstallation = new Atend.Global.Calculation.Mechanical.CAutoPoleInstallation();
                        //ed.WriteMessage("--$$--1\n");
                        _AutoPoleInstallation.Se = Convert.ToDouble(txtSe.Text);
                        //ed.WriteMessage("--$$--2\n");
                        _AutoPoleInstallation.ChangePercent = Convert.ToDouble(txtTolerance.Text);
                        //ed.WriteMessage("--$$--3\n");
                        _AutoPoleInstallation.UTS = Convert.ToDouble(txtUTS.Text);
                        //ed.WriteMessage("--$$--4\n");
                        _AutoPoleInstallation.NetCrossCode = Convert.ToInt32(cboConsolCross.SelectedValue);
                        //ed.WriteMessage("--$$--5\n");
                        _AutoPoleInstallation.Relibility = Convert.ToDouble(txtRelibility.Text);
                        //ed.WriteMessage("--$$--6\n");
                        _AutoPoleInstallation.MaxSectionLength = Convert.ToDouble(txtMaxSectionLength.Text);
                        //ed.WriteMessage("--$$--7\n");
                        _AutoPoleInstallation.SelectedBranch = Atend.Base.Design.DBranch.AccessSelectByCode(new Guid(gvBranches.Rows[i].Cells["BranchCode"].Value.ToString()));
                        //ed.WriteMessage("--$$--8\n");



                        Atend.Base.Design.DPackage PolePackage = Atend.Base.Design.DPackage.AccessSelectByNodeCode(new Guid(gvBranches.Rows[i].Cells["PoleCode"].Value.ToString()));
                        if (PolePackage.Type == (int)Atend.Control.Enum.ProductType.Pole)
                        {
                            _AutoPoleInstallation.SelectedPole = Atend.Base.Equipment.EPole.AccessSelectByCode(PolePackage.ProductCode);
                        }
                        else if (PolePackage.Type == (int)Atend.Control.Enum.ProductType.PoleTip)
                        {
                            Atend.Base.Equipment.EPoleTip PoleTip = Atend.Base.Equipment.EPoleTip.AccessSelectByCode(PolePackage.ProductCode);
                            if (PoleTip.Code != -1)
                            {
                                _AutoPoleInstallation.SelectedPole = Atend.Base.Equipment.EPole.AccessSelectByCode(PoleTip.PoleCode);
                            }
                        }



                        //ed.WriteMessage("--$$--9\n");


                        if (cboBranchType.SelectedIndex == 0)
                        {
                            DataRow[] drs = dtMergeConsol.Select("ROWNO=" + cboConsolCross.SelectedValue.ToString());
                            if (drs.Length > 0 && Convert.ToBoolean(drs[0]["IsSql"]) == true)
                            {
                                _AutoPoleInstallation.SelectedConsol = Atend.Base.Equipment.EConsol.SelectByXCodeForDesign(new Guid(drs[0]["XCode"].ToString()));
                            }
                            else
                            {
                                _AutoPoleInstallation.SelectedConsol = Atend.Base.Equipment.EConsol.AccessSelectByCode(Convert.ToInt32(drs[0]["Code"]));
                            }

                            drs = dtMergeConsol.Select("ROWNO=" + cboConsolTension.SelectedValue.ToString());
                            if (drs.Length > 0 && Convert.ToBoolean(drs[0]["IsSql"]) == true)
                            {
                                _AutoPoleInstallation.SelectedConsolTension = Atend.Base.Equipment.EConsol.SelectByXCodeForDesign(new Guid(drs[0]["XCode"].ToString()));
                            }
                            else
                            {
                                _AutoPoleInstallation.SelectedConsolTension = Atend.Base.Equipment.EConsol.AccessSelectByCode(Convert.ToInt32(drs[0]["Code"]));
                            }

                            _AutoPoleInstallation.SelectedClamp        = null;
                            _AutoPoleInstallation.SelectedClampTension = null;
                        }
                        else
                        {
                            _AutoPoleInstallation.SelectedConsol        = null;
                            _AutoPoleInstallation.SelectedConsolTension = null;

                            DataRow[] drs = dtMergeClamp.Select("ROWNO=" + cboClampCross.SelectedValue.ToString());
                            if (drs.Length > 0 && Convert.ToBoolean(drs[0]["IsSql"]) == true)
                            {
                                _AutoPoleInstallation.SelectedClamp = Atend.Base.Equipment.EClamp.SelectByXCodeForDesign(new Guid(drs[0]["XCode"].ToString()));
                            }
                            else
                            {
                                _AutoPoleInstallation.SelectedClamp = Atend.Base.Equipment.EClamp.AccessSelectByCode(Convert.ToInt32(drs[0]["Code"]));
                            }


                            drs = dtMergeClamp.Select("ROWNO=" + cboClampTension.SelectedValue.ToString());
                            if (drs.Length > 0 && Convert.ToBoolean(drs[0]["IsSql"]) == true)
                            {
                                _AutoPoleInstallation.SelectedClampTension = Atend.Base.Equipment.EClamp.SelectByXCodeForDesign(new Guid(drs[0]["XCode"].ToString()));
                            }
                            else
                            {
                                _AutoPoleInstallation.SelectedClampTension = Atend.Base.Equipment.EClamp.AccessSelectByCode(Convert.ToInt32(drs[0]["Code"]));
                            }
                        }
                        //ed.WriteMessage("CLAMP CROSS : {0} \n", _AutoPoleInstallation.SelectedClamp.Name);
                        //ed.WriteMessage("CLAMP CROSS TENSION : {0} \n", _AutoPoleInstallation.SelectedClampTension.Name);


                        _AutoPoleInstallation.BranchEntity = Atend.Global.Acad.UAcad.GetEntityByObjectID(new Autodesk.AutoCAD.DatabaseServices.ObjectId(new IntPtr(Convert.ToInt32(gvBranches.Rows[i].Cells["BranchOI"].Value)))) as Autodesk.AutoCAD.DatabaseServices.Line;
                        //_AutoPoleInstallation.BranchEntity = Atend.Global.Acad.UAcad.GetEntityByObjectID(BranchOi) as Autodesk.AutoCAD.DatabaseServices.Line;
                        if (_AutoPoleInstallation.PoleInstallationWithoutForbiddenArea(new Guid(gvBranches.Rows[i].Cells["PoleCode"].Value.ToString())))

                        //ed.WriteMessage("--$$--11\n");
                        //double answer = 0;
                        //int t = _AutoPoleInstallation.SpanCalculation(out answer);
                        //MessageBox.Show("answer:" + answer + "t:" + t);
                        {
                            DataGridViewImageCell _IC = gvBranches.Rows[i].Cells["StatusImage"] as DataGridViewImageCell;
                            if (_IC != null)
                            {
                                _IC.Value = new Bitmap(Atend.Control.Common.fullPath + @"\Icon\button_ok.png");
                                ed.WriteMessage("image assigned \n");
                                gvBranches.Refresh();
                            }
                        }
                        else
                        {
                            MessageBox.Show("خطا در زمان انجام پایه گذاری اتوماتیک");
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            this.Cursor = Cursors.Default;
        }
Ejemplo n.º 16
0
        //Get complex aligment properties.
        private void GetStationLocationPoint(String alignmentName)
        {
            ObjectId  alignOid = doc.GetSitelessAlignmentId(alignmentName);
            Alignment align    = ts.GetObject(alignOid, OpenMode.ForRead) as Alignment;

            m_editor.WriteMessage("\n------User Story 1 :Station should return location as Point2d ----------------\n");
            int stationIndex = 0;

            Station[] stationSet = align.GetStationSet(StationTypes.Major, 100);

            m_editor.WriteMessage("Alignment Station Location Type: {0} \n\n", stationSet[0].Location.GetType());
            foreach (Station MajorStation in stationSet)
            {
                m_editor.WriteMessage("Alignment station:{0}   Location: {1} \n", stationIndex, stationSet[stationIndex++].Location);
            }

            m_editor.WriteMessage("\n\n");
        }
Ejemplo n.º 17
0
 public static void RemoveClipboard()
 {
     DemandLoading.RegistryUpdate.UnregisterForDemandLoading();
     Ed.Editor ed = App.Application.DocumentManager.MdiActiveDocument.Editor;
     ed.WriteMessage("\nThe Clipboard Manager will not be loaded  automatically in future editing sessions.");
 }
Ejemplo n.º 18
0
        public bool Update()
        {
            //Получаю конфигурационный файл
            var config = ConfigurationManager.OpenExeConfiguration(
                Assembly.GetExecutingAssembly().Location);
            var userSection = (ClientSettingsSection)config.
                              GetSection("applicationSettings/TheodoliteStrokeParser.Properties.Settings");


            //Настройки Controller

            allScale = userSection.Settings.Get("С_ScaleListParam").Value.ValueXml.InnerText;
            //На всякий случай страхуюсь от невозможности прочитать
            allScale = (allScale != null & allScale.Length < 3) ? "500;0.5;1.5;1.5|1000;1;3;4|2000;2;6;8|5000;6;15;16" : allScale;

            List <string> strAllScale = (from q in allScale.Split('|') select q).ToList();

            ScaleList.Clear();
            foreach (var i in strAllScale)
            {
                List <string> str = i.Split(';').ToList();

                Scale s = new Scale();
                s.Number = int.Parse(str[0]);
                s.Circle = double.Parse(str[1]);
                s.Coord  = double.Parse(str[2]);
                s.Marker = double.Parse(str[3]);

                ScaleList.Add(s);
            }



            //Настройки Model
            double _coordinateTolerance;
            double _areaTolerance;
            double _allAreaTolerance;
            int    _startNumberPoint;
            int    _startNumberCurve;

            _coordinateTolerance = double.TryParse(userSection.Settings.Get("M_СoordinateTolerance")
                                                   .Value.ValueXml.InnerText, out _coordinateTolerance) ? _coordinateTolerance : 0.0001;

            _areaTolerance = double.TryParse(userSection.Settings.Get("M_AreaTolerance")
                                             .Value.ValueXml.InnerText, out _areaTolerance) ? _areaTolerance : 1;

            _allAreaTolerance = double.TryParse(userSection.Settings.Get("M_AllAreaTolerance")
                                                .Value.ValueXml.InnerText, out _allAreaTolerance) ? _allAreaTolerance : 0.0001;

            //Начальный номер вершины
            _startNumberPoint = int.TryParse(userSection.Settings.Get("M_StartNumberPoint")
                                             .Value.ValueXml.InnerText, out _startNumberPoint) ? _startNumberPoint : 1;

            //Начальный номер выбранной линии
            _startNumberCurve = int.TryParse(userSection.Settings.Get("M_StartNumberCurve")
                                             .Value.ValueXml.InnerText, out _startNumberCurve) ? _startNumberCurve : 1;

            coordinateTolerance = _coordinateTolerance;
            areaTolerance       = _areaTolerance;
            allAreaTolerance    = _allAreaTolerance;
            startNumberPoint    = _startNumberPoint;
            startNumberCurve    = _startNumberCurve;



            //Настройки View


            coordinatFormat = userSection.Settings.Get("V_CoordinatFormat").Value.ValueXml.InnerText;
            coordinatFormat = (coordinatFormat != null & coordinatFormat.Length < 1) ? "#0.0000" : coordinatFormat;

            layerText = userSection.Settings.Get("V_LayerText").Value.ValueXml.InnerText;
            layerText = (layerText != null & layerText.Length < 1) ? "ГИС_ЗУ_текст" : layerText;

            layerPoint = userSection.Settings.Get("V_LayerPoint").Value.ValueXml.InnerText;
            layerPoint = (layerPoint != null & layerPoint.Length < 1) ? "ГИС_ЗУ_точки" : layerPoint;


            layerPointNumber = userSection.Settings.Get("V_LayerPointNumber").Value.ValueXml.InnerText;
            layerPointNumber = (layerPointNumber != null & layerPointNumber.Length < 1) ? "ГИС_ЗУ_точки_номер" : layerPointNumber;

            mleaderCoordStyle = userSection.Settings.Get("V_MleaderCoordStyle").Value.ValueXml.InnerText;
            mleaderCoordStyle = (mleaderCoordStyle != null & mleaderCoordStyle.Length < 1) ? "tspCoord" : mleaderCoordStyle;

            mleaderMarkerStyle = userSection.Settings.Get("V_MleaderMarkerStyle").Value.ValueXml.InnerText;
            mleaderMarkerStyle = (mleaderMarkerStyle != null & mleaderMarkerStyle.Length < 1) ? "tspMarker" : mleaderMarkerStyle;

            double _CoordTransform;

            _CoordTransform = double.TryParse(userSection.Settings.Get("V_CoordTransform").Value.ValueXml.InnerText, out _CoordTransform) ? _CoordTransform : 8;
            CoordTransform  = _CoordTransform;

            double MarkerTransformX = double.TryParse(userSection.Settings.Get("V_MarkerTransformX").Value.ValueXml.InnerText, out MarkerTransformX) ? MarkerTransformX : 0;
            double MarkerTransformY = double.TryParse(userSection.Settings.Get("V_MarkerTransformY").Value.ValueXml.InnerText, out MarkerTransformY) ? MarkerTransformY : 0;

            MarkerTransform = (MarkerTransformX != 0 & MarkerTransformY != 0) ? new Gem.Vector3d(MarkerTransformX, MarkerTransformY, 0) : MarkerTransform;

            //BaseCircleRadius = double.TryParse(userSection.Settings.Get("V_BaseCircleRadius").Value.ValueXml.InnerText, out BaseCircleRadius) ? BaseCircleRadius : 1;

            markerText = userSection.Settings.Get("V_MarkerText").Value.ValueXml.InnerText;
            markerText = (markerText != null & markerText.Length < 1) ? @":ЗУ|n| \P S= |s| кв.м" : markerText;

            bool _startExcel;

            _startExcel = bool.TryParse(userSection.Settings.Get("V_startExcel").Value.ValueXml.InnerText, out _startExcel) ? _startExcel : true;
            startExcel  = _startExcel;

            bool _MTextMask;

            _MTextMask = bool.TryParse(userSection.Settings.Get("V_MTextMask").Value.ValueXml.InnerText, out _MTextMask) ? _MTextMask : true;
            MTextMask  = _MTextMask;

            double _MTextMaskKoefficient;

            _MTextMaskKoefficient = double.TryParse(userSection.Settings.Get("V_MTextMaskKoefficient").Value.ValueXml.InnerText, out _MTextMaskKoefficient) ? _MTextMaskKoefficient : 1.1;
            MTextMaskKoefficient  = _MTextMaskKoefficient;

            //_Scale = scale;

            //тут подготавливаем окружение для работы и загружаем стили мультивыноски
            App.Document acDoc   = App.Application.DocumentManager.MdiActiveDocument;
            Db.Database  acCurDb = acDoc.Database;
            Ed.Editor    acEd    = acDoc.Editor;

            bool returnBool = false;

            //Копируем из репозитория слои
            if (!CheckLocalRepository.CloneFromRepository <Db.LayerTableRecord>(acCurDb, layerText, CheckLocalRepository.GetRepository()))
            {
                acEd.WriteMessage($"\n Error! Can not clone Layer \"{layerText}\" from repository! Layer for Marker = \"0\"");
                layerText = "0";
            }

            if (!CheckLocalRepository.CloneFromRepository <Db.LayerTableRecord>(acCurDb, layerPoint, CheckLocalRepository.GetRepository()))
            {
                acEd.WriteMessage($"\n Error! Can not clone Layer \"{layerPoint}\" from repository! Layer for Circle = \"0\"");
                layerPoint = "0";
            }
            if (!CheckLocalRepository.CloneFromRepository <Db.LayerTableRecord>(acCurDb, layerPointNumber, CheckLocalRepository.GetRepository()))
            {
                acEd.WriteMessage($"\n Error! Can not clone Layer \"{layerPointNumber}\" from repository! Layer for Point Marker = \"0\"");
                layerPointNumber = "0";
            }


            //Копируем из репозитория стили МультиВыноски
            if (!CheckLocalRepository.CloneFromRepository <Db.MLeaderStyle>(acCurDb, mleaderCoordStyle, CheckLocalRepository.GetRepository()))
            {
                returnBool = false;
                acEd.WriteMessage($"\n Error! Can not clone MLeader Style \"{mleaderCoordStyle}\" from repository! ");
            }


            if (!CheckLocalRepository.CloneFromRepository <Db.MLeaderStyle>(acCurDb, mleaderMarkerStyle, CheckLocalRepository.GetRepository()))
            {
                acEd.WriteMessage($"\n Error! Can not clone MLeader Style \"{mleaderMarkerStyle}\" from repository! ");
                returnBool = false;
            }

            return(returnBool);
        }
Ejemplo n.º 19
0
        // This code based on Kean Walmsley's article:
        // http://through-the-interface.typepad.com/through_the_interface/2007/10/plotting-a-wind.html
        public static void PlotRegion(Db.ObjectId regionId, String pcsFileName,
                                      String mediaName, String outputFileName)
        {
            if (regionId.IsNull)
            {
                throw new ArgumentException("regionId.IsNull == true");
            }
            if (!regionId.IsValid)
            {
                throw new ArgumentException("regionId.IsValid == false");
            }

            if (regionId.ObjectClass.Name != "AcDbRegion")
            {
                throw new ArgumentException("regionId.ObjectClass.Name != AcDbRegion");
            }

            if (pcsFileName == null)
            {
                throw new ArgumentNullException("pcsFileName");
            }
            if (pcsFileName.Trim() == String.Empty)
            {
                throw new ArgumentException("pcsFileName.Trim() == String.Empty");
            }

            if (mediaName == null)
            {
                throw new ArgumentNullException("mediaName");
            }
            if (mediaName.Trim() == String.Empty)
            {
                throw new ArgumentException("mediaName.Trim() == String.Empty");
            }

            if (outputFileName == null)
            {
                throw new ArgumentNullException("outputFileName");
            }
            if (outputFileName.Trim() == String.Empty)
            {
                throw new ArgumentException("outputFileName.Trim() == String.Empty");
            }

            Db.Database previewDb = Hs.WorkingDatabase;
            Db.Database db        = null;
            Ap.Document doc       = cad.DocumentManager.MdiActiveDocument;
            if (doc == null || doc.IsDisposed)
            {
                return;
            }

            Ed.Editor ed = doc.Editor;
            try
            {
                if (regionId.Database != null && !regionId.Database.IsDisposed)
                {
                    Hs.WorkingDatabase = regionId.Database;
                    db = regionId.Database;
                }
                else
                {
                    db = doc.Database;
                }

                using (doc.LockDocument())
                {
                    using (Db.Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        Db.Region region = tr.GetObject(regionId,
                                                        Db.OpenMode.ForRead) as Db.Region;

                        Db.Extents3d        extends = region.GeometricExtents;
                        Db.ObjectId         modelId = Us.GetBlockModelSpaceId(db);
                        Db.BlockTableRecord model   = tr.GetObject(modelId,
                                                                   Db.OpenMode.ForRead) as Db.BlockTableRecord;

                        Db.Layout layout = tr.GetObject(model.LayoutId,
                                                        Db.OpenMode.ForRead) as Db.Layout;

                        using (Pt.PlotInfo pi = new Pt.PlotInfo())
                        {
                            pi.Layout = model.LayoutId;

                            using (Db.PlotSettings ps = new Db.PlotSettings(layout.ModelType)
                                   )
                            {
                                ps.CopyFrom(layout);

                                Db.PlotSettingsValidator psv = Db.PlotSettingsValidator
                                                               .Current;

                                Gm.Point2d bottomLeft = Gm.Point2d.Origin;
                                Gm.Point2d topRight   = Gm.Point2d.Origin;

                                region.GetVisualBoundary(0.1, ref bottomLeft,
                                                         ref topRight);

                                Gm.Point3d bottomLeft_3d = new Gm.Point3d(bottomLeft.X,
                                                                          bottomLeft.Y, 0);
                                Gm.Point3d topRight_3d = new Gm.Point3d(topRight.X, topRight.Y,
                                                                        0);

                                Db.ResultBuffer rbFrom = new Db.ResultBuffer(new Db.TypedValue(
                                                                                 5003, 1));
                                Db.ResultBuffer rbTo = new Db.ResultBuffer(new Db.TypedValue(
                                                                               5003, 2));

                                double[] firres = new double[] { 0, 0, 0 };
                                double[] secres = new double[] { 0, 0, 0 };

                                acedTrans(bottomLeft_3d.ToArray(), rbFrom.UnmanagedObject,
                                          rbTo.UnmanagedObject, 0, firres);
                                acedTrans(topRight_3d.ToArray(), rbFrom.UnmanagedObject,
                                          rbTo.UnmanagedObject, 0, secres);

                                Db.Extents2d extents = new Db.Extents2d(
                                    firres[0],
                                    firres[1],
                                    secres[0],
                                    secres[1]
                                    );

                                psv.SetZoomToPaperOnUpdate(ps, true);

                                psv.SetPlotWindowArea(ps, extents);
                                psv.SetPlotType(ps, Db.PlotType.Window);
                                psv.SetUseStandardScale(ps, true);
                                psv.SetStdScaleType(ps, Db.StdScaleType.ScaleToFit);
                                psv.SetPlotCentered(ps, true);
                                psv.SetPlotRotation(ps, Db.PlotRotation.Degrees000);

                                // We'll use the standard DWF PC3, as
                                // for today we're just plotting to file
                                psv.SetPlotConfigurationName(ps, pcsFileName, mediaName);

                                // We need to link the PlotInfo to the
                                // PlotSettings and then validate it
                                pi.OverrideSettings = ps;
                                Pt.PlotInfoValidator piv = new Pt.PlotInfoValidator();
                                piv.MediaMatchingPolicy = Pt.MatchingPolicy.MatchEnabled;
                                piv.Validate(pi);

                                // A PlotEngine does the actual plotting
                                // (can also create one for Preview)
                                if (Pt.PlotFactory.ProcessPlotState == Pt.ProcessPlotState
                                    .NotPlotting)
                                {
                                    using (Pt.PlotEngine pe = Pt.PlotFactory.CreatePublishEngine()
                                           )
                                    {
                                        // Create a Progress Dialog to provide info
                                        // and allow thej user to cancel

                                        using (Pt.PlotProgressDialog ppd =
                                                   new Pt.PlotProgressDialog(false, 1, true))
                                        {
                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.DialogTitle, "Custom Plot Progress");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.CancelJobButtonMessage,
                                                "Cancel Job");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.CancelSheetButtonMessage,
                                                "Cancel Sheet");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.SheetSetProgressCaption,
                                                "Sheet Set Progress");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.SheetProgressCaption,
                                                "Sheet Progress");

                                            ppd.LowerPlotProgressRange = 0;
                                            ppd.UpperPlotProgressRange = 100;
                                            ppd.PlotProgressPos        = 0;

                                            // Let's start the plot, at last
                                            ppd.OnBeginPlot();
                                            ppd.IsVisible = true;
                                            pe.BeginPlot(ppd, null);

                                            // We'll be plotting a single document
                                            pe.BeginDocument(pi, doc.Name, null, 1, true,
                                                             // Let's plot to file
                                                             outputFileName);
                                            // Which contains a single sheet
                                            ppd.OnBeginSheet();
                                            ppd.LowerSheetProgressRange = 0;
                                            ppd.UpperSheetProgressRange = 100;
                                            ppd.SheetProgressPos        = 0;
                                            Pt.PlotPageInfo ppi = new Pt.PlotPageInfo();
                                            pe.BeginPage(ppi, pi, true, null);
                                            pe.BeginGenerateGraphics(null);
                                            pe.EndGenerateGraphics(null);

                                            // Finish the sheet
                                            pe.EndPage(null);
                                            ppd.SheetProgressPos = 100;
                                            ppd.OnEndSheet();

                                            // Finish the document
                                            pe.EndDocument(null);

                                            // And finish the plot
                                            ppd.PlotProgressPos = 100;
                                            ppd.OnEndPlot();
                                            pe.EndPlot(null);
                                        }
                                    }
                                }
                                else
                                {
                                    ed.WriteMessage("\nAnother plot is in progress.");
                                }
                            }
                        }
                        tr.Commit();
                    }
                }
            }
            finally
            {
                Hs.WorkingDatabase = previewDb;
            }
        }
Ejemplo n.º 20
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            Autodesk.AutoCAD.EditorInput.Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            if (Validation())
            {
                Atend.Base.Design.NodeTransaction _NodeTransaction = new Atend.Base.Design.NodeTransaction();

                SqlConnection  sConnection  = null;
                SqlTransaction sTransaction = null;

                OleDbTransaction aTransaction = null;
                OleDbConnection  aConnection  = null;

                try
                {
                    if (_NodeTransaction.CreateTransactionAndConnection(out sTransaction, out sConnection, out aTransaction, out aConnection, false))
                    {
                        Atend.Control.Common.DesignId = Atend.Base.Design.DDesignProfile.AccessSelect(aTransaction, aConnection).DesignId;
                        if (Atend.Control.Common.DesignId == 0)
                        {
                            if (MessageBox.Show("آیا طرح در پشتیبان تعریف شده است", "ذخیره سازی طرح", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                            {
                                //طرح کد نداره ولی در پشتیبان است  پس به پشتیبان اختصاص می دهیم
                                ed.WriteMessage("~~~ No design Id  and is Poshtiban file ~~~\n");
                                if (gvDesign.SelectedRows.Count > 0)
                                {
                                    if (chkIsComplement.Checked)
                                    {
                                        //Is Postiban and is complement
                                        ed.WriteMessage("~~~ is complement ~~~\n");
                                        Atend.Base.Design.DDesign currentDessign = Atend.Base.Design.DDesign.SelectByID(sTransaction, sConnection, Convert.ToInt32(gvDesign.SelectedRows[0].Cells["Id"].Value));
                                        if (currentDessign.Id != -1)
                                        {
                                            DataTable Designs = Atend.Base.Design.DDesign.SelectByCode(sTransaction, sConnection, currentDessign.Code);
                                            if (Designs.Rows.Count > 0)
                                            {
                                                DataView dv = new DataView(Designs);
                                                dv.Sort = "RequestType";
                                                Atend.Base.Design.DDesign NewDesign = Atend.Base.Design.DDesign.SelectByID(sTransaction, sConnection, Convert.ToInt32(dv.Table.Rows[0]["Id"].ToString()));
                                                if (NewDesign.Id != -1)
                                                {
                                                    NewDesign.RequestType++;
                                                    if (!NewDesign.Insert(sTransaction, sConnection))
                                                    {
                                                        throw new System.Exception("NewDesign.Insert 2");
                                                    }

                                                    Atend.Base.Design.DDesignProfile currentProfile = Atend.Base.Design.DDesignProfile.AccessSelect(aTransaction, aConnection);
                                                    if (currentProfile.DesignId != -1)
                                                    {
                                                        currentProfile.DesignId = NewDesign.Id;
                                                        if (!currentProfile.AccessUpdate(aTransaction, aConnection))
                                                        {
                                                            throw new System.Exception("currentProfile.AccessUpdate 2");
                                                        }

                                                        Atend.Base.Design.DDesignFile NewDesignFile = new Atend.Base.Design.DDesignFile();
                                                        NewDesignFile.DesignId = NewDesign.Id;
                                                        NewDesignFile.File     = null;
                                                        FileStream fs;
                                                        fs = new FileStream(string.Format(@"{0}\{1}", Atend.Control.Common.DesignFullAddress, Atend.Control.Common.DesignName.Replace(".DWG", ".ATNX")), FileMode.Open);
                                                        BinaryReader br = new BinaryReader(fs);
                                                        NewDesignFile.File = br.ReadBytes((Int32)br.BaseStream.Length);
                                                        fs.Dispose();
                                                        if (!NewDesignFile.Insert(sTransaction, sConnection))
                                                        {
                                                            throw new System.Exception("NewDesignFile.Insert 2");
                                                        }

                                                        if (!currentProfile.Insert(sTransaction, sConnection))
                                                        {
                                                            throw new System.Exception("currentProfile.Insert 2");
                                                        }
                                                        MessageBox.Show("Well done 2");
                                                    }
                                                }
                                            }
                                        }////////
                                    }
                                    else
                                    {
                                        //Is Poshtiban and is not complement
                                        ed.WriteMessage("~~~ is not complement ~~~\n");
                                        Atend.Base.Design.DDesignFile CurrentDesignFile = Atend.Base.Design.DDesignFile.SelectByDesignId(sTransaction, sConnection, Convert.ToInt32(gvDesign.SelectedRows[0].Cells["Id"].Value));
                                        if (CurrentDesignFile.Id != -1)
                                        {
                                            ed.WriteMessage("~~~  have file ~~~\n");
                                            Atend.Base.Design.DDesignProfile currentDesignProfile = Atend.Base.Design.DDesignProfile.AccessSelect(aTransaction, aConnection);
                                            if (currentDesignProfile.DesignId != -1)
                                            {
                                                currentDesignProfile.DesignId = Convert.ToInt32(gvDesign.SelectedRows[0].Cells["Id"].Value);
                                                if (!currentDesignProfile.AccessUpdate(aTransaction, aConnection))
                                                {
                                                    throw new System.Exception("currentDesignProfile.AccessUpdate 6");
                                                }

                                                CurrentDesignFile.File = null;
                                                FileStream fs;
                                                fs = new FileStream(string.Format(@"{0}\{1}", Atend.Control.Common.DesignFullAddress, Atend.Control.Common.DesignName.Replace(".DWG", ".ATNX")), FileMode.Open);
                                                BinaryReader br = new BinaryReader(fs);
                                                CurrentDesignFile.File = br.ReadBytes((Int32)br.BaseStream.Length);
                                                fs.Dispose();
                                                if (!CurrentDesignFile.Update(sTransaction, sConnection))
                                                {
                                                    throw new System.Exception("CurrentDesignFile.Update 6");
                                                }


                                                if (!currentDesignProfile.UpdateByDesignId(sTransaction, sConnection))
                                                {
                                                    throw new System.Exception("currentDesignProfile.Update 6");
                                                }
                                                MessageBox.Show("well done 6");
                                            }
                                        }
                                        else
                                        {
                                            ed.WriteMessage("~~~ does not have file ~~~\n");
                                            Atend.Base.Design.DDesignProfile currentDesignProfile = Atend.Base.Design.DDesignProfile.AccessSelect(aTransaction, aConnection);
                                            if (currentDesignProfile.DesignId != -1)
                                            {
                                                currentDesignProfile.DesignId = Convert.ToInt32(gvDesign.SelectedRows[0].Cells["Id"].Value);
                                                if (!currentDesignProfile.AccessUpdate(aTransaction, aConnection))
                                                {
                                                    throw new System.Exception("currentDesignProfile.AccessUpdate 5");
                                                }

                                                Atend.Base.Design.DDesignFile NewDesignFile = new Atend.Base.Design.DDesignFile();
                                                NewDesignFile.DesignId = Convert.ToInt32(gvDesign.SelectedRows[0].Cells["Id"].Value);
                                                NewDesignFile.File     = null;
                                                FileStream fs;
                                                fs = new FileStream(string.Format(@"{0}\{1}", Atend.Control.Common.DesignFullAddress, Atend.Control.Common.DesignName.Replace(".DWG", ".ATNX")), FileMode.Open);
                                                BinaryReader br = new BinaryReader(fs);
                                                NewDesignFile.File = br.ReadBytes((Int32)br.BaseStream.Length);
                                                fs.Dispose();
                                                if (!NewDesignFile.Insert(sTransaction, sConnection))
                                                {
                                                    throw new System.Exception("NewDesignFile.Insert 5");
                                                }


                                                if (!currentDesignProfile.Insert(sTransaction, sConnection))
                                                {
                                                    throw new System.Exception("currentDesignProfile.Insert 5");
                                                }

                                                MessageBox.Show("well done 5");
                                            }
                                        }
                                    }
                                }
                            }
                            else /////////////////////////////////////////////////////////////////////////////////
                            {
                                //طرح کد نداره و در پشتیبان طرحی نداره پی یک طرح جدید تولید می کنیم
                                ed.WriteMessage("~~~ No design Id  and is atend file ~~~\n");
                                Atend.Base.Design.DDesignProfile currentDesignProfile = Atend.Base.Design.DDesignProfile.AccessSelect(aTransaction, aConnection);
                                Atend.Base.Design.DDesign        currentDesign        = new Atend.Base.Design.DDesign();
                                currentDesign.Code           = 0;
                                currentDesign.Title          = currentDesignProfile.DesignName;
                                currentDesign.ArchiveNo      = currentDesignProfile.DesignCode;
                                currentDesign.PRGCode        = 0;
                                currentDesign.RequestType    = 0;
                                currentDesign.AdditionalCode = 0;
                                if (!currentDesign.Insert(sTransaction, sConnection))
                                {
                                    throw new System.Exception("currentDesign.Insert 1");
                                }

                                currentDesignProfile.DesignId = currentDesign.Id;
                                if (!currentDesignProfile.AccessUpdate(aTransaction, aConnection))
                                {
                                    throw new System.Exception("currentDesignProfile.AccessUpdate 1");
                                }

                                Atend.Base.Design.DDesignFile currentDesignFile = new Atend.Base.Design.DDesignFile();
                                currentDesignFile.DesignId = currentDesign.Id;
                                currentDesignFile.File     = null;
                                FileStream fs;
                                fs = new FileStream(string.Format(@"{0}\{1}", Atend.Control.Common.DesignFullAddress, Atend.Control.Common.DesignName.Replace(".DWG", ".ATNX")), FileMode.Open);
                                BinaryReader br = new BinaryReader(fs);
                                currentDesignFile.File = br.ReadBytes((Int32)br.BaseStream.Length);
                                fs.Dispose();
                                if (!currentDesignFile.Insert(sTransaction, sConnection))
                                {
                                    throw new System.Exception("currentDesignFile.Insert 1");
                                }

                                if (!currentDesignProfile.Insert(sTransaction, sConnection))
                                {
                                    throw new System.Exception("currentDesignProfile.Insert 1");
                                }

                                MessageBox.Show("Well Done 1");
                            }
                        }
                        else////////////////////////////////////// ALL DESIGN HAVE DESIGN ID ///////////////////////////////////////
                        {
                            //means Design has DesignId
                            MessageBox.Show(Atend.Control.Common.DesignId.ToString());
                            if (chkIsComplement.Checked)
                            {
                                //means design is complement
                                Atend.Base.Design.DDesign currentDessign = Atend.Base.Design.DDesign.SelectByID(sTransaction, sConnection, Atend.Control.Common.DesignId);
                                if (currentDessign.Id != -1)
                                {
                                    DataTable Designs = Atend.Base.Design.DDesign.SelectByCode(sTransaction, sConnection, currentDessign.Code);
                                    if (Designs.Rows.Count > 0)
                                    {
                                        DataView dv = new DataView(Designs);
                                        dv.Sort = "RequestType";
                                        Atend.Base.Design.DDesign NewDesign = Atend.Base.Design.DDesign.SelectByID(sTransaction, sConnection, Convert.ToInt32(dv.Table.Rows[0]["Id"].ToString()));
                                        if (NewDesign.Id != -1)
                                        {
                                            NewDesign.RequestType++;
                                            if (!NewDesign.Insert(sTransaction, sConnection))
                                            {
                                                throw new System.Exception("NewDesign.Insert 3");
                                            }

                                            Atend.Base.Design.DDesignProfile currentProfile = Atend.Base.Design.DDesignProfile.AccessSelect(aTransaction, aConnection);
                                            if (currentProfile.DesignId != -1)
                                            {
                                                currentProfile.DesignId = NewDesign.Id;
                                                if (!currentProfile.AccessUpdate(aTransaction, aConnection))
                                                {
                                                    throw new System.Exception("currentProfile.AccessUpdate 3");
                                                }

                                                Atend.Base.Design.DDesignFile NewDesignFile = new Atend.Base.Design.DDesignFile();
                                                NewDesignFile.DesignId = NewDesign.Id;
                                                NewDesignFile.File     = null;
                                                FileStream fs;
                                                fs = new FileStream(string.Format(@"{0}\{1}", Atend.Control.Common.DesignFullAddress, Atend.Control.Common.DesignName.Replace(".DWG", ".ATNX")), FileMode.Open);
                                                BinaryReader br = new BinaryReader(fs);
                                                NewDesignFile.File = br.ReadBytes((Int32)br.BaseStream.Length);
                                                fs.Dispose();
                                                if (!NewDesignFile.Insert(sTransaction, sConnection))
                                                {
                                                    throw new System.Exception("NewDesignFile.Insert 3");
                                                }

                                                if (!currentProfile.Insert(sTransaction, sConnection))
                                                {
                                                    throw new System.Exception("currentProfile.Insert 3");
                                                }
                                                MessageBox.Show("Well done 3");
                                            }
                                        }
                                    }
                                }////////
                            }
                            else
                            {
                                //means design is not complement
                                Atend.Base.Design.DDesignFile CurrentDesignFile = Atend.Base.Design.DDesignFile.SelectByDesignId(sTransaction, sConnection, Atend.Control.Common.DesignId);
                                if (CurrentDesignFile.Id != -1)
                                {
                                    ed.WriteMessage("~~~  have file ~~~\n");
                                    Atend.Base.Design.DDesignProfile currentDesignProfile = Atend.Base.Design.DDesignProfile.AccessSelect(aTransaction, aConnection);
                                    if (currentDesignProfile.DesignId != -1)
                                    {
                                        CurrentDesignFile.File = null;
                                        FileStream fs;
                                        fs = new FileStream(string.Format(@"{0}\{1}", Atend.Control.Common.DesignFullAddress, Atend.Control.Common.DesignName.Replace(".DWG", ".ATNX")), FileMode.Open);
                                        BinaryReader br = new BinaryReader(fs);
                                        CurrentDesignFile.File = br.ReadBytes((Int32)br.BaseStream.Length);
                                        fs.Dispose();
                                        if (!CurrentDesignFile.Update(sTransaction, sConnection))
                                        {
                                            throw new System.Exception("CurrentDesignFile.Update 4");
                                        }

                                        if (!currentDesignProfile.UpdateByDesignId(sTransaction, sConnection))
                                        {
                                            throw new System.Exception("currentDesignProfile.Update 4");
                                        }
                                        MessageBox.Show("well done 4");
                                    }
                                    else
                                    {
                                        throw new System.Exception("DDesignProfile access record was not found");
                                    }
                                }
                                else
                                {
                                    ed.WriteMessage("~~~ does not have file ~~~\n");
                                    Atend.Base.Design.DDesignProfile currentDesignProfile = Atend.Base.Design.DDesignProfile.AccessSelect(aTransaction, aConnection);
                                    if (currentDesignProfile.DesignId != -1)
                                    {
                                        Atend.Base.Design.DDesignFile NewDesignFile = new Atend.Base.Design.DDesignFile();
                                        NewDesignFile.DesignId = Atend.Control.Common.DesignId;
                                        NewDesignFile.File     = null;
                                        FileStream fs;
                                        fs = new FileStream(string.Format(@"{0}\{1}", Atend.Control.Common.DesignFullAddress, Atend.Control.Common.DesignName.Replace(".DWG", ".ATNX")), FileMode.Open);
                                        BinaryReader br = new BinaryReader(fs);
                                        NewDesignFile.File = br.ReadBytes((Int32)br.BaseStream.Length);
                                        fs.Dispose();
                                        if (!NewDesignFile.Insert(sTransaction, sConnection))
                                        {
                                            throw new System.Exception("NewDesignFile.Insert 5");
                                        }

                                        if (!currentDesignProfile.Insert(sTransaction, sConnection))
                                        {
                                            throw new System.Exception("currentDesignProfile.Insert 5");
                                        }

                                        MessageBox.Show("well done 4-2");
                                    }
                                }
                            }
                        }
                    }

                    aTransaction.Commit();
                    sTransaction.Commit();

                    aConnection.Close();
                    sConnection.Close();
                }
                catch
                {
                    aTransaction.Rollback();
                    sTransaction.Rollback();

                    aConnection.Close();
                    sConnection.Close();


                    ed.WriteMessage("ERROR WHILE SAVE FILE ON SERVER");
                    //AllowToClose = false;
                }
                DataTable dt = Atend.Base.Design.DDesign.SelectAll();
                gvDesign.AutoGenerateColumns = false;
                gvDesign.DataSource          = dt;
            }
            else
            {
                AllowToClose = false;
            }
        }
Ejemplo n.º 21
0
        // This code based on Kean Walmsley's article:
        // http://through-the-interface.typepad.com/through_the_interface/2007/10/plotting-a-wind.html
        public static void PlotOnePaper(Database db, Document doc, BlockReference br, String pcsFileName,
                                        String mediaName, String outputFileName)
        {
            ;

            if (pcsFileName == null)
            {
                throw new ArgumentNullException("pcsFileName");
            }
            if (pcsFileName.Trim() == String.Empty)
            {
                throw new ArgumentException("pcsFileName.Trim() == String.Empty");
            }

            if (mediaName == null)
            {
                throw new ArgumentNullException("mediaName");
            }
            if (mediaName.Trim() == String.Empty)
            {
                throw new ArgumentException("mediaName.Trim() == String.Empty");
            }

            if (outputFileName == null)
            {
                throw new ArgumentNullException("outputFileName");
            }
            if (outputFileName.Trim() == String.Empty)
            {
                throw new ArgumentException("outputFileName.Trim() == String.Empty");
            }



            Ed.Editor ed = doc.Editor;

            try
            {
                using (doc.LockDocument())
                {
                    using (Db.Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        Db.Extents3d extends = br.GeometryExtentsBestFit();
                        Point3d      pmin    = extends.MinPoint;
                        Point3d      pmax    = extends.MaxPoint;



                        Db.ObjectId         modelId = Us.GetBlockModelSpaceId(db);
                        Db.BlockTableRecord model   = tr.GetObject(modelId,
                                                                   Db.OpenMode.ForRead) as Db.BlockTableRecord;

                        Db.Layout layout = tr.GetObject(model.LayoutId,
                                                        Db.OpenMode.ForRead) as Db.Layout;

                        using (Pt.PlotInfo PltInfo = new Pt.PlotInfo())
                        {
                            PltInfo.Layout = model.LayoutId;

                            using (Db.PlotSettings PltSet = new Db.PlotSettings(layout.ModelType)
                                   )
                            {
                                PltSet.CopyFrom(layout);

                                Db.PlotSettingsValidator PltSetVald = Db.PlotSettingsValidator
                                                                      .Current;


                                Db.Extents2d extents = new Db.Extents2d(
                                    pmin.X * (1 - 0.0001),
                                    pmin.Y * (1 + 0.001),
                                    pmax.X,
                                    pmax.Y
                                    );

                                Log4NetHelper.WriteInfoLog("左上角坐标:" + pmin.X + "," + pmin.Y + "\n");
                                Log4NetHelper.WriteInfoLog("右下角角坐标:" + pmax.X + "," + pmax.Y + "\n");



                                PltSetVald.SetZoomToPaperOnUpdate(PltSet, true);

                                PltSetVald.SetPlotWindowArea(PltSet, extents);
                                PltSetVald.SetPlotType(PltSet, Db.PlotType.Window);
                                PltSetVald.SetUseStandardScale(PltSet, true);
                                PltSetVald.SetStdScaleType(PltSet, Db.StdScaleType.ScaleToFit);
                                PltSetVald.SetPlotCentered(PltSet, true);
                                PltSetVald.SetPlotRotation(PltSet, Db.PlotRotation.Degrees000);

                                // We'll use the standard DWF PC3, as
                                // for today we're just plotting to file
                                PltSetVald.SetPlotConfigurationName(PltSet, pcsFileName, mediaName);

                                // We need to link the PlotInfo to the
                                // PlotSettings and then validate it
                                PltInfo.OverrideSettings = PltSet;
                                Pt.PlotInfoValidator PltInfoVald = new Pt.PlotInfoValidator();
                                PltInfoVald.MediaMatchingPolicy = Pt.MatchingPolicy.MatchEnabled;
                                PltInfoVald.Validate(PltInfo);

                                // A PlotEngine does the actual plotting
                                // (can also create one for Preview)
                                if (Pt.PlotFactory.ProcessPlotState == Pt.ProcessPlotState
                                    .NotPlotting)
                                {
                                    using (Pt.PlotEngine pe = Pt.PlotFactory.CreatePublishEngine()
                                           )
                                    {
                                        // Create a Progress Dialog to provide info
                                        // and allow thej user to cancel

                                        using (Pt.PlotProgressDialog ppd =
                                                   new Pt.PlotProgressDialog(false, 1, true))
                                        {
                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.DialogTitle, "Custom Plot Progress");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.CancelJobButtonMessage,
                                                "Cancel Job");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.CancelSheetButtonMessage,
                                                "Cancel Sheet");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.SheetSetProgressCaption,
                                                "Sheet Set Progress");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.SheetProgressCaption,
                                                "Sheet Progress");

                                            ppd.LowerPlotProgressRange = 0;
                                            ppd.UpperPlotProgressRange = 100;
                                            ppd.PlotProgressPos        = 0;

                                            // Let's start the plot, at last
                                            ppd.OnBeginPlot();
                                            ppd.IsVisible = true;
                                            pe.BeginPlot(ppd, null);

                                            // We'll be plotting a single document
                                            pe.BeginDocument(PltInfo, doc.Name, null, 1, true,
                                                             // Let's plot to file
                                                             outputFileName);
                                            // Which contains a single sheet
                                            ppd.OnBeginSheet();
                                            ppd.LowerSheetProgressRange = 0;
                                            ppd.UpperSheetProgressRange = 100;
                                            ppd.SheetProgressPos        = 0;
                                            Pt.PlotPageInfo ppi = new Pt.PlotPageInfo();
                                            pe.BeginPage(ppi, PltInfo, true, null);
                                            pe.BeginGenerateGraphics(null);
                                            pe.EndGenerateGraphics(null);

                                            // Finish the sheet
                                            pe.EndPage(null);
                                            ppd.SheetProgressPos = 100;
                                            ppd.OnEndSheet();

                                            // Finish the document
                                            pe.EndDocument(null);

                                            // And finish the plot
                                            ppd.PlotProgressPos = 100;
                                            ppd.OnEndPlot();
                                            pe.EndPlot(null);
                                        }
                                    }
                                }
                                else
                                {
                                    ed.WriteMessage("\nAnother plot is in progress.");
                                }
                            }
                        }
                        tr.Commit();
                    }
                }
            }
            finally
            {
                //  Hs.WorkingDatabase = previewDb;
            }
        }
Ejemplo n.º 22
0
        public void StructurePipesLabels()
        {
            Ed.Editor         ed     = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Civ.CivilDocument civDoc = Autodesk.Civil.ApplicationServices.CivilApplication.ActiveDocument;
            // Document AcadDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            // Check that there's a pipe network to parse
            if (civDoc.GetPipeNetworkIds() == null)
            {
                ed.WriteMessage("There are no pipe networks to export.  Open a document that contains at least one pipe network");
                return;
            }


            // Iterate through each pipe network
            using (Db.Transaction ts = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database.TransactionManager.StartTransaction()) {
                Dictionary <string, char> dictPipe = new Dictionary <string, char>(); // track data parts column

                Ed.PromptEntityOptions opt = new Ed.PromptEntityOptions("\nSelect an Structure");
                opt.SetRejectMessage("\nObject must be an Structure.\n");
                opt.AddAllowedClass(typeof(CivDb.Structure), false);
                Db.ObjectId structureID = ed.GetEntity(opt).ObjectId;

                try {
                    //////Db.ObjectId oNetworkId = civDoc.GetPipeNetworkIds()[0];
                    //////CivDb.Network oNetwork = ts.GetObject(oNetworkId, Db.OpenMode.ForWrite) as CivDb.Network;

                    //// Get pipes:
                    //ObjectIdCollection oPipeIds = oNetwork.GetPipeIds();
                    //int pipeCount = oPipeIds.Count;

                    //// we can edit the slope, so make that column yellow
                    //Range colRange = xlWsPipes.get_Range("D1", "D" + ( pipeCount + 1 ));
                    //colRange.Interior.ColorIndex = 6;
                    //colRange.Interior.Pattern = XlPattern.xlPatternSolid;
                    //colRange.Interior.PatternColorIndex = XlColorIndex.xlColorIndexAutomatic;

                    //foreach ( ObjectId oid in oPipeIds ) {

                    //    Pipe oPipe = ts.GetObject(oid, OpenMode.ForRead) as Pipe;
                    //    ed.WriteMessage("   " + oPipe.Name);
                    //    col = 'B';
                    //    row++;
                    //    aRange = xlWsPipes.get_Range("A" + row, System.Type.Missing);
                    //    aRange.Value2 = oPipe.Handle.Value.ToString();
                    //    aRange = xlWsPipes.get_Range("B" + row, System.Type.Missing);
                    //    aRange.Value2 = oPipe.StartPoint.X + "," + oPipe.StartPoint.Y + "," + oPipe.StartPoint.Z;
                    //    aRange = xlWsPipes.get_Range("C" + row, System.Type.Missing);
                    //    aRange.Value2 = oPipe.EndPoint.X + "," + oPipe.EndPoint.Y + "," + oPipe.EndPoint.Z;

                    //    // This only gives the absolute value of the slope:
                    //    // aRange = xlWsPipes.get_Range("D" + row, System.Type.Missing);
                    //    // aRange.Value2 = oPipe.Slope;
                    //    // This gives a signed value:
                    //    aRange = xlWsPipes.get_Range("D" + row, System.Type.Missing);
                    //    aRange.Value2 = ( oPipe.EndPoint.Z - oPipe.StartPoint.Z ) / oPipe.Length2DCenterToCenter;

                    //    // Get the catalog data to use later
                    //    ObjectId partsListId = doc.Styles.PartsListSet["Standard"];
                    //    PartsList oPartsList = ts.GetObject(partsListId, OpenMode.ForRead) as PartsList;
                    //    ObjectIdCollection oPipeFamilyIdCollection = oPartsList.GetPartFamilyIdsByDomain(DomainType.Pipe);

                    //    foreach ( PartDataField oPartDataField in oPipe.PartData.GetAllDataFields() ) {
                    //        // Make sure the data has a column in Excel, if not, add the column
                    //        if ( !dictPipe.ContainsKey(oPartDataField.ContextString) ) {
                    //            char nextCol = ( char )( ( int )'E' + dictPipe.Count );
                    //            aRange = xlWsPipes.get_Range("" + nextCol + "1", System.Type.Missing);
                    //            aRange.Value2 = oPartDataField.ContextString + "(" + oPartDataField.Name + ")";
                    //            dictPipe.Add(oPartDataField.ContextString, nextCol);

                    //            // We can edit inner diameter or width, so make those yellow
                    //            if ( ( oPartDataField.ContextString == "PipeInnerDiameter" ) || ( oPartDataField.ContextString == "PipeInnerWidth" ) ) {
                    //                colRange = xlWsPipes.get_Range("" + nextCol + "1", "" + nextCol + ( pipeCount + 1 ));
                    //                colRange.Interior.ColorIndex = 6;
                    //                colRange.Interior.Pattern = XlPattern.xlPatternSolid;
                    //                colRange.Interior.PatternColorIndex = XlColorIndex.xlColorIndexAutomatic;
                    //            }

                    //            // Check the part catalog data to see if this part data is user-modifiable
                    //            foreach ( ObjectId oPipeFamliyId in oPipeFamilyIdCollection ) {
                    //                PartFamily oPartFamily = ts.GetObject(oPipeFamliyId, OpenMode.ForRead) as PartFamily;
                    //                SizeFilterField oSizeFilterField = null;

                    //                try {
                    //                    oSizeFilterField = oPartFamily.PartSizeFilter[oPartDataField.Name];
                    //                } catch ( System.Exception e ) { }

                    //                /* You can also iterate through all defined size filter fields this way:
                    //                 SizeFilterRecord oSizeFilterRecord = oPartFamily.PartSizeFilter;
                    //                 for ( int i = 0; i < oSizeFilterRecord.ParamCount; i++ ) {
                    //                     oSizeFilterField = oSizeFilterRecord[i];
                    //                  } */

                    //                if ( oSizeFilterField != null ) {
                    //                         // Check whether it can be modified:
                    //                         if ( oSizeFilterField.DataSource == PartDataSourceType.Optional ) {
                    //                             colRange = xlWsPipes.get_Range("" + nextCol + "1", "" + nextCol + ( pipeCount + 1 ));
                    //                             colRange.Interior.ColorIndex = 4;
                    //                             colRange.Interior.Pattern = XlPattern.xlPatternSolid;
                    //                             colRange.Interior.PatternColorIndex = XlColorIndex.xlColorIndexAutomatic;
                    //                         }

                    //                         break;
                    //                     }

                    //            }
                    //        }
                    //        char iColumnPipes = dictPipe[oPartDataField.ContextString];
                    //        aRange = aRange = xlWsPipes.get_Range("" + iColumnPipes + row, System.Type.Missing);
                    //        aRange.Value2 = oPartDataField.Value;

                    //    }
                    //}

                    // Now export the structures

                    Dictionary <string, char> dictStructures = new Dictionary <string, char>(); // track data parts column

                    // Get structures:

                    //Db.ObjectIdCollection oStructureIds = oNetwork.GetStructureIds();
                    //foreach ( Db.ObjectId oid in structureID ) {
                    CivDb.Structure    oStructure    = ts.GetObject(structureID, Db.OpenMode.ForRead) as CivDb.Structure;
                    CivDb.Network      oNetwork      = ts.GetObject(oStructure.NetworkId, Db.OpenMode.ForWrite) as CivDb.Network;
                    string[]           connPipeNames = oStructure.GetConnectedPipeNames();
                    PipeData.BIVPipe   pipe          = new PipeData.BIVPipe();
                    List <Db.ObjectId> pipeIds       = pipe.GetPipeIdByName(connPipeNames);
                    ed.WriteMessage("\nК колодцу присоеденены следующие трубы: ");
                    foreach (Db.ObjectId pipeId in pipeIds)
                    {
                        CivDb.Pipe oPipe = ts.GetObject(pipeId, Db.OpenMode.ForRead) as CivDb.Pipe;
                        ed.WriteMessage("{0} | {1:0.000}   |||   ", oPipe.Name, oStructure.get_PipeCenterDepth(new int()));
                    }
                    //col = 'B';
                    //row++;
                    //aRange = xlWsStructures.get_Range("" + col + row, System.Type.Missing);
                    //aRange.Value2 = oStructure.Handle.Value;
                    //aRange = xlWsStructures.get_Range("" + ++col + row, System.Type.Missing);
                    //aRange.Value2 = oStructure.Position.X + "," + oStructure.Position.Y + "," + oStructure.Position.Z;

                    //foreach ( CivDb.PartDataField oPartDataField in oStructure.PartData.GetAllDataFields() ) {
                    //    // Make sure the data has a column in Excel, if not, add the column
                    //    if ( !dictStructures.ContainsKey(oPartDataField.ContextString) ) {
                    //        char nextCol = ( char )( ( int )'D' + dictStructures.Count );
                    //        //aRange = xlWsStructures.get_Range("" + nextCol + "1", System.Type.Missing);
                    //        //aRange.Value2 = oPartDataField.ContextString;
                    //        dictStructures.Add(oPartDataField.ContextString, nextCol);

                    //    }
                    //    char iColumnStructure = dictStructures[oPartDataField.ContextString];
                    //ed.WriteMessage("\npartDataField.Name: " + oPartDataField.Name + "   ===   ColumnStructure to string: " + iColumnStructure + "   ===   PartDataField.Value: " + oPartDataField.Value.ToString() + "\n");
                    //    //aRange = aRange = xlWsStructures.get_Range("" + iColumnStructure + row, System.Type.Missing);
                    //    //aRange.Value2 = oPartDataField.Value;
                    //}
                    //}
                } catch (Autodesk.AutoCAD.Runtime.Exception ex) {
                    ed.WriteMessage("StructurePipesData: " + ex.Message);
                    return;
                }
            }
        }