public static bool EditFFLOrLevels() { // Add comment to explain what following code does Document acDoc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument; Database acCurrDb = acDoc.Database; Editor acEditor = acDoc.Editor; ObjectId FFLToEditId = getFFLToEdit(); if (FFLToEditId == null) { return(false); } bool userEditing = true; while (userEditing) { // Ask user if he wants to edit the FFL or the levels PromptStringOptions strOptions = new PromptStringOptions("\nEdit FLL or level(F or L, X to finish)? "); PromptResult userChoice = acEditor.GetString(strOptions); if (userChoice.Status == PromptStatus.Cancel) { userEditing = false; } else if (userChoice.Status == PromptStatus.Error) { acEditor.WriteMessage("\nError selecting what to edit."); return(false); } else { switch (userChoice.StringResult.ToUpper()) { case "F": // Call the edit FFL value function if (!EditFFLValue(FFLToEditId)) { return(false); } break; case "L": if (!EditLevels(FFLToEditId)) { return(false); } break; case "X": userEditing = false; break; default: acEditor.WriteMessage("\nPlease enter 'f' or 'l' or 'x' to finish."); break; } } } return(true); }
public void ERN() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; PromptStringOptions pso = new PromptStringOptions("\nADT——新建图层\n请输入新图层名称") { AllowSpaces = true }; PromptResult pr = ed.GetString(pso); if (pr.Status == PromptStatus.OK) { string layname = pr.StringResult; using (Transaction trans = db.TransactionManager.StartTransaction()) { LayerTable lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForWrite); if (!lt.Has(layname)) { LayerTableRecord ltr = new LayerTableRecord { Name = layname }; lt.Add(ltr); trans.AddNewlyCreatedDBObject(ltr, true); trans.Commit(); } } } }
public MText addText() { MText tx = new MText(); Document acDoc = Application.DocumentManager.MdiActiveDocument; PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter Text: "); pStrOpts.AllowSpaces = true; PromptResult pStrRes = acDoc.Editor.GetString(pStrOpts); tx.Contents = pStrRes.StringResult; tx.Layer = "DIM"; //if the angle is between 90 degrees and 270 degrees if (angleA > 1.570796327 && angleA < 4.71238898) { tx.Location = new Point3d(m_pts[1].X - .25, m_pts[1].Y, 0); tx.Attachment = AttachmentPoint.MiddleRight; } else { tx.Location = new Point3d(m_pts[1].X + .25, m_pts[1].Y, 0); tx.Attachment = AttachmentPoint.MiddleLeft; } return(tx); }
public static void GetUserString() { BaseClass.UseTransaction(trans => { try { //prompt user using PromptStringOptions PromptStringOptions prompt = new PromptStringOptions("\n>>Enter your name: \n>>"); prompt.AllowSpaces = true; //Get the result of the user input PromptResult result = BaseClass.Editor.GetString(prompt); if (result.Status == PromptStatus.OK) { string name = result.StringResult; BaseClass.Editor.WriteMessage("\nHello " + name); Application.ShowAlertDialog("Your name is :" + name); } else { BaseClass.Editor.WriteMessage("\nNo name entered"); Application.ShowAlertDialog("\nNo name entered"); } } catch (System.Exception ex) { BaseClass.Editor.WriteMessage("Error encountered: " + ex.Message); trans.Abort(); } }); }
static public string getParam(string message) { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; PromptStringOptions pStr = null; PromptResult pStrRes = null; while (true) { pStr = new PromptStringOptions(message); pStr.AllowSpaces = false; pStrRes = ed.GetString(pStr); if (pStrRes.Status == PromptStatus.OK) { if (pStrRes.StringResult.Length == 0) { continue; } else { return(pStrRes.StringResult); } } else { return(null); } } }
public static void Clear() { Database acCurDb = HostApplicationServices.WorkingDatabase; Document acDoc = Application.DocumentManager.MdiActiveDocument; Editor acEdt = acDoc.Editor; /// 让用户选择是否清除块内的图元,Y:清除,N:不清除 PromptStringOptions optRecurseIn = new PromptStringOptions("是否包括块内和锁定图层内的图元?[是(Y)/否(N)]") { AllowSpaces = false, DefaultValue = "N" }; PromptResult resStringResult; do { resStringResult = acEdt.GetString(optRecurseIn); } while (resStringResult.StringResult.ToUpper() != "Y" && resStringResult.StringResult.ToUpper() != "N"); bool recurseIn = (resStringResult.StringResult.ToUpper() == "Y"); //对图形进行修改 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { ulong countTotal = 0; ulong countCleared = 0; //遍历模型空间的清零 BlockTableRecord btRecord = (BlockTableRecord)acTrans.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(acCurDb), OpenMode.ForRead, false, true); btRecord.Clear(ref countTotal, ref countCleared, recurseIn); acEdt.WriteMessage("共检查了" + countTotal + "个对象,其中" + countCleared + "个对象的Z坐标已经清除。\n"); //提交执行 acTrans.Commit(); } }
/** * @brief Metodo que contiene toda la lógica de interacción con el usuario final para decidir si * una capa concreta debe ser procesada. * * @param c Objeto de tipo dwgCapa que contiene toda la información obtenida de la capa. * * @return Retorna una cadena de texto con 3 valores posibles:<br/><br/> * 1) C: Cancelar el proceso.<br/> * 2) S: incluir la capa en el proceso de extracción de la información.<br/> * 3) N: no incluir la capa en el proceso de extracción de la información.<br/> * * */ private static String IncluirCapa(dwgCapa c) { String incluir = ""; while (incluir == "") { PromptStringOptions pStrOpts = new PromptStringOptions("\nIntroduzca si desea procesar la capa " + c.nombreCapa + "(" + c.objectId.ToString() + ") (s/n): "); PromptResult pStrRes = ed.GetString(pStrOpts); if (pStrRes.Status == PromptStatus.Cancel) { incluir = "C"; break; } else if (pStrRes.Status == PromptStatus.OK) { incluir = pStrRes.StringResult; if ((incluir == "S") || (incluir == "s")) { break; } else if ((incluir == "N") || (incluir == "n")) { break; } else { incluir = ""; } } } return(incluir); }
static public void CreatePolyLine() { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Database db = doc.Database; HostApplicationServices hs = HostApplicationServices.Current; string outputPath = hs.FindFile(doc.Name, doc.Database, FindFileHint.Default); //get user input //select point input file ed.WriteMessage("Select the Excel file contains the door step points"); string excelPath = FileOps.SelectFile(); #region get Excel Sheet Name PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter Sheet Name: "); pStrOpts.AllowSpaces = true; PromptResult pStrRes = doc.Editor.GetString(pStrOpts); string shtName = pStrRes.StringResult; #endregion List <Point3d> doorStepPts = Excel.getAllpoint(doc, excelPath, shtName); CADops.CreatePolylineFromPoint(doc, doorStepPts); }
public void EditLayerColor() { Database db = HostApplicationServices.WorkingDatabase; Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; PromptStringOptions optStr = new PromptStringOptions("\nÊäÈëͼ²ãµÄÃû³Æ"); PromptResult resStr = ed.GetString(optStr); if (resStr.Status != PromptStatus.OK) { return; } String layName = resStr.StringResult; using (Transaction trans = db.TransactionManager.StartTransaction()) { LayerTable lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForRead); if (lt.Has(layName) == false) { ed.WriteMessage("\n¸Ãͼ²ã²»´æÔÚ£¡"); return; } LayerTableRecord ltr = (LayerTableRecord)trans.GetObject(lt[layName], OpenMode.ForWrite); ColorDialog dialogObj = new ColorDialog(); System.Windows.Forms.DialogResult dialogResultValue = dialogObj.ShowDialog(); if (dialogResultValue == System.Windows.Forms.DialogResult.OK) { Color newColor = dialogObj.Color; ltr.Color = newColor; } trans.Commit(); } }
/// <summary> 通过命令行交互,设置中文与英文的字高,以逗号(中文逗号或英文逗号)分隔。比如“2.5,2.5”,表示中文字高3.5,英文字高2.5 </summary> /// <returns>操作成功,则返回 true,操作失败或手动取消操作,则返回 false</returns> private bool SetTextHeight() { var defaultValue = ChiHeight.ToString("0.00") + "," + EngHeight.ToString("0.00"); // var op = new PromptStringOptions(message: "\n设置中英文字高:") { AllowSpaces = false, DefaultValue = defaultValue, UseDefaultValue = true }; // var res = _docMdf.acEditor.GetString(op); if (res.Status == PromptStatus.OK) { var v = res.StringResult; var s = v.Split(','); double num; var isNum = double.TryParse(s[0], out num); if (isNum) { ChiHeight = num; } if (s.Length > 1) { isNum = double.TryParse(s[1], out num); if (isNum) { EngHeight = num; } } return(true); } return(false); }
public void LayerDel() { string layerName = ""; PromptStringOptions propStrOps = new PromptStringOptions("请输入图层名称:\n"); do { var propStrRes = Ed.GetString(propStrOps); if (propStrRes.Status == PromptStatus.OK) { layerName = propStrRes.StringResult; } } while (layerName == ""); try { SymbolUtilityServices.ValidateSymbolName(layerName, false); if (DeleteLayer(Db, layerName)) { Ed.WriteMessage("delete ok"); } else { Ed.WriteMessage("delete not ok"); } } catch (Autodesk.AutoCAD.Runtime.Exception e) { Ed.WriteMessage(e.Message + "\n"); } }
public void testdelLayer() { Database db = HostApplicationServices.WorkingDatabase; Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; PromptStringOptions optStr = new PromptStringOptions("\nÊäÈëͼ²ãµÄÃû³Æ"); PromptResult resStr = ed.GetString(optStr); if (resStr.Status != PromptStatus.OK) { return; } String layName = resStr.StringResult; using (Transaction trans = db.TransactionManager.StartTransaction()) { LayerTable lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForWrite); if (lt.Has(layName) == false) { ed.WriteMessage("\n¸Ãͼ²ã²»´æÔÚ£¡"); return; } LayerTableRecord ltr = (LayerTableRecord)trans.GetObject(lt[layName], OpenMode.ForWrite); LayerTableRecord curLtr = (LayerTableRecord)trans.GetObject(db.Clayer, OpenMode.ForRead); if (layName == curLtr.Name) { ed.WriteMessage("\n²»ÄÜɾ³ýµ±Ç°Í¼²ã£¡"); } else { ltr.Erase(true); } trans.Commit(); } }
public void MyMLeaderJig() { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Database db = doc.Database; string text = null; bool escape = false; // Get the text outside of the jig PromptStringOptions pso = new PromptStringOptions("\nEnter text: "); pso.AllowSpaces = true; PromptResult pr = ed.GetString(pso); text = pr.StringResult; do { PromptStringOptions pso2 = new PromptStringOptions("\nEnter Next Line: "); PromptResult pr2 = ed.GetString(pso2); text = text + @"\P" + pr2.StringResult; if (pr2.StringResult == "") { escape = true; } }while (!escape); if (pr.Status == PromptStatus.OK) { // Create MleaderJig MLeaderJig jig = new MLeaderJig(text); // Loop to set vertices bool bSuccess = true; for (int i = 0; i < 2; i++) { PromptResult dragres = ed.Drag(jig); bSuccess = (dragres.Status == PromptStatus.OK); // A new point was added if (bSuccess) { jig.AddVertex(); } } jig.RemoveLastVertex(); // Append entity Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead, false); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false); btr.AppendEntity(jig.GetEntity()); tr.AddNewlyCreatedDBObject(jig.GetEntity(), true); tr.Commit(); } } }
// Ask the user to enter a mandatory string field private static string GetMandatoryString( Editor ed, string prompt, object defVal ) { PromptStringOptions pso = new PromptStringOptions("\n" + prompt + ": "); pso.AllowSpaces = true; if (defVal != null) { pso.DefaultValue = (string)defVal; pso.UseDefaultValue = true; } PromptResult pr; bool isEmpty; do { pr = ed.GetString(pso); if (pr.Status != PromptStatus.OK) { throw new CancellationException(); } isEmpty = String.IsNullOrEmpty(pr.StringResult); if (isEmpty) { ed.WriteMessage("\nRequired field."); } }while (isEmpty); return(pr.StringResult); }
public void GetParameters() { _fileServerName = null; _mapCenterCoordinate = new Point2d(0, 0); var options = new PromptStringOptions("\nZone (Est|West): ") { DefaultValue = "West" }; var ed = acApp.DocumentManager.MdiActiveDocument.Editor; var pr = ed.GetString(options); if (pr.Status != PromptStatus.OK) { ed.WriteMessage("Command canceled\n"); return; } switch (pr.StringResult.ToUpper()) { case "E": case "EST": _fileServerName = "RWA004"; _mapCenterCoordinate = new Point2d(184000, 127000); break; case "W": case "WEST": _fileServerName = "RWA005"; _mapCenterCoordinate = new Point2d(155500, 122000); break; default: ed.WriteMessage("Command canceled\n"); break; } }
public static void MyNetLoad() { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; PromptStringOptions pso = new PromptStringOptions("\n输入要加载的程序集全路径: "); pso.AllowSpaces = true; PromptResult pr = ed.GetString(pso); if (pr.Status != PromptStatus.OK) { return; } try { // byte[] buff = File.ReadAllBytes(pr.StringResult); //先将插件拷贝到内存缓冲。一般情况下,当加载的文件大小大于2^32 byte (即4.2 GB),就会出现OutOfMemoryException,在实际测试中的极限值为630MB。 var ass = Assembly.Load(buff); // var ass = Assembly.LoadFile(pr.StringResult); //var ass = System.Reflection.Assembly.LoadFrom(pr.StringResult); } catch (System.Exception ex) { ed.WriteMessage("\n无法加载程序集{0}: {1}", pr.StringResult, ex.Message); } }
private bool GetAxisName() { var doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; var ed = doc.Editor; PromptStringOptions opts = new PromptStringOptions("Aks adı: "); opts.DefaultValue = AxisName; PromptResult res = ed.GetString(opts); string name = res.StringResult; if (res.Status == PromptStatus.None) { name = AxisName; } else if (res.Status != PromptStatus.OK) { return(false); } // Break axis name into parts var regex = new System.Text.RegularExpressions.Regex(@"\d"); if (regex.IsMatch(name)) { var match = regex.Match(name); Prefix = name.Substring(0, match.Index); Number = int.Parse(name.Substring(match.Index, match.Length)); Suffix = name.Substring(match.Index + match.Length); return(true); } return(false); }
/// <summary> /// Starts The Pong Game /// </summary> public void StartGame() { keyPress = ""; Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; if (doc != null) { ed.WriteMessage("\n USE THE UP AND DOWN ARROW KEYS TO MOVE THE PADDE. \n \n PRESS ESCAPE OR CLOSE DIALOG BOX TO STOP THE GAME."); PromptStringOptions promptOptions = new PromptStringOptions("\n Run Pong Game? \n Type Y or N"); PromptResult run = ed.GetString(promptOptions); if (run.StringResult.ToUpper() == "Y") { #region Create the entities bbox = DrawEntity.DrawBox(new Point2d(0, 20), new Point2d(20, 20), new Point2d(20, 0), new Point2d(0, 0), "PongGameBoundingBox"); userPaddle = DrawEntity.DrawBox(new Point2d(2, 2), new Point2d(2.25, 2), new Point2d(2.25, 6), new Point2d(2, 6), "PongGamePaddle", 50); enemyPaddle = DrawEntity.DrawBox(new Point2d(17.75, 2), new Point2d(18, 2), new Point2d(18, 6), new Point2d(17.75, 6), "PongGamePaddle", 50); scoreLabelEnt = DrawEntity.DrawText(new Point2d(7, 21.5), "SCORE: " + curScore.ToString(), "PongGameScore", 30); ball = DrawEntity.DrawCircle(0.35, new Point3d(10, 10, 0), "PongGameBall", 10); #endregion DrawEntity.ZoomExtents(); //Zoom extents. timer.Interval = 10; timer.Tick += GameEngine; timer.Start(); keyHandler.Show(); //Show modeless form that listens for key inputs. } } }
public Drawing CreateDefaultDrawingWithFileName() { try { Drawing d = DBCommon.CreateDefaultDrawing(); d.FileName = _db.Filename; try { d.Number = Path.GetFileNameWithoutExtension(d.FileName); while (DBCommon.DrawingComboExists(d.Number, d.Sheet)) { PromptStringOptions pso = new PromptStringOptions(string.Format("Drawing {0} sheet {1} already exists. Please enter a new sheet number:", d.Number, d.Sheet)); string str = _ed.DoPrompt(pso).StringResult; _ed.WriteMessage(str + Environment.NewLine); if (str == "") { return(null); } d.Sheet = str; } } catch (Exception ex) { _ed.WriteMessage(ex.ToString()); } return(d); } catch { return(null); } }
public void PTIns() { m_ed = Application.DocumentManager.MdiActiveDocument.Editor; PromptPointOptions prPtOpt = new PromptPointOptions("Bitte Position wählen:"); bool bBeenden = false; while (!bBeenden) { PromptPointResult prPtRes = m_ed.GetPoint("Position wählen:"); if (prPtRes.Status == PromptStatus.OK) { PromptStringOptions prStringOpt = new PromptStringOptions("Nr: " + PNrZähler); prStringOpt.AllowSpaces = false; PromptResult prRes = m_ed.GetString(prStringOpt); if (prRes.Status == PromptStatus.OK) { if (prRes.StringResult != "") { PNrZähler = prRes.StringResult; PNrZähler = objUtil.incString(PNrZähler); } } Messpunkt objMP = new Messpunkt(PNrZähler, prPtRes.Value.X, prPtRes.Value.Y, null, null, 0); objMP.draw("MP", "MP-P"); } else { bBeenden = true; } } }
public async void _INOUTBLK() { Settings.Variables.ATTDIA = false; PromptStringOptions pso = new PromptStringOptions("\nEnter BlockName") { AllowSpaces = false, UseDefaultValue = true, DefaultValue = _blockName }; var pr = Ed.GetString(pso); if (pr.Status != PromptStatus.OK) { return; } _blockName = pr.StringResult.ToUpper(); try { await InsertBlock(_blockName); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { if (ex.ErrorStatus != ErrorStatus.UserBreak) { throw; } } }
public static bool EditLevels(ObjectId fflToEditId) { Document acDoc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument; Database acCurrDb = acDoc.Database; Editor acEditor = acDoc.Editor; bool userEditing = true; while (userEditing) { // Ask user if he wants to edit the level values or move levels PromptStringOptions strOptions = new PromptStringOptions("\nEdit, move or delete level (E, M, D or X to finish)? "); PromptResult userChoice = acEditor.GetString(strOptions); if (userChoice.Status == PromptStatus.Cancel) { return(true); } else if (userChoice.Status == PromptStatus.Error) { acEditor.WriteMessage("\nError selecting what to edit."); return(false); } else { switch (userChoice.StringResult.ToUpper()) { case "E": // Call the edit level value function if (!EditLevelValue(fflToEditId)) { return(false); } break; case "M": if (!MoveLevelText(fflToEditId)) { return(false); } break; case "D": if (!DeleteLevelText(fflToEditId)) { return(false); } break; case "X": userEditing = false; break; default: acEditor.WriteMessage("\nPlease enter 'E' or 'M' or 'X' to finish."); break; } } } return(true); }
public void InoutblKx() { var pso = new PromptStringOptions("\nEnter BlockName") { AllowSpaces = false, UseDefaultValue = true, DefaultValue = _blockName }; var pr = Ed.GetString(pso); if (pr.Status != PromptStatus.OK) { return; } _blockName = pr.StringResult.ToUpper(); try { InoutblKxAsync(_blockName); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { if (ex.ErrorStatus != ErrorStatus.UserBreak) { throw; } } }
static public void SelectDynamicBlocks() { var doc = Active.Document; var ed = doc.Editor; var pso = new PromptStringOptions("\nName of dynamic block to search for"); pso.AllowSpaces = true; var pr = ed.GetString(pso); if (pr.Status != PromptStatus.OK) { return; } string blkName = pr.StringResult; List <string> blkNames = new List <string>(); blkNames.Add(blkName); var tr = doc.TransactionManager.StartTransaction(); try { using (tr) { var bt = (BlockTable)tr.GetObject(doc.Database.BlockTableId, OpenMode.ForRead); // Start by getting access to our block, if it exists if (!bt.Has(blkName)) { ed.WriteMessage("\nCannot find block called \"{0}\".", blkName); return; } // Get the anonymous block names var btr = (BlockTableRecord)tr.GetObject(bt[blkName], OpenMode.ForRead); if (!btr.IsDynamicBlock) { ed.WriteMessage("\nCannot find a dynamic block called \"{0}\".", blkName); return; } // Get the anonymous blocks and add them to our list var anonBlks = btr.GetAnonymousBlockIds(); foreach (ObjectId bid in anonBlks) { var btr2 = (BlockTableRecord)tr.GetObject(bid, OpenMode.ForRead); blkNames.Add(btr2.Name); } tr.Commit(); } // Build a conditional filter list so that only // entities with the specified properties are // selected SelectionFilter sf = new SelectionFilter(CreateFilterListForBlocks(blkNames)); PromptSelectionResult psr = ed.SelectAll(sf); ed.WriteMessage("\nFound {0} entit{1}.", psr.Value.Count, (psr.Value.Count == 1 ? "y" : "ies")); } catch (Autodesk.AutoCAD.Runtime.Exception e) { Console.WriteLine(e.Message); throw; } }
Stream(ArrayList data, PromptEditorOptions opts) { data.Add(new Snoop.Data.ClassSeparator(typeof(PromptEditorOptions))); PromptCornerOptions promptCornerOpts = opts as PromptCornerOptions; if (promptCornerOpts != null) { Stream(data, promptCornerOpts); return; } PromptStringOptions promptStrOpts = opts as PromptStringOptions; if (promptStrOpts != null) { Stream(data, promptStrOpts); return; } PromptKeywordOptions promptKwordOpts = opts as PromptKeywordOptions; if (promptKwordOpts != null) { Stream(data, promptKwordOpts); return; } PromptNumericalOptions promptNumpericalOpts = opts as PromptNumericalOptions; if (promptNumpericalOpts != null) { Stream(data, promptNumpericalOpts); return; } PromptEntityOptions promptEntOpts = opts as PromptEntityOptions; if (promptEntOpts != null) { Stream(data, promptEntOpts); return; } PromptAngleOptions promptAngleOpts = opts as PromptAngleOptions; if (promptAngleOpts != null) { Stream(data, promptAngleOpts); return; } PromptDragOptions promptDragOpts = opts as PromptDragOptions; if (promptDragOpts != null) { Stream(data, promptDragOpts); return; } }
public static void CMD_NUnit_Command() { // Put your command code here //Application.ShowAlertDialog("nunit-command"); try { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; PromptStringOptions opt = new PromptStringOptions("args:"); opt.AllowSpaces = true; PromptResult res = ed.GetString(opt); string[] args = new string[0]; switch (res.Status) { case PromptStatus.OK: if (res.StringResult.Trim() != "") { args = res.StringResult.Split(' '); } break; default: break; } RunnerArxNet.Main(args); } catch (Autodesk.AutoCAD.Runtime.Exception e) { Application.ShowAlertDialog(e.Message); } catch (System.Exception e) { Application.ShowAlertDialog(e.Message); } }
public static void pointLoadTest() { Document apdoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; PromptStringOptions strOpts = new PromptStringOptions("\nPlease enter the point live load in pounds: "); strOpts.AllowSpaces = false; PromptResult strRes = apdoc.Editor.GetString(strOpts); double[] lbs = { 0, 0 }; lbs[0] = double.Parse(strRes.StringResult) / 12; //loads stored in lbs strOpts.Message = "\nPlease enter the point dead load in pounds: "; strRes = apdoc.Editor.GetString(strOpts); lbs[1] = double.Parse(strRes.StringResult) / 12; //loads stored in lbs strOpts.Message = "\nPlease enter the length of the beam in feet: "; strRes = apdoc.Editor.GetString(strOpts); double beamLength = double.Parse(strRes.StringResult) * 12; //Beam length stored in inches strOpts.Message = "\nPlease enter the modulus of elasticity in pounds force per square inch: "; strRes = apdoc.Editor.GetString(strOpts); double elasticity = double.Parse(strRes.StringResult); strOpts.Message = "\nPlease enter the planar moment of inertia in quartic inches: "; strRes = apdoc.Editor.GetString(strOpts); double mInertia = double.Parse(strRes.StringResult); calcs.pointLoadTest(lbs, beamLength, elasticity, mInertia); }
getUserInput(string deflt, string prompt, out string result, bool spaces = false) { bool escape = false; Editor ed = BaseObjs._editor; PromptStringOptions pso = new PromptStringOptions(prompt); pso.UseDefaultValue = true; pso.DefaultValue = deflt; pso.AllowSpaces = spaces; result = string.Empty; PromptResult pr = ed.GetString(pso); switch (pr.Status) { case PromptStatus.OK: result = pr.StringResult.ToUpper(); if (result == "") { result = deflt; } break; case PromptStatus.Cancel: escape = true; break; case PromptStatus.None: result = deflt; break; } return(escape); }
public async void _INOUTBLK() { Settings.Variables.ATTDIA = false; PromptStringOptions pso = new PromptStringOptions("\nEnter BlockName") { AllowSpaces = false, UseDefaultValue = true, DefaultValue = _blockName }; var pr = Ed.GetString(pso); if (pr.Status != PromptStatus.OK) return; _blockName = pr.StringResult.ToUpper(); try { await InsertBlock(_blockName); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { if (ex.ErrorStatus != ErrorStatus.UserBreak) { throw; } } }
public void CreateReddit() { EntityData dimStyles = new EntityData(); Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed; if (doc != null) { ed = doc.Editor; PromptStringOptions prmptStrOpt = new PromptStringOptions("\n\n Type subreddit name. Do not include '/r/' "); PromptResult prmpRes = ed.GetString(prmptStrOpt); PromptPointOptions prmptPtOptions = new PromptPointOptions("\n\nPick insertion point...."); PromptPointResult result = ed.GetPoint(prmptPtOptions); PromptCornerOptions prmptCnrOptions = new PromptCornerOptions("\n\n Click on bottom corner..", result.Value); PromptPointResult prmptCnrResult; prmptCnrResult = ed.GetCorner(prmptCnrOptions); string chosenSubReddit = prmpRes.StringResult; RedditCAD.FormatRedditDim(dimStyles, result.Value, prmptCnrResult.Value); if (RedditCAD.PlotSubReddit(dimStyles, chosenSubReddit) == "FAILED") { ed.WriteMessage("\n\nFAILED"); } } }
public async void Inoutblk() { var pso = new PromptStringOptions("\nEnter BlockName") { AllowSpaces = false, UseDefaultValue = true, DefaultValue = _blockName }; var pr = Ed.GetString(pso); if (pr.Status != PromptStatus.OK) return; _blockName = pr.StringResult.ToUpper(); { try { bool promptOk = true; while (promptOk) { promptOk = await InsertBlock(_blockName); } } catch (Autodesk.AutoCAD.Runtime.Exception ex) { if (ex.ErrorStatus != ErrorStatus.UserBreak) { throw; } } } }
public static void InsertLayer() { Document acDoc = Application.DocumentManager.MdiActiveDocument; PromptStringOptions pStrOpts = new PromptStringOptions(""); //from the menu macro command gets the filename of the text file to use PromptResult pStrRes = acDoc.Editor.GetString(pStrOpts); //concatenates the full file path string FileName = MyPlugin.GetRoot() + @"CSV\" + pStrRes.StringResult; //gets each line in the text file and adds each line to an element in a string array string[] fileLines = SplitFileByLine(FileName); //parses each element in individual line to get the variables we need for (int index = 0; index < fileLines.Length; index++) { string[] items = fileLines[index].Trim().Split(','); if (items.Length > 1) { string Name = items[0]; short Color = short.Parse(items[1]); string LineType = items[2]; //makes sure the linetype exists GeneralMenu.LoadLinetype(LineType); //creates the layer GeneralMenu.CreateLayer(Name, Color, LineType, false); acDoc.Editor.WriteMessage("\n " + Name + " Layer created"); } } }
public void OpenSheetSet() { // User Input: editor equals command line // To talk to the user you use the command line, aka the editor Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; PromptStringOptions pso = new PromptStringOptions("\nHello Nadia! \nWhat Sheet Set would you like to open?"); pso.DefaultValue = @"C:\Users\rhale\Documents\AutoCAD Sheet Sets\Squid666.dst"; pso.UseDefaultValue = true; pso.AllowSpaces = true; PromptResult pr = ed.GetString(pso); // Get a reference to the Sheet Set Manager object IAcSmSheetSetMgr sheetSetManager = default(IAcSmSheetSetMgr); sheetSetManager = new AcSmSheetSetMgr(); // Open a Sheet Set file AcSmDatabase sheetSetDatabase = default(AcSmDatabase); //sheetSetDatabase = sheetSetManager.OpenDatabase(@"C:\Users\Robert\Documents\AutoCAD Sheet Sets\Expedia.dst", false); sheetSetDatabase = sheetSetManager.OpenDatabase(pr.StringResult, false); // Return the namd and description of the sheet set MessageBox.Show("Sheet Set Name: " + sheetSetDatabase.GetSheetSet().GetName() + "\nSheet Set Description: " + sheetSetDatabase.GetSheetSet().GetDesc()); // Close the sheet set sheetSetManager.Close(sheetSetDatabase); }
public void ChangeAttributeMethod() { Document activeDoc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument; Editor ed = activeDoc.Editor; PromptStringOptions pso1 = new PromptStringOptions("\nAttribute tag name: "); pso1.AllowSpaces = true; PromptResult pr1 = ed.GetString(pso1); if (pr1.Status != PromptStatus.OK) return; String AttributeTagName = pr1.StringResult; PromptStringOptions pso2 = new PromptStringOptions("\nold value : "); pso2.AllowSpaces = true; PromptResult pr2 = ed.GetString(pso2); if (pr2.Status != PromptStatus.OK) return; String oldValue = pr2.StringResult; PromptStringOptions pso3 = new PromptStringOptions("\nnew value : "); pso3.AllowSpaces = true; PromptResult pr3 = ed.GetString(pso3); if (pr3.Status != PromptStatus.OK) return; String newValue = pr3.StringResult; ChangeAttributeValue(AttributeTagName, oldValue, newValue); }
private static ScriptSource read_code(string line, ScriptEngine engine, ScriptScope scope) { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; PromptStringOptions opts = new PromptStringOptions(" "); opts.AllowSpaces = true; PromptResult res; string code = line; while (true) { try { ScriptSource interactive_code = engine.CreateScriptSourceFromString(code, SourceCodeKind.InteractiveCode); ScriptCodeParseResult props = interactive_code.GetCodeProperties(); switch (props) { case ScriptCodeParseResult.Complete: return interactive_code; case ScriptCodeParseResult.Invalid: return interactive_code; default: ed.WriteMessage("\nrb| "); res = ed.GetString(opts); if (res.Status == PromptStatus.OK) { code += res.StringResult; code += "\n"; } else { return interactive_code; } break; } } catch (System.Exception e) { ed.WriteMessage("\nError: {0}", e.Message); } } }
public static void RubyRepl() { AcadOutputStream io_stream = new AcadOutputStream(); var engine = Ruby.CreateEngine(); engine.Runtime.IO.SetOutput(io_stream, System.Text.Encoding.ASCII); var scope = engine.CreateScope(); var exception_services = engine.GetService<ExceptionOperations>(); Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; PromptStringOptions opts = new PromptStringOptions(" "); opts.AllowSpaces = true; PromptResult res; string line = ""; while (true) { try { ed.WriteMessage("\nrb> "); res = ed.GetString(opts); if (res.Status == PromptStatus.OK) { line = res.StringResult; line += "\n"; } else break; if (line == "\n") break; if (line == "#exit\n") break; ScriptSource source = read_code(line, engine, scope); source.Execute(scope); } catch (System.Exception e) { ed.WriteMessage("\nError: {0}", e.Message); } } }
private bool AecomBlockToDatabase(BlockReference block, Transaction tr) { try { Dictionary<string, AttributeReference> attribs = GetBlockAttributes(block, tr); string sheet = "";//aecom blocks have no sheet attribute so lets keep track of it separate. string number = ""; PromptStringOptions pso = new PromptStringOptions("Drawing Number:"); pso.DefaultValue = GetAttribute(attribs, "Number"); PromptResult pr1 = _ed.GetString(pso); if (pr1.Status == PromptStatus.Cancel) return false; if (string.IsNullOrWhiteSpace(pr1.StringResult)) return false; number = pr1.StringResult; pso = new PromptStringOptions("Sheet Number:"); pso.DefaultValue = "1"; pr1 = _ed.GetString(pso); if (pr1.Status == PromptStatus.Cancel) return false; if (string.IsNullOrWhiteSpace(pr1.StringResult)) return false; sheet = pr1.StringResult; DrawingsDataContext dc = DBCommon.NewDC; Drawing drawing = DrawingHelper.GetDrawing(dc, number, sheet); if (drawing == null) { drawing = new Drawing(); dc.Drawings.InsertOnSubmit(drawing); } foreach (var kvp in attribs) { if (DrawingHelper.AttributeExists(kvp.Key)) //only save the desired attributes drawing.SetAttribute(kvp.Key, kvp.Value.TextString); } drawing.Number = number; //override the block with what we know from earlier drawing.Sheet = sheet; drawing.DrawnDate = drawing.ApprovedDate; drawing.SheetSize = "A3"; drawing.Consultant = "AECOM / MAUNSEL"; drawing.Category = DrawingCategory.ZoneSubstation; _ed.WriteMessage("INFO: Drawing Category set to ZONE SUBSTATION.\n"); //TODO: check this if (_db.Filename.EndsWith("sv$", StringComparison.OrdinalIgnoreCase)) { _ed.WriteMessage("File has not been saved since autosave, filename not put into the database.\n"); } else { drawing.FileName = _db.Filename; } //If we're putting this in via the CAD, then it must be electronic drawing.Electronic = true; dc.SubmitChanges(); if (drawing.Category == DrawingCategory.Undefined) { System.Windows.MessageBox.Show("Your drawing has an invalid category. Please fix it and try again.", "OI. CHECK YOUR SPELLING DUMMY"); _ed.WriteMessage("WARNING: Drawing Category is undefined!\n"); } if (drawing.Status == DrawingStatus.Undefined) { System.Windows.MessageBox.Show("Your drawing has an invalid status. Please fix it and try again.", "OI. CHECK YOUR SPELLING DUMMMY"); _ed.WriteMessage("WARNING: Drawing Status is undefined!\n"); } _ed.WriteMessage("Data successfully written to the database from block " + block.Name + "\n"); return true; } catch (Exception ex) { _ed.WriteMessage(ex.Message); return false; } }
public string ReadLine( string initial, int time, TimedInputCallback callback, byte[] terminatingKeys, out byte terminator ) { if (_non0.Count == 199) { _lastLoc = _non0[locIdx]; var sb = new StringBuilder(); sb.AppendFormat( "{{\"id\":\"{0}\",\"name\":\"{1}\",\"dir\":\"{2}\"}}", _curLoc, _lastLoc, _lastMove.ToUpper() ); acjsInvokeAsync("setloc", sb.ToString()); } terminator = 13; var prompt = _non0.Count == 199 && _showProgress ? String.Format( "\n<Location: {0}, Score {1}, Moves {2}> ", _non0[locIdx], _non0[scoIdx], _non0[movIdx] ) : ""; var pso = new PromptStringOptions(prompt); pso.AllowSpaces = true; var pr = _ed.GetString(pso); if (pr.Status == PromptStatus.OK && pr.StringResult == "-") { pr = _ed.GetString(pso); } _lastMove = pr.Status == PromptStatus.OK ? pr.StringResult : ""; _non0.Clear(); return _lastMove; }
/** * @brief Metodo que contiene toda la lógica de interacción con el usuario final para decidir si * una capa concreta debe ser procesada. * * @param c Objeto de tipo dwgCapa que contiene toda la información obtenida de la capa. * * @return Retorna una cadena de texto con 3 valores posibles:<br/><br/> * 1) C: Cancelar el proceso.<br/> * 2) S: incluir la capa en el proceso de extracción de la información.<br/> * 3) N: no incluir la capa en el proceso de extracción de la información.<br/> * * */ private static String IncluirCapa(dwgCapa c) { String incluir = ""; while (incluir == "") { PromptStringOptions pStrOpts = new PromptStringOptions("\nIntroduzca si desea procesar la capa " + c.nombreCapa + "(" + c.objectId.ToString() + ") (s/n): "); PromptResult pStrRes = ed.GetString(pStrOpts); if (pStrRes.Status == PromptStatus.Cancel) { incluir = "C"; break; } else if (pStrRes.Status == PromptStatus.OK) { incluir = pStrRes.StringResult; if ((incluir == "S") || (incluir == "s")) { break; } else if ((incluir == "N") || (incluir == "n")) { break; } else { incluir = ""; } } } return incluir; }
/** * @brief Metodo que contiene toda la lógica de interacción con el usuario final para realizar la * configuración necesaria del proceso:<br/><br/> * * 1) Activación del log (s/n).<br/> * 2) En caso afirmativo, activación de la información de debug.<br/> * 3) Ruta del fichero donde se guardará la información obtenida de la base de datos de AutoCAD.<br/> * 4) Selección manual de las capas a procesar (s/n) * * @return Devuelve "Verdadero" si ha podido finalizar la configuración del usuario.<br/> * Devuelve "Falso" si el usuario ha cancelado la configuración o se ha producido un error.<br/> * */ private static bool ConfiguracionUsuario() { try { String userLog = ""; while (userLog == "") { PromptStringOptions pStrOpts = new PromptStringOptions("\nIntroduzca si desea log de la decodificación (s/n): "); PromptResult pStrRes = ed.GetString(pStrOpts); if (pStrRes.Status == PromptStatus.Cancel) { return false; } else if (pStrRes.Status == PromptStatus.OK) { userLog = pStrRes.StringResult; if ((userLog == "S") || (userLog == "s")) { logActivo = true; break; } else if ((userLog == "N") || (userLog == "n")) { logActivo = false; break; } else { userLog = ""; } } } if (logActivo == true) { String userDebug = ""; while (userDebug == "") { PromptStringOptions pStrOpts = new PromptStringOptions("\nIntroduzca si desea un log con información de debug del proceso de decodificación (s/n): "); PromptResult pStrRes = ed.GetString(pStrOpts); if (pStrRes.Status == PromptStatus.Cancel) { return false; } else if (pStrRes.Status == PromptStatus.OK) { userDebug = pStrRes.StringResult; if ((userDebug == "S") || (userDebug == "s")) { logDebug = true; break; } else if ((userDebug == "N") || (userDebug == "n")) { logDebug = false; break; } else { userDebug = ""; } } } } // System.IO.Path.IsPathRooted(@"c:\foo"); String filePath = ""; while (filePath == "") { PromptStringOptions pStrOpts = new PromptStringOptions("\nIntroduzca el nombre del fichero (ruta completa) donde quiere guardar la salida del proceso: "); PromptResult pStrRes = ed.GetString(pStrOpts); if (pStrRes.Status == PromptStatus.Cancel) { return false; } else if (pStrRes.Status == PromptStatus.OK) { filePath = pStrRes.StringResult; try { filePath = Path.GetFullPath(filePath); log("El fichero con toda la información sera creado en la ruta: " + filePath, false, false); ruta = filePath; } catch (System.Exception e) { log("Error. No es una ruta válida", false, false); log(e.ToString(),false,false); filePath = ""; } } } String userLayers = ""; while (userLayers == "") { PromptStringOptions pStrOpts = new PromptStringOptions("\nIntroduzca si desea configurar manualmente las capas a procesar (s/n): "); PromptResult pStrRes = ed.GetString(pStrOpts); if (pStrRes.Status == PromptStatus.Cancel) { return false; } else if (pStrRes.Status == PromptStatus.OK) { userLayers = pStrRes.StringResult; if ((userLayers == "S") || (userLayers == "s")) { selectLayers = true; break; } else if ((userLayers == "N") || (userLayers == "n")) { selectLayers = false; break; } else { userLayers = ""; } } } return true; } catch (System.Exception e) { log("No ha sido posible realizar la configuración de usuario.", false, false); log(e.ToString(), false, false); return false; } }
public string ReadLine( string initial, int time, TimedInputCallback callback, byte[] terminatingKeys, out byte terminator ) { terminator = 13; var prompt = _non0.Count == 199 && _showProgress ? String.Format( "\n<Location: {0}, Score {1}, Moves {2}> ", _non0[locIdx], _non0[scoIdx], _non0[movIdx] ) : ""; var pso = new PromptStringOptions(prompt); pso.AllowSpaces = true; var pr = _ed.GetString(pso); _non0.Clear(); return pr.Status == PromptStatus.OK ? pr.StringResult : "quit"; }
public static IAcedCmdArg Argument(PromptStringOptions options) { return new PromptStringArgument(options); }
public void Create() { Database db = HostApplicationServices.WorkingDatabase; Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; try { using (Transaction trans = db.TransactionManager.StartTransaction()) { //Prompts for each employee detail PromptStringOptions prName = new PromptStringOptions("Enter Employee Name"); PromptStringOptions prDiv = new PromptStringOptions("Enter Employee Division"); PromptDoubleOptions prSal = new PromptDoubleOptions("Enter Employee Salary"); PromptPointOptions prPos = new PromptPointOptions("Enter Employee Position or"); //Add keywords when prompting for position prPos.Keywords.Add("Name"); prPos.Keywords.Add("Division"); prPos.Keywords.Add("Salary"); //Set the default values for each of these prName.DefaultValue = "Earnest Shackleton"; prDiv.DefaultValue = "Sales"; prSal.DefaultValue = 10000.0f; //Set conditions for prompting prPos.AllowNone = false; //Do not allow null values //prompt results - set explicitly to null PromptResult prNameRes = null; PromptResult prDivRes = null; PromptDoubleResult prSalRes = null; PromptPointResult prPosRes = null; //Loop to get employee details. Exit the loop when positon is entered while (prPosRes == null || prPosRes.Status != PromptStatus.OK) { //Prompt for position prPosRes = ed.GetPoint(prPos); if (prPosRes.Status == PromptStatus.Keyword) //Got a keyword { switch (prPosRes.StringResult) { case "Name": //Get employee name prName.AllowSpaces = true; prNameRes = ed.GetString(prName); if (prNameRes.Status != PromptStatus.OK) throw new System.Exception("Error or User Cancelled"); break; case "Division": //Get employee division prDiv.AllowSpaces = true; prDivRes = ed.GetString(prDiv); if (prDivRes.Status != PromptStatus.OK) throw new System.Exception("Error or User Cancelled"); break; case "Salary": //Get employee salary prSal.AllowNegative = false; prSal.AllowNone = true; prSal.AllowZero = false; prSalRes = ed.GetDouble(prSal); if (prSalRes.Status != PromptStatus.OK & prSalRes.Status != PromptStatus.None) throw new System.Exception("Error or User Cancelled"); break; } } if (prPosRes.Status == PromptStatus.Cancel || prPosRes.Status == PromptStatus.Error) throw new System.Exception("Error or User Cancelled"); } //Create the Employee - either use the input value or the default value... string empName = (prNameRes == null ? prName.DefaultValue : prNameRes.StringResult); string divName = (prDivRes == null ? prDiv.DefaultValue : prDivRes.StringResult); double salary = (prSalRes == null ? prSal.DefaultValue : prSalRes.Value); CreateEmployee(empName, divName, salary, prPosRes.Value); //Now create the division //Pass an empty string for manager to check if it already exists string manager = ""; ObjectId xRecId = CreateDivision(divName, manager); //Open the department manager XRecord Xrecord depMgrXRec = (Xrecord)trans.GetObject(xRecId, OpenMode.ForRead); TypedValue[] typedVal = depMgrXRec.Data.AsArray(); foreach (TypedValue val in typedVal) { string str = (string)val.Value; if (str == "") { //Manager was not set, now set it // Prompt for manager name first ed.WriteMessage("\r\n"); PromptStringOptions prManagerName = new PromptStringOptions("No manager set for the division! Enter Manager Name"); prManagerName.DefaultValue = "Delton T. Cransley"; prManagerName.AllowSpaces = true; PromptResult prManagerNameRes = ed.GetString(prManagerName); if (prManagerNameRes.Status != PromptStatus.OK) throw new System.Exception("Error or User Cancelled"); //Set a manager name depMgrXRec.Data = new ResultBuffer(new TypedValue((int)DxfCode.Text, prManagerNameRes.StringResult)); } } trans.Commit(); } } catch (System.Exception ex) { ed.WriteMessage("\nError: " + ex.Message + "\n"); } }
static public string getParam(string message) { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; PromptStringOptions pStr = null; PromptResult pStrRes = null; while (true) { pStr = new PromptStringOptions(message); pStr.AllowSpaces = false; pStrRes = ed.GetString(pStr); if (pStrRes.Status == PromptStatus.OK) { if (pStrRes.StringResult.Length == 0) { continue; } else { return pStrRes.StringResult; } } else { return null; } } }
public static void Clear() { Database db = HostApplicationServices.WorkingDatabase; Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; PromptStringOptions optRecurseIn = new PromptStringOptions("是否包括块内的图元?[是(Y)/否(N)]") { AllowSpaces = false, DefaultValue = "N" }; PromptResult resStringResult; do { resStringResult = ed.GetString(optRecurseIn); } while (resStringResult.StringResult.ToUpper() != "Y" && resStringResult.StringResult.ToUpper() != "N"); bool recurseIn = (resStringResult.StringResult == "Y"); using (Transaction trans = db.TransactionManager.StartTransaction()) { try { List<Entity> objList = db.GetEntsInDatabase(); ulong countTotal = (ulong) objList.Count; ulong countCleared = Clear(objList, recurseIn); ed.WriteMessageWithReturn( "共检查了" + countTotal + "个对象,其中" + countCleared + "个对象的Z坐标已经清除。"); trans.Commit(); } catch (Exception e) { trans.Abort(); ed.WriteMessageWithReturn(e.ToString()); } } }
private string getSection() { string resSection = string.Empty; var opt = new PromptStringOptions("Номер секции"); opt.DefaultValue = string.IsNullOrEmpty(_section) ? "1" : _section; var res = _ed.GetString(opt); if (res.Status == PromptStatus.OK) { resSection = res.StringResult; } return resSection; }
/// <summary> /// Creates a default drawing, assigns the filename from the current drawing, and prompts for a drawing and sheet number. /// </summary> /// <returns></returns> public Drawing CreateDefaultDrawingWithFileName() { try { Drawing d = DBCommon.CreateDefaultDrawing(); d.FileName = _db.Filename; try { d.Number = Path.GetFileNameWithoutExtension(d.FileName); while (DBCommon.DrawingComboExists(d.Number, d.Sheet)) { PromptStringOptions pso = new PromptStringOptions(string.Format("Drawing {0} sheet {1} already exists. Please enter a new sheet number:", d.Number, d.Sheet)); string str = _ed.DoPrompt(pso).StringResult; _ed.WriteMessage(str + Environment.NewLine); if (str == "") { return null; } d.Sheet = str; } } catch (Exception ex){ _ed.WriteMessage(ex.ToString()); } return d; } catch { return null; } }
private void SelecteazaIncapere(out List<Incapere> incapere, Editor ed, Database acCurDb) { //int nrIncapere = 1; bool selectez = true; incapere = new List<Incapere>(); while (selectez) { PromptEntityResult select = ed.GetEntity("Selecteaza Incapere"); if (select.Status == PromptStatus.OK) { using (Transaction trans = acCurDb.TransactionManager.StartTransaction()) { Incapere camera = new Incapere(); DBObject obj = trans.GetObject(select.ObjectId, OpenMode.ForRead); if (obj.GetType() == typeof(Polyline)) { Polyline poly = (Polyline)obj; camera.SuprafataIncapere = poly.Area; PromptResult result; PromptStringOptions interogare; interogare = new PromptStringOptions("\nNr. Incapere: "); result = ed.GetString(interogare); camera.NrIncapere = result.StringResult; interogare = new PromptStringOptions("\nDestinatie Incapere: "); result = ed.GetString(interogare); camera.DestinatieIncapere = result.StringResult; incapere.Add(camera); } else { ed.WriteMessage("\nEntitatea selectata nu este o polilinie"); } trans.Commit(); } } else { selectez = false; } } }
public void KWandStringTest() { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; PromptStringOptions stropts = new PromptStringOptions("Enter a string you want to use as keyword"); PromptKeywordOptions kwopts = new PromptKeywordOptions("Enter a string you want to use as keyword"); stropts.AllowSpaces = false; PromptResult str = ed.GetString(stropts); kwopts.Keywords.Add(str.StringResult); kwopts.Keywords.Add("onemore"); kwopts.Message = "Enter the word that u just enterd to test if its a valid keyword or not"; PromptResult kw = ed.GetKeywords(kwopts); if(kw.Status == PromptStatus.OK) { ed.WriteMessage("You entered a valid keyword"); } else { ed.WriteMessage("You didn't enter a valid keyword: "+kw.Status.ToString()); } }
private PromptResult GetFloorNumber() { PromptStringOptions floorNumberOptions = new PromptStringOptions("Numer kondygnacji : "); floorNumberOptions.DefaultValue = "+1"; PromptResult stageNumber = editor.GetString(floorNumberOptions); return stageNumber; }
public static void Autograder() { const string systemVar_DwgCheck = "DWGCHECK"; Int16 dwgCheckPrevious = (Int16)Application.GetSystemVariable(systemVar_DwgCheck); Application.SetSystemVariable(systemVar_DwgCheck, 2); Document acDoc = Application.DocumentManager.MdiActiveDocument; PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter entire path to the folder containing all the submissions"); pStrOpts.AllowSpaces = true; PromptResult pStrRes = acDoc.Editor.GetString(pStrOpts); /*string[] folderpaths = Directory.GetDirectories(@"C:\Users\Vaibhav\Desktop\2D\2D Cad project\");*/ string[] folderpaths = Directory.GetDirectories(pStrRes.StringResult); int i = 0; foreach (string strFolderStudname in folderpaths) { i = i + 1; //define dictionary for storing data. Dictionary<string, string> dict1 = new Dictionary<string, string>(); dict1["auxinfodim"] = ""; dict1["blocksinlastlayout"] = ""; dict1["filename"] = i.ToString() + ": " + strFolderStudname; //writestuff(strwrite,i.ToString()+": "+strFolderStudname,1); Directory.SetCurrentDirectory(strFolderStudname + "/Submission attachment(s)/"); string[] filepaths = Directory.GetFiles(Directory.GetCurrentDirectory()); bool checkfilepass = false; bool checkfilepdf = false; bool checkfilepdfmulti = false; int checkblockexistance = 0; foreach (string strFileName in filepaths) { string newStr = strFileName.Substring(strFileName.Length - 3, 3); if (newStr.Equals("dwg")) { /*Application.DocumentManager.Open(strFileName,false); //the boolean is for read only Document acDoc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database;*/ Database acCurDb = new Database(false, true); acCurDb.ReadDwgFile(strFileName, FileOpenMode.OpenForReadAndAllShare, false, null); acCurDb.CloseInput(true); checkfilepass = true; Layout taborderlayout = null; int vp2 = 0; string[] Layerlist = { }; using (Transaction acTrans2 = acCurDb.TransactionManager.StartTransaction()) { DBDictionary lays = acTrans2.GetObject(acCurDb.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary; LayoutManager Lm = LayoutManager.Current; string currentLayout = Lm.CurrentLayout; int layoutnum = 0; string slayouts = "NA"; int tabordercheck = 0; int tabviewports = 0; bool tabcheck = false; Viewport taborderviewport=null; Viewport tempviewport = null; Layout firsttaborderlayout=null; Viewport firsttaporderviewport=null; int firsttabviewports = 0; foreach (DBDictionaryEntry de in lays) { layoutnum += 1; Layout layout = de.Value.GetObject(OpenMode.ForRead) as Layout; string layoutName = layout.LayoutName; if (layoutName != "Model") { if (slayouts.Equals("NA")) { slayouts = layoutName; } else { slayouts = layoutName + " , " + slayouts; } ObjectIdCollection vpIdCol = layout.GetViewports(); if (tabordercheck < layout.TabOrder) { tabordercheck = layout.TabOrder; taborderlayout = layout; tabcheck = true; } else { tabcheck = false; } int nviewports = -1; foreach (ObjectId vpId in vpIdCol) { Viewport vp = vpId.GetObject(OpenMode.ForRead) as Viewport; nviewports += 1; tempviewport = vp; if (tabcheck == true) { tabviewports = nviewports; } if (layout.TabOrder == 2) { firsttaborderlayout = layout; firsttaporderviewport = vp; firsttabviewports = nviewports; } // now check for dimensions inside the viewports int numdin = 0; LayerTable lyrtbl1 = acTrans2.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable; foreach (ObjectId acobj1 in lyrtbl1) { LayerTableRecord Lyrtblrec1 = acTrans2.GetObject(acobj1, OpenMode.ForRead) as LayerTableRecord; bool isfrozenlayer1 = false; foreach (ObjectId acobj3 in vp.GetFrozenLayers()) { if (Lyrtblrec1.Id == acobj3) { isfrozenlayer1 = true; } } if (isfrozenlayer1 == false) { BlockTable BlckTbl1 = acTrans2.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord acBlkTblRec1 = acTrans2.GetObject(BlckTbl1[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord; foreach (ObjectId BlockId1 in acBlkTblRec1) { try { Dimension Diment = acTrans2.GetObject(BlockId1, OpenMode.ForRead) as Dimension; if (Diment.Layer == Lyrtblrec1.Name) { numdin += 1; } } catch { //catch nothing - the exception is that its not a dim, all i care about is it being a dim } } } } if (nviewports > 0) { //writestuff(strwrite,layoutName + " The number of dimensions in viewport number "+ nviewports.ToString() + " are" + numdin.ToString(),0); //dict1.Add("auxinfodim", dict1["auxinfodim"] + layoutName + " The number of dimensions in viewport number " + nviewports.ToString() + " are" + numdin.ToString() + "/n"); dict1["auxinfodim"]=dict1["auxinfodim"] +" " +layoutName + ": The number of dimensions in viewport number " + nviewports.ToString() + " are " + numdin.ToString() + "\r\n"; } //end of this code block for the viewports } if (nviewports >= 2) { vp2 += 1; } } if (tabviewports >= 1 && layoutName.Equals(taborderlayout.LayoutName)) { taborderviewport = null; } if (tabviewports == 1 && layoutName.Equals(taborderlayout.LayoutName)) { taborderviewport = tempviewport; } } Lm.CurrentLayout = currentLayout; //writestuff("Number of layouts: " + (layoutnum - 1).ToString()); //dict1.Add("layoutnum", "Number of layouts: " + (layoutnum - 1).ToString()); dict1.Add("layoutnum","Number of layouts: " + (layoutnum - 1).ToString()); //writestuff("Names of layouts: " + slayouts); dict1.Add("layoutnames", "Names of layouts: " + slayouts); //writestuff("Number of layouts containing two or greater viewports" + vp2.ToString()); dict1.Add("Numviewports2", "Number of layouts containing two or greater viewports: " + vp2.ToString()); if (firsttabviewports != 1) { //writestuff("First layout scale: The First layout has more than one viewports"); dict1.Add("firstlayoutscale", "First layout scale: The First layout has more than one viewports"); } else { //writestuff("First layout scale: 1:" + (1 / firsttaporderviewport.AnnotationScale.Scale).ToString()); dict1.Add("firstlayoutscale", "First layout scale: 1:" + (1 / firsttaporderviewport.AnnotationScale.Scale).ToString()); } //writestuff("Name of last layout: " + taborderlayout.LayoutName); dict1.Add("lastlayoutname", "Name of last layout: " + taborderlayout.LayoutName); if (taborderviewport == null) { //writestuff("The last layout has more than one viewports. But this can also be a bug.please check manually"); dict1.Add("lastlayoutscale", "The last layout has more than one viewports. But this can also be a bug.please check manually"); //writestuff("As there are multiple viewports, the software will not check for presence of blocks"); //dict1.Add("blocksinlastlayout", "As there are multiple viewports, the software will not check for presence of blocks"); dict1["blocksinlastlayout"] = "As there are multiple viewports, the software will not check for presence of blocks"; } else { //writestuff("Last Layout scale: 1:" + (1 / taborderviewport.AnnotationScale.Scale).ToString()); dict1.Add("lastlayoutscale", "Last Layout scale: 1:" + (1 / taborderviewport.AnnotationScale.Scale).ToString()); // The following codeblock is for the black presence in the last layout. LayerTable lyrtbl = acTrans2.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable; foreach (ObjectId acobj in lyrtbl) { LayerTableRecord Lyrtblrec = acTrans2.GetObject(acobj, OpenMode.ForRead) as LayerTableRecord; bool isfrozenlayer = false; foreach (ObjectId acobj2 in taborderviewport.GetFrozenLayers()) { if (Lyrtblrec.Id == acobj2) { isfrozenlayer = true; } } if (isfrozenlayer==false) { BlockTable BlckTbl=acTrans2.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord acBlkTblRec=acTrans2.GetObject(BlckTbl[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord; foreach (ObjectId BlockId in acBlkTblRec) { if ((BlockId.ObjectClass.DxfName).Equals("INSERT")) { Entity ent = acTrans2.GetObject(BlockId, OpenMode.ForRead) as Entity; if (ent.Layer == Lyrtblrec.Name) { //writestuff("Block present in layer" + Lyrtblrec.Name+" in the last layout"); //dict1.Add("blocksinlastlayout", dict1["blocksinlastlayout"] + "Block present in layer" + Lyrtblrec.Name + " in the last layout"); dict1["blocksinlastlayout"]=dict1["blocksinlastlayout"] + " "+ "Block present in layer" + Lyrtblrec.Name + " in the last layout."+"\r\n"; } } } } } } } //starting a transcation for layers using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { LayerTable acLyrTbl; acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,OpenMode.ForRead) as LayerTable; string sLayerNames = "NA"; int number1 = 0; int uniquelayers = 0; foreach (ObjectId acObjId in acLyrTbl) { LayerTableRecord acLyrTblRec; acLyrTblRec = acTrans.GetObject(acObjId, OpenMode.ForRead) as LayerTableRecord; if (acLyrTblRec.Name.Equals("dimension") || acLyrTblRec.Name.Equals("center_line") || acLyrTblRec.Name.Equals("semester") || acLyrTblRec.Name.Equals("cuttingplane_line") || acLyrTblRec.Name.Equals("hidden_line") || acLyrTblRec.Name.Equals("Defpoints") || acLyrTblRec.Name.Equals("mview1") || acLyrTblRec.Name.Equals("0")) { //deprecated as of 9/20/2013. dont need this part } else { Layerlist = new string[Layerlist.Length + 1]; Layerlist[Layerlist.Length - 1] = acLyrTblRec.Name; uniquelayers = uniquelayers + 1; if (sLayerNames.Equals("NA")) { sLayerNames = acLyrTblRec.Name; } else { sLayerNames = acLyrTblRec.Name + " , " + sLayerNames; } } number1 = number1 + 1; } //writestuff("Total Number of Layers: " + number1.ToString() + "\n"); dict1.Add("layernum", "Total Number of Layers: " + number1.ToString() + "\n"); //writestuff("Total Number of User Defined layers: " + uniquelayers + "\n"); dict1.Add("userdefinedlayernum", "Total Number of User Defined layers: " + uniquelayers + "\n"); //writestuff("The User defined layers are:" + sLayerNames + "\n"); dict1.Add("userdefinedlayernames", "The User defined layers are:" + sLayerNames + "\n"); } //starting a new transaction for blocks using (Transaction acTrans3 = acCurDb.TransactionManager.StartTransaction()) { BlockTable BlckTbl; BlckTbl = acTrans3.GetObject(acCurDb.BlockTableId,OpenMode.ForRead) as BlockTable; BlockTableRecord acBlkTblRec = acTrans3.GetObject(BlckTbl[BlockTableRecord.ModelSpace],OpenMode.ForRead) as BlockTableRecord; foreach (ObjectId BlockId in acBlkTblRec) { if ((BlockId.ObjectClass.DxfName).Equals("INSERT")) { checkblockexistance += 1; } } if (checkblockexistance > 0) { //writestuff("There are " + checkblockexistance + " Blocks inserted in the model space"); dict1.Add("blocksexist", "There are " + checkblockexistance + " Blocks inserted in the model space"); } else { //writestuff("There are no blocks inserted in the modelspace"); dict1.Add("blocksexist","There are no blocks inserted in the modelspace"); } } //check bock existance in last layout using (Transaction acTrans7 = acCurDb.TransactionManager.StartTransaction()) { BlockTable bt = acTrans7.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; foreach (ObjectId objid in bt) { BlockTableRecord Btr = acTrans7.GetObject(objid, OpenMode.ForRead) as BlockTableRecord; if (Btr.IsLayout) { ObjectId lid = Btr.LayoutId; Layout lt = acTrans7.GetObject(lid, OpenMode.ForRead) as Layout; if (lt==taborderlayout) { foreach (ObjectId eid in Btr) { Entity ent; if ((eid.ObjectClass.DxfName).Equals("INSERT")) { Application.ShowAlertDialog("block present"); } ent = acTrans7.GetObject(eid, OpenMode.ForRead) as Entity; } } } } } /*acDoc.CloseAndDiscard();*/ } //if close if (newStr.Equals("pdf")) { if (checkfilepdf) { //there is more than one pdf file checkfilepdfmulti = true; break; } checkfilepdf = true; } } //foreach for the document finder close if (checkfilepass == false) { writestuff("No .dwg file could be found.Please check manually though and if the file exists, send bug report to [email protected]", dict1, pStrRes.StringResult); } else { if (checkfilepdf == false) { //writestuff("PDF:No PDF file can be found"); dict1.Add("pdfpresent", "PDF:No PDF file can be found"); writestuff("0", dict1, pStrRes.StringResult); } if (checkfilepdf == true && checkfilepdfmulti == true) { //writestuff("PDF:Multiple PDF files present"); dict1.Add("pdfpresent", "PDF:Multiple PDF files present"); writestuff("0", dict1,pStrRes.StringResult); } if (checkfilepdf == true && checkfilepdfmulti == false) { //writestuff("PDF: Only one(1) PDF file present"); dict1.Add("pdfpresent", "PDF: Only one(1) PDF file present"); writestuff("0", dict1, pStrRes.StringResult); } } //writestuff("\r\n"); //terminating space dict1.Clear(); } //foreach for the folders Application.SetSystemVariable(systemVar_DwgCheck, dwgCheckPrevious); Application.ShowAlertDialog("Program Execution Over. Please ceck your grade file.Any bugs must be reported to [email protected]"); }