/// <summary> /// TODO /// </summary> /// <param name="nat"></param> /// <param name="axis"></param> /// <returns></returns> private Vector3d GetTangent(Curve3d nat, Axis axis) { var vec = new Vector3d(); try { if (nat is LinearEntity3d || nat.IsClosed()) { vec = axis.ToVector(); } else if (nat.StartPoint == axis.Start || nat.EndPoint == axis.Start) { using (var curved = nat.GetClosestPointTo(axis.Start)) { vec = curved.GetDerivative(1).GetNormal() * axis.Length; } using (var curved2 = nat.GetClosestPointTo(axis.Start + vec)) { if (curved2.Point.IsEqualTo(axis.Start)) { vec = vec.Negate(); } } } } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); } return(vec); }
public void MailAgent_ExtendedDelivery() { // Make sure that we can queue and deliver several messages over an // extended period of time where the background thread will perform // multiple polls. string folder = Path.Combine(Path.GetTempPath(), "MailAgent"); using (var agent = new MailAgent(new NetworkBinding(Server), Account, Password, folder, TimeSpan.FromSeconds(1))) { MailMessage message; for (int i = 0; i < 10; i++) { message = new MailMessage("*****@*****.**", "*****@*****.**"); message.Subject = string.Format("Test Message #{0}", i); message.Body = "This is a test of the emergency broadcasting system.\r\nThis is only a test.\r\n"; agent.Enqueue(message); Thread.Sleep(2000); } Thread.Sleep(5000); // Wait 5 seconds to give the agent a chance to deliver the messages. } }
// POST: api/MailNotification public IHttpActionResult Post([FromBody] MailEntity entity) { try { var agent = new MailAgent( new MailConfig { SmtpServer = "*.com", Port = 25 }); CoerceEntity(entity); if (!agent.Send(entity)) { return(BadRequest()); } return(Ok()); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
/// <summary> /// TODO /// </summary> /// <param name="senderObj"></param> /// <param name="docBegClsEvtArgs"></param> private static void BeginDocClose(object senderObj, DocumentCollectionEventArgs docBegClsEvtArgs) { try { // Get the current document var acDocMan = Application.DocumentManager; var acDoc = acDocMan.MdiActiveDocument; if (acDoc == null) { return; } acDoc.ImpliedSelectionChanged -= Doc_ImpliedSelectionChanged; //RCLEADER acDoc.CommandWillStart -= RcLeader.rcLeader_CommandWillStart; acDoc.CommandEnded -= RcLeader.rcLeader_CommandEnded; acDoc.CommandCancelled -= RcLeader.rcLeader_CommandEnded; acDoc.CommandFailed -= RcLeader.rcLeader_CommandEnded; acDoc.Database.ObjectModified -= RcLeader.rcLeader_ObjectModified; //AUTOLAYER acDoc.CommandWillStart -= RcAutoLayer.autoLayer_CommandWillStart; acDoc.CommandEnded -= RcAutoLayer.autoLayer_CommandEnded; acDoc.CommandCancelled -= RcAutoLayer.autoLayer_CommandEnded; acDoc.CommandFailed -= RcAutoLayer.autoLayer_CommandEnded; } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); throw; } }
/// <summary> /// TODO /// </summary> /// <param name="loop"></param> /// <returns></returns> public static bool IsLargestLoop(this BoundaryLoop loop) { var length = loop.GetLength(); if (length == 0) { return(false); } try { foreach (var fLoop in loop.Face.Loops) { if (fLoop.IsEqualTo(loop)) { continue; } var fLength = fLoop.GetLength(); if (fLength > length) { return(false); } } return(true); } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); return(false); } }
/// <summary> /// TODO /// </summary> /// <param name="vtx"></param> /// <param name="owner"></param> /// <returns></returns> private List <EdgeExt> GetEdges(Vertex vtx, BoundaryLoop owner) { var eList = new List <EdgeExt>(); try { foreach (var edge in vtx.Edges) { var eInfo = new EdgeExt(edge, vtx, owner); if (eInfo.IsNull) { continue; } eList.Add(eInfo); } } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); } return(eList); }
public void DoStartServer() { var listener = new HttpListener(); listener.Prefixes.Add(uri); isStarted = true; listener.Start(); var context = listener.GetContext(); using (var reader = new StreamReader(context.Request.InputStream)) { var body = reader.ReadToEnd(); var notifyData = new NotifyData(); notifyData.Deserialize(body); if (notifyData.Type == NotifyType.Email) { var json = notifyData.Data.ToString(); var entity = JsonConvert.DeserializeObject <MailEntity>(json); var agent = new MailAgent(); agent.Send(entity); } } var output = context.Response.OutputStream; output.Flush(); output.Close(); }
public void Cmd_AutoLayer() { if (!LicensingAgent.Check()) { return; } var acCurDoc = Application.DocumentManager.MdiActiveDocument; _ = acCurDoc.Database; var acCurEd = acCurDoc.Editor; var enable = acCurEd.GetBool("\nSet AutoLayer variable: ", "On", "Off"); if (enable != null) { return; } try { SettingsUser.AutoLayerEnabled = enable.Value; } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); } }
/// <summary> /// TODO /// </summary> internal static void AddDocEvents() { try { // Get the current document var acDocMan = Application.DocumentManager; var acDoc = acDocMan.MdiActiveDocument; //Doc Manager Handlers acDocMan.DocumentToBeDeactivated += BeginDocClose; acDocMan.DocumentActivated += DocActivated; //Doc Handlers acDoc.ImpliedSelectionChanged += Doc_ImpliedSelectionChanged; //RCLEADER acDoc.CommandWillStart += RcLeader.rcLeader_CommandWillStart; acDoc.CommandEnded += RcLeader.rcLeader_CommandEnded; acDoc.CommandCancelled += RcLeader.rcLeader_CommandEnded; acDoc.CommandFailed += RcLeader.rcLeader_CommandEnded; acDoc.Database.ObjectModified += RcLeader.rcLeader_ObjectModified; //AUTOLAYER acDoc.CommandWillStart += RcAutoLayer.autoLayer_CommandWillStart; acDoc.CommandEnded += RcAutoLayer.autoLayer_CommandEnded; acDoc.CommandCancelled += RcAutoLayer.autoLayer_CommandEnded; acDoc.CommandFailed += RcAutoLayer.autoLayer_CommandEnded; } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); throw; } }
/// <summary> /// TODO /// </summary> /// <param name="acSol"></param> private void GetLayMatrix(Solid3d acSol) { try { var bestVerts = GetBestVerts(acSol); if (bestVerts == null) { LayMatrix = GetAbstractMatrix(acSol); } else if (bestVerts.Count == 0) { LayMatrix = new Matrix3d(); } else { LayMatrix = RefineLayMatrix(bestVerts); } } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); } }
/// <summary> /// TODO /// </summary> /// <param name="edge"></param> /// <param name="vtx"></param> /// <param name="owner"></param> public EdgeExt(Edge edge, Vertex vtx, BoundaryLoop owner) { OnLoop = edge.IsOnLoop(owner); try { using (var curve = edge.Curve) { if (!(curve is ExternalCurve3d)) { return; } using (var extCurve = curve as ExternalCurve3d) { using (var natCurve = extCurve.NativeCurve) { IsClosed = natCurve.IsClosed(); if (IsClosed) { using (var inv = natCurve.GetInterval()) { Eaxis = new Axis(natCurve.StartPoint, natCurve.EvaluatePoint(inv.LowerBound + inv.UpperBound) / 2); } } else { if (natCurve.StartPoint.IsEqualTo(vtx.Point)) { Eaxis = new Axis(natCurve.EndPoint, natCurve.StartPoint); } else { Eaxis = new Axis(natCurve.StartPoint, natCurve.EndPoint); } } IsLinear = natCurve is LinearEntity3d; if (IsLinear) { Normal = natCurve.GetNormal(); } Tangent = GetTangent(natCurve, Eaxis); Length = Eaxis.Length; } } } } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); } }
public ActionResult Register([Bind(Exclude = "IsEmailVerified,ActivationCode")] User registatingUser) { bool status = false; string message = ""; if (ModelState.IsValid) { //register the user if the name or the email doesn't exist if (!registatingUser.IsEmailOrNameExist(ref message)) { #region Generate Activation Code registatingUser.ActivationCode = Guid.NewGuid(); #endregion #region Password Hashing registatingUser.Password = Crypto.GetHash(registatingUser.Password); registatingUser.ConfirmPassword = registatingUser.Password; #endregion registatingUser.IsEmailVerified = false; #region Save to the Database using (RunetSoftDbEntities dbContext = new RunetSoftDbEntities()) { try { dbContext.tblUsers.Add(registatingUser); dbContext.SaveChanges(); } catch (DbEntityValidationException ex) { status = true; ViewBag.Message = ex.Message; return(View(registatingUser)); } //send email to the user MailAgent.SendVerificationLinkEmail(registatingUser.Email, registatingUser.ActivationCode.ToString()); message = "Регистрация прошла успешно. Для дальнейшего использования аккаунта необходимо воспользоваться ссылкой, " + " отправленной на ваш e-mail:" + registatingUser.Email; status = true; } #endregion } } else { message = "Неверный запрос"; } ViewBag.Message = message; ViewBag.Status = status; return(View(registatingUser)); }
/// <summary> /// TODO /// </summary> /// <param name="transMat"></param> public void TransformBy(Matrix3d transMat) { try { Start.TransformBy(transMat); End.TransformBy(transMat); } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); } }
public void MailAgent_Send_Success() { var entity = new MailEntity(); entity.From = "tester@***.com"; entity.To.Add("tester@***.com"); entity.Subject = "This is test subject"; entity.Body = "This is test body"; entity.Attachments.Add(MailAttachment.FromString("1.txt", "this is attachment data")); var agent = new MailAgent(); agent.Send(entity); }
/// <summary> /// TODO /// </summary> /// <param name="layerName"></param> /// <param name="acColor"></param> private void SetLayer(string layerName, Color acColor) { try { if (!LicensingAgent.Check()) { return; } var acCurDoc = Application.DocumentManager.MdiActiveDocument; if (acCurDoc == null) { return; } var acCurDb = acCurDoc.Database; var acCurEd = acCurDoc.Editor; using (acCurDoc.LockDocument()) { Utils.SetFocusToDwgView(); var objIds = acCurEd.GetAllSelection(false); using (var acTrans = acCurDb.TransactionManager.StartTransaction()) { acCurDb.AddLayer(layerName, acColor, SettingsUser.RcVisibleLT, acTrans); foreach (var obj in objIds) { var acEnt = acTrans.GetObject(obj, OpenMode.ForWrite) as Entity; if (acEnt == null) { continue; } acEnt.Layer = layerName; acEnt.Color = Color.FromColorIndex(ColorMethod.ByLayer, 256); } acTrans.Commit(); } } } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); } }
public void Cmd_EmptyDwg() { if (!LicensingAgent.Check()) { return; } var acCurDoc = Application.DocumentManager.MdiActiveDocument; var acCurDb = acCurDoc.Database; var newLayoutName = "BlankLayout"; LayoutManager.Current.CurrentLayout = "Model"; using (var acTrans = acCurDb.TransactionManager.StartTransaction()) { try { LayoutManager.Current.CreateLayout(newLayoutName); } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); } var layoutDict = acTrans.GetObject(acCurDb.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary; if (layoutDict != null) { foreach (var de in layoutDict) { var layoutName = de.Key; if (layoutName != "Model" && layoutName != newLayoutName) { LayoutManager.Current.DeleteLayout(layoutName); } } } acTrans.Commit(); } acCurDb.PurgeAll(true); }
public ActionResult RestorePassword(string email) { //if the user is already authenticated - redirect to the home page if (Request.IsAuthenticated) { return(RedirectToAction("Index", "Home")); } string message = null; bool status = false; //checking if the user has specified the email if (!string.IsNullOrEmpty(email)) { using (RunetSoftDbEntities dataContext = new RunetSoftDbEntities()) { var user = dataContext.tblUsers.Where(usr => usr.Email == email).FirstOrDefault(); //checking if the user exists in the database if (user != null) { //sending the link to user's email which will redirect to the OnPasswordRestoring view //and the user could change the pass there. If the Guid mathes of course user.ActivationCode = Guid.NewGuid(); dataContext.Configuration.ValidateOnSaveEnabled = false; dataContext.SaveChanges(); MailAgent.SendVerificationLinkEmail(user.Email, user.ActivationCode.ToString(), true); message = "На вашу почту отправлена ссылка для восстановления пароля."; status = true; } else { message = "Пользователь с таким почтовым адресом не зарегистрирован."; } } } else { message = "Укажите почтовый адрес, для восстановления пароля."; } ViewBag.Status = status; ViewBag.Message = message; return(View()); }
/// <summary> /// Todo /// </summary> /// <param name="acEdge"></param> /// <returns></returns> public static double GetLength(this Edge acEdge) { try { using (var acCurve = acEdge.Curve) { using (var intv = acCurve.GetInterval()) { return(acCurve.GetLength(intv.LowerBound, intv.UpperBound, SettingsUser.TolPoint)); } } } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); return(0); } }
private static void DocActivated(object senderObj, DocumentCollectionEventArgs docActEvent) { try { // Get the current document var acDocMan = Application.DocumentManager; var acDoc = acDocMan.MdiActiveDocument; if (acDoc == null) { return; } //Notebook Handlers if (SettingsInternal.EnNotePal) { RcPaletteNotebook.UpdNotePal(); } acDoc.ImpliedSelectionChanged += Doc_ImpliedSelectionChanged; //RCLEADER acDoc.CommandWillStart += RcLeader.rcLeader_CommandWillStart; acDoc.CommandEnded += RcLeader.rcLeader_CommandEnded; acDoc.CommandCancelled += RcLeader.rcLeader_CommandEnded; acDoc.CommandFailed += RcLeader.rcLeader_CommandEnded; acDoc.Database.ObjectModified += RcLeader.rcLeader_ObjectModified; //AUTOLAYER acDoc.CommandWillStart += RcAutoLayer.autoLayer_CommandWillStart; acDoc.CommandEnded += RcAutoLayer.autoLayer_CommandEnded; acDoc.CommandCancelled += RcAutoLayer.autoLayer_CommandEnded; acDoc.CommandFailed += RcAutoLayer.autoLayer_CommandEnded; } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); throw; } }
/// <summary> /// Todo /// </summary> /// <param name="loop"></param> /// <returns></returns> public static double GetLength(this BoundaryLoop loop) { try { double length = 0; foreach (var edge in loop.Edges) { length += edge.GetLength(); } return(length); } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); return(0); } }
public bool Start3DsMax() { var pFinder = new PathFinder(); var _3DsPath = pFinder.GetAppPath("3ds Max 2018"); var startInfo = new ProcessStartInfo(_3DsPath + "3dsmax.exe"); startInfo.WindowStyle = ProcessWindowStyle.Maximized; startInfo.Arguments = "C:\\Drawing1.dwg"; try { _ = Process.Start(startInfo); return(true); } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); return(false); } }
public ActionResult Send([Required][FromBody] SendMailModel model) { EmailTemplate template = _ctx.emailTemplates.Where(t => t.Id == model.bodyTemplate).FirstOrDefault(); if (null == template) { throw new ApplicationException($"Email template with id {model.bodyTemplate} was not found"); } MailAgent agent = new MailAgent(_logger); DateTime utcNow = DateTime.UtcNow; EmailMessage m = new EmailMessage { clientMsgId = model.clientMsgId, from = model.from, to = model.to, template = template, subjectModel = model.subjectModel?.ToString(), bodyModel = model.bodyModel?.ToString(), createdAt = utcNow, expiration = model.expiration //lastAttemptAt = utcNow }; //m.resultMessage = agent.Send(m); _ctx.emailMessages.Add(m); _ctx.SaveChanges(); return(Ok(new EmailStatus { messageId = m.Id, clientMsgId = model.clientMsgId, status = m.resultMessage })); }
/// <summary> /// TODO /// </summary> /// <param name="acSol"></param> /// <returns></returns> private Matrix3d GetAbstractMatrix(Solid3d acSol) { var bestMatrix = new Matrix3d(); using (var acBrep = acSol.GetBrep()) { try { if (acBrep.Faces.Any()) { double largest = 0; foreach (var acFace in acBrep.Faces) { var fArea = acFace.GetArea(); if (fArea.IsEqualArea(largest) || fArea < largest) { continue; } largest = fArea; bestMatrix = acFace.GetLayMatrix(); } } } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); return(bestMatrix); } } return(bestMatrix); }
/// <summary> /// TODO /// </summary> private void PopulatePal() { var acCurDoc = Application.DocumentManager.MdiActiveDocument; if (acCurDoc == null) { return; } var acCurDb = acCurDoc.Database; const int imageColumn = 0; const int buttonColumn = 1; const int barOffset = 10; const int buttonOffset = 1; const int buttonHeight = 25; var backColor = Colors.GetCadBackColor(); var foreColor = Colors.GetCadForeColor(); var textColor = Colors.GetCadTextColor(); var rowCounter = 0; try { using (acCurDoc.LockDocument()) { _palPanel.SuspendLayout(); _palPanel.BackColor = backColor; _palPanel.Controls.Clear(); _palPanel.AutoScroll = false; #region Table Layout var palLayout = new TableLayoutPanel { AutoScroll = true, AutoSizeMode = AutoSizeMode.GrowAndShrink, BackColor = Colors.GetCadBackColor(), ForeColor = Colors.GetCadForeColor(), ColumnCount = 3, Dock = DockStyle.Fill }; palLayout.MouseEnter += (s, e) => palLayout.Focus(); palLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 25F)); palLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F)); palLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 5F)); #endregion using (var acTrans = acCurDb.TransactionManager.StartTransaction()) { var layerGroups = acCurDb.GetLayerTableRecord(acTrans, 0) .GroupBy(layer => layer.Name.Split(SettingsUser.LayerDelimiter)[0]) .OrderBy(layer => layer.Key); foreach (var group in layerGroups) { palLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, buttonHeight + 5)); if (group.Count() > 1) { var spButton = new SplitButton { ShowSplit = true, BackColor = foreColor, ForeColor = textColor, Dock = DockStyle.Fill, Height = buttonHeight, ContextMenuStrip = new ContextMenuStrip(), FlatStyle = FlatStyle.Flat }; spButton.Click += Button_Click; spButton.FlatAppearance.BorderColor = Colors.GetCadBorderColor(); spButton.FlatAppearance.BorderSize = 1; spButton.ContextMenuStrip.BackColor = foreColor; spButton.ContextMenuStrip.ForeColor = textColor; spButton.ContextMenuStrip.ShowImageMargin = false; spButton.ContextMenuStrip.ShowCheckMargin = false; Color spColor = null; var firstParse = true; foreach (var layer in group) { if (firstParse) { spButton.Text = layer.Name; spColor = layer.Color; firstParse = false; } var tsButton = new ToolStripButton(layer.Name, GetLayerImage(layer.Color), ContextItem_Click) { ImageAlign = TopLeft, TextAlign = BottomLeft, BackColor = foreColor, ForeColor = textColor }; spButton.ContextMenuStrip.Items.Add(tsButton); } var picBox = new PictureBox { Height = buttonHeight, Image = GetLayerImage(spColor), Dock = DockStyle.Fill }; palLayout.Controls.Add(spButton, buttonColumn, rowCounter); palLayout.Controls.Add(picBox, imageColumn, rowCounter); rowCounter++; } else { var layer = group.First(); var button = new Button { Text = layer.Name, BackColor = foreColor, ForeColor = textColor, Dock = DockStyle.Fill, Height = buttonHeight, FlatStyle = FlatStyle.Flat }; button.Click += Button_Click; button.FlatAppearance.BorderColor = Colors.GetCadBorderColor(); button.FlatAppearance.BorderSize = 1; var picBox = new PictureBox { Height = buttonHeight, Image = GetLayerImage(layer.Color), Dock = DockStyle.Fill }; palLayout.Controls.Add(button, buttonColumn, rowCounter); palLayout.Controls.Add(picBox, imageColumn, rowCounter); rowCounter++; } } //Add a blank label to the final row to keep from having a giant row at the bottom var blankLabel = new Label { Height = buttonHeight }; palLayout.Controls.Add(blankLabel, buttonColumn, rowCounter + 1); palLayout.RowCount++; acTrans.Commit(); } palLayout.AutoScroll = true; palLayout.AutoSize = true; palLayout.Refresh(); if (palLayout.VerticalScroll.Visible) { palLayout.ColumnStyles[2].SizeType = SizeType.Absolute; palLayout.ColumnStyles[2].Width = barOffset; } else { palLayout.ColumnStyles[2].SizeType = SizeType.Absolute; palLayout.ColumnStyles[2].Width = buttonOffset; } palLayout.Refresh(); var bLayout = new TableLayoutPanel { BackColor = Colors.GetCadBackColor(), ForeColor = Colors.GetCadForeColor(), ColumnCount = 2, Height = 30, Dock = DockStyle.Bottom }; bLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 80F)); bLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 20F)); bLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 30f)); var loadButton = new Button(); loadButton.Click += Load_Click; loadButton.Text = "Load From Dwg"; loadButton.BackColor = foreColor; loadButton.ForeColor = textColor; loadButton.Dock = DockStyle.Fill; loadButton.Height = 30; loadButton.FlatStyle = FlatStyle.Flat; loadButton.FlatAppearance.BorderColor = Colors.GetCadBorderColor(); loadButton.FlatAppearance.BorderSize = 1; var updButton = new Button(); updButton.Click += Update_Click; updButton.Image = Properties.Resources.RcUpdate16X16__I_; updButton.ImageAlign = MiddleCenter; updButton.BackColor = foreColor; updButton.ForeColor = textColor; updButton.Dock = DockStyle.Fill; loadButton.Height = 30; updButton.FlatStyle = FlatStyle.Flat; updButton.FlatAppearance.BorderColor = Colors.GetCadBorderColor(); updButton.FlatAppearance.BorderSize = 1; bLayout.Controls.Add(loadButton, 0, 0); bLayout.Controls.Add(updButton, 1, 0); _palPanel.Controls.Add(palLayout); _palPanel.Controls.Add(bLayout); _palPanel.ResumeLayout(); } } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); } }
public void Cmd_CrossJoint() { if (!LicensingAgent.Check()) { return; } var acCurDoc = Application.DocumentManager.MdiActiveDocument; var acCurDb = acCurDoc.Database; var acCurEd = acCurDoc.Editor; var cutId = acCurEd.GetFilteredSelection(Enums.DxfNameEnum._3Dsolid, true, null, "\nSelect 3D Solid to cut: "); if (cutId.Length <= 0) { return; } var cutterId = acCurEd.GetFilteredSelection(Enums.DxfNameEnum._3Dsolid, true, null, "\nSelect 3D Solid use as cutter: "); if (cutterId.Length <= 0) { return; } using (var acTrans = acCurDb.TransactionManager.StartTransaction()) { var objToCut = acTrans.GetObject(cutId[0], OpenMode.ForWrite) as Solid3d; var objCutter = acTrans.GetObject(cutterId[0], OpenMode.ForWrite) as Solid3d; if (objToCut != null && objCutter != null) { var toCutClone = objToCut.Clone() as Solid3d; var cutterClone = objCutter.Clone() as Solid3d; if (cutterClone != null && toCutClone != null) { toCutClone.BooleanOperation(BooleanOperationType.BoolIntersect, cutterClone); acCurDb.AppendEntity(toCutClone, acTrans); var gExt = toCutClone.GeometricExtents; var gCen = gExt.MinPoint.GetMidPoint(gExt.MaxPoint); var gPlane = new Plane(gCen, acCurEd.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis); try { var slicedObj = toCutClone.Slice(gPlane, true); acCurDb.AppendEntity(slicedObj, acTrans); objToCut.BooleanOperation(BooleanOperationType.BoolSubtract, toCutClone); objCutter.BooleanOperation(BooleanOperationType.BoolSubtract, slicedObj); } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); throw; } } } acTrans.Commit(); } }
/// <summary> /// Method to update mleaders with substitution text /// </summary> /// <param name="acCurDoc"></param> private static void UpdateLeader(Document acCurDoc) { var acCUrDb = acCurDoc.Database; var acCurEd = acCurDoc.Editor; using (var acTrans = acCUrDb.TransactionManager.StartTransaction()) { try { if (_curLeaderId == ObjectId.Null) { return; } var mLeader = acTrans.GetObject(_curLeaderId, OpenMode.ForWrite) as MLeader; if (mLeader == null) { acTrans.Abort(); return; } var obj = mLeader.GetObjectUnderArrow(); if (obj != ObjectId.Null) { var ent = acTrans.GetObject(obj, OpenMode.ForWrite) as Entity; if (mLeader.ContentType == ContentType.MTextContent) { var mt = new MText(); mt.SetDatabaseDefaults(); //TODO let user set the type of contents mt.Contents = ent.GetPartName(); mLeader.MText = mt; mt.Dispose(); } else if (mLeader.ContentType == ContentType.BlockContent) { var blkTblRef = acTrans.GetObject(mLeader.BlockContentId, OpenMode.ForWrite) as BlockTableRecord; blkTblRef?.UpdateMleaderBlockSubst(mLeader, ent, acCurDoc, acCurEd); } } else { acTrans.Abort(); return; } } catch (Exception ex) { acCurEd.WriteMessage("\n" + ex.Message); MailAgent.Report(ex.Message); acTrans.Abort(); return; } acTrans.Commit(); } }
/// <summary> /// Method to prompt user for a layout to import the layout template of /// </summary> /// <returns></returns> private List <ImportedViewport> ImportViewports(Editor acCurEd, ref double layoutHeight, ref double layoutWidth) { var viewports = new List <ImportedViewport>(); try { using (var exDb = acCurEd.GetTemplate(ref SettingsUser.ViewTemplatePath)) { var exLayouts = new List <Layout>(); using (var exTrans = exDb.TransactionManager.StartTransaction()) { var dbDict = (DBDictionary)exTrans.GetObject(exDb.LayoutDictionaryId, OpenMode.ForRead); foreach (var curEntry in dbDict) { var exLayout = (Layout)exTrans.GetObject(curEntry.Value, OpenMode.ForRead); exLayouts.Add(exLayout); } var pKeyOpts = new PromptKeywordOptions(string.Empty) { Message = "\nSelect layout to copy viewports from: ", AllowArbitraryInput = true }; var iterator = 'A'; var keyDict = new Dictionary <string, string>(); foreach (var layout in exLayouts) { if (layout.LayoutName != "Model") { keyDict.Add(layout.LayoutName, iterator.ToString()); pKeyOpts.Keywords.Add(iterator.ToString(), iterator.ToString(), iterator + ": " + layout.LayoutName.ToLower()); iterator++; } } pKeyOpts.AllowNone = false; var pKeyRes = acCurEd.GetKeywords(pKeyOpts); if (pKeyRes.Status != PromptStatus.OK) { return(viewports); } var returnIterator = pKeyRes.StringResult; ObjectId id; var layoutName = string.Empty; foreach (var entry in keyDict) { if (entry.Value == returnIterator) { layoutName = entry.Key; break; } } if (dbDict.Contains(layoutName)) { id = dbDict.GetAt(layoutName); } else { acCurEd.WriteMessage("\nLayout contains no viewports."); return(viewports); } var chosenLayout = exTrans.GetObject(id, OpenMode.ForRead) as Layout; if (chosenLayout == null) { return(viewports); } var laySize = GetLayoutSize(chosenLayout); layoutHeight = laySize.Height; layoutWidth = laySize.Width; //Get viewports from chosen layout using ( var blkTblRec = exTrans.GetObject(chosenLayout.BlockTableRecordId, OpenMode.ForRead) as BlockTableRecord ) { if (blkTblRec != null) { foreach (var objId in blkTblRec) { if (objId == exDb.PaperSpaceVportId) { continue; } var exView = exTrans.GetObject(objId, OpenMode.ForRead) as Viewport; if (exView != null && !exView.IsErased && exView.Visible) { var vHeight = exView.Height; var vWidth = exView.Width; var vCen = exView.CenterPoint; viewports.Add(new ImportedViewport(vHeight, vWidth, vCen, exView.ViewDirection)); } } } } exTrans.Commit(); } } } catch (System.Exception e) { acCurEd.WriteMessage(e.Message); MailAgent.Report(e.Message); } return(viewports); }
public void Cmd_GenViews() { if (!LicensingAgent.Check()) { return; } var acCurDoc = Application.DocumentManager.MdiActiveDocument; var acCurDb = acCurDoc.Database; var acCurEd = acCurDoc.Editor; var modelView = acCurEd.GetCurrentView().Clone() as ViewTableRecord; var uSelOpts = new PromptSelectionOptions { MessageForAdding = "\nSelect objects to use in view creation: " }; var userSelection = acCurEd.GetSelection(uSelOpts); if (userSelection.Status != PromptStatus.OK) { return; } using (var acTrans = acCurDb.TransactionManager.StartTransaction()) { var boundBox = acTrans.GetBoundingBox(userSelection.Value.GetObjectIds(), acCurDb); //Get all Layouts in the Drawing var layoutList = new List <Layout>(); var dbDict = (DBDictionary)acTrans.GetObject(acCurDb.LayoutDictionaryId, OpenMode.ForRead); foreach (var curEntry in dbDict) { var layout = (Layout)acTrans.GetObject(curEntry.Value, OpenMode.ForRead); if (layout != null) { layoutList.Add(layout); } } var pKeyOpts = new PromptKeywordOptions(string.Empty) { Message = "\nWhich layout would you like to create views in?", AllowArbitraryInput = true }; var iterator = 'A'; var keyDict = new Dictionary <string, string>(); foreach (var layout in layoutList) { if (layout.LayoutName != "Model") { keyDict.Add(layout.LayoutName, iterator.ToString()); pKeyOpts.Keywords.Add(iterator.ToString(), iterator.ToString(), iterator + ": " + layout.LayoutName.ToLower()); iterator++; } } pKeyOpts.AllowNone = false; var pKeyRes = acCurEd.GetKeywords(pKeyOpts); if (pKeyRes.Status != PromptStatus.OK) { return; } var returnIterator = pKeyRes.StringResult; ObjectId id; var layoutName = string.Empty; foreach (var entry in keyDict) { if (entry.Value == returnIterator) { layoutName = entry.Key; break; } } if (dbDict.Contains(layoutName)) { id = dbDict.GetAt(layoutName); } else { acCurEd.WriteMessage("\nLayout not found. Cannot continue."); acTrans.Abort(); return; } var chosenLayout = acTrans.GetObject(id, OpenMode.ForRead) as Layout; if (chosenLayout == null) { return; } // Reference the Layout Manager var acLayoutMgr = LayoutManager.Current; // Set the layout current if it is not already if (chosenLayout.TabSelected == false) { acLayoutMgr.CurrentLayout = chosenLayout.LayoutName; } acCurEd.SwitchToPaperSpace(); var layOutSize = GetLayoutSize(chosenLayout); var importSize = new LayoutSize(0, 0); var iPorts = ImportViewports(acCurEd, ref importSize.Height, ref importSize.Width); var vStyles = acTrans.GetObject(acCurDb.VisualStyleDictionaryId, OpenMode.ForRead) as DBDictionary; if (iPorts.Count > 0) { foreach (var iPort in iPorts) { var ht = CalcUnit.GetProportion(iPort.VHeight, importSize.Height, layOutSize.Height); var wd = CalcUnit.GetProportion(iPort.VWidth, importSize.Width, layOutSize.Width); if (ht > layOutSize.Height || wd > layOutSize.Width) { continue; } var vPort = new Viewport { Height = ht, Width = wd }; var importPt = iPort.InsertPoint; var xProp = CalcUnit.GetProportion(importPt.X, importSize.Width, layOutSize.Width); var yProp = CalcUnit.GetProportion(importPt.Y, importSize.Height, layOutSize.Height); vPort.CenterPoint = new Point3d(xProp, yProp, 0); acCurDb.AppendEntity(vPort, acTrans); vPort.ViewDirection = iPort.ViewDirection; ZoomViewport(acCurDb, vPort, boundBox); //TODO find closest scale to zoom //TODO allow user to set these if (vStyles != null) { vPort.SetShadePlot(ShadePlotType.Hidden, vStyles.GetAt("Hidden")); } // Enable the viewport vPort.Visible = true; vPort.On = true; vPort.UpdateDisplay(); } } boundBox.Dispose(); LayoutManager.Current.CurrentLayout = "Model"; using (var view = acCurEd.GetCurrentView()) { view.CopyFrom(modelView); acCurEd.SetCurrentView(view); } try { Thread.Sleep(100); LayoutManager.Current.CurrentLayout = chosenLayout.LayoutName; } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); } if (modelView != null) { modelView.Dispose(); } acTrans.Commit(); } }
/// <summary> /// TODO /// </summary> /// <param name="acSol"></param> /// <returns></returns> private List <VertExt> GetBestVerts(Solid3d acSol) { var vList = new List <VertExt>(); using (var acBrep = new Brep(acSol)) { if (acBrep.IsNull) { return(vList); } if (!acBrep.IsNull) { var y = 0.0; try { foreach (var face in acBrep.Faces) { FaceCount++; var fArea = 0.0; if (SubId.Type == SubentityType.Face && SubId == face.SubentityPath.SubentId) { fArea = face.GetArea(); SubArea = fArea.RoundArea(); SubPerimeter = face.GetPerimeterLength().RoundToTolerance(); } using (var surface = face.Surface as ExternalBoundedSurface) { if (!surface.IsPlane) { if (!surface.IsCylinder) { Has3DFaces = true; } HasNonFlatFaces = true; continue; } } if (fArea == 0.0) { fArea = face.GetArea(); } var x = fArea; try { foreach (var acLoop in face.Loops) { var lType = acLoop.GetLoopType(); if (lType == LoopKit.Interior) { HasHoles = true; continue; } if (lType != LoopKit.Error) { if (lType == LoopKit.RightAngle) { x *= 1.5; } if (!x.IsEqualArea(y)) { if (x < y) { continue; } vList.Clear(); y = x; MaxArea = x.RoundArea(); MaxPerimeter = face.GetPerimeterLength().RoundToTolerance(); } try { foreach (var vtx in acLoop.Vertices) { vList.Add(new VertExt(vtx, acLoop)); if (vList.Count > 1000) { break; } } } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); } } } } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); } } } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); } } else { if (SubId.Type == SubentityType.Edge) { try { foreach (var acEdge in acBrep.Edges) { var subentityPath = acEdge.SubentityPath; if (subentityPath.SubentId == SubId) { SubPerimeter = acEdge.GetLength().RoundToTolerance(); break; } } } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); } } } return(MaxArea != 0.0 ? vList : null); } }
/// <summary> /// TODO /// </summary> /// <param name="acEdge"></param> /// <param name="startPt"></param> /// <returns></returns> public static Vector3d GetVectorFrom(this Edge acEdge, Point3d startPt) { Vector3d vectorTo; try { using (var acCurve = acEdge.Curve) { if (acCurve is ExternalCurve3d) { using (var exCurve = acCurve as ExternalCurve3d) { using (var natCurve = exCurve.NativeCurve) { if (!(natCurve is LinearEntity3d)) { if (!natCurve.IsClosed()) { if (natCurve.StartPoint.DistanceTo(startPt).IsGreaterThanTol()) { var endPt = natCurve.EndPoint; if (endPt.DistanceTo(startPt).IsGreaterThanTol()) { return(new Vector3d()); } } using (var pCurve = natCurve.GetClosestPointTo(startPt)) { var deriv = pCurve.GetDerivative(1); using (var pDeriv = natCurve.GetClosestPointTo(startPt + deriv)) { if (pDeriv.Point.IsEqualTo(startPt)) { deriv = deriv.Negate(); } } vectorTo = deriv; } } else { vectorTo = new Vector3d(); } } else if (natCurve.StartPoint.DistanceTo(startPt).IsGreaterThanTol()) { vectorTo = startPt.GetVectorTo(natCurve.EndPoint); } else if (natCurve.EndPoint.DistanceTo(startPt).IsGreaterThanTol()) { vectorTo = startPt.GetVectorTo(natCurve.StartPoint); } else { vectorTo = new Vector3d(); } } } } else { vectorTo = new Vector3d(); } } } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); vectorTo = new Vector3d(); } return(vectorTo); }