Esempio n. 1
0
        private Viewport AddViewToSheet(Document doc, ViewSheet sheet, ElementType noTitle, XYZ pt, ElementId view)
        {
            if (Viewport.CanAddViewToSheet(doc, sheet.Id, view))
            {
                Viewport p3D = Viewport.Create(doc, sheet.Id, view, pt);
                if (noTitle.Name == "No Title")
                {
                    p3D.ChangeTypeId(noTitle.Id);
                }
                return(p3D);
            }

            return(null);
        }
Esempio n. 2
0
        private void AddLegendToSheetView(View legendView, ElementType viewPortType, ViewSheet viewSheet)
        {
            XYZ refPoint = new XYZ(1.355, 0.061, 0);

            if (legendView != null)
            {
                Viewport v1                  = Viewport.Create(_doc, viewSheet.Id, legendView.Id, XYZ.Zero);
                Outline  lvOutline           = v1.GetBoxOutline();
                XYZ      legendViewCenter    = (lvOutline.MaximumPoint + lvOutline.MinimumPoint) / 2.0;
                XYZ      rightCornerToCenter = legendViewCenter - new XYZ(lvOutline.MaximumPoint.X, lvOutline.MinimumPoint.Y, 0);
                v1.ChangeTypeId(viewPortType.Id);
                XYZ diffToMove = refPoint + rightCornerToCenter;
                ElementTransformUtils.MoveElement(_doc, v1.Id, diffToMove);
            }
        }
Esempio n. 3
0
        private void placeViewsOnNewSheets(Document detailLibrary, Document templateFile, ViewSheet sheet)
        {
            ICollection <ElementId> placedViewports = sheet.GetAllViewports();
            ElementId sourceSheetId = sheet.Id;
            ElementId newSheetId;

            //if (this.sheetIDMap.ContainsKey(sourceSheetId))
            //{
            newSheetId = sheetIDMap[sourceSheetId];
            //}
            ICollection <Viewport> viewsOnSheet = extractViewportsonSheets(detailLibrary, sheet);

            foreach (Viewport viewPort in viewsOnSheet)
            {
                ElementId viewsId = viewPort.ViewId;
                ElementId newViewId;
                //if (this.draftingViewIDMap.ContainsKey(viewsId))
                //{
                newViewId = draftingViewIDMap[viewsId];
                //}
                string      detailNumber = viewPort.get_Parameter(BuiltInParameter.VIEWPORT_DETAIL_NUMBER).AsString();
                XYZ         temp         = viewPort.GetBoxCenter();
                ElementId   temp2        = viewPort.get_Parameter(BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM).AsElementId();
                ElementType type         = detailLibrary.GetElement(temp2) as ElementType;
                ElementId   typeID       = type.GetTypeId();
                string      typeName     = type.Name;

                ElementId viewTitle = temp2;

                Element vpp = new FilteredElementCollector(templateFile).OfCategory(BuiltInCategory.OST_Viewports).FirstOrDefault(q => q.Name == type.Name);

                ElementType type2 = templateFile.GetElement(viewTitle) as ElementType;


                using (Transaction t = new Transaction(templateFile, "Place View"))
                {
                    t.Start();
                    Viewport newvp = Viewport.Create(templateFile, newSheetId, newViewId, temp);
                    newvp.get_Parameter(BuiltInParameter.VIEWPORT_DETAIL_NUMBER).Set(detailNumber);
                    newvp.ChangeTypeId(vpp.GetTypeId());
                    t.Commit();
                }
            }
        }
Esempio n. 4
0
        //changes a viewport on the given sheets viewporttype into another type
        public void ChangeViewPortType(string sheetName, ElementId viewportId, string typeName)
        {
            ElementId i = GetSheetId(sheetName);

            //make sure we have a sheet to work with
            if (i == null)
            {
                return;
            }

            //get the viewport we are after
            IEnumerable <Viewport> viewports = new FilteredElementCollector(doc, i)
                                               .OfClass(typeof(Viewport))
                                               .Cast <Viewport>()
                                               .Where(v => v.Id.Equals(viewportId));

            Viewport vp = viewports.FirstOrDefault();

            //make sure we have a viewport to work with
            if (vp == null)
            {
                return;
            }

            if (!vp.Name.Equals(typeName))
            {
                foreach (ElementId id in vp.GetValidTypes())
                {
                    ElementType type = doc.GetElement(id) as ElementType;
                    if (type.Name.Equals(typeName))
                    {
                        using (Transaction t = new Transaction(doc))
                        {
                            t.Start("Changing viewport type of sheet: '" + sheetName + "' of id: '" + viewportId.ToString() + "'");
                            vp.ChangeTypeId(type.Id);
                            t.Commit();
                        }

                        return;
                    }
                }
            }
        }
Esempio n. 5
0
        private void AddLegendToSheetView(View legendView, ElementType viewPortType, ViewSheet viewSheet, string position)
        {
            if (legendView != null)
            {
                Viewport v1               = Viewport.Create(_doc, viewSheet.Id, legendView.Id, XYZ.Zero);
                Outline  lvOutline        = v1.GetBoxOutline();
                XYZ      legendViewCenter = (lvOutline.MaximumPoint + lvOutline.MinimumPoint) / 2.0;

                // The position of the legend is Bottom Right by default
                double refX = Default.LEGEND_POSITION_X_MAX;
                double refY = Default.LEGEND_POSITION_Y_MIN_R;

                XYZ legendRefPointToCenter = legendViewCenter - new XYZ(lvOutline.MaximumPoint.X, lvOutline.MinimumPoint.Y, 0);

                if (position.Equals("TopRight"))
                {
                    refX = Default.LEGEND_POSITION_X_MAX;
                    refY = Default.LEGEND_POSITION_Y_MAX_R;

                    legendRefPointToCenter = legendViewCenter - new XYZ(lvOutline.MaximumPoint.X, lvOutline.MaximumPoint.Y, 0);
                }
                else if (position.Equals("BottomLeft"))
                {
                    refX = Default.LEGEND_POSITION_X_MIN;
                    refY = Default.LEGEND_POSITION_Y_MIN_L;

                    legendRefPointToCenter = legendViewCenter - new XYZ(lvOutline.MinimumPoint.X, lvOutline.MinimumPoint.Y, 0);
                }
                else if (position.Equals("TopLeft"))
                {
                    refX = Default.LEGEND_POSITION_X_MIN;
                    refY = Default.LEGEND_POSITION_Y_MAX_L;

                    legendRefPointToCenter = legendViewCenter - new XYZ(lvOutline.MinimumPoint.X, lvOutline.MaximumPoint.Y, 0);
                }

                XYZ refPoint = new XYZ(refX, refY, 0);

                v1.ChangeTypeId(viewPortType.Id);
                XYZ diffToMove = refPoint + legendRefPointToCenter;
                ElementTransformUtils.MoveElement(_doc, v1.Id, diffToMove);
            }
        }
        /// <summary>
        /// Bring viewport to front by
        /// deleting and recreating it.
        /// </summary>
        void ViewportBringToFront(
            ViewSheet sheet,
            Viewport viewport)
        {
            Document doc = sheet.Document;

            // Element id of the view in the viewport.

            ElementId viewId    = viewport.ViewId;
            ElementId typeId    = viewport.GetTypeId();
            XYZ       boxCenter = viewport.GetBoxCenter();

            // The viewport might be pinned. Most overlayed
            // viewports are maintained pinned to prevent
            // accidental displacement. Record that state so
            // the replacement viewport can reproduce it.

            bool pinnedState = viewport.Pinned;

            //View view = doc.ActiveView;

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Delete and Recreate Viewport");

                // At least in Revit 2016, pinned viewports
                // can be deleted without error.

                sheet.DeleteViewport(viewport);

                Viewport vvp = Viewport.Create(doc,
                                               sheet.Id, viewId, boxCenter);

                vvp.ChangeTypeId(typeId);
                vvp.Pinned = pinnedState;

                t.Commit();
            }
        }
Esempio n. 7
0
        // TODO : Enhencement for this function
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            _uiapp = commandData.Application;
            _uidoc = _uiapp.ActiveUIDocument;
            _doc   = _uidoc.Document;

            try
            {
                // Get list of all viewplans who have entity
                IList <ViewPlan> viewplans = GetAllStructuralPlans(_doc, true);
                // If no viewplan has entity, show a message
                if (viewplans.Count == 0)
                {
                    return(Result.Cancelled);
                }

                // Get list of all sheets who have entity
                IList <ViewSheet> viewsheets = GetAllSheets(_doc, true);
                // If no sheet has entity, show a message
                if (viewsheets.Count == 0)
                {
                    return(Result.Cancelled);
                }

                // Get view port type for adding viewplans to sheets
                ElementType viewPortType_WithoutTitle = GetElementTypeByName(_doc, Default.TYPE_NAME_VIEWPORT_WITHOUT_TITLE);

                // Count num of views added to all sheets
                int numOfViews = 0;

                using (Transaction t = new Transaction(_doc, "Add ViewPlans to the corresponding Sheets"))
                {
                    t.Start();

                    foreach (ViewSheet sheet in viewsheets)
                    {
                        ElementId sheetLevelId = GetAssociateLevelOfSheet(sheet);
                        foreach (ViewPlan viewplan in viewplans)
                        {
                            ElementId viewplanLevelId = GetAssociateLevelOfViewPlan(viewplan);
                            // Add viewplan to the sheet
                            if (viewplanLevelId == sheetLevelId)
                            {
                                // if the viewplan is already on the sheet
                                bool viewExistsOnSheet = sheet.GetAllViewports().Any(
                                    viewportId =>
                                    (_doc.GetElement(viewportId) as Viewport).ViewId == viewplan.Id
                                    );

                                if (!viewExistsOnSheet)
                                {
                                    BoundingBoxUV sheetOutline     = sheet.Outline;
                                    UV            titleblockCenter = (sheetOutline.Max + sheetOutline.Min) / 2.0;
                                    XYZ           xyzToMove        = new XYZ(titleblockCenter.U, titleblockCenter.V, 0);
                                    Viewport      v1 = Viewport.Create(_doc, sheet.Id, viewplan.Id, xyzToMove);
                                    if (v1 != null)
                                    {
                                        v1.ChangeTypeId(viewPortType_WithoutTitle.Id);
                                        // num +1
                                        numOfViews++;
                                    }
                                }
                            }
                        }
                    }
                    t.Commit();
                }

                // TODO : show user which view is added to which sheet
                TaskDialog.Show("Revit", $"{numOfViews} vues en plan sont ajoutées aux toutes les feuilles");

                return(Result.Succeeded);
            }
            catch (Autodesk.Revit.Exceptions.ArgumentException)
            {
                TaskDialog.Show("Revit", "Erreur dans le process, la commande va être annulée");
                return(Result.Cancelled);
            }
        }
Esempio n. 8
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();
            }
        }
Esempio n. 9
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //Get the current Document from the Command Data
            Document doc = commandData.Application.ActiveUIDocument.Document;

            //Check to make sure the user is on a sheet before continuing.
            if (doc.ActiveView.ViewType == ViewType.DrawingSheet)
            {
                //Get a new UIDocument from the current document to use to make a selection
                UIDocument uidoc = new UIDocument(doc);
                //Create a new instance of the ViewSelectionFilter to only allow the user to select a Legend Viewport
                ISelectionFilter selectionFilter = new ViewSelectionFilter();
                //A selection of elements from the current Document
                Selection picked = uidoc.Selection;
                //Try block to catch if the user cancels the selection process
                try
                {
                    //Prompt the user to make a single selection in the Revit interface. Only Legend Viewports will be available based onour SelectionFilter. The string is what the status bar displays in the Lower Left
                    Reference selection = picked.PickObject(ObjectType.Element, selectionFilter, "Select Legend on Sheet");
                    //Make sure the user made a selection
                    if (picked != null)
                    {
                        //Set the Class variable to the Viewport the user selected
                        viewPort = doc.GetElement(selection) as Viewport;
                        //Get the Location of the Legend Viewport selected
                        XYZ locPt = viewPort.GetBoxCenter();
                        //Prompt the user with a model dialog to select the sheets to place or update the Legends on
                        WPF.SheetSelectionWPF frm = new WPF.SheetSelectionWPF(doc);
                        //Make sure the Sheet Selection Form returns the correct DialogResult
                        if (frm.ShowDialog().Value)
                        {
                            //Make sure the user selected at least 1 sheet
                            if (frm.ViewSheetIds.Count > 0)
                            {
                                //Use this try to make sure Revit doesn't crash when trying to place or update the Legend Viewports
                                try
                                {
                                    //Create a Transaction within a using block to dispose of everything when complete
                                    using (Transaction Trans = new Transaction(doc))
                                    {
                                        //Provide a name for the transaction in the Undo / Redo List
                                        Trans.Start("Place Multiple Legends");
                                        //Loop through each Sheet Element Id from the sheets selected by the User
                                        foreach (ElementId viewSheetId in frm.ViewSheetIds)
                                        {
                                            //Get the ViewSheet (Sheet) fro each Element Id in the Document
                                            ViewSheet viewSheet = doc.GetElement(viewSheetId) as ViewSheet;
                                            //Get all of the Viewport Element Ids on that ViewSheet
                                            ICollection <ElementId> viewPortIds = viewSheet.GetAllViewports();
                                            //Use this check to see if the viewport already exists or if it needs to be created
                                            bool PlaceViewport = true;
                                            //Loop through each ElementId for all Viewports on the Sheet
                                            foreach (ElementId elementId in viewPortIds)
                                            {
                                                //Get the Viewport from the ElementId so we can get the ViewId
                                                Viewport vp = doc.GetElement(elementId) as Viewport;
                                                //If the Viewport ViewId of the Legend selected matches the ViewId of the current Viewport then we now have the matching legend on the Sheet
                                                if (vp.ViewId == viewPort.ViewId)
                                                {
                                                    //Set the bool parameter to False since we will not need to Place a new viewport
                                                    PlaceViewport = false;
                                                    //Set the location on the sheet to the same location as the Legend selected
                                                    vp.SetBoxCenter(locPt);
                                                    //Break the loop so we don't have to loop through any extra Viewports
                                                    break;
                                                }
                                            }
                                            //If the Legend Viewport wasn't found, then the bool parameters remains True and a new Viewport for the Legend will be created
                                            if (PlaceViewport)
                                            {
                                                //Create a new viewport at the correct location and sheet
                                                Viewport viewport = Viewport.Create(doc, viewSheetId, viewPort.ViewId, locPt);
                                                //Set the Viewport Type to the same as the Legend selected
                                                viewport.ChangeTypeId(viewPort.GetTypeId());
                                            }
                                        }
                                        //Commit the Transaction to keep the changes
                                        Trans.Commit();
                                        //Return a successful result to Revit so the changes are kept
                                        return(Result.Succeeded);
                                    }
                                }
                                //Catch an exceptions when adding or updating the Legend Viewports. Tell the user and return a Failed Result so Revit does not keep any changes
                                catch (Exception ex)
                                {
                                    TaskDialog.Show("Legend Placement Error", ex.ToString());
                                    return(Result.Failed);
                                }
                            }
                            //Tell the user that they did not select any sheets and return a Cancelled result so Revit does not keep any changes
                            else
                            {
                                TaskDialog.Show("Sheet Selection", "No Sheets were selected");
                                return(Result.Cancelled);
                            }
                        }
                        //If the Sheet Selection form was closed or cancelled then return a Cancelled result so Revit does not keep any changes
                        else
                        {
                            return(Result.Cancelled);
                        }
                    }
                    //Retrun a Cancelled Reseult if no eleemnts are picked
                    return(Result.Cancelled);
                }
                //Catch the Operation canceled Exception which is raised when the user "Escapes" during a Pick Object operation and return a Failed result
                catch (Autodesk.Revit.Exceptions.OperationCanceledException)
                {
                    return(Result.Failed);
                }
            }
            //Tell the user that they need to be in a Sheet View to run this Command
            else
            {
                TaskDialog.Show("Sheet Required", "Active view must be a Sheet");
                return(Result.Failed);
            }
        }
Esempio n. 10
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;

            FilteredElementCollector fec = new FilteredElementCollector(doc).OfClass(typeof(ElementType)).WhereElementIsElementType();

            Dictionary <string, ElementId> viewTypes = new Dictionary <string, ElementId>();

            foreach (ElementType e in fec)
            {
                if (e.FamilyName == "Viewport")
                {
                    try
                    {
                        viewTypes.Add(e.Name, e.Id);
                    }
                    catch { }
                }
            }

            try
            {
                string inputFile = @"C:\Temp\ExportedData.csv";

                using (Transaction t = new Transaction(doc, "Update Viewports from Excel"))
                {
                    t.Start();

                    using (var reader = new StreamReader(inputFile))
                    {
                        List <string> parameters = reader.ReadLine().Split(',').ToList();


                        while (!reader.EndOfStream)
                        {
                            var line = reader.ReadLine();

                            var values = line.Split(',').ToList();

                            //TaskDialog.Show("R", values.Count.ToString());

                            int id = Convert.ToInt32(values[0]);

                            //TaskDialog.Show("R", id.ToString());

                            ElementId currentId = new ElementId(id);

                            Viewport vp = doc.GetElement(currentId) as Viewport;

                            ElementId selectedType = null;
                            viewTypes.TryGetValue(values[3], out selectedType);

                            vp.LookupParameter("View Name").Set(values[2]);
                            vp.ChangeTypeId(selectedType);

                            vp.SetBoxCenter(new XYZ(Convert.ToDouble(values[4]), Convert.ToDouble(values[5]), Convert.ToDouble(values[6])));
                        }
                    } //close reader
                    t.Commit();
                }     //close transaction

                TaskDialog.Show("Result", "Done");

                return(Result.Succeeded);
            }

            catch (Exception ex)
            {
                TaskDialog.Show("Error", ex.Message);
                return(Result.Failed);
            }

            #region Old Method
            //try
            //{
            //        ICollection<ElementId> selectedSheetsId = uidoc.Selection.GetElementIds();

            //        TaskDialog.Show("r", selectedSheetsId.Count.ToString() + " selected");

            //        ICollection<ViewSheet> selectedSheets = new List<ViewSheet>();

            //        foreach (var eid in selectedSheetsId)
            //        {
            //            selectedSheets.Add(doc.GetElement(eid) as ViewSheet);
            //        }

            //        uidoc.ActiveView = uidoc.ActiveGraphicalView;


            //        string outputFile = @"C:\Temp\ExportedData.csv";

            //        var sortedList = selectedSheets.OrderBy(pd => pd.SheetNumber);

            //        string headers = "ElementId, Sheet Number, Sheet Name, ARUP_BDR_TITLE1,ARUP_BDR_TITLE2,ARUP_BDR_TITLE3, View Type, View Name, View PosX, View PosY, View PosZ\n";

            //        StringBuilder sb = new StringBuilder();

            //        File.WriteAllText(outputFile, headers);


            //        foreach (ViewSheet vs in sortedList)
            //        {

            //            ICollection<ElementId> viewports = vs.GetAllViewports();
            //            foreach (var vpid in viewports)
            //            {
            //                Viewport vport = doc.GetElement(vpid) as Viewport;
            //                View view = doc.GetElement(vport.ViewId) as View;

            //                string viewId = vpid.ToString();
            //                string sheetNumber = vs.LookupParameter("Sheet Number").AsString();
            //                string sheetName = vs.LookupParameter("Sheet Name").AsString();
            //                string sheetTitle1 = vs.LookupParameter("ARUP_BDR_TITLE1").AsString();
            //                string sheetTitle2 = vs.LookupParameter("ARUP_BDR_TITLE2").AsString();
            //                string sheetTitle3 = vs.LookupParameter("ARUP_BDR_TITLE3").AsString();
            //                string viewType = view.ViewType.ToString();
            //                string viewName = view.Name;
            //                string viewPosition = vport.GetBoxCenter().ToString().Remove(0, 1).TrimEnd(')');
            //                sb.AppendLine(System.String.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}",
            //                                            viewId, sheetNumber, sheetName, sheetTitle1, sheetTitle2, sheetTitle3,
            //                                            viewType, viewName, viewPosition));

            //            }
            //        }
            //        File.AppendAllText(outputFile, sb.ToString());

            //        System.Diagnostics.Process process = new System.Diagnostics.Process();
            //        process.StartInfo.FileName = outputFile;
            //        process.Start();


            //        return Result.Succeeded;

            //    }
            //    catch (Exception ex)
            //    {
            //        TaskDialog.Show("Error", ex.Message);
            //        return Result.Failed;
            //    //}

            #endregion
        }
Esempio n. 11
0
        /// <summary>
        /// Duplicates the input sheet a number of times. It allows for ViewDuplicateOption for dependent views.
        /// </summary>
        /// <param name="m_doc"></param>
        /// <param name="sourceSheet"></param>
        /// <param name="copies"></param>
        /// <param name="dependentOption"></param>
        private void DuplicateSheets(Document m_doc, ViewSheet sourceSheet, int copies, ViewDuplicateOption dependentOption)
        {
            // get Title Block
            FamilyInstance titleBlock = new FilteredElementCollector(m_doc)
                                        .OfClass(typeof(FamilyInstance))
                                        .OfCategory(BuiltInCategory.OST_TitleBlocks)
                                        .Cast <FamilyInstance>()
                                        .First(q => q.OwnerViewId == sourceSheet.Id);

            using (TransactionGroup tg = new TransactionGroup(m_doc, "Duplicate Sheet"))
            {
                tg.Start();
                for (int i = 0; i < copies; i++)
                {
                    // create unique sheet number
                    string uniqueSheetNumber = Data.Helpers.CreateUniqueSheetNumber(m_doc, sourceSheet);

                    using (Transaction t = new Transaction(m_doc, "Duplicate Sheet"))
                    {
                        t.Start();

                        // create new SHEET, new NUMBER and new NAME
                        ViewSheet newSheet = ViewSheet.Create(m_doc, titleBlock.GetTypeId());
                        newSheet.SheetNumber = uniqueSheetNumber;
                        newSheet.Name        = sourceSheet.Name;

                        #region Loop through viewports (except schedules) because GetAllPlacedViews() does not return Schedules
                        foreach (ElementId eid in sourceSheet.GetAllPlacedViews())
                        {
                            // get view element
                            Autodesk.Revit.DB.View sourceView = m_doc.GetElement(eid) as Autodesk.Revit.DB.View;
                            Autodesk.Revit.DB.View newView    = null; // declare newView variable

                            // DUPLICATE views
                            // if view element is legend newView is equal to sourceView
                            if (sourceView.ViewType == ViewType.Legend)
                            {
                                newView = sourceView;
                            }
                            else // for non-legend views
                            {
                                if (sourceView.GetPrimaryViewId() == ElementId.InvalidElementId) // if parent view
                                {
                                    ElementId newViewId = sourceView.Duplicate(ViewDuplicateOption.WithDetailing);
                                    newView      = m_doc.GetElement(newViewId) as Autodesk.Revit.DB.View;
                                    newView.Name = Data.Helpers.CreateUniqueViewName(m_doc, sourceView);
                                    //newView.ChangeTypeId(sourceTypeId);
                                }
                                else // if dependent view
                                {
                                    ElementId newViewId = sourceView.Duplicate(dependentOption);
                                    newView      = m_doc.GetElement(newViewId) as Autodesk.Revit.DB.View;
                                    newView.Name = Data.Helpers.CreateUniqueViewName(m_doc, sourceView);
                                    //newView.ChangeTypeId(sourceTypeId);
                                }
                            }
                            // CREATE viewport and MOVE it
                            foreach (Viewport vp in new FilteredElementCollector(m_doc).OfClass(typeof(Viewport)))
                            {
                                if (vp.SheetId == sourceSheet.Id && vp.ViewId == sourceView.Id)
                                {
                                    XYZ       sourceCenter = vp.GetBoxCenter();
                                    ElementId sourceTypeId = vp.GetTypeId();

                                    Viewport newViewport = Viewport.Create(m_doc, newSheet.Id, newView.Id, XYZ.Zero);
                                    newViewport.ChangeTypeId(sourceTypeId);
                                    Ana_NoOfViewports += 1; // add 1 to the viewport counter

                                    XYZ newCenter = newViewport.GetBoxCenter();

                                    ElementTransformUtils.MoveElement(m_doc, newViewport.Id, new XYZ(
                                                                          sourceCenter.X - newCenter.X,
                                                                          sourceCenter.Y - newCenter.Y,
                                                                          0));
                                }
                            }
                        }
                        #endregion

                        #region Loop through schedules
                        foreach (ScheduleSheetInstance si in (new FilteredElementCollector(m_doc).OfClass(typeof(ScheduleSheetInstance))))
                        {
                            if (si.OwnerViewId == sourceSheet.Id)
                            {
                                if (!si.IsTitleblockRevisionSchedule)
                                {
                                    foreach (ViewSchedule viewSchedule in new FilteredElementCollector(m_doc).OfClass(typeof(ViewSchedule)))
                                    {
                                        if (si.ScheduleId == viewSchedule.Id)
                                        {
                                            XYZ sourceCenter = si.Point;
                                            ScheduleSheetInstance newSSheetInstance = ScheduleSheetInstance.Create(m_doc, newSheet.Id, viewSchedule.Id, XYZ.Zero);
                                            XYZ newCenter = newSSheetInstance.Point;
                                            ElementTransformUtils.MoveElement(m_doc, newSSheetInstance.Id, new XYZ(
                                                                                  sourceCenter.X - newCenter.X,
                                                                                  sourceCenter.Y - newCenter.Y,
                                                                                  0));
                                        }
                                    }
                                }
                            }
                        }
                        #endregion

                        t.Commit();
                    }
                }
                tg.Assimilate();
            }
        }
Esempio n. 12
0
        public SheetsCSLRequest(UIApplication uiApp, String text)
        {
            MainUI uiForm = BARevitTools.Application.thisApp.newMainUi;

            //Reset the progress bar
            uiForm.sheetsCSLProgressBar.Value   = 0;
            uiForm.sheetsCSLProgressBar.Minimum = 0;
            uiForm.sheetsCSLProgressBar.Step    = 1;
            uiForm.sheetsCSLProgressBar.Visible = true;

            UIDocument uidoc           = uiApp.ActiveUIDocument;
            var        sheetsCollector = new FilteredElementCollector(uidoc.Document).OfClass(typeof(ViewSheet)).ToElements();

            //Create some objects for storage
            string           selectedSheetNumber = uiForm.sheetsCSLComboBox.Text;
            List <string>    selectedSheets      = new List <string>();
            List <ElementId> viewsToCopy         = new List <ElementId>();
            List <ElementId> viewportTypeIds     = new List <ElementId>();
            List <XYZ>       viewportLocations   = new List <XYZ>();

            //Count the number of sheets with checkboxes in the DataGridView. Use that to set the number of steps for the progress bar
            int countOfSheets = 0;

            foreach (DataGridViewRow row in uiForm.sheetsCSLDataGridView.Rows)
            {
                if (row.Cells["Select"].Value != null)
                {
                    if (row.Cells["Select"].Value.ToString() == "True")
                    {
                        selectedSheets.Add(row.Cells["Sheet Number"].Value.ToString());
                        countOfSheets++;
                    }
                    else
                    {
                        continue;
                    }
                }
                else
                {
                    continue;
                }
            }
            uiForm.sheetsCSLProgressBar.Maximum = countOfSheets;

            //Get the sheet to copy legends from
            if (uiForm.sheetsCSLComboBox.Text != "<Originating Sheet>")
            {
                //Cycle through the collection of sheets
                foreach (ViewSheet sheet in sheetsCollector)
                {
                    //If the current sheet number matches the sheet number of the sheet to copy from, continue
                    if (sheet.SheetNumber.ToString() == selectedSheetNumber)
                    {
                        //Collect the viewports from the sheet
                        ICollection <ElementId> viewportIds = sheet.GetAllViewports();
                        foreach (ElementId viewportId in viewportIds)
                        {
                            //For each viewport, get the ViewId, TypeId, and location
                            Viewport  viewportElement           = uidoc.Document.GetElement(viewportId) as Viewport;
                            ElementId viewportViewId            = viewportElement.ViewId;
                            ElementId viewportViewTypeId        = viewportElement.GetTypeId();
                            XYZ       viewportLocation          = viewportElement.GetBoxCenter();
                            Autodesk.Revit.DB.View viewportView = uidoc.Document.GetElement(viewportViewId) as Autodesk.Revit.DB.View;
                            //If the viewport is a legend, continue
                            if (viewportView.ViewType.ToString() == "Legend")
                            {
                                //Add the three sets of data to the lists
                                viewsToCopy.Add(viewportViewId);
                                viewportTypeIds.Add(viewportViewTypeId);
                                viewportLocations.Add(viewportLocation);
                            }
                            else
                            {
                                continue;
                            }
                        }
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }
            }

            //Start a new transaction
            Transaction t1 = new Transaction(uidoc.Document, "CopyLegendsFromSheetToSheets");

            t1.Start();
            //For each sheet in the collector...
            foreach (ViewSheet sheet in sheetsCollector)
            {
                //If the selected sheets contains the sheet number, continue
                if (selectedSheets.Contains(sheet.SheetNumber.ToString()))
                {
                    //Step forward the progress bar
                    uiForm.sheetsCSLProgressBar.PerformStep();
                    int x = viewsToCopy.Count();
                    int i = 0;

                    //For each sheet in viewsToCopy
                    while (i < x)
                    {
                        try
                        {
                            //Create a new viewport and place it on the sheet in the same location
                            Viewport newViewport = Viewport.Create(uidoc.Document, sheet.Id, viewsToCopy[i], viewportLocations[i]);
                            newViewport.ChangeTypeId(viewportTypeIds[i]);
                            i++;
                        }
                        catch { i++; }
                    }
                }
                else
                {
                    continue;
                }
            }
            t1.Commit();
            t1.Dispose();
            //Reset the filter text box if it was set
            uiForm.sheetsCSLFilterTextBox.Text = "";

            //Reset the backcolor of each row in the DataGridView
            foreach (DataGridViewRow row in uiForm.sheetsCSLDataGridView.Rows)
            {
                row.Cells["Select"].Value           = false;
                row.Cells["Select"].Style.BackColor = uiForm.sheetsCSLDataGridView.DefaultCellStyle.BackColor;
            }
        }
Esempio n. 13
0
        public static void makeSheets(Document curDoc, string[] tblockName, string vPortName, string CSVFile, string sheetType)
        {
            //arguments are: document, title block to use for new sheets, viewport type for views and path to CSV file with sheet names, numbers and views

            //check if title block exists
            FamilySymbol tblock = null;

            if (mFunctions.doesTblockExist(curDoc, tblockName) == true)
            {
                //get tblock
                tblock = mFunctions.getTitleblock(curDoc, tblockName);
            }
            else
            {
                TaskDialog.Show("alert", "Could not find titleblock");
                return;
            }

            //success and failures
            List <string> m_s = new List <string>();
            List <string> m_f = new List <string>();

            //check if CSV file exists
            if (System.IO.File.Exists(CSVFile) == false)
            {
                //file doesn't exist - abort
                TaskDialog.Show("Error", "The CSV file " + CSVFile + " cannot be found.");
                return;
            }

            //transaction
            using (Transaction t = new Transaction(curDoc, "Create Sheets")) {
                if (t.Start() == TransactionStatus.Started)
                {
                    //the sheet object
                    ViewSheet m_vs = null;

                    //read CSV file and create sheet based on info
                    IList <structSheet> sheetList = null;
                    sheetList = mFunctions.ReadCSV(CSVFile, true);

                    //create sheet for each sheet in list
                    foreach (structSheet curSheet in sheetList)
                    {
                        try {
                            //create sheets
                            if (sheetType == "Placeholder Sheet")
                            {
                                m_vs = ViewSheet.CreatePlaceholder(curDoc);
                            }
                            else
                            {
                                m_vs = ViewSheet.Create(curDoc, tblock.Id);
                            }

                            m_vs.Name        = curSheet.sheetName;
                            m_vs.SheetNumber = curSheet.sheetNum;

                            //record success
                            m_s.Add("Created sheet: " + m_vs.SheetNumber + " " + Constants.vbCr);

                            //loop through view string and add views to sheet
                            foreach (string tmpView in curSheet.viewName.Split(new char[] { ',' }))
                            {
                                //get current view
                                View curView = mFunctions.getView(tmpView.Trim(), curDoc);

                                Viewport curVP = null;
                                try {
                                    if (Viewport.CanAddViewToSheet(curDoc, m_vs.Id, curView.Id))
                                    {
                                        //add it
                                        curVP = Viewport.Create(curDoc, m_vs.Id, curView.Id, new XYZ(0, 0, 0));

                                        //center viewport on sheet
                                        mFunctions.centerViewOnSheet(curVP, curView, m_vs, curDoc);

                                        //change viewport type of plan view to no title
                                        ElementId vpTypeID = null;
                                        vpTypeID = mFunctions.getViewportTypeID(vPortName, curDoc);
                                        curVP.ChangeTypeId(vpTypeID);

                                        //record success
                                        m_s.Add("Added view: " + curView.Name + " " + Constants.vbCr);
                                    }
                                } catch (Exception ex1) {
                                    m_f.Add("Could not add view " + tmpView + " to sheet " + m_vs.SheetNumber + Constants.vbCr);
                                }
                            }
                        } catch (Exception ex2) {
                            //record failure
                            m_f.Add("sheet error: " + ex2.Message);
                        }
                    }

                    //commit
                    t.Commit();

                    //report sheets created
                    if (m_s.Count > 0)
                    {
                        using (TaskDialog m_td = new TaskDialog("Success!!")) {
                            m_td.MainInstruction = "Created Sheets:";
                            foreach (string x_loopVariable in m_s)
                            {
                                //x = x_loopVariable;
                                m_td.MainContent += x_loopVariable;
                            }

                            //show dialog
                            m_td.Show();
                        }
                    }

                    if (m_f.Count > 0)
                    {
                        using (TaskDialog m_td2 = new TaskDialog("Failures")) {
                            m_td2.MainInstruction = "Problems:";
                            foreach (string x_loopVariable in m_f)
                            {
                                //x = x_loopVariable;
                                m_td2.MainContent += x_loopVariable;
                            }

                            //show dialog
                            m_td2.Show();
                        }
                    }
                }
            }
        }
Esempio n. 14
0
        private static Viewport DuplicateViewPort(PreviewMap preview, ViewSheet copiedSheet, ViewDrafting copiedView)
        {
            Viewport recipientViewport = null;
            Viewport sourceViewport    = null;

            try
            {
                if (null != preview.SourceViewProperties.SheetObj)
                {
                    sourceViewport = preview.SourceViewProperties.ViewportObj;

                    if (null != sourceViewport)
                    {
                        using (Transaction trans = new Transaction(preview.RecipientModelInfo.Doc, "Place Viewports"))
                        {
                            try
                            {
                                trans.Start("Create Viewport");


                                XYZ    viewportLocation = preview.SourceViewProperties.ViewLocation;
                                string viewportTypeName = preview.SourceViewProperties.ViewportTypeName;

                                recipientViewport = Viewport.Create(preview.RecipientModelInfo.Doc, copiedSheet.Id, copiedView.Id, viewportLocation);

                                if (null != recipientViewport)
                                {
                                    ElementId        viewportTypeId = ElementId.InvalidElementId;
                                    List <ElementId> elementTypeIds = recipientViewport.GetValidTypes().ToList();
                                    foreach (ElementId typeId in elementTypeIds)
                                    {
                                        ElementType eType = preview.RecipientModelInfo.Doc.GetElement(typeId) as ElementType;
                                        if (eType.Name == viewportTypeName)
                                        {
                                            viewportTypeId = typeId; break;
                                        }
                                    }

                                    if (viewportTypeId != ElementId.InvalidElementId)
                                    {
                                        ElementId typeId = recipientViewport.ChangeTypeId(viewportTypeId);
                                    }
                                    else
                                    {
                                        CopyPasteOptions options = new CopyPasteOptions();
                                        options.SetDuplicateTypeNamesHandler(new HideAndAcceptDuplicateTypeNamesHandler());

                                        List <ElementId> typeIds = new List <ElementId>();
                                        typeIds.Add(sourceViewport.GetTypeId());

                                        ICollection <ElementId> copiedTypeIds = ElementTransformUtils.CopyElements(preview.SourceModelInfo.Doc, typeIds, preview.RecipientModelInfo.Doc, Transform.Identity, options);
                                        if (copiedTypeIds.Count > 0)
                                        {
                                            viewportTypeId = copiedTypeIds.First();
                                            ElementId typeId = recipientViewport.ChangeTypeId(viewportTypeId);
                                        }
                                    }
                                    FailureHandlingOptions failOpt = trans.GetFailureHandlingOptions();
                                    failOpt.SetFailuresPreprocessor(new WarningMessagePreprocessor());
                                    trans.Commit(failOpt);

                                    if (null != recipientViewport)
                                    {
                                        trans.Start("Wirte Parameter Values");
                                        foreach (Parameter param in sourceViewport.Parameters)
                                        {
                                            if (!param.IsReadOnly)
                                            {
#if RELEASE2014
                                                Parameter rParam = recipientViewport.get_Parameter(param.Definition.Name);
#elif RELEASE2015 || RELEASE2016 || RELEASE2017
                                                Parameter rParam = recipientViewport.LookupParameter(param.Definition.Name);
#endif

                                                if (null != rParam)
                                                {
                                                    if (!rParam.IsReadOnly)
                                                    {
                                                        if (rParam.StorageType == param.StorageType)
                                                        {
                                                            switch (param.StorageType)
                                                            {
                                                            case StorageType.Double:
                                                                rParam.Set(param.AsDouble());
                                                                break;

                                                            case StorageType.Integer:
                                                                rParam.Set(param.AsInteger());
                                                                break;

                                                            case StorageType.String:
                                                                rParam.Set(param.AsString());
                                                                break;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                        FailureHandlingOptions failureOptions = trans.GetFailureHandlingOptions();
                                        failureOptions.SetFailuresPreprocessor(new HideSameParameterValuePreprocessor());
                                        trans.Commit(failureOptions);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Failed to duplicate the viewport.\n" + ex.Message, "Duplicate Viewport", MessageBoxButton.OK, MessageBoxImage.Warning);
                                trans.RollBack();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                errorMessage.AppendLine("Failed to duplicate viewports.\n" + ex.Message);
                //MessageBox.Show("Failed to find the viewport.\n"+ex.Message, "Find Source Viewport", MessageBoxButton.OK, MessageBoxImage.Warning);
            }


            return(recipientViewport);
        }
Esempio n. 15
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = commandData.Application.ActiveUIDocument.Document;

            //get viewport
            TaskDialog.Show("GOA", "请选择视口作为样例.");
            Reference viewportref = uidoc.Selection.PickObject(ObjectType.Element, "选择图例.");
            Viewport  viewport    = doc.GetElement(viewportref.ElementId) as Viewport;

            if (viewport == null) // || viewport.Id.IntegerValue != (int)BuiltInCategory.OST_Viewports)
            {
                TaskDialog.Show("wrong", "未选中视口"); return(Result.Failed);
            }
            ElementId legendid = viewport.ViewId;

            //get titleBlock & name
            TaskDialog.Show("GOA", "请选择图框作为样例.");
            Reference      titleblockref      = uidoc.Selection.PickObject(ObjectType.Element, "选择图框.");
            FamilyInstance titleblock         = doc.GetElement(titleblockref.ElementId) as FamilyInstance;
            Category       titleblockcategory = titleblock.Category;

            if (titleblock == null || titleblockcategory.Id.IntegerValue != (int)BuiltInCategory.OST_TitleBlocks)
            {
                TaskDialog.Show("wrong", "未选中图框"); return(Result.Failed);
            }
            string titleblockname = titleblock.Symbol.Family.Name;

            //get viewsheet
            ElementId viewsheetid = titleblock.OwnerViewId;

            //get location(by boundingbox)
            XYZ    viewportposition   = viewport.GetBoxCenter();
            XYZ    titleblockposition = titleblock.get_BoundingBox(uidoc.ActiveView).Max;
            double distanceX          = titleblockposition.X - viewportposition.X;
            double distanceY          = titleblockposition.Y - viewportposition.Y;

            //get all titleBlocks
            FilteredElementCollector collector = new FilteredElementCollector(doc);

            collector.OfCategory(BuiltInCategory.OST_TitleBlocks).WhereElementIsNotElementType();
            if (collector == null)
            {
                TaskDialog.Show("wrond", "未找到图纸");
            }

            //prompt
            string prompt = "水平偏移:" + (distanceX * 304.8).ToString() + "\n垂直偏移:" + (distanceY * 304.8).ToString() + "\n同类型图框有:\n";
            List <FamilyInstance> titleblocks = new List <FamilyInstance>();

            foreach (Element ele in collector)
            {
                FamilyInstance tb = ele as FamilyInstance;
                if (tb == null)
                {
                    TaskDialog.Show("wrond", "未找到图框"); continue;
                }
                ViewSheet vs = doc.GetElement(tb.OwnerViewId) as ViewSheet;
                if (vs == null)
                {
                    TaskDialog.Show("wrond", "未找到图纸"); continue;
                }
                if (tb.Symbol.Family.Name == titleblockname)
                {
                    titleblocks.Add(tb); prompt += vs.Name; prompt += "\n";
                }
            }
            TaskDialog.Show("GOA", prompt);

            //dele all viewport
            FilteredElementCollector viewports = new FilteredElementCollector(doc);

            viewports.OfCategory(BuiltInCategory.OST_Viewports).WhereElementIsNotElementType();
            List <ElementId> deleids = new List <ElementId>();

            foreach (Element ele in viewports)
            {
                Viewport vp = ele as Viewport;
                if (vp.ViewId == legendid)
                {
                    deleids.Add(vp.Id);
                }
            }

            //get type
            FilteredElementCollector typecol = new FilteredElementCollector(doc);

            typecol.OfClass(typeof(ElementType));
            ElementType type = null;

            foreach (Element ele in typecol)
            {
                ElementType tmp = ele as ElementType;
                if (tmp == null)
                {
                    continue;
                }
                if (tmp.Name == "A-VIEW-NONE")
                {
                    type = tmp; break;
                }
            }
            if (type == null)
            {
                TaskDialog.Show("wrong", "未找到<A-VIEW-NONE>类型,请载入后重试.");
            }

            //create viewport and move
            using (Transaction transaction = new Transaction(doc))
            {
                transaction.Start("creat legends");
                doc.Delete(deleids);
                foreach (FamilyInstance tb in titleblocks)
                {
                    //if(tb.OwnerViewId == viewsheetid) {continue; }
                    XYZ postiontmp = tb.get_BoundingBox(doc.GetElement(tb.OwnerViewId) as ViewSheet).Max;
                    XYZ postion    = new XYZ(postiontmp.X - distanceX, postiontmp.Y - distanceY, postiontmp.Z);
                    if (Viewport.CanAddViewToSheet(doc, tb.OwnerViewId, legendid))
                    {
                        Viewport newvp = Viewport.Create(doc, tb.OwnerViewId, legendid, postion);
                        newvp.ChangeTypeId(type.Id);
                    }
                }

                transaction.Commit();
            }
            TaskDialog.Show("GOA", "生成成功.如果图框内已有一样的区位图会被删除并生成在新的位置.");


            return(Result.Succeeded);
        }