public void CMD_BOQEdit() { if (!CheckLicense.Check()) { return; } Autodesk.AutoCAD.EditorInput.Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; // Edit entity if there is a pickset PromptSelectionResult selectionRes = ed.SelectImplied(); if (selectionRes.Status != PromptStatus.Error && selectionRes.Value.Count > 0) { ObjectId id = selectionRes.Value[0].ObjectId; ed.SetImpliedSelection(new ObjectId[0]); ItemEdit(id, MonitoredPoint); return; } PromptEntityOptions opts = new PromptEntityOptions("Select entity: "); opts.AllowNone = false; PromptEntityResult result = ed.GetEntity(opts); if (result.Status == PromptStatus.OK) { ItemEdit(result.ObjectId, result.PickedPoint); } }
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Это не примитив!"); } } } }
/// <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"); }
// 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(); } }
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); } } }
static public void SpaceOnAttributeName() { // Получение текущего документа и базы данных App.Document acDoc = App.Application.DocumentManager.MdiActiveDocument; Db.Database acCurDb = acDoc.Database; Ed.Editor acEd = acDoc.Editor; // старт транзакции using (Db.Transaction acTrans = acCurDb.TransactionManager.StartOpenCloseTransaction()) { Db.TypedValue[] acTypValAr = new Db.TypedValue[1]; acTypValAr.SetValue(new Db.TypedValue((int)Db.DxfCode.Start, "INSERT"), 0); Ed.SelectionFilter acSelFtr = new Ed.SelectionFilter(acTypValAr); Ed.PromptSelectionResult acSSPrompt = acDoc.Editor.GetSelection(acSelFtr); if (acSSPrompt.Status == Ed.PromptStatus.OK) { Ed.SelectionSet acSSet = acSSPrompt.Value; foreach (Ed.SelectedObject acSSObj in acSSet) { if (acSSObj != null) { if (acSSObj.ObjectId.ObjectClass.IsDerivedFrom(Rtm.RXClass.GetClass(typeof(Db.BlockReference)))) { Db.BlockReference acEnt = acTrans.GetObject(acSSObj.ObjectId, Db.OpenMode.ForRead) as Db.BlockReference; Db.BlockTableRecord blr = acTrans.GetObject(acEnt.BlockTableRecord, Db.OpenMode.ForRead) as Db.BlockTableRecord; if (acEnt.IsDynamicBlock) { blr = acTrans.GetObject(acEnt.DynamicBlockTableRecord, Db.OpenMode.ForRead) as Db.BlockTableRecord; } if (blr.HasAttributeDefinitions) { foreach (Db.ObjectId id in blr) { if (id.ObjectClass.IsDerivedFrom(Rtm.RXClass.GetClass(typeof(Db.AttributeDefinition)))) { Db.AttributeDefinition acAttrRef = acTrans.GetObject(id, Db.OpenMode.ForWrite) as Db.AttributeDefinition; if (acAttrRef != null) { acAttrRef.Tag = acAttrRef.Tag.Replace('_', ' '); } } } } } } } } acTrans.Commit(); } }
static public void mainTheodoliteStrokeParser() { // Получение текущего документа и базы данных App.Document acDoc = App.Application.DocumentManager.MdiActiveDocument; if (acDoc == null) { return; } SettingsParser settings = SettingsParser.getInstance(); if (settings.Update()) { return; } Ed.Editor acEd = acDoc.Editor; //тут запросить масштаб //Предполагается всего 4 вида стандартных масштабов - 1:500, 1:1000, 1:2000, 1:5000. Ed.PromptKeywordOptions pKeyOpts = new Ed.PromptKeywordOptions(""); pKeyOpts.Message = "\nEnter an option: 1/"; foreach (Scale i in settings.ScaleList) { pKeyOpts.Keywords.Add(i.Number.ToString()); } pKeyOpts.AllowNone = false; pKeyOpts.AppendKeywordsToMessage = true; Ed.PromptResult pKeyRes = acDoc.Editor.GetKeywords(pKeyOpts); if (pKeyRes.Status != Ed.PromptStatus.OK) { return; } settings._Scale = settings.ScaleList.FirstOrDefault(s => s.Number == int.Parse(pKeyRes.StringResult)); Model.Init(); bool goOn = true; //Продолжать ли выбор do { Ed.PromptEntityOptions opt = new Ed.PromptEntityOptions("\n Select polyline: "); opt.AllowNone = false; opt.AllowObjectOnLockedLayer = false; opt.SetRejectMessage("\nNot a pline try again: "); opt.AddAllowedClass(typeof(Db.Polyline), true); Ed.PromptEntityResult res = acEd.GetEntity(opt); goOn = (res.Status == Ed.PromptStatus.OK) ? Model.GetData(res.ObjectId) : false; } while (goOn); Model.OutPutData(); }
//////////////////////////// //// 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; }
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); } }
private void NewPos() { Autodesk.AutoCAD.EditorInput.Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; PromptPointResult result = ed.GetPoint("Baz noktası: "); if (result.Status == PromptStatus.OK) { Database db = HostApplicationServices.WorkingDatabase; using (Transaction tr = db.TransactionManager.StartTransaction()) { try { BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); Point3d pt = result.Value; RebarPos pos = new RebarPos(); pos.TransformBy(Matrix3d.Displacement(pt.GetAsVector())); pos.TransformBy(Matrix3d.Scaling(25.0, pt)); pos.Pos = ""; pos.Count = "1"; pos.Diameter = "12"; pos.Spacing = ""; pos.Shape = "GENEL"; pos.A = "1000"; pos.Note = ""; #if DEBUG pos.Pos = "1"; pos.Count = "2x3"; pos.Diameter = "12"; pos.Spacing = "200"; pos.Shape = "00"; pos.A = "1000"; pos.Note = ""; #endif pos.SetDatabaseDefaults(db); btr.AppendEntity(pos); tr.AddNewlyCreatedDBObject(pos, true); tr.Commit(); } catch (System.Exception ex) { MessageBox.Show("Error: " + ex.Message, "RebarPos", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
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)}"); } }
public void CMD_DumpShapes() { Autodesk.AutoCAD.EditorInput.Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; PromptPointResult result = ed.GetPoint("Baz noktası: "); if (result.Status != PromptStatus.OK) { return; } Point3d pt = result.Value; foreach (string name in PosShape.GetAllPosShapes()) { DWGUtility.DrawShape(name, pt, 100); pt = pt.Add(new Vector3d(0, 120, 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"); }
public static void DOinBlock() { App.Document dwg = App.Application.DocumentManager.MdiActiveDocument; Ed.Editor ed = dwg.Editor; //Ask user to select a block. In real world, I use code //to select all targeting blocks by its name, so that //user does not have to select block manually Ed.PromptEntityOptions opt = new Ed.PromptEntityOptions("\nSelect a block:"); opt.SetRejectMessage("\nInvalid: not a block."); opt.AddAllowedClass(typeof(Db.BlockReference), true); Ed.PromptEntityResult res = ed.GetEntity(opt); if (res.Status != Ed.PromptStatus.OK) { return; } SetDrawOrderInBlock(dwg, res.ObjectId); ed.Regen(); Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt(); }
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 (SelectGroundCabelTipXCode == Guid.Empty && IsDefault) { MessageBox.Show("کاربر گرامی شما اجازه ثبت تجهیز به صورت پیش فرض ندارید", "خطا"); return(false); } else { Atend.Base.Equipment.EGroundCabelTip Equip = Atend.Base.Equipment.EGroundCabelTip.SelectByXCode(SelectGroundCabelTipXCode); if (Equip.IsDefault || IsDefault) { MessageBox.Show("کاربر گرامی شما اجازه ویرایش تجهیز به صورت پیش فرض ندارید", "خطا"); return(false); } } } return(true); }
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; }
// 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(); }
// Zooms to given objects public static void ZoomToObjects(IEnumerable <ObjectId> ids) { Autodesk.AutoCAD.EditorInput.Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; Extents3d outerext = new Extents3d(); Database db = HostApplicationServices.WorkingDatabase; using (Transaction tr = db.TransactionManager.StartTransaction()) { try { foreach (ObjectId id in ids) { Entity ent = tr.GetObject(id, OpenMode.ForRead) as Entity; Extents3d ext = ent.GeometricExtents; outerext.AddExtents(ext); } } catch { ; } } outerext.TransformBy(ed.CurrentUserCoordinateSystem.Inverse()); Point2d min2d = new Point2d(outerext.MinPoint.X, outerext.MinPoint.Y); Point2d max2d = new Point2d(outerext.MaxPoint.X, outerext.MaxPoint.Y); ViewTableRecord view = new ViewTableRecord(); view.CenterPoint = min2d + ((max2d - min2d) / 2.0); view.Height = max2d.Y - min2d.Y; view.Width = max2d.X - min2d.X; ed.SetCurrentView(view); }
public void CMD_Pos() { if (!CheckLicense.Check()) { return; } Autodesk.AutoCAD.EditorInput.Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; // Edit entity if there is a pickset PromptSelectionResult selectionRes = ed.SelectImplied(); if (selectionRes.Status != PromptStatus.Error && selectionRes.Value.Count > 0) { ObjectId id = selectionRes.Value[0].ObjectId; ed.SetImpliedSelection(new ObjectId[0]); ItemEdit(id, MonitoredPoint); return; } bool cont = true; while (cont) { PromptEntityOptions opts = new PromptEntityOptions("Poz secin veya [Yeni/Numaralandir/Kopyala/kOntrol/Metraj/bul Degistir/numara Sil/Acilimlar/Tablo stili/ayaRlar]: ", "New Numbering Copy Check BOQ Find Empty Shapes Table Preferences"); opts.AllowNone = false; PromptEntityResult result = ed.GetEntity(opts); if (result.Status == PromptStatus.Keyword) { switch (result.StringResult) { case "New": NewPos(); break; case "Numbering": NumberPos(); break; case "Empty": EmptyBalloons(); break; case "Copy": CopyPos(); break; case "Check": PosCheck(); break; case "BOQ": DrawBOQ(); break; case "Find": FindReplace(false); break; case "Shapes": PosShapes(); break; case "Table": TableStyles(); break; case "Preferences": PosGroups(); break; } cont = false; } else if (result.Status == PromptStatus.OK) { ItemEdit(result.ObjectId, result.PickedPoint); cont = true; } else { cont = false; } } }
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); }
// 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; } }
/// <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 }
/// <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 }
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; } }
/// <summary> /// insert signatures /// </summary> /// <param name="dwgPath"></param> /// <param name="dwgNameList"></param> public void InsertSign(string dwgPath, List <string> dwgNameList) { AdeskAppSvr.Document doc = AdeskAppSvr.Application.DocumentManager.MdiActiveDocument; this.Hide(); AdeskDBSvr.Database CurrDB = doc.Database;//current database AdeskEdIn.Editor ed = doc.Editor; AdeskEdIn.PromptPointResult prPointRes_Base = ed.GetPoint(new AdeskEdIn.PromptPointOptions("选择插入的基点")); AdeskEdIn.PromptPointResult prPointRes_opp = ed.GetPoint(new AdeskEdIn.PromptPointOptions("选择基点的对角点")); //In order to make the signs look nicely , calculate the base point and its opposite point AdeskGeo.Point3d P_base = CalPoint(prPointRes_Base.Value, prPointRes_opp.Value, 0.1); AdeskGeo.Point3d P_opp = CalPoint(prPointRes_Base.Value, prPointRes_opp.Value, 0.9); //sign's width and height double SignWidth = P_opp.X - P_base.X; double SignHeight = P_opp.Y - P_base.Y; //distance between each other double distanceW = prPointRes_opp.Value.X - prPointRes_Base.Value.X; double distanceH = prPointRes_opp.Value.Y - prPointRes_Base.Value.Y; //scale of signature. 36 is the width of sign, and 17 is the height. you should adjust them in your condition. double scaleWidth = SignWidth / 36; double scaleHeight = SignHeight / 17; //today string date = System.DateTime.Today.ToLocalTime().ToString().Split(' ')[0]; try { for (int i = 0; i < dwgNameList.Count; i++) { using (AdeskDBSvr.Database tmpdb = new AdeskDBSvr.Database(false, false)) { //read drawing tmpdb.ReadDwgFile(dwgPath + dwgNameList[i], FileShare.Read, true, null); //insert it as a new block AdeskDBSvr.ObjectId idBTR = CurrDB.Insert(this.ICCardList[i], tmpdb, false); using (AdeskDBSvr.Transaction trans = CurrDB.TransactionManager.StartTransaction()) { AdeskDBSvr.BlockTable bt = (AdeskDBSvr.BlockTable)trans.GetObject(CurrDB.BlockTableId, AdeskDBSvr.OpenMode.ForRead); AdeskDBSvr.BlockTableRecord btr = (AdeskDBSvr.BlockTableRecord)trans.GetObject(bt[AdeskDBSvr.BlockTableRecord.ModelSpace], AdeskDBSvr.OpenMode.ForWrite); //insert point AdeskGeo.Point3d inPt = new AdeskGeo.Point3d(P_base.X, P_base.Y - i * distanceH, P_base.Z); #region signature date //signature date AdeskDBSvr.MText SignDate = new AdeskDBSvr.MText(); AdeskDBSvr.TextStyleTable TextStyleTB = (AdeskDBSvr.TextStyleTable)trans.GetObject(CurrDB.TextStyleTableId, AdeskDBSvr.OpenMode.ForWrite); AdeskDBSvr.TextStyleTableRecord TextStyleTBRec = new AdeskDBSvr.TextStyleTableRecord(); TextStyleTBRec.Font = new AdeskGra.FontDescriptor("宋体", true, false, 0, 0); TextStyleTB.Add(TextStyleTBRec); trans.AddNewlyCreatedDBObject(TextStyleTBRec, true); //trans.Commit(); SignDate.TextStyle = TextStyleTBRec.Id; SignDate.Contents = date; SignDate.TextHeight = SignHeight / 2; SignDate.Width = SignWidth / 3; //date's location should fit the frame SignDate.Location = new AdeskGeo.Point3d((inPt.X + distanceW), (inPt.Y + 1.5 * SignDate.TextHeight), inPt.Z); btr.AppendEntity(SignDate); trans.AddNewlyCreatedDBObject(SignDate, true); #endregion try { //create a ref to the block using (AdeskDBSvr.BlockReference bref = new AdeskDBSvr.BlockReference(inPt, idBTR)) { bref.ScaleFactors = new AdeskGeo.Scale3d(scaleWidth, scaleHeight, 1.0); btr.AppendEntity(bref); trans.AddNewlyCreatedDBObject(bref, true); } trans.Commit(); } catch (System.Exception err) { MessageBox.Show("one: " + err.Message); } } } } } catch (Autodesk.AutoCAD.Runtime.Exception err) { MessageBox.Show("insert: " + err.Message); } this.Show(); }
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; }
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; } } }
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."); }
// Regenerates the drawing window public static void Regen() { Autodesk.AutoCAD.EditorInput.Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; ed.Regen(); }
// 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; } }