Пример #1
0
        public static void ListTextStyles(UIDocument uiDoc)
        {
            Document  currentDoc = uiDoc.Document;
            Selection sel        = uiDoc.Selection;
            XYZ       BasePt     = sel.PickPoint();

            FilteredElementCollector TextCollector = new FilteredElementCollector(currentDoc);
            List <ElementId>         Notes         = TextCollector.OfCategory(BuiltInCategory.OST_TextNotes).ToElementIds().ToList();

            int adjustment = 10;
            Dictionary <string, TextNote> TextNotes = new Dictionary <string, TextNote>();

            for (int i = 0; i < Notes.Count(); i++)
            {
                TextNote tn = currentDoc.GetElement(Notes[i]) as TextNote;
                if (!TextNotes.Keys.Contains(tn.TextNoteType.Name))
                {
                    TextNotes.Add(tn.TextNoteType.Name, tn);
                }
            }
            List <string> StyleName = TextNotes.Keys.ToList();

            StyleName.Sort();
            for (int i = 0; i < StyleName.Count(); i++)
            {
                XYZ      TextPoint = new XYZ(BasePt.X, (BasePt.Y - (adjustment * i)), 0);
                TextNote txNote    = TextNote.Create(currentDoc, uiDoc.ActiveView.Id, TextPoint, StyleName[i], TextNotes[StyleName[i]].GetTypeId());
            }
        }
        public void PlaceTextNotesAtNodes()
        {
            using (Transaction t = new Transaction(doc))
            {
                t.Start("Create TextNotes");
                foreach (Node node in Model.AllNodes)
                {
                    XYZ location = null;
                    if (node.NextCon != null)
                    {
                        location = node.NextCon.Origin;
                    }
                    else if (node.NextLoc != null)
                    {
                        location = node.NextLoc;
                    }
                    else if (node.PreviousCon != null)
                    {
                        location = node.PreviousCon.Origin;
                    }
                    else if (node.PreviousLoc != null)
                    {
                        location = node.PreviousLoc;
                    }

                    TextNote.Create(doc, doc.ActiveView.Id, location, node.Number.ToString(), new ElementId(361));
                }
                t.Commit();
            }
        }
Пример #3
0
        public void CreateTextNote(Document doc, List <Reference> references, Selection sel)
        {
            var             listtextnote = GetText(doc, references);
            var             converttext  = (from x in listtextnote select x.Text).ToList();
            var             text         = string.Join("", converttext.ToArray());
            ElementId       elementId    = listtextnote.First().TextNoteType.Id;
            XYZ             point        = sel.PickPoint();
            TextNoteOptions options      = new TextNoteOptions();

            options.TypeId = elementId;
            options.HorizontalAlignment = HorizontalTextAlignment.Left;
            double noteWidth = 0.2;
            double minWidth  = TextNote.GetMinimumAllowedWidth(doc, elementId);
            double maxWidth  = TextNote.GetMaximumAllowedWidth(doc, elementId);

            if (noteWidth < minWidth)
            {
                noteWidth = minWidth;
            }
            else if (noteWidth > maxWidth)
            {
                noteWidth = maxWidth;
            }
            using (Transaction tran = new Transaction(doc, "Create Text"))
            {
                tran.Start();
                TextNote textNote = TextNote.Create(doc, doc.ActiveView.Id, point, noteWidth, text, options);
                tran.Commit();
            }
        }
Пример #4
0
        public TextNote AddNewTextNote(UIDocument uiDoc, XYZ textLoc, double noteWidth, string text)
        {
            Document  doc = uiDoc.Document;
            ElementId defaultTextTypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);


            // make sure note width works for the text type
            double minWidth = TextNote.GetMinimumAllowedWidth(doc, defaultTextTypeId);
            double maxWidth = TextNote.GetMaximumAllowedWidth(doc, defaultTextTypeId);

            if (noteWidth < minWidth)
            {
                noteWidth = minWidth;
            }
            else if (noteWidth > maxWidth)
            {
                noteWidth = maxWidth;
            }

            TextNoteOptions opts = new TextNoteOptions(defaultTextTypeId);

            opts.HorizontalAlignment = HorizontalTextAlignment.Left;
            opts.Rotation            = 0;

            TextNote textNote = TextNote.Create(doc, doc.ActiveView.Id, textLoc, noteWidth, text, opts);

            return(textNote);
        }
Пример #5
0
        /// <summary>
        /// Batch creation of TextNotes
        /// </summary>
        /// <returns>If batch creation succeeds, return true; otherwise, return false</returns>
        private bool CreateTextNotes()
        {
            try
            {
                //Try to get View named "Level 1" where the TextNotes are
                View view = (from elem in new FilteredElementCollector(m_doc).OfClass(typeof(ViewPlan)).ToElements()
                             let var = elem as View
                                       where var != null && !var.IsTemplate && null != var.Name && "Level 1" == var.Name && ViewType.FloorPlan == var.ViewType
                                       select var).First();

                if (null == view)
                {
                    return(false);
                }

                // Create TextNotes
                ElementId typeId = m_doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);

                for (int i = 1; i < 6; i++)
                {
                    Autodesk.Revit.DB.XYZ origin = new Autodesk.Revit.DB.XYZ(i * -20, -100, 0);
                    if (null == TextNote.Create(m_doc, view.Id, origin, "TextNote", typeId))
                    {
                        return(false);
                    }
                }
            }
            catch (Exception)
            {
                return(false);
            }

            return(true);
        }
Пример #6
0
        public void CreateTextNote(Document doc, CSAZDimCallout dim, Selection sel, ref TextNote textNote)
        {
            var    typetextnote      = (from TextNoteType x in new FilteredElementCollector(doc).OfClass(typeof(TextNoteType)) where x.Name == "3/32\" Arial" select x).First();
            XYZ    Point             = sel.PickPoint();
            double SpaceToStartPoint = Point.DistanceTo(dim.Startpoint);
            double SpaceToEndPoint   = Point.DistanceTo(dim.Endpoint);

            if (SpaceToEndPoint < SpaceToStartPoint)
            {
                using (Transaction tran = new Transaction(doc, "Create Text"))
                {
                    tran.Start();
                    textNote = TextNote.Create(doc, doc.ActiveView.Id, dim.Endpoint, dim.Numbersegment + " " + dim.ControlMark, typetextnote.Id);

                    tran.Commit();
                }
            }
            else
            {
                using (Transaction tran = new Transaction(doc, "Create Text"))
                {
                    tran.Start();
                    textNote = TextNote.Create(doc, doc.ActiveView.Id, dim.Startpoint, dim.Numbersegment + " " + dim.ControlMark, typetextnote.Id);
                    double value = textNote.Width;
                    XYZ    p1    = Timdiemdimngang(dim.Startpoint, dim.VectorDirection, value);
                    doc.Create.NewDetailCurve(doc.ActiveView, Line.CreateBound(dim.Startpoint, p1));
                    tran.Commit();
                }
            }
        }
Пример #7
0
        public void Generate(Document doc, CSAModel model, Element element, XYZ offset)
        {
            CompoundStructure compoundStructure = model.GetCompoundStructure(element);//获取文本载体

            if (compoundStructure == null)
            {
                return;
            }
            var texts = model.FetchTextsFromCompoundStructure(doc, compoundStructure);//获取文本数据

            if (texts.Count == 0)
            {
                return;
            }
            if (texts.Count == 1)
            {
                TaskDialog.Show("警告", "暂不支持单层的结构做法标注");
            }
            else
            {
                model.TargetId = element.Id;                                                     //主体
                var            lineFamilySymbol = VLConstraintsForCSA.GetMultipleTagSymbol(doc); //获取线标注类型
                bool           isRegenerate     = offset != null;
                FamilyInstance line;
                if (isRegenerate)
                {
                    line = doc.GetElement(model.LineId) as FamilyInstance;
                    model.CalculateLocations(element, line, offset);                                         //计算内容定位
                    Clear(doc, model);
                    line = doc.Create.NewFamilyInstance(new XYZ(0, 0, 0), lineFamilySymbol, doc.ActiveView); //生成 线
                }
                else
                {
                    line = doc.Create.NewFamilyInstance(new XYZ(0, 0, 0), lineFamilySymbol, doc.ActiveView); //生成 线
                    model.CalculateLocations(element, line, offset);                                         //计算内容定位
                }
                var lineLocation  = model.LineLocation;
                var textLocations = model.TextLocations;
                ElementTransformUtils.MoveElement(doc, line.Id, lineLocation); //线定位
                LocationPoint locationPoint = line.Location as LocationPoint;  //线 旋转处理
                locationPoint.RotateByXY(lineLocation, model.VerticalVector);
                model.LineId = line.Id;
                model.UpdateLineParameters(line, model.LineHeight, model.LineWidth, model.LineSpace, model.Texts.Count()); //线参数设置
                List <TextNote> textNotes = new List <TextNote>();
                foreach (var text in model.Texts)                                                                          //生成 文本
                {
                    var textLocation = model.TextLocations[model.Texts.IndexOf(text)];
                    var textNote     = TextNote.Create(doc, doc.ActiveView.Id, textLocation, text, model.TextNoteTypeElementId);
                    textNotes.Add(textNote);
                    textNote.Location.RotateByXY(textLocation, model.VerticalVector);
                }
                model.TextNoteIds = textNotes.Select(c => c.Id).ToList();
                //测试用
                //GraphicsDisplayerManager.Display(@"E:\WorkingSpace\Outputs\Images\1023结构做法标注.png", lines, Model.TextLocations);
            }
        }
Пример #8
0
        public void CreteaTextnode(Document doc, string value, TextNoteType textNoteType)
        {
            ElementId       defaultTextTypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);
            TextNoteOptions opts = new TextNoteOptions(defaultTextTypeId);

            opts.TypeId = textNoteType.Id;
            XYZ      point    = sel.PickPoint();
            PLane3D  pLane3D  = new PLane3D(doc.ActiveView.Origin, doc.ActiveView.ViewDirection);
            var      P        = pLane3D.ProjectPointOnPlane(point);
            TextNote textNote = TextNote.Create(doc, doc.ActiveView.Id, P, value, opts);
        }
Пример #9
0
        /// <summary>
        /// Create a TextNote on the specified XYZ.
        /// This function is useful during debugging to attach
        /// a label to points in space
        /// </summary>
        public static TextNote CreateTextNote(string text, XYZ origin, Document doc)
        {
            var options = new TextNoteOptions
            {
                HorizontalAlignment = HorizontalTextAlignment.Center,
                VerticalAlignment   = VerticalTextAlignment.Middle,
                TypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType)
            };

            return(TextNote.Create(doc, doc.ActiveView.Id, origin, text, options));
        }
Пример #10
0
        internal override void Execute()
        {
            #region 与revit文档交互入口
            UIDocument uidoc    = this.uiapp.ActiveUIDocument;
            Document   doc      = uidoc.Document;
            Selection  sel      = uidoc.Selection;
            View       actiView = doc.ActiveView;
            #endregion

            IList <Element> textNoteTypes = (new FilteredElementCollector(doc)).OfClass(typeof(TextNoteType)).ToElements();
            string          tntfield      = "仿宋_3.5mm";//目标文字注释类型
            ElementId       tntId         = null;
            foreach (Element tnt in textNoteTypes)
            {
                if (tnt.Name == tntfield)//需要确认是否存在门窗标记类型的文字注释
                {
                    tntId = tnt.Id;
                }
            }
            TextNoteOptions opts = new TextNoteOptions(tntId);
            opts.Rotation = 0;


            IList <Element> selElements1 = sel.PickElementsByRectangle("请框选元素");
            using (Transaction trans = new Transaction(doc, "SetSurfaceTransparencyr"))
            {
                trans.Start();
                foreach (Element element in selElements1)
                {
                    if (!element.IsValidObject)
                    {
                        continue;                        //判断物体是否为有效物体
                    }
                    //if (element.Pinned) continue;
                    BoundingBoxXYZ boundingBoxXYZ = element.get_BoundingBox(actiView);
                    if (boundingBoxXYZ == null)
                    {
                        continue;
                    }

                    XYZ      textLoc  = boundingBoxXYZ.Min - new XYZ(20, 0, 0);
                    TextNote textNote = TextNote.Create(doc, actiView.Id, textLoc, element.Id.ToString(), opts);
                }
                trans.Commit();
            }

            //throw new NotImplementedException();
        }
Пример #11
0
        public Autodesk.Revit.UI.Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            try
            {
                // get the active document and view
                UIDocument             revitDoc = commandData.Application.ActiveUIDocument;
                Autodesk.Revit.DB.View view     = revitDoc.ActiveView;
                Document  dbDoc             = revitDoc.Document;
                ElementId currentTextTypeId = dbDoc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);

                foreach (ElementId elemId in revitDoc.Selection.GetElementIds())
                {
                    Element elem = dbDoc.GetElement(elemId);
                    if (elem.GetType() == typeof(Autodesk.Revit.DB.Structure.Rebar))
                    {
                        // cast to Rebar and get its first curve
                        Autodesk.Revit.DB.Structure.Rebar rebar = (Autodesk.Revit.DB.Structure.Rebar)elem;
                        Autodesk.Revit.DB.Curve           curve = rebar.GetCenterlineCurves(false, false, false)[0];

                        // calculate necessary arguments
                        Autodesk.Revit.DB.XYZ origin = new XYZ(
                            curve.GetEndPoint(0).X + curve.Length,
                            curve.GetEndPoint(0).Y,
                            curve.GetEndPoint(0).Z);
                        string strText = "This is " + rebar.Category.Name + " : " + rebar.Name;

                        // create the text
                        using (Transaction t = new Transaction(dbDoc))
                        {
                            t.Start("New text note");
                            TextNote.Create(dbDoc, view.Id, origin, strText, currentTextTypeId);
                            t.Commit();
                        }
                        return(Autodesk.Revit.UI.Result.Succeeded);
                    }
                }
                message = "No rebar selected!";
                return(Autodesk.Revit.UI.Result.Failed);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Autodesk.Revit.UI.Result.Failed);
            }
        }
Пример #12
0
        private void drawLines(Document doc, List <Line> lines)
        {
            var defaultNoteTypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);

            bool isReset = false;
            var  counter = 0;

            for (int i = 0; i < lines.Count; i++)
            {
                var line = lines[i];

                var plane       = new Plane(XYZ.BasisY.Negate(), line.GetEndPoint(0));
                var sketchPlane = SketchPlane.Create(doc, plane);

                var noteOptions = new TextNoteOptions()
                {
                    HorizontalAlignment = HorizontalTextAlignment.Center,
                    TypeId = defaultNoteTypeId
                };

                var no = TextNote.Create(doc,
                                         doc.ActiveView.Id,
                                         line.GetEndPoint(0) + line.Direction * line.Length / 2,
                                         counter.ToString(),
                                         noteOptions);

                no.Width = no.Width / 2;

                var direction = TextNote.Create(doc,
                                                doc.ActiveView.Id,
                                                line.GetEndPoint(1) - line.Direction * line.Length * 0.05,
                                                "X",
                                                noteOptions);

                doc.Create.NewModelCurve(line, sketchPlane);

                if (counter == 3 && !isReset)
                {
                    counter = 0;
                    isReset = true;
                }
                else
                {
                    counter++;
                }
            }
        }
Пример #13
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //Get application and documnet objects
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;
            View          view  = doc.ActiveView;
            //TextNoteOptions options = new TextNoteOptions();
            ElementId typeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);
            Collector co     = new Collector();
            //int i = 1;

            int i = co.GetMaxValue(doc);
            IList <Reference> pickedObjs = uidoc.Selection.PickObjects(ObjectType.Element, "Select Multiple Elements");
            List <ElementId>  ids        = (from Reference r in pickedObjs select r.ElementId).ToList();

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("transaction");
                if (pickedObjs != null && pickedObjs.Count > 0)
                {
                    foreach (ElementId eid in ids)
                    {
                        Element e = doc.GetElement(eid);
                        //string strng = "random";
                        //FamilyInstance faminst = e as FamilyInstance;
                        LocationPoint locPoint = e.Location as LocationPoint;
                        if (null != locPoint)
                        {
                            XYZ      point_a = locPoint.Point;
                            TextNote note    = TextNote.Create(doc, view.Id, point_a, i.ToString(), typeId);
                        }
                        else
                        {
                            LocationCurve locCurve = e.Location as LocationCurve;
                            XYZ           point_a  = locCurve.Curve.Evaluate(0.5, true);
                            TextNote      note     = TextNote.Create(doc, view.Id, point_a, i.ToString(), typeId);
                        }
                        i += 1;
                    }
                }
                tx.Commit();
            }
            return(Result.Succeeded);
        }
Пример #14
0
        //创建门窗标记字体实例
        public TextNote AddNewTextNote(Document doc, ElementId viewId, XYZ textLoc, String str, double angle)
        {
            IList <Element> textNoteTypes = (new FilteredElementCollector(doc)).OfClass(typeof(TextNoteType)).ToElements();
            string          tntfield      = "Arial Narrow-2.0-1.00-HDDN";//目标文字注释类型
            ElementId       tntId         = null;

            foreach (Element tnt in textNoteTypes)
            {
                if (tnt.Name == tntfield)//需要确认是否存在门窗标记类型的文字注释
                {
                    tntId = tnt.Id;
                }
            }
            TextNoteOptions opts = new TextNoteOptions(tntId);

            opts.Rotation = angle;
            TextNote textNote = TextNote.Create(doc, viewId, textLoc, str, opts);

            return(textNote);
        }
Пример #15
0
        public static void ListLineStyles(UIDocument uiDoc)
        {
            Document  currentDoc = uiDoc.Document;
            Selection sel        = uiDoc.Selection;
            XYZ       BasePt     = sel.PickPoint();

            FilteredElementCollector LineCollector = new FilteredElementCollector(currentDoc);
            List <ElementId>         Lines         = LineCollector.OfCategory(BuiltInCategory.OST_Lines).ToElementIds().ToList();
            FilteredElementCollector txtCollector  = new FilteredElementCollector(currentDoc);
            ElementId txtnoteTypeId = txtCollector.OfCategory(BuiltInCategory.OST_TextNotes).FirstElement().GetTypeId();

            int adjustment = 10;
            Dictionary <string, CurveElement> LineStyles = new Dictionary <string, CurveElement>();

            for (int i = 0; i < Lines.Count(); i++)
            {
                CurveElement l = currentDoc.GetElement(Lines[i]) as CurveElement;
                if (!LineStyles.Keys.Contains(l.LineStyle.Name))
                {
                    LineStyles.Add(l.LineStyle.Name, l);
                }
            }
            List <string> StyleName = LineStyles.Keys.ToList();

            StyleName.Sort();
            for (int i = 0; i < StyleName.Count(); i++)
            {
                XYZ startpoint = new XYZ(BasePt.X, (BasePt.Y - (adjustment * i)), 0);
                XYZ endpoint   = new XYZ((BasePt.X + (adjustment * 3)), (BasePt.Y - (adjustment * i)), 0);
                XYZ TextPoint  = new XYZ(BasePt.X + (adjustment * 4), (BasePt.Y - (adjustment * i)), 0);

                Curve       baseCurve = Line.CreateBound(startpoint, endpoint) as Curve;
                DetailCurve addedLine = currentDoc.Create.NewDetailCurve(uiDoc.ActiveView, baseCurve);

                TextNote txNote = TextNote.Create(currentDoc, uiDoc.ActiveView.Id, TextPoint, StyleName[i], txtnoteTypeId);
                addedLine.LineStyle = LineStyles[StyleName[i]].LineStyle;
            }
        }
Пример #16
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            try
            {
                XYZ origin = uidoc.Selection.PickPoint("Select insertion point");

                double width = 0.2; //feet

                Category c = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines);

                CategoryNameMap subcats = c.SubCategories;

                double offset = 0;

                TextNoteOptions options = new TextNoteOptions();
                options.HorizontalAlignment = HorizontalTextAlignment.Left;
                options.TypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);

                var dict = new SortedDictionary <string, GraphicsStyle>();

                foreach (Category lineStyle in subcats)
                {
                    GraphicsStyle gs = lineStyle.GetGraphicsStyle(GraphicsStyleType.Projection);

                    dict.Add(gs.Name, gs);
                }


                var output = dict.OrderBy(e => e.Key).Select(e => new { graphicStyle = e.Value, linestyleName = e.Key }).ToList();


                using (Transaction t = new Transaction(doc, "Place Lines"))
                {
                    t.Start();

                    //foreach( Line item in ordered) {
                    foreach (var item in output)
                    {
                        //					GraphicsStyle gs = lineStyle.GetGraphicsStyle(GraphicsStyleType.Projection);

                        XYZ newOrigin   = new XYZ(origin.X, origin.Y + offset, 0);
                        XYZ offsetPoint = new XYZ(origin.X + width, origin.Y + offset, 0);

                        Line L1 = Line.CreateBound(newOrigin, offsetPoint);

                        try
                        {
                            TextNote note = TextNote.Create(doc, doc.ActiveView.Id, new XYZ(origin.X - 0.2, origin.Y + offset + 0.01, 0), 0.2, item.linestyleName, options);

                            DetailCurve e = doc.Create.NewDetailCurve(doc.ActiveView, L1);

                            Parameter p = e.LookupParameter("Line Style");

                            p.Set(item.graphicStyle.Id);
                        }
                        catch
                        {
                        }
                        offset -= 0.03;
                    }

                    t.Commit();
                }


                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error", ex.Message);
                return(Result.Failed);
            }
        }
Пример #17
0
        //Get the Selected Viewports from the linked model, check to see if the sheet they are on exists and if they are already placed.
        //If not, create and set the properties of both.
        private void btnOK_Click(object sender, EventArgs e)
        {
            int         itemCount     = 0;
            bool        TitleLocation = true;
            ElementId   typeId        = (ElementId)cbViewPortTypes.SelectedValue;
            ElementType vpType        = doc.GetElement(typeId) as ElementType;

            //Check to see if the Viewport Type has the Show Title property set to Yes, if it is not, we can't calculate its location
            //relative to the viewport to move it to the same location as the Linked Model
            if (vpType.LookupParameter("Show Title").AsInteger() != 1)
            {
                if (TaskDialog.Show("Viewport Show Title", "The Viewport Type selected does not have the 'Show Title' property set to Yes and the View placement may not be as expected.\nWould you like to continue?", TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No, TaskDialogResult.No) == TaskDialogResult.No)
                {
                    return;
                }
                else
                {
                    TitleLocation = false;
                }
            }

            //Use a Transaction Group for multiple transactions to be grouped as one. This enables the creation of sheets and views during the method
            //without throwing an exception that the elements don't exist
            using (TransactionGroup tGroup = new TransactionGroup(doc, "Create Linked Views"))
            {
                tGroup.Start();
                using (Transaction t = new Transaction(doc))
                {
                    ElementId vpTypeId = ((Element)cboTitleBlock.SelectedValue).Id;
                    foreach (DataGridViewRow row in dgvLinkedViews.SelectedRows)
                    {
                        //use a try block to make sure any errors don't crash revit
                        try
                        {
                            t.Start("Create View");
                            string         detailNumber   = (string)row.Cells[1].Value;
                            ViewFamilyType viewfamilyType = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).Cast <ViewFamilyType>().FirstOrDefault(x => x.ViewFamily == ViewFamily.Drafting);
                            TextNoteType   textnoteType   = new FilteredElementCollector(doc).OfClass(typeof(TextNoteType)).Cast <TextNoteType>().FirstOrDefault();
                            ViewDrafting   draftingView   = ViewDrafting.Create(doc, viewfamilyType.Id);
                            draftingView.Name = (string)row.Cells[3].Value;
                            draftingView.LookupParameter("Title on Sheet").Set("REFERENCE VIEW - DO NOT PRINT");

                            //Set additional View Parameters based on Firm standards and Project Broswer Sorting templates
                            //if (dView.LookupParameter("Sheet Sort") is Parameter sSort)
                            //{
                            //    sSort.Set("PLANS");
                            //}

                            //Set the Linked View Yes/No Parameter to "Yes" for the Reload Function to Track
                            if (draftingView.LookupParameter("Linked View") is Parameter lView)
                            {
                                //Using 0 or 1 to set Yes (1) / No (0) parameters
                                lView.Set(1);
                            }
                            else
                            {
                                TaskDialog.Show("Missing Parameter", "Linked View Yes/No parameter is missing from View category and cannot continue.");
                                break;
                            }
                            //Set the Linked View GUID parameter to track the view in the Linked model
                            if (draftingView.LookupParameter("Linked View GUID") is Parameter lGUID)
                            {
                                lGUID.Set((string)row.Cells[5].Value);
                            }
                            else
                            {
                                TaskDialog.Show("Missing Parameter", "Linked View GUID Text parameter is missing from View category and cannot continue.");
                                break;
                            }
                            //Set the Link Name parameter to trak which Linked Model it came from.
                            if (draftingView.LookupParameter("Link Name") is Parameter lName)
                            {
                                lName.Set(cboLinks.Text);
                            }
                            else
                            {
                                TaskDialog.Show("Missing Parameter", "Link Name Text parameter is missing from View category and cannot continue.");
                                break;
                            }

                            //Creates one Text Note in the middle of the view to alert users that it is a Linked View and not to print it.
                            TextNote.Create(doc, draftingView.Id, new XYZ(0, 0, 0), "REFERENCE VIEW - DO NOT PRINT", textnoteType.Id);
                            t.Commit();

                            //Check to see if sheet with that number exits in the document
                            t.Start("Create Sheet");
                            ViewSheet sheet = CheckSheet((string)row.Cells[2].Value, vpTypeId);
                            t.Commit();

                            //Place the Drafting View reference on the sheet in the same location as in the Linked Model
                            t.Start("Place View");
                            if (sheet != null)
                            {
                                //Check to see if Viewport can be placed on sheet
                                if (Viewport.CanAddViewToSheet(doc, sheet.Id, draftingView.Id))
                                {
                                    if (CheckViewport(detailNumber, sheet))
                                    {
                                        XYZ      labelPoint = (XYZ)row.Cells[7].Value;
                                        Viewport vPort      = Viewport.Create(doc, sheet.Id, draftingView.Id, labelPoint);
                                        draftingView.get_Parameter(BuiltInParameter.VIEWPORT_DETAIL_NUMBER).Set(detailNumber);

                                        if (typeId != ElementId.InvalidElementId)
                                        {
                                            vPort.ChangeTypeId(typeId);
                                        }

                                        if (TitleLocation)
                                        {
                                            //Get the location of the Viewport and Viewport Label and Move the Viewport to match the Linked Document
                                            ElementTransformUtils.MoveElement(doc, vPort.Id, labelPoint - vPort.GetLabelOutline().MinimumPoint);
                                        }
                                        else
                                        {
                                            //If the Viewport Type does not have the Show Title property set to yes, we can't calculate the location
                                            //and we just place it int he location from the Linked model. This may not be the same location.
                                            ElementTransformUtils.MoveElement(doc, vPort.Id, labelPoint);
                                        }
                                    }
                                    else
                                    {
                                        TaskDialog.Show("Existing Viewport", "Sheet " + sheet.SheetNumber + "-" + sheet.Name + " already contains a Viewport with Detail Number " + detailNumber + ", but detail " + draftingView.Name + " was created.");
                                    }
                                }
                            }
                            t.Commit();
                            itemCount++;
                        }
                        catch (Exception ex)
                        {
                            //This Exception will check if the View already exits in the project
                            if (ex.GetType() == typeof(Autodesk.Revit.Exceptions.ArgumentException))
                            {
                                TaskDialog.Show("Existing View", "View '" + (string)row.Cells[3].Value + "' already exists and will not be created.");
                                if (t.HasStarted())
                                {
                                    t.RollBack();
                                }
                                continue;
                            }
                            else
                            {
                                TaskDialog.Show("Error", ex.ToString());
                                //Check to see if a Transaction is active and roll it back if so
                                if (t.HasStarted())
                                {
                                    t.RollBack();
                                }
                                //check to see if the Group Transaction has started and roll it back if so
                                if (tGroup.HasStarted())
                                {
                                    tGroup.RollBack();
                                }
                            }
                        }
                    }
                }
                //Commit all of the changes from the Transaction group and other transactions
                tGroup.Assimilate();

                DialogResult = DialogResult.OK;
                Close();
            }
        }
        public Result Execute_1(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;
            View          view  = doc.ActiveView;

            XYZ p;

            try
            {
                p = uidoc.Selection.PickPoint(
                    "Please pick text insertion point");
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                return(Result.Cancelled);
            }

            //TextNoteType boldTextType = doc.GetElement(
            //  new ElementId( 1212838 ) ) as TextNoteType; // Arial 3/32" Bold

            // 1 inch = 72 points
            // 3/32" = 72 * 3/32 points = ...

            TextNoteType textType
                = new FilteredElementCollector(doc)
                  .OfClass(typeof(TextNoteType))
                  .FirstElement() as TextNoteType;

            Debug.Print("TextNoteType.Name = " + textType.Name);

            // 6 mm Arial happens to be the first text type found
            // 6 mm = 6 / 25.4 inch = 72 * 6 / 25.4 points = 17 pt.
            // Nowadays, Windows does not assume that a point is
            // 1/72", but moved to 1/96" instead.

            float text_type_height_mm = 6;

            float mm_per_inch = 25.4f;

            float points_per_inch = 96; // not 72

            float em_size = points_per_inch
                            * (text_type_height_mm / mm_per_inch);

            em_size += 2.5f;

            Font font = new Font("Arial", em_size,
                                 FontStyle.Regular);

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Create TextNote");

                //string s = "TEST BOLD";

                string s = "The quick brown fox jumps over the lazy dog";

                Size txtBox = System.Windows.Forms.TextRenderer
                              .MeasureText(s, font);

                double w_inch  = txtBox.Width / DpiX;
                double v_scale = view.Scale; // ratio of true model size to paper size

                Debug.Print(
                    "Text box width in pixels {0} = {1} inch, "
                    + "view scale = {2}",
                    txtBox.Width, w_inch, v_scale);

                double newWidth = w_inch / 12;

                //TextNote txNote = doc.Create.NewTextNote(
                //  doc.ActiveView, p, XYZ.BasisX, XYZ.BasisY,
                //  newWidth, TextAlignFlags.TEF_ALIGN_LEFT
                //  | TextAlignFlags.TEF_ALIGN_BOTTOM, s ); // 2015
                //txNote.TextNoteType = textType; // 2015

                TextNote txNote = TextNote.Create(doc,
                                                  doc.ActiveView.Id, p, s, textType.Id); // 2016

                Debug.Print(
                    "NewTextNote lineWidth {0} times view scale "
                    + "{1} = {2} generated TextNote.Width {3}",
                    Util.RealString(newWidth),
                    Util.RealString(v_scale),
                    Util.RealString(newWidth * v_scale),
                    Util.RealString(txNote.Width));

                // This fails.

                //Debug.Assert(
                //  Util.IsEqual( newWidth * v_scale, txNote.Width ),
                //  "expected the NewTextNote lineWidth "
                //  + "argument to determine the resulting "
                //  + "text note width" );

                txNote.Width = newWidth * v_scale;

                //6mm Arial
                //Text box width in pixels 668 = 6.95833349227905 inch, scale 100
                //NewTextNote lineWidth 0.58 times view scale 100 = 57.99 generated TextNote.Width 59.32

                t.Commit();
            }
            return(Result.Succeeded);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            Result commandResult = Result.Succeeded;

            try
            {
                UIApplication uiApp = commandData.Application;
                UIDocument    uiDoc = uiApp.ActiveUIDocument;
                Document      dbDoc = uiDoc.Document;
                View          view  = uiDoc.ActiveGraphicalView;

                XYZ pLoc = XYZ.Zero;

                try
                {
                    pLoc = uiDoc.Selection.PickPoint(
                        "Please pick text insertion point");
                }
                catch (Autodesk.Revit.Exceptions.OperationCanceledException)
                {
                    Debug.WriteLine("Operation cancelled.");
                    message = "Operation cancelled.";

                    return(Result.Succeeded);
                }

                List <TextNoteType> noteTypeList
                    = new FilteredElementCollector(dbDoc)
                      .OfClass(typeof(TextNoteType))
                      .Cast <TextNoteType>()
                      .ToList();

                // Sort note types into ascending text size

                BuiltInParameter bipTextSize
                    = BuiltInParameter.TEXT_SIZE;

                noteTypeList.Sort((a, b)
                                  => a.get_Parameter(bipTextSize).AsDouble()
                                  .CompareTo(
                                      b.get_Parameter(bipTextSize).AsDouble()));

                foreach (TextNoteType textType in noteTypeList)
                {
                    Debug.WriteLine(textType.Name);

                    Parameter paramTextFont
                        = textType.get_Parameter(
                              BuiltInParameter.TEXT_FONT);

                    Parameter paramTextSize
                        = textType.get_Parameter(
                              BuiltInParameter.TEXT_SIZE);

                    Parameter paramBorderSize
                        = textType.get_Parameter(
                              BuiltInParameter.LEADER_OFFSET_SHEET);

                    Parameter paramTextBold
                        = textType.get_Parameter(
                              BuiltInParameter.TEXT_STYLE_BOLD);

                    Parameter paramTextItalic
                        = textType.get_Parameter(
                              BuiltInParameter.TEXT_STYLE_ITALIC);

                    Parameter paramTextUnderline
                        = textType.get_Parameter(
                              BuiltInParameter.TEXT_STYLE_UNDERLINE);

                    Parameter paramTextWidthScale
                        = textType.get_Parameter(
                              BuiltInParameter.TEXT_WIDTH_SCALE);

                    string fontName = paramTextFont.AsString();

                    double textHeight = paramTextSize.AsDouble();

                    bool textBold = paramTextBold.AsInteger() == 1
            ? true : false;

                    bool textItalic = paramTextItalic.AsInteger() == 1
            ? true : false;

                    bool textUnderline = paramTextUnderline.AsInteger() == 1
            ? true : false;

                    double textBorder = paramBorderSize.AsDouble();

                    double textWidthScale = paramTextWidthScale.AsDouble();

                    FontStyle textStyle = FontStyle.Regular;

                    if (textBold)
                    {
                        textStyle |= FontStyle.Bold;
                    }

                    if (textItalic)
                    {
                        textStyle |= FontStyle.Italic;
                    }

                    if (textUnderline)
                    {
                        textStyle |= FontStyle.Underline;
                    }

                    float fontHeightInch = (float)textHeight * 12.0f;
                    float displayDpiX    = GetDpiX();

                    float fontDpi   = 96.0f;
                    float pointSize = (float)(textHeight * 12.0 * fontDpi);

                    Font font = new Font(fontName, pointSize, textStyle);

                    int viewScale = view.Scale;

                    using (Transaction t = new Transaction(dbDoc))
                    {
                        t.Start("Test TextNote lineWidth calculation");

                        string textString = textType.Name
                                            + " (" + fontName + " "
                                            + (textHeight * 304.8).ToString("0.##") + "mm, "
                                            + textStyle.ToString() + ", "
                                            + (textWidthScale * 100.0).ToString("0.##")
                                            + "%): The quick brown fox jumps over the lazy dog.";

                        double stringWidthPx = GetStringWidth(textString, font);

                        double stringWidthIn = stringWidthPx / displayDpiX;

                        Debug.WriteLine("String Width in pixels: "
                                        + stringWidthPx.ToString("F3"));
                        Debug.WriteLine((stringWidthIn * 25.4 * viewScale).ToString("F3")
                                        + " mm at 1:" + viewScale.ToString());

                        double stringWidthFt = stringWidthIn / 12.0;

                        double lineWidth = ((stringWidthFt * textWidthScale)
                                            + (textBorder * 2.0)) * viewScale;

                        //TextNote textNote = dbDoc.Create.NewTextNote(
                        //  view, pLoc, XYZ.BasisX, XYZ.BasisY, 0.001,
                        //  TextAlignFlags.TEF_ALIGN_LEFT
                        //  | TextAlignFlags.TEF_ALIGN_TOP, textString ); // 2015
                        //textNote.TextNoteType = textType; // 2015

                        TextNote textNote = TextNote.Create(dbDoc,
                                                            view.Id, pLoc, textString, textType.Id); // 2016

                        textNote.Width = lineWidth;

                        t.Commit();
                    }

                    // Place next text note below this one with 5 mm gap

                    pLoc += view.UpDirection.Multiply(
                        (textHeight + (5.0 / 304.8))
                        * viewScale).Negate();
                }
            }
            catch (Autodesk.Revit.Exceptions.ExternalApplicationException e)
            {
                message = e.Message;
                Debug.WriteLine("Exception Encountered (Application)\n"
                                + e.Message + "\nStack Trace: " + e.StackTrace);

                commandResult = Result.Failed;
            }
            catch (Exception e)
            {
                message = e.Message;
                Debug.WriteLine("Exception Encountered (General)\n"
                                + e.Message + "\nStack Trace: " + e.StackTrace);

                commandResult = Result.Failed;
            }
            return(commandResult);
        }
Пример #20
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            try
            {
                XYZ origin = uidoc.Selection.PickPoint("Select insertion point");

                double Yoffset = origin.Y;

                double width = 0.5; //feet

                TextNoteOptions options = new TextNoteOptions();
                options.HorizontalAlignment = HorizontalTextAlignment.Left;
                options.TypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);

                ICollection <Element> textNoteTypes = new FilteredElementCollector(doc).OfClass(typeof(TextNoteType)).OrderBy(x => x.Name).ToList();

                ElementClassFilter filter = new ElementClassFilter(typeof(TextNote));

                using (Transaction t = new Transaction(doc, "Place text"))
                {
                    t.Start();

                    foreach (Element e in textNoteTypes)
                    {
                        TextNoteType textNoteElement = doc.GetElement(e.Id) as TextNoteType;

                        FilteredElementCollector collector = new FilteredElementCollector(doc).WherePasses(filter).WhereElementIsNotElementType();

                        var query = from element in collector
                                    where element.GetTypeId() == e.Id
                                    select element;

                        double fontSize = Convert.ToDouble(textNoteElement.LookupParameter("Text Size").AsValueString().Replace("mm", "")) / 304.8;

                        double borderOffset = textNoteElement.LookupParameter("Leader/Border Offset").AsDouble();

                        XYZ offsetPoint = new XYZ(origin.X, Yoffset, 0);

                        TextNote note = TextNote.Create(doc, doc.ActiveView.Id, offsetPoint, width, textNoteElement.Name + " count: " + query.Count().ToString(), options);

                        note.ChangeTypeId(e.Id);

                        Yoffset -= (fontSize + borderOffset * 2 + 0.03);
                    }

                    t.Commit();
                }
                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error", ex.Message);
                return(Result.Failed);
            }
        }
Пример #21
0
        RoomArea()
        {
            Revit.Creation.Document doc         = m_revitApp.ActiveUIDocument.Document.Create;
            SketchPlane             sketchPlane = Utils.Geometry.GetWorldPlane(m_revitApp);

            RevitLookup.Test.Forms.Levels lev = new RevitLookup.Test.Forms.Levels(m_revitApp);
            if (lev.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            Level curLevel = lev.LevelSelected;

            if (curLevel == null)
            {
                MessageBox.Show("No Level was selected.");
                return;
            }

            // Get the plan topology of the active doc first
            PlanTopology            planTopo = m_revitApp.ActiveUIDocument.Document.get_PlanTopology(curLevel);
            ICollection <ElementId> roomIds  = planTopo.GetRoomIds();

            if (roomIds.Count > 0)
            {
                IEnumerator <ElementId> setIter = roomIds.GetEnumerator();
                while (setIter.MoveNext())
                {
                    Room room = m_revitApp.ActiveUIDocument.Document.GetElement(setIter.Current) as Room;
                    if (null != room)
                    {
                        Autodesk.Revit.DB.View view          = m_revitApp.ActiveUIDocument.Document.ActiveView;
                        LocationPoint          locationPoint = room.Location as LocationPoint;

                        Double area = room.get_Parameter(BuiltInParameter.ROOM_AREA).AsDouble();

                        Double roundedArea = Math.Round(area, 2);

                        // providing an offset so that the Room Tag and the Area Tag dont overlap. Overlapping leads to an
                        // alignment related assert.

                        XYZ offset = new XYZ(5.0, 0, 0);

                        /// align text middle and center
                        TextNoteOptions op      = new TextNoteOptions();
                        TextNote        txtNote = TextNote.Create(m_revitApp.ActiveUIDocument.Document, view.Id, offset + locationPoint.Point, .25, roundedArea.ToString(), op);
                    }
                }
            }
            else
            {
                MessageBox.Show("No rooms found in the Active Document", "RevitLookup", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }


            // TBD: Tried to play around with PlanCircuits and there seems to be a problem with the IsRoomLocated property.
            // arj 1/23/07

            //Revit.PlanCircuitSet circSet = planTopo.Circuits;
            //Revit.PlanCircuitSetIterator setIters = circSet.ForwardIterator();

            //while (setIters.MoveNext())
            //{
            //    Revit.PlanCircuit planCircuit = setIters.Current as Revit.PlanCircuit;

            //    if (null != planCircuit)
            //    {
            //
            //        if (planCircuit.IsRoomLocated) // throws an exception always "Attempted to read or write protected memory.
            // This is often an indication that other memory is corrupt."
            //        {
            //        }
            //    }
            //}
        }
Пример #22
0
        /// <summary>
        /// Handler method for ViewPrinting event.
        /// This method will dump EventArgument information of event firstly and then create TextNote element for this view.
        /// View print will be canceled if TextNote creation failed.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event arguments of ViewPrinting event.</param>
        public void AppViewPrinting(object sender, Autodesk.Revit.DB.Events.ViewPrintingEventArgs e)
        {
            // Setup log file if it still is empty
            if (null == m_eventsLog)
            {
                SetupLogFiles();
            }
            //
            // header information
            Trace.WriteLine(System.Environment.NewLine + "View Print Start: ------------------------");
            //
            // Dump the events arguments
            DumpEventArguments(e);
            //
            // Create TextNote for current view, cancel the event if TextNote creation failed
            bool failureOccured = false; // Reserves whether failure occurred when create TextNote

            try
            {
                String strText = String.Format("Printer Name: {0}{1}User Name: {2}",
                                               e.Document.PrintManager.PrinterName, System.Environment.NewLine, System.Environment.UserName);
                //
                // Use non-debug compile symbol to write constant text note
#if !(Debug || DEBUG)
                strText = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
#endif
                using (Transaction eventTransaction = new Transaction(e.Document, "External Tool"))
                {
                    eventTransaction.Start();
                    TextNoteOptions options = new TextNoteOptions();
                    options.HorizontalAlignment = HorizontalTextAlignment.Center;
                    options.TypeId = e.Document.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);
                    TextNote newTextNote = TextNote.Create(e.Document, e.View.Id, XYZ.Zero, strText, options);
                    eventTransaction.Commit();

                    // Check to see whether TextNote creation succeeded
                    if (null != newTextNote)
                    {
                        Trace.WriteLine("Create TextNote element successfully...");
                        m_newTextNoteId = newTextNote.Id;
                    }
                    else
                    {
                        failureOccured = true;
                    }
                }
            }
            catch (System.Exception ex)
            {
                failureOccured = true;
                Trace.WriteLine("Exception occurred when creating TextNote, print will be canceled, ex: " + ex.Message);
            }
            finally
            {
                // Cancel the TextNote creation when failure occurred, meantime the event is cancellable
                if (failureOccured && e.Cancellable)
                {
                    e.Cancel();
                }
            }
        }
Пример #23
0
        public Result SetLevelAnnotations(Document doc, Form1 ui)
        {
            try
            {
                List <View3D> listOfViews           = new List <View3D>();
                List <string> listOfTeamplates      = new List <string>();
                var           textNoteTypeCollector = new FilteredElementCollector(doc).OfClass(typeof(TextNoteType));
                var           levelCollector        = new FilteredElementCollector(doc).OfClass(typeof(Level));
                var           View3DCollector       = new FilteredElementCollector(doc).OfClass(typeof(View3D)).Cast <View3D>().Where(x => !x.IsTemplate);
                foreach (View3D view in View3DCollector)
                {
                    var teamplateId             = view.ViewTemplateId;
                    var isViewLocked            = view.IsLocked;
                    var isTeamplateIdNotInvalid = view.ViewTemplateId != ElementId.InvalidElementId;
                    if (isViewLocked && isTeamplateIdNotInvalid)
                    {
                        var viewTeamplateName = doc.GetElement(view.ViewTemplateId).Name;
                        if (!listOfTeamplates.Contains(viewTeamplateName))
                        {
                            listOfTeamplates.Add(viewTeamplateName);
                        }
                        listOfViews.Add(view);
                    }
                }
                foreach (var name in listOfTeamplates)
                {
                    var teamplateNode = ui.TreeView.Nodes.Add(name);

                    foreach (var nameOfView in listOfViews)
                    {
                        if (doc.GetElement(nameOfView.ViewTemplateId).Name == teamplateNode.Text)
                        {
                            var viewNode = teamplateNode.Nodes.Add(nameOfView.Name);
                        }
                    }
                }
                foreach (var txtnote in textNoteTypeCollector)
                {
                    ui.TextNoteTypeComboBox.Items.Add(txtnote.Name);
                }
                foreach (Parameter param in levelCollector.FirstOrDefault().Parameters)
                {
                    if (param.IsReadOnly == false && (param.StorageType == StorageType.Integer || param.StorageType == StorageType.String))
                    {
                        ui.LevelComboBox.Items.Add(param.Definition.Name);
                    }
                }
                var uiResult = ui.ShowDialog();
                if (uiResult != DialogResult.OK)
                {
                    return(Result.Cancelled);
                }
                Transaction tr = new Transaction(doc, "Отметки Уровней");
                tr.Start();
                var listOfCheckedNames = new List <string>();
                foreach (TreeNode node in ui.TreeView.Nodes)
                {
                    foreach (TreeNode childNode in node.Nodes)
                    {
                        if (childNode.Checked == true)
                        {
                            listOfCheckedNames.Add(childNode.Text);
                        }
                    }
                }

                var listOfChecked3DViews = new List <View3D>();
                foreach (var name in listOfCheckedNames)
                {
                    foreach (var el in View3DCollector)
                    {
                        if (name == el.Name)
                        {
                            listOfChecked3DViews.Add(el);
                        }
                    }
                }
                var list = new List <TextNote>();
                foreach (var view in listOfChecked3DViews)
                {
                    foreach (Level lvl in levelCollector)
                    {
                        BoundingBoxXYZ boxXYZ = new BoundingBoxXYZ();
                        boxXYZ.Max = new XYZ(100000, 100000, lvl.ProjectElevation);
                        boxXYZ.Min = new XYZ(-100000, -10000, lvl.ProjectElevation);
                        Outline outline = new Outline(boxXYZ.Min, boxXYZ.Max);
                        BoundingBoxIntersectsFilter intersectsFilter = new BoundingBoxIntersectsFilter(outline);
                        FilteredElementCollector    elementsOnView   = new FilteredElementCollector(doc, view.Id).OfClass(typeof(Pipe)).WherePasses(intersectsFilter);
                        Element pipe = elementsOnView.FirstOrDefault();
                        if (elementsOnView.Count() > 0)
                        {
                            XYZ origin         = new XYZ();
                            var originX        = pipe.get_BoundingBox(view).Max.X;
                            var originY        = pipe.get_BoundingBox(view).Max.Y;
                            var originZ        = lvl.ProjectElevation;
                            var direction      = view.RightDirection;
                            var leftDirectionx = view.RightDirection.X;
                            var leftDirectiony = view.RightDirection.Y;
                            if (ui.radioButtonLeft.Checked)
                            {
                                XYZ leftDirection = new XYZ(leftDirectionx * -6, leftDirectiony * -6, view.RightDirection.Z);
                                XYZ origin1       = new XYZ(originX, originY, originZ) + leftDirection;
                                origin = origin1;
                            }
                            else if (ui.radioButtonRight.Checked)
                            {
                                XYZ origin1 = new XYZ(originX, originY, originZ) + direction;
                                origin = origin1;
                            }
                            string highMark = lvl.get_Parameter(BuiltInParameter.LEVEL_ELEV).AsValueString();
                            if (highMark.Length == 5)
                            {
                                highMark = highMark.Insert(2, ".");
                            }
                            else
                            {
                                highMark = highMark.Insert(1, ".");
                            }
                            var       text         = lvl.LookupParameter(ui.LevelComboBox.Text).AsString() + " " + "Эт." + " " + highMark;
                            ElementId textNoteType = null;
                            foreach (var type in textNoteTypeCollector)
                            {
                                if (type.Name == ui.TextNoteTypeComboBox.Text)
                                {
                                    textNoteType = type.Id;
                                }
                            }
                            TextNote note = TextNote.Create(doc, view.Id, origin, text, textNoteType);
                        }
                    }
                }
                tr.Commit();
                TaskDialog.Show("Готово", "Отметки уровней ВК выставлены");
                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace);
                return(Result.Failed);
            }
        }
Пример #24
0
        /// <summary>
        /// Tag wall layers by creating text note element on user
        /// specified point and populate it with layer information
        /// </summary>
        /// <param name="commandData"></param>
        /// <param name="message"></param>
        /// <param name="elements"></param>
        /// <returns></returns>
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            // Application context
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            // Get access the current view
            var activeView = uidoc.ActiveView;

            // Check if Text note can be created in currently active view
            bool canCreateTextNoteInView = false;

            switch (activeView.ViewType)
            {
            case ViewType.FloorPlan:
                canCreateTextNoteInView = true;
                break;

            case ViewType.CeilingPlan:
                canCreateTextNoteInView = true;
                break;

            case ViewType.Detail:
                canCreateTextNoteInView = true;
                break;
            }

            if (!canCreateTextNoteInView)
            {
                TaskDialog.Show("ERROR", "Text note can't be created in the current active view");
                return(Result.Cancelled);
            }

            // Ask user to pick location point for Text Note
            var pt = uidoc.Selection.PickPoint("Pick text note location point");

            // Ask user the select one basic wall
            Reference selectionReference = uidoc.Selection.PickObject(ObjectType.Element, "Select one wall");
            Element   selectionElement   = doc.GetElement(selectionReference);

            // Cast generic element type to more specific wall type
            Wall wall = selectionElement as Wall;

            // Check if wall is type of basic wall
            if (wall.IsStackedWall)
            {
                TaskDialog.Show("Warning", "Wall you selected is category of the  Stacked Wall.\nIt's not supported by this command");
                return(Result.Cancelled);
            }

            // Access list of wall layers
            IList <CompoundStructureLayer> layers = wall.WallType.GetCompoundStructure().GetLayers();

            // Get layer information in structured string format for Text note
            string a = "";

            a += "Layer Function     ||    " + "Material Name     ||    " + "Layer Width" + "\n";
            foreach (var l in layers)
            {
                var material = doc.GetElement(l.MaterialId) as Material;
                if (material != null)
                {
                    a += l.Function.ToString() + "        " + material.Name + "        " + FeetTomm(l.Width).ToString() + "mm" + "\n";
                }
            }

            // Create text note options
            var textNoteOptions = new TextNoteOptions
            {
                VerticalAlignment   = VerticalTextAlignment.Top,
                HorizontalAlignment = HorizontalTextAlignment.Left,
                TypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType)
            };

            // Open transaction for access to revit UI level document changing
            using (Transaction t = new Transaction(doc))
            {
                t.Start("Tag Wall Layers");

                // Create text note with wall layers information on user specified point in the current active view
                var textNote = TextNote.Create(doc, activeView.Id, pt, a, textNoteOptions);

                t.Commit();
            }
            return(Result.Succeeded);
        }
Пример #25
0
        private void Report(Document doc)
        {
            View      active  = doc.ActiveView;
            ElementId levelId = null;

            Parameter level = active.LookupParameter("Associated Level");

            FilteredElementCollector lvlCollector  = new FilteredElementCollector(doc);
            ICollection <Element>    lvlCollection = lvlCollector.OfClass(typeof(Level)).ToElements();

            foreach (Element l in lvlCollection)
            {
                Level lvl = l as Level;
                if (lvl.Name == level.AsString())
                {
                    levelId = lvl.Id;
                    //TaskDialog.Show("test", lvl.Name + "\n"  + lvl.Id.ToString());
                }
            }
            using (Transaction trans = new Transaction(doc))
            {
                trans.Start("Labels");
                // Find all Room instances in the document by using category filter
                ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_Rooms);

                // Apply the filter to the elements in the active document
                // Use shortcut WhereElementIsNotElementType() to find wall instances only
                IEnumerable <Room> rooms = new FilteredElementCollector(doc)
                                           .WhereElementIsNotElementType()
                                           .OfClass(typeof(SpatialElement))
                                           .Where(e => e.GetType() == typeof(Room))
                                           .Where(e => e.LevelId.IntegerValue == levelId.IntegerValue)
                                           .Cast <Room>();


                foreach (Element e in rooms)
                {
                    Room          room     = e as Room;
                    LocationPoint locPoint = doc.GetElement(e.Id).Location as LocationPoint;
                    XYZ           textloc  = locPoint.Point;

                    ElementId defaultTextTypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);
                    double    noteWidth         = .2;

                    // make sure note width works for the text type
                    double minWidth = TextNote.GetMinimumAllowedWidth(doc, defaultTextTypeId);
                    double maxWidth = TextNote.GetMaximumAllowedWidth(doc, defaultTextTypeId);
                    if (noteWidth < minWidth)
                    {
                        noteWidth = minWidth;
                    }
                    else if (noteWidth > maxWidth)
                    {
                        noteWidth = maxWidth;
                    }

                    TextNoteOptions opts = new TextNoteOptions(defaultTextTypeId);
                    opts.HorizontalAlignment = HorizontalTextAlignment.Left;
                    opts.Rotation            = 0;


                    TextNote textNote = TextNote.Create(doc, doc.ActiveView.Id, textloc, noteWidth, room.Name, opts);
                }
                trans.Commit();
            }
        }
Пример #26
0
        public static void Place(UIApplication uiapp, TextLeaderPosition _textLeader, double _textWidth, double _leaderLength)
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            IList <UIView> uiviews = uidoc.GetOpenUIViews();
            UIView         uiview  = null;

            foreach (UIView uv in uiviews)
            {
                if (uv.ViewId.Equals(doc.ActiveView.Id))
                {
                    uiview = uv;
                    break;
                }
            }


            IList <XYZ> corners = uiview.GetZoomCorners();
            XYZ         p       = corners[0];
            XYZ         q       = corners[1];
            XYZ         v       = q - p;
            XYZ         center  = p + 0.5 * v;

            try
            {
                using (Transaction tran = new Transaction(doc, "Text note created"))
                {
                    if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
                    {
                        //uses PresentationCore
                        string textNoteContent = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();

                        //double width = 3.0 / 12.0; // feet on paper

                        TextNoteOptions options = new TextNoteOptions();
                        options.HorizontalAlignment = HorizontalTextAlignment.Left;

                        options.TypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);
                        double noteWidth = _textWidth / 12;

                        tran.Start();
                        TextNote note = TextNote.Create(doc, doc.ActiveView.Id, center, textNoteContent, options);
                        note.Width = noteWidth;



                        if (_textLeader == TextLeaderPosition.Both)
                        {
                            note.AddLeader(TextNoteLeaderTypes.TNLT_STRAIGHT_L);
                            Leader lead = note.AddLeader(TextNoteLeaderTypes.TNLT_STRAIGHT_R);
                            note.LeaderLeftAttachment  = LeaderAtachement.TopLine;
                            note.LeaderRightAttachment = LeaderAtachement.TopLine;
                            note.Width = noteWidth;

                            lead.End = new XYZ(center.X + _leaderLength, center.Y - 0.8, center.Z);
                        }
                        else if (_textLeader == TextLeaderPosition.Left)
                        {
                            note.AddLeader(TextNoteLeaderTypes.TNLT_STRAIGHT_L);
                            note.LeaderLeftAttachment = LeaderAtachement.TopLine;
                            note.Width = noteWidth;
                        }
                        else if (_textLeader == TextLeaderPosition.Right)
                        {
                            Leader lead = note.AddLeader(TextNoteLeaderTypes.TNLT_STRAIGHT_R);
                            note.LeaderRightAttachment = LeaderAtachement.TopLine;
                            note.Width = noteWidth;


                            //lead.Elbow = new XYZ(center.X, center.Y, center.Z);

                            lead.End = new XYZ(center.X + _leaderLength, center.Y - 0.8, center.Z);
                        }

                        tran.Commit();
                    }
                    else
                    {
                        TaskDialog.Show("Warning", "Clipboard is empty. Try to copy something.");
                    }
                }
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error", ex.Message);
            }
        }
Пример #27
0
        public void CreateTextNote(Document doc, Dictionary <string, List <string> > dic, TextNoteType textNoteType, Selection sel)
        {
            var point = sel.PickPoint();

            if (doc.ActiveView.IsAssemblyView)
            {
                XYZ    direction    = doc.ActiveView.UpDirection;
                string assemblyname = (doc.GetElement(doc.ActiveView.AssociatedAssemblyInstanceId) as AssemblyInstance).Name;
                var    list         = dic[assemblyname].ToList();
                list.Sort();
                Sortliststring(list);
                if (direction.X != 0)
                {
                    using (Transaction tran = new Transaction(doc, "Create new type text"))
                    {
                        XYZ xYZ = XYZ.Zero;
                        tran.Start();
                        for (int i = 0, j = 0; i < list.Count; i++, j += 1)
                        {
                            if (i == 0)
                            {
                                var p2 = new XYZ(point.X, point.Y, point.Z + 0.016);
                                xYZ = p2;
                                TextNote textNote = TextNote.Create(doc, doc.ActiveView.Id, xYZ, list[i], textNoteType.Id);
                            }
                            else
                            {
                                var p2 = new XYZ(xYZ.X, xYZ.Y, xYZ.Z + 0.016);
                                xYZ = p2;
                                TextNote textNote = TextNote.Create(doc, doc.ActiveView.Id, xYZ, list[i], textNoteType.Id);
                            }
                        }
                        tran.Commit();
                    }
                }
                if (direction.Y != 0)
                {
                    using (Transaction tran = new Transaction(doc, "Create new type text"))
                    {
                        XYZ xYZ = XYZ.Zero;
                        tran.Start();
                        for (int i = 0, j = 0; i < list.Count; i++, j += 1)
                        {
                            if (i == 0)
                            {
                                var p2 = new XYZ(point.X, point.Y + 0.016, point.Z);
                                xYZ = p2;
                                TextNote textNote = TextNote.Create(doc, doc.ActiveView.Id, xYZ, list[i], textNoteType.Id);
                            }
                            else
                            {
                                var p2 = new XYZ(xYZ.X, xYZ.Y + 0.016, xYZ.Z);
                                xYZ = p2;
                                TextNote textNote = TextNote.Create(doc, doc.ActiveView.Id, xYZ, list[i], textNoteType.Id);
                            }
                        }
                        tran.Commit();
                    }
                }
                if (direction.Z != 0)
                {
                    using (Transaction tran = new Transaction(doc, "Create new type text"))
                    {
                        XYZ xYZ = XYZ.Zero;
                        tran.Start();
                        for (int i = 0, j = 0; i < list.Count; i++, j += 1)
                        {
                            if (i == 0)
                            {
                                var p2 = new XYZ(point.X, point.Y, point.Z + 0.016);
                                xYZ = p2;
                                TextNote textNote = TextNote.Create(doc, doc.ActiveView.Id, xYZ, list[i], textNoteType.Id);
                            }
                            else
                            {
                                var p2 = new XYZ(xYZ.X, xYZ.Y, xYZ.Z + 0.016);
                                xYZ = p2;
                                TextNote textNote = TextNote.Create(doc, doc.ActiveView.Id, xYZ, list[i], textNoteType.Id);
                            }
                        }
                        tran.Commit();
                    }
                }
            }
        }
Пример #28
0
        /// <summary>
        /// Tag wall layers by creating text note element on user specified point and populate it with layer information.
        /// </summary>
        /// <param name="commandData">The command data.</param>
        /// <param name="message">The message.</param>
        /// <param name="elements">The elements.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            // Application context.
            var uidoc = commandData.Application.ActiveUIDocument;
            var doc   = uidoc.Document;

            // Check if we are in the Revit project , not in family one.
            if (doc.IsFamilyDocument)
            {
                Message.Display("Can't use command in family document", WindowType.Warning);
                return(Result.Cancelled);
            }

            // Get access to current view.
            var activeView = uidoc.ActiveView;

            // Check if Text Note can be created in currently active project view.
            bool canCreateTextNoteInView = false;

            switch (activeView.ViewType)
            {
            case ViewType.FloorPlan:
            case ViewType.CeilingPlan:
            case ViewType.Detail:
            case ViewType.Elevation:
            case ViewType.Section:
            case ViewType.EngineeringPlan:
                canCreateTextNoteInView = true;
                break;
            }

            // Collector for data provided in window.
            var userInfo = new TagWallLayersCommandData();

            if (!canCreateTextNoteInView)
            {
                Message.Display("Text Note element can't be created in the current view.", WindowType.Error);
                return(Result.Cancelled);
            }

            try
            {
                // Get user provided information from window and show dialog.
                using (var window = new TagWallLayersForm(uidoc))
                {
                    window.ShowDialog();

                    if (window.DialogResult == DialogResult.Cancel)
                    {
                        return(Result.Cancelled);
                    }

                    userInfo = window.GetInformation();
                }

                // Ask user to select one basic wall.
                var selectionReference = uidoc.Selection.PickObject(ObjectType.Element,
                                                                    //new SelectionFilterByCategory("Walls"),
                                                                    new SelectionFilterByCategory(BuiltInCategory.OST_Walls),
                                                                    "Select one basic wall.");
                var selectionElement = doc.GetElement(selectionReference);

                // Cast generic element type to more specific Wall type.
                var wall = selectionElement as Wall;

                // Check if wall is type of basic wall.
                if (wall == null || wall.IsStackedWall)
                {
                    Message.Display("Wall you selected is category of the Stacked Wall.\nIt's not supported by this command.", WindowType.Warning);
                    return(Result.Cancelled);
                }

                // Access list of wall layers.
                var layers = wall.WallType.GetCompoundStructure().GetLayers();

                // Get layer information in structured string format for Text Note.
                var msg = new StringBuilder();

                foreach (var layer in layers)
                {
                    var material = doc.GetElement(layer.MaterialId) as Material;

                    msg.AppendLine();

                    if (userInfo.Function)
                    {
                        msg.Append(layer.Function.ToString());
                    }

                    // Check if material is attached to the layer in wall compound structure.
                    if (userInfo.Name)
                    {
                        if (material != null)
                        {
                            msg.Append(" " + material.Name);
                        }
                        else
                        {
                            msg.Append("  <by category>");
                        }
                    }

                    // Convert units to metric.
                    // Revit by default uses imperial units.
                    if (userInfo.Thickness)
                    {
                        msg.Append(" " + LengthUnitConverter
                                   .ConvertToMetric(layer.Width, userInfo.UnitType, userInfo.Decimals)
                                   .ToString(CultureInfo.InvariantCulture));
                    }
                }

                // Create Text Note options.
                var textNoteOptions = new TextNoteOptions
                {
                    VerticalAlignment   = VerticalTextAlignment.Top,
                    HorizontalAlignment = HorizontalTextAlignment.Left,
                    TypeId = userInfo.TextTypeId
                };

                // Open Revit document transaction to create new Text Note element.
                using (var transaction = new Transaction(doc))
                {
                    transaction.Start("Tag Wall Layers Command");

                    var pt = new XYZ();

                    // Construct sketch plane for user to pick point if we are in elevation or section view.
                    if (activeView.ViewType == ViewType.Elevation || activeView.ViewType == ViewType.Section)
                    {
                        var plane       = Plane.CreateByNormalAndOrigin(activeView.ViewDirection, activeView.Origin);
                        var sketchPlane = SketchPlane.Create(doc, plane);
                        activeView.SketchPlane = sketchPlane;
                    }
                    // Ask user to pick location point for the Text Note Element
                    pt = uidoc.Selection.PickPoint("Pick text note location point");

                    // Create Text Note with wall layers information on user specified point in the current active view.
                    var textNote = TextNote.Create(doc, activeView.Id, pt, msg.ToString(), textNoteOptions);

                    transaction.Commit();
                }
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException ex)
            {
                return(Result.Cancelled);
            }
            catch
            {
                return(Result.Failed);
            }

            return(Result.Succeeded);
        }
Пример #29
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            // get view types
            FilteredElementCollector viewCol
                = new FilteredElementCollector(doc)
                  .WhereElementIsElementType()
                  .OfClass(typeof(ViewFamilyType));

            ViewFamilyType viewFamilyTypeFP = null;
            ViewFamilyType viewFamilyTypeS  = null;
            ViewFamilyType viewFamilyTypeD  = null;

            foreach (ViewFamilyType view in viewCol)
            {
                if (view.ViewFamily == ViewFamily.FloorPlan)
                {
                    viewFamilyTypeFP = view;
                }
                if (view.ViewFamily == ViewFamily.Section)
                {
                    viewFamilyTypeS = view;
                }
                if (view.ViewFamily == ViewFamily.Detail)
                {
                    viewFamilyTypeD = view;
                }
            }

            // collecting categories which must be visible (structural stiffener, structural column and text note
            List <ElementId> categoriesToShow = new List <ElementId>();

            categoriesToShow.Add(new FilteredElementCollector(doc)
                                 .OfCategory(BuiltInCategory.OST_StructuralStiffener)
                                 .ToElements()
                                 .First().Category.Id);
            categoriesToShow.Add(new FilteredElementCollector(doc)
                                 .OfCategory(BuiltInCategory.OST_StructuralColumns)
                                 .ToElements()
                                 .First().Category.Id);
            categoriesToShow.Add(new FilteredElementCollector(doc)
                                 .OfCategory(BuiltInCategory.OST_TextNotes)
                                 .ToElements()
                                 .First().Category.Id);
            categoriesToShow.Add(new FilteredElementCollector(doc)
                                 .OfCategory(BuiltInCategory.OST_Dimensions)
                                 .ToElements()
                                 .First().Category.Id);

            // declaring elementsCol and elementsToHide variables
            Categories categories = doc.Settings.Categories;
            TextNote   textNote;
            Leader     leader;
            ElementId  defaultTextNoteTypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);


            // retrieve elements from database
            FilteredElementCollector col
                = new FilteredElementCollector(doc)
                  .WhereElementIsNotElementType()
                  .OfCategory(BuiltInCategory.OST_StructuralStiffener);

            // create a list to save the types already handled
            List <string> typesHandled = new List <string>();

            // modify document within a transaction
            using (Transaction tx = new Transaction(doc))
            {
                bool warningKey = true;
                tx.Start("Criar detalhe das chapas");
                // get first element for tests
                foreach (Element e in col)
                {
                    // handling plate type with comment
                    Parameter commentParam = e.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS);

                    // checking comment param
                    if (commentParam.AsString() == null)
                    {
                        if (warningKey)
                        {
                            System.Windows.Forms.MessageBox.Show("Foi encontrada uma chapa sem indicação de tipo, " +
                                                                 "ela será ignorada pelo add-in.", "Aviso");
                            warningKey = false;
                        }
                        continue;
                    }

                    string[] splittedParam = (from str in commentParam.AsString().Split(_Separators)
                                              select str.ToLower())
                                             .ToArray();

                    int plateType = 0;
                    try
                    {
                        plateType = int.Parse(splittedParam.Last().Split(' ').Last());
                    }
                    catch (Exception)
                    {
                        System.Windows.Forms.MessageBox.Show("Problemas ao identificar o tipo da chapa. " +
                                                             splittedParam.Last(), "Erro");
                        tx.RollBack();
                        return(Result.Failed);
                    }

                    if (typesHandled.ToArray().Intersect(splittedParam).Any())
                    {
                        continue;
                    }

                    List <View> existingViews = new List <View>();
                    if (!CheckNameAvailability(doc, plateType, ref existingViews))
                    {
                        switch (AskOverwriteDetailView(plateType))
                        {
                        case System.Windows.Forms.DialogResult.Yes:
                            doc.Delete((from view in existingViews select view.Id).ToList());
                            break;

                        case System.Windows.Forms.DialogResult.No:
                            tx.RollBack();
                            return(Result.Cancelled);

                        case System.Windows.Forms.DialogResult.Cancel:
                            tx.RollBack();
                            return(Result.Cancelled);
                        }
                    }

                    // get boundingbox of element
                    BoundingBoxXYZ ebbox = e.get_BoundingBox(null);
                    double         w     = ebbox.Max.X - ebbox.Min.X;
                    double         d     = ebbox.Max.Y - ebbox.Min.Y;
                    double         h     = ebbox.Max.Z - ebbox.Min.Z;

                    // creating boundingbox for vertical view section
                    BoundingBoxXYZ vBbox = new BoundingBoxXYZ();
                    vBbox.Enabled = true;
                    vBbox.Max     = new XYZ(w + 0.2, h + 2, d + 0.2);
                    vBbox.Min     = new XYZ(-w - 0.2, -h - 0.2, -d - 0.2);

                    // creating boundingbox for horizontal view section
                    BoundingBoxXYZ hBbox = new BoundingBoxXYZ();
                    hBbox.Enabled = true;
                    hBbox.Max     = new XYZ(w + 0.2, d + 0.2, h + 0.2);
                    hBbox.Min     = new XYZ(-w - 0.2, -d - 0.2, -h - 0.2);

                    // set the transform
                    Transform vTrans = Transform.Identity;
                    Transform hTrans = Transform.Identity;

                    // find the element mid point
                    XYZ midPt = 0.5 * (ebbox.Max + ebbox.Min);

                    // set it as origin
                    vTrans.Origin = midPt;
                    hTrans.Origin = midPt;

                    // determine view direction for vView
                    vTrans.BasisX = XYZ.BasisX;
                    vTrans.BasisY = XYZ.BasisZ;
                    vTrans.BasisZ = -XYZ.BasisY;

                    // determine view direction for hView
                    hTrans.BasisX = -XYZ.BasisX;
                    hTrans.BasisY = XYZ.BasisY;
                    hTrans.BasisZ = -XYZ.BasisZ;

                    // transforming
                    vBbox.Transform = vTrans;
                    hBbox.Transform = hTrans;

                    // creating vertical view section
                    ViewSection vView = ViewSection.CreateDetail(doc, viewFamilyTypeD.Id, vBbox);

                    // hidding categories in vertical view section
                    foreach (Category category in categories)
                    {
                        if (!categoriesToShow.Contains(category.Id) &&
                            vView.CanCategoryBeHidden(category.Id))
                        {
                            vView.SetCategoryHidden(category.Id, true);
                        }
                    }

                    // scale
                    int scaleValue = 20;

                    // configuring vertical view properties
                    vView.Name           = MakeViewNames(plateType)[0];
                    vView.DetailLevel    = ViewDetailLevel.Fine;
                    vView.DisplayStyle   = DisplayStyle.FlatColors;
                    vView.CropBoxVisible = false;
                    vView.Scale          = scaleValue;

                    // creating textNotes
                    String text0 = "LIGAÇÃO COLUNA X CHAPA \nFEITA ATRAVÉS DE SOLDA";
                    textNote = TextNote.Create(doc, vView.Id, vBbox.Transform.Origin + new XYZ(0, 12, 3), text0, defaultTextNoteTypeId);
                    //leader = textNote.AddLeader(TextNoteLeaderTypes.TNLT_STRAIGHT_R);
                    //leader.End = vBbox.Transform.Origin + new XYZ(0, -5, 0);

                    String text1 = "CHUMBAR CHAPA COM ADESIVO \nEPOXI SIKADUR 32 OU SIMILAR" +
                                   "\nVERIFICAR MODO DE UTILIZAÇÃO \nJUNTO AO FORNECEDOR";
                    textNote = TextNote.Create(doc, vView.Id, vBbox.Transform.Origin + new XYZ(0, 12, 3), text1, defaultTextNoteTypeId);
                    //leader = textNote.AddLeader(TextNoteLeaderTypes.TNLT_STRAIGHT_L);
                    //leader.End = vBbox.Transform.Origin + new XYZ(0, -50, 0);

                    String text2 = "PREENCHER COM EPS";
                    textNote = TextNote.Create(doc, vView.Id, vBbox.Transform.Origin + new XYZ(0, 12, 3), text2, defaultTextNoteTypeId);

                    String text3 = "CHUMBAR CHAPA \nCOM ADESIVO EPOXI";
                    textNote = TextNote.Create(doc, vView.Id, vBbox.Transform.Origin + new XYZ(0, 12, 3), text3, defaultTextNoteTypeId);

                    // creating horizontal view section
                    ViewSection hView = ViewSection.CreateDetail(doc, viewFamilyTypeD.Id, hBbox);

                    // hidding categories in horizontal view section
                    foreach (Category category in categories)
                    {
                        if (!categoriesToShow.Contains(category.Id) &&
                            hView.CanCategoryBeHidden(category.Id))
                        {
                            hView.SetCategoryHidden(category.Id, true);
                        }
                    }

                    // configuring hView properties
                    hView.Name           = MakeViewNames(plateType)[1];
                    hView.DetailLevel    = ViewDetailLevel.Fine;
                    hView.DisplayStyle   = DisplayStyle.HLR;
                    hView.CropBoxVisible = false;
                    hView.Scale          = scaleValue;

                    // adding type handled to list
                    typesHandled.Add(String.Format("tipo {0}", (plateType).ToString()));
                }
                tx.Commit();
            }

            return(Result.Succeeded);
        }
        public void QTO_2_PlaceHoldersFromDWFMarkups(
            Document doc,
            string activityId)
        {
            View activeView = doc.ActiveView;

            if (!(activeView is ViewSheet))
            {
                TaskDialog.Show("QTO",
                                "The current view must be a Sheet View with DWF markups");
                return;
            }

            ViewSheet vs = activeView as ViewSheet;

            Viewport vp = doc.GetElement(
                vs.GetAllViewports().First()) as Viewport;

            View plan = doc.GetElement(vp.ViewId) as View;

            int scale = vp.Parameters.Cast <Parameter>()
                        .First(x => x.Id.IntegerValue.Equals(
                                   (int)BuiltInParameter.VIEW_SCALE))
                        .AsInteger();

            IEnumerable <Element> dwfMarkups
                = new FilteredElementCollector(doc)
                  .OfClass(typeof(ImportInstance))
                  .WhereElementIsNotElementType()
                  .Where(x => x.Name.StartsWith("Markup") &&
                         x.OwnerViewId.IntegerValue.Equals(
                             activeView.Id.IntegerValue));

            using (TransactionGroup tg = new TransactionGroup(doc))
            {
                tg.Start("DWF markups placeholders");

                using (Transaction t = new Transaction(doc))
                {
                    t.Start("DWF Transfer");

                    plan.Parameters.Cast <Parameter>()
                    .First(x => x.Id.IntegerValue.Equals(
                               (int)BuiltInParameter.VIEWER_CROP_REGION))
                    .Set(1);

                    XYZ VC = (plan.CropBox.Min + plan.CropBox.Max) / 2;

                    XYZ BC = vp.GetBoxCenter();

                    t.RollBack();

                    foreach (Element e in dwfMarkups)
                    {
                        GeometryElement GeoElem = e.get_Geometry(new Options());

                        GeometryInstance gi = GeoElem.Cast <GeometryInstance>().First();

                        GeometryElement gei = gi.GetSymbolGeometry();

                        IList <GeometryObject> gos = new List <GeometryObject>();

                        if (gei.Cast <GeometryObject>().Count(x => x is Arc) > 0)
                        {
                            continue;
                        }

                        foreach (GeometryObject go in gei)
                        {
                            XYZ med = new XYZ();

                            if (go is PolyLine)
                            {
                                PolyLine pl = go as PolyLine;

                                XYZ min = new XYZ(pl.GetCoordinates().Min(p => p.X),
                                                  pl.GetCoordinates().Min(p => p.Y),
                                                  pl.GetCoordinates().Min(p => p.Z));

                                XYZ max = new XYZ(pl.GetCoordinates().Max(p => p.X),
                                                  pl.GetCoordinates().Max(p => p.Y),
                                                  pl.GetCoordinates().Max(p => p.Z));

                                med = (min + max) / 2;
                            }

                            med = med - BC;

                            // Convert DWF sheet coordinates into model coordinates

                            XYZ a = VC + new XYZ(med.X * scale, med.Y * scale, 0);
                        }
                    }

                    t.Start("DWF Transfer");

                    foreach (Element e in dwfMarkups)
                    {
                        GeometryElement GeoElem = e.get_Geometry(new Options());

                        GeometryInstance gi = GeoElem.Cast <GeometryInstance>().First();

                        GeometryElement gei = gi.GetSymbolGeometry();

                        IList <GeometryObject> gos = new List <GeometryObject>();

                        if (gei.Cast <GeometryObject>().Count(x => x is Arc) == 0)
                        {
                            continue;
                        }

                        foreach (GeometryObject go in gei)
                        {
                            if (go is Arc)
                            {
                                Curve c = go as Curve;

                                XYZ med = c.Evaluate(0.5, true);

                                med = med - BC;

                                XYZ a = VC + new XYZ(med.X * scale, med.Y * scale, 0);

                                // Warning CS0618:
                                // Autodesk.Revit.Creation.ItemFactoryBase.NewTextNote(
                                //   View, XYZ, XYZ, XYZ, double, TextAlignFlags, string)
                                // is obsolete:
                                // This method is deprecated in Revit 2016.
                                // Please use one of the TextNote.Create methods instead.

                                //doc.Create.NewTextNote( plan,
                                //                       a,
                                //                       XYZ.BasisX,
                                //                       XYZ.BasisY,
                                //                       MMtoFeet( 5 ),
                                //                       TextAlignFlags.TEF_ALIGN_CENTER,
                                //                       activityId );

                                ElementId textTypeId = new FilteredElementCollector(doc)
                                                       .OfClass(typeof(TextNoteType))
                                                       .FirstElementId();

                                TextNote.Create(doc, plan.Id, a, activityId, textTypeId);
                            }
                        }

                        t.Commit();
                    }
                }

                tg.Assimilate();
            }
        }